text
stringlengths
14
6.51M
unit uFreeFundsSelect; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, Buttons, ExtCtrls, cxGridTableView, ActnList, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridDBTableView, cxGrid, uCommonSp, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, iBase, dxBar, dxBarExtItems, UpStyleContainer; type TUPFunds = class(TSprav) private public constructor Create; procedure Show; override; end; function CreateSprav: TSprav; stdcall; exports CreateSprav; type TfmFreeFundsSelect = class(TForm) Grid: TcxGrid; TableView: TcxGridDBTableView; GridLevel1: TcxGridLevel; ActionList1: TActionList; SelectAction: TAction; QuitAction: TAction; RefreshAction: TAction; ShowId: TAction; TableViewSMETA_FULL_TITLE: TcxGridDBColumn; TableViewKOL_STAVOK: TcxGridDBColumn; TableViewKOL_VACANT_STAVOK: TcxGridDBColumn; TableViewOKLAD: TcxGridDBColumn; TableViewKOEFF_PPS: TcxGridDBColumn; TableViewSMETA_PPS_FULL_TITLE: TcxGridDBColumn; TableViewSR_NAME: TcxGridDBColumn; TableViewID_SR: TcxGridDBColumn; TableViewSMETA_TITLE: TcxGridDBColumn; TableViewSMETA_KOD: TcxGridDBColumn; TableViewOKLAD_PPS: TcxGridDBColumn; TableViewSMETA_PPS_TITLE: TcxGridDBColumn; TableViewSMETA_PPS_KOD: TcxGridDBColumn; TableViewID_SMETA: TcxGridDBColumn; TableViewID_SMETA_PPS: TcxGridDBColumn; TableViewID_WORK_COND: TcxGridDBColumn; TableViewNAME_WORK_COND: TcxGridDBColumn; TableViewID_WORK_MODE: TcxGridDBColumn; TableViewNAME_WORK_MODE: TcxGridDBColumn; GetFreeFunds: TpFIBDataSet; GetFreeFundsSMETA_FULL_TITLE: TFIBStringField; GetFreeFundsKOL_STAVOK: TFIBFloatField; GetFreeFundsKOL_VACANT_STAVOK: TFIBFloatField; GetFreeFundsOKLAD: TFIBFloatField; GetFreeFundsKOEFF_PPS: TFIBFloatField; GetFreeFundsSMETA_PPS_FULL_TITLE: TFIBStringField; GetFreeFundsSR_NAME: TFIBStringField; GetFreeFundsID_SR: TFIBIntegerField; GetFreeFundsSMETA_TITLE: TFIBStringField; GetFreeFundsSMETA_KOD: TFIBIntegerField; GetFreeFundsOKLAD_PPS: TFIBFloatField; GetFreeFundsSMETA_PPS_TITLE: TFIBStringField; GetFreeFundsSMETA_PPS_KOD: TFIBIntegerField; GetFreeFundsID_SMETA: TFIBIntegerField; GetFreeFundsID_SMETA_PPS: TFIBIntegerField; GetFreeFundsID_WORK_COND: TFIBIntegerField; GetFreeFundsNAME_WORK_COND: TFIBStringField; GetFreeFundsID_WORK_MODE: TFIBIntegerField; GetFreeFundsNAME_WORK_MODE: TFIBStringField; FreeFundsSource: TDataSource; ReadTransaction: TpFIBTransaction; DB: TpFIBDatabase; dxBarDockControl1: TdxBarDockControl; dxBarManager1: TdxBarManager; RefreshBtn: TdxBarLargeButton; SelectBtn: TdxBarLargeButton; ExitBtn: TdxBarLargeButton; procedure TableViewDblClick(Sender: TObject); procedure TableViewKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure RefreshBtnClick(Sender: TObject); procedure SelectBtnClick(Sender: TObject); procedure ExitBtnClick(Sender: TObject); private pStylesDM:TStyleContainer; public constructor Create(AOwner:TForm;DBHandle:TISC_DB_HANDLE; Id_post_salary,ID_department,Id_type_post:variant; Act_date:TDate;Id_level:variant);reintroduce; end; var fmFreeFundsSelect: TfmFreeFundsSelect; implementation {$R *.dfm} constructor TfmFreeFundsSelect.Create(AOwner:TForm;DBHandle:TISC_DB_HANDLE; Id_post_salary,ID_department,Id_type_post:variant; Act_date:TDate;Id_level:variant); begin inherited Create(AOwner); DB.Handle := DBHandle; GetFreeFunds.ParamByName('ID_POST_SALARY').AsVariant := Id_post_salary; GetFreeFunds.ParamByName('ID_DEPARTMENT').AsVariant := ID_department; GetFreeFunds.ParamByName('ID_TYPE_POST').AsVariant := Id_type_post; GetFreeFunds.ParamByName('ID_LEVEL').AsVariant := Id_level; GetFreeFunds.ParamByName('ACT_DATE').AsDate := Act_date; { ShowMessage(GetFreeFunds.SQLs.SelectSQL.Text+#13+ 'ID_POST_SALARY = '+VarToStrDef(GetFreeFunds.ParamByName('ID_POST_SALARY').AsVariant,'NULL')+#13+ 'ID_DEPARTMENT = '+VarToStrDef(GetFreeFunds.ParamByName('ID_DEPARTMENT').AsVariant,'NULL')+#13+ 'ID_TYPE_POST = '+VarToStrDef(GetFreeFunds.ParamByName('ID_TYPE_POST').AsVariant,'NULL')+#13+ 'ID_LEVEL = '+VarToStrDef(GetFreeFunds.ParamByName('ID_LEVEL').AsVariant,'NULL')+#13+ 'ACT_DATE = '+VarToStrDef(GetFreeFunds.ParamByName('ACT_DATE').AsVariant,'NULL'));} GetFreeFunds.Open; pStylesDM := TStyleContainer.Create(self); TableView.Styles.StyleSheet := pStylesDM.TableViewSheet; end; constructor TUPFunds.Create; begin inherited Create; // создание входных/выходных полей Input.FieldDefs.Add('Id_post_salary',ftVariant); Input.FieldDefs.Add('Id_department',ftVariant); Input.FieldDefs.Add('id_type_post',ftVariant); Input.FieldDefs.Add('Act_date',ftVariant); Input.FieldDefs.Add('Id_level',ftVariant); Output.FieldDefs.Add('Id_Smeta',ftVariant); Output.FieldDefs.Add('Smeta_Title',ftString,255); Output.FieldDefs.Add('Kol_Vacant_Stavok',ftFloat); Output.FieldDefs.Add('Koeff_Pps',ftFloat); Output.FieldDefs.Add('Id_Smeta_Pps',ftVariant); Output.FieldDefs.Add('Smeta_Pps_Title',ftString,255); // подготовить параметры PrepareMemoryDatasets; end; function CreateSprav: TSprav; begin Result := TUPFunds.Create; end; procedure TUPFunds.Show; var fm: TfmFreeFundsSelect; begin fm := TfmFreeFundsSelect.Create(Application.MainForm,TISC_DB_Handle(Integer(Input['DBHandle'])), Input['Id_post_salary'],Input['Id_department'],Input['id_type_post'], Input['Act_date'],Input['Id_level']); if fm.ShowModal = mrOk then with fm do begin OutPut.Append; Output.FieldValues['Id_Smeta'] := fm.GetFreeFunds['ID_SMETA']; Output.FieldValues['Smeta_Title'] := fm.GetFreeFunds['SMETA_TITLE']; Output.FieldValues['Kol_Vacant_Stavok'] := fm.GetFreeFunds['KOL_VACANT_STAVOK']; Output.FieldValues['Koeff_Pps'] := fm.GetFreeFunds['KOEFF_PPS']; Output.FieldValues['Id_Smeta_Pps'] := fm.GetFreeFunds['ID_SMETA_PPS']; Output.FieldValues['Smeta_Pps_Title'] := fm.GetFreeFunds['SMETA_PPS_TITLE']; Output.Post; end; fm.Free; end; procedure TfmFreeFundsSelect.TableViewDblClick(Sender: TObject); begin SelectBtn.Click; end; procedure TfmFreeFundsSelect.TableViewKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then SelectBtn.Click; end; procedure TfmFreeFundsSelect.RefreshBtnClick(Sender: TObject); begin TableView.DataController.DataSet.Refresh; end; procedure TfmFreeFundsSelect.SelectBtnClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TfmFreeFundsSelect.ExitBtnClick(Sender: TObject); begin ModalResult := mrCancel; end; end.
{**************************************************************************************} { } { CCR.VirtualKeying - sending virtual keystrokes on OS X and Windows } { } { The contents of this file are subject to the Mozilla Public License Version 2.0 } { (the "License"); you may not use this file except in compliance with the License. } { You may obtain a copy of the License at https://www.mozilla.org/MPL/2.0 } { } { Software distributed under the License is distributed on an "AS IS" basis, WITHOUT } { WARRANTY OF ANY KIND, either express or implied. See the License for the specific } { language governing rights and limitations under the License. } { } { The Initial Developer of the Original Code is Chris Rolliston. Portions created by } { Chris Rolliston are Copyright (C) 2015 Chris Rolliston. All Rights Reserved. } { } {**************************************************************************************} unit VirtualKeying; interface uses System.SysUtils, System.Classes, System.TypInfo, System.Rtti; type TVirtualKeyEventType = (keDown, keUp); IVirtualKeySequence = interface ['{6625BA86-FFAF-4820-B432-FAE1315F0A16}'] function Add(Key: Word; Shift: TShiftState; const EventTypes: array of TVirtualKeyEventType): IVirtualKeySequence; overload; function Add(Ch: Char; const EventTypes: array of TVirtualKeyEventType): IVirtualKeySequence; overload; function AddKeyPresses(const Chars: array of Char): IVirtualKeySequence; overload; function AddKeyPresses(const Chars: string): IVirtualKeySequence; overload; function AddShortCut(const ShortCut: TShortCut): IVirtualKeySequence; overload; function Execute: IVirtualKeySequence; end; TVirtualKeySequenceBase = class(TInterfacedObject) protected function Add(Key: Word; Shift: TShiftState; const EventTypes: array of TVirtualKeyEventType): IVirtualKeySequence; overload; virtual; abstract; function Add(Ch: Char; const EventTypes: array of TVirtualKeyEventType): IVirtualKeySequence; overload; virtual; abstract; function AddKeyPresses(const Chars: array of Char): IVirtualKeySequence; overload; function AddKeyPresses(const Chars: string): IVirtualKeySequence; overload; function AddShortCut(const ShortCut: TShortCut): IVirtualKeySequence; overload; end; TVirtualKeySequence = record strict private class var FDefaultImplementation: TClass; FConstructor: TRttiMethod; FRttiContext: TRttiContext; public class function Create: IVirtualKeySequence; static; class procedure Execute(const Chars: string; DelayMSecs: Cardinal = 0); overload; static; class procedure Execute(const ShortCut: TShortCut; DelayMSecs: Cardinal = 0); overload; static; class procedure SetDefaultImplementation<T: class, constructor, IVirtualKeySequence>; static; end; procedure ShortCutToKey(ShortCut: TShortCut; var Key: Word; var Shift: TShiftState); implementation uses System.SysConst, System.RTLConsts, {$IFDEF MACOS} VirtualKeying.Mac, {$ENDIF} {$IFDEF MSWINDOWS} VirtualKeying.Win, {$ENDIF} VirtualKeying.Consts; procedure ShortCutToKey(ShortCut: TShortCut; var Key: Word; var Shift: TShiftState); begin Key := Lo(ShortCut); Shift := []; if ShortCut and scCommand <> 0 then Include(Shift, ssCommand); if ShortCut and scShift <> 0 then Include(Shift, ssShift); if ShortCut and scCtrl <> 0 then Include(Shift, ssCtrl); if ShortCut and scAlt <> 0 then Include(Shift, ssAlt); end; { TVirtualKeySequenceBase } function TVirtualKeySequenceBase.AddKeyPresses(const Chars: array of Char): IVirtualKeySequence; var Ch: Char; begin for Ch in Chars do Add(Ch, [keDown, keUp]); end; function TVirtualKeySequenceBase.AddKeyPresses(const Chars: string): IVirtualKeySequence; var Ch: Char; begin for Ch in Chars do Add(Ch, [keDown, keUp]); end; function TVirtualKeySequenceBase.AddShortCut(const ShortCut: TShortCut): IVirtualKeySequence; var Key: Word; Shift: TShiftState; begin ShortCutToKey(ShortCut, Key, Shift); Result := Add(Key, Shift, [keDown, keUp]); end; { TVirtualKeySequence } class function TVirtualKeySequence.Create: IVirtualKeySequence; begin if FConstructor = nil then raise ENotSupportedException.CreateRes(@SVirtualKeyingUnsupported); Result := FConstructor.Invoke(FDefaultImplementation, []).AsType<IVirtualKeySequence>; end; class procedure TVirtualKeySequence.Execute(const Chars: string; DelayMSecs: Cardinal); var Proc: TProc; begin Proc := procedure var Sequence: IVirtualKeySequence; begin if DelayMSecs > 0 then Sleep(DelayMSecs); Sequence := TVirtualKeySequence.Create; Sequence.AddKeyPresses(Chars); Sequence.Execute; end; if DelayMSecs <= 0 then Proc() else TThread.CreateAnonymousThread(Proc).Start; end; class procedure TVirtualKeySequence.Execute(const ShortCut: TShortCut; DelayMSecs: Cardinal); var Proc: TProc; begin Proc := procedure var Sequence: IVirtualKeySequence; begin if DelayMSecs > 0 then Sleep(DelayMSecs); Sequence := TVirtualKeySequence.Create; Sequence.AddShortCut(ShortCut); Sequence.Execute; end; if DelayMSecs <= 0 then Proc() else TThread.CreateAnonymousThread(Proc).Start; end; class procedure TVirtualKeySequence.SetDefaultImplementation<T>; var LConstructor, Method: TRttiMethod; begin LConstructor := nil; for Method in FRttiContext.GetType(TypeInfo(T)).GetMethods do if Method.IsConstructor and (Method.Visibility >= mvPublic) and (Method.GetParameters = nil) then begin LConstructor := Method; Break; end; if LConstructor = nil then raise EInsufficientRtti.CreateRes(@SInsufficientRtti); FConstructor := LConstructor; FDefaultImplementation := T; end; end.
namespace keyboardapplet; interface // Sample applet project by Brian Long (http://blong.com) // Translated from Michael McGuffin's Keyboard2 applet // from http://profs.etsmtl.ca/mmcguffin/learn/java/05-keyboardInput uses java.applet, java.awt, java.awt.event, java.util; type KeyboardApplet = public class(Applet, KeyListener, MouseListener, MouseMotionListener) private const N = 25; // the number of colors created var spectrum: array of Color; // arrays of elements, each of type Color var listOfPositions: Vector; var s: String := ''; var skip: Integer := 0; public method init(); override; method paint(g: Graphics); override; method keyPressed(e: KeyEvent); method keyReleased(e: KeyEvent); method keyTyped(e: KeyEvent); method mouseEntered(e: MouseEvent); method mouseExited(e: MouseEvent); method mouseClicked(e: MouseEvent); method mousePressed(e: MouseEvent); method mouseReleased(e: MouseEvent); method mouseMoved(e: MouseEvent); method mouseDragged(e: MouseEvent); end; implementation method KeyboardApplet.init(); begin Background := Color.BLACK; spectrum := new Color[N]; for i: Integer := 0 to N - 1 do spectrum[i] := new Color(Color.HSBtoRGB(i / Double(N), 1, 1)); listOfPositions := new Vector; addKeyListener(self); addMouseListener(self); addMouseMotionListener(self); end; method KeyboardApplet.paint(g: Graphics); begin if s <> '' then begin for j: Integer := 0 to listOfPositions.size - 1 do begin g.Color := spectrum[j]; var p := Point(listOfPositions.elementAt(j)); g.drawString(s, p.x, p.y) end; end end; method KeyboardApplet.mouseEntered(e: MouseEvent); begin end; method KeyboardApplet.mouseExited(e: MouseEvent); begin end; method KeyboardApplet.mouseClicked(e: MouseEvent); begin s := ''; repaint; e.consume end; method KeyboardApplet.mousePressed(e: MouseEvent); begin end; method KeyboardApplet.mouseReleased(e: MouseEvent); begin end; method KeyboardApplet.mouseMoved(e: MouseEvent); begin // only process every 5th mouse event if &skip > 0 then begin dec(&skip); exit end else &skip := 5; if listOfPositions.size >= N then // delete the first element in the list listOfPositions.removeElementAt(0); // add the new position to the end of the list listOfPositions.addElement(new Point(e.X, e.Y)); repaint(); e.consume() end; method KeyboardApplet.mouseDragged(e: MouseEvent); begin end; method KeyboardApplet.keyPressed(e: KeyEvent); begin end; method KeyboardApplet.keyReleased(e: KeyEvent); begin end; method KeyboardApplet.keyTyped(e: KeyEvent); begin var c := e.KeyChar; if c <> KeyEvent.CHAR_UNDEFINED then begin s := s + c; repaint; e.consume end end; end.
unit uFrmConsultaCliente; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFrmConsultaBase, DB, DBClient, Grids, DBGrids, StdCtrls, ExtCtrls, uClienteDAOClient, Cliente; type TFrmConsultaCliente = class(TFrmConsultaBase) cdsConsultaCODIGO: TStringField; cdsConsultaNOME: TStringField; cdsConsultaTELEFONE: TStringField; private { Private declarations } DAOClient: TClienteDAOClient; protected procedure OnCreate; override; procedure OnDestroy; override; procedure OnListar; override; procedure OnConsultar; override; procedure OnSelecionar; override; public { Public declarations } Cliente: TCliente; end; var FrmConsultaCliente: TFrmConsultaCliente; implementation uses DataUtils; {$R *.dfm} { TFrmConsultaBase1 } procedure TFrmConsultaCliente.OnConsultar; begin inherited; cdsConsulta.Filtered := False; cdsConsulta.Filter := 'UPPER(CODIGO) LIKE ' + QuotedStr('%'+UpperCase(edtConsultar.Text)+'%') + ' OR UPPER(NOME) LIKE ' + QuotedStr('%'+UpperCase(edtConsultar.Text)+'%'); cdsConsulta.Filtered := True; end; procedure TFrmConsultaCliente.OnCreate; begin inherited; DAOClient := TClienteDAOClient.Create(DBXConnection); end; procedure TFrmConsultaCliente.OnDestroy; begin inherited; DAOClient.Free; end; procedure TFrmConsultaCliente.OnListar; begin inherited; CopyReaderToClientDataSet(DAOClient.List, cdsConsulta); end; procedure TFrmConsultaCliente.OnSelecionar; begin inherited; Cliente := TCliente.Create(cdsConsultaCODIGO.AsString, cdsConsultaNOME.AsString, cdsConsultaTELEFONE.AsString); Self.Close; end; end.
unit MultiIndexView; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StdCtrls, AmlView, HadithView, IslUtils, IndexStruct, CompDoc, ImgList, CheckLst, DFSSplitter, RXCtrls, CSTCBase, CSTC32, Tabs, islctrls, Htmlview, Mask, ToolEdit, XmlObjModel, sEdits, Menus, RxMenus; type TIndexData = class(TAmlData) protected function GetLibName : String; override; function CreateViewer : TAmlViewer; override; end; TSingleIndexInfo = record Data : TAmlData; Display : Boolean; MenuItem : TMenuItem; end; TSingleIndexInfoArray = array of TSingleIndexInfo; TMultiIndexViewer = class(TForm) IndexImages: TImageList; IndexTabs: TTabControl; Entries: TTreeView; IndexToolsPanel: TPanel; RxSpeedButton1: TRxSpeedButton; BooksMenu: TRxPopupMenu; FindEdit: TsEdit; procedure EntriesClick(Sender: TObject); procedure LocationsCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean); procedure IndexTabsChange(Sender: TObject); procedure EntriesDblClick(Sender: TObject); procedure FindEditChange(Sender: TObject); procedure FindEditEnter(Sender: TObject); procedure FindEditExit(Sender: TObject); procedure EntriesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); protected FDataMgr : TDataManager; FAddrMgr : IAddressManager; FStatus : IStatusDisplay; FActiveIndexName : String; FEntryIcon : Integer; FIndexes : TSingleIndexInfoArray; FMergedEntries : TStringList; FLocsList : TList; procedure ClearLocsList; procedure BooksMenuItemClick(Sender : TObject); procedure ExpandNode(const AExpandNode : TTreeNode); procedure CreateBooksMenu(const AIndexName : String); procedure MergeEntries(const AIndexName : String); procedure SetDataMgr(const ADataMgr : TDataManager); function GetEntry : String; procedure SetEntry(const AName : String); procedure SetIndexName(const ANewName : String); procedure SeeAlso(const AEntry : String); public destructor Destroy; override; property ActiveIndexName : String read FActiveIndexName write SetIndexName; property Entry : String read GetEntry write SetEntry; property DataMgr : TDataManager read FDataMgr write SetDataMgr; property AddressMgr : IAddressManager read FAddrMgr write FAddrMgr; property Status : IStatusDisplay read FStatus write FStatus; end; implementation {$R *.DFM} const SeeAlsoCaption = 'See Also'; CombineAllBooksTag = -99999; SingleBookSubmenuTag = -99998; function TIndexData.GetLibName : String; begin Result := ''; end; function TIndexData.CreateViewer : TAmlViewer; begin Result := Nil; end; {------------------------------------------------------------------------------} type PLocRec = ^TLocRec; TLocRec = record Kind : TEntryLocKind; LinkData : PString; end; destructor TMultiIndexViewer.Destroy; begin if FMergedEntries <> Nil then FMergedEntries.Free; ClearLocsList; if FLocsList <> Nil then FLocsList.Free; inherited Destroy; end; procedure TMultiIndexViewer.ClearLocsList; var I : Integer; begin if (FLocsList <> Nil) and (FLocsList.Count > 0) then begin for I := 0 to FLocsList.Count-1 do begin DisposeStr(PLocRec(FLocsList[I]).LinkData); Dispose(FLocsList[I]); end; FLocsList.Clear; end; end; procedure TMultiIndexViewer.BooksMenuItemClick(Sender : TObject); var MenuItem : TMenuItem; I, IndexIdx : Integer; begin if Length(FIndexes) <= 0 then Exit; MenuItem := Sender as TMenuItem; if MenuItem.Tag = CombineAllBooksTag then begin for I := Low(FIndexes) to High(FIndexes) do begin with FIndexes[I] do Display := True; end; end else if MenuItem.Tag >= 0 then begin with FIndexes[MenuItem.Tag] do Display := not Display; end else if MenuItem.Tag < 0 then begin IndexIdx := Abs(MenuItem.Tag)-1; for I := Low(FIndexes) to High(FIndexes) do begin with FIndexes[I] do Display := IndexIdx = I; end; end; for I := Low(FIndexes) to High(FIndexes) do begin with FIndexes[I] do MenuItem.Checked := Display; end; MergeEntries(FActiveIndexName); end; procedure TMultiIndexViewer.SetDataMgr(const ADataMgr : TDataManager); var I : Integer; Indexes : TDataList; IndexName, SelIndex : String; begin IndexTabs.Tabs.Clear; FDataMgr := ADataMgr; SelIndex := ''; for I := 0 to FDataMgr.PageIndexesDict.Count-1 do begin IndexName := FDataMgr.PageIndexesDict.Strings[I]; Indexes := FDataMgr.PageIndexes[IndexName]; if SelIndex = '' then SelIndex := IndexName; IndexTabs.Tabs.AddObject(IndexName, Indexes); end; end; function TMultiIndexViewer.GetEntry : String; begin if Entries.Selected <> Nil then Result := Entries.Selected.Text else Result := ''; end; procedure TMultiIndexViewer.SetEntry(const AName : String); var I : Integer; SelItem : TTreeNode; begin I := FMergedEntries.IndexOf(AName); if I >= 0 then begin SelItem := FMergedEntries.Objects[I] as TTreeNode; if Entries.Selected <> SelItem then Entries.Selected := SelItem; Entries.TopItem := SelItem; ExpandNode(SelItem); end else ShowMessage(Format('Index entry %s not found', [AName])); end; procedure TMultiIndexViewer.ExpandNode(const AExpandNode : TTreeNode); function PopulateLocs(const EntryLocs : TEntryLocs; const AParentNode : TTreeNode = Nil) : Integer; var SeeAlso, SubNode, ThisNode : TTreeNode; L : Integer; Kind : TEntryLocKind; Caption : String; SubLocs : TEntryLocs; LocRec : PLocRec; Addr : TAddress; begin Result := 0; if (EntryLocs = Nil) or (EntryLocs.Count <= 0) then Exit; SeeAlso := Nil; for L := 0 to EntryLocs.Count-1 do begin EntryLocs.GetEntryDetails(L, Kind, Caption, SubLocs); case Kind of ekUnknown : ; ekAddress : begin New(LocRec); FLocsList.Add(LocRec); LocRec.Kind := Kind; LocRec.LinkData := NewStr(Caption); Addr := TAddress.Create; Addr.Address := Caption; ThisNode := Entries.Items.AddChildObject(AParentNode, FAddrMgr.GetAddressCaption(Addr, True), LocRec); Addr.Free; ThisNode.ImageIndex := 2; ThisNode.SelectedIndex := 2; Inc(Result); end; ekAlias : begin if FMergedEntries.IndexOf(Caption) >= 0 then begin if SeeAlso = Nil then begin SeeAlso := Entries.Items.AddChild(AParentNode, SeeAlsoCaption); SeeAlso.ImageIndex := 3; SeeAlso.SelectedIndex := 3; end; New(LocRec); FLocsList.Add(LocRec); LocRec.Kind := Kind; LocRec.LinkData := NewStr(Caption); ThisNode := Entries.Items.AddChildObject(SeeAlso, Caption, LocRec); ThisNode.ImageIndex := 4; ThisNode.SelectedIndex := 4; end; end; ekSubentry : begin SubNode := Entries.Items.AddChild(AParentNode, Caption); SubNode.ImageIndex := 7; SubNode.SelectedIndex := 7; Inc(Result, PopulateLocs(SubLocs, SubNode)); end; end; end; end; var I : Integer; BookIndex : TPageIndex; EntryLocs : TEntryLocs; begin Assert(FMergedEntries <> Nil); if (Length(FIndexes) <= 0) or (AExpandNode = Nil) then Exit; if AExpandNode.HasChildren then Exit; if FLocsList = Nil then FLocsList := TList.Create; Entries.Items.BeginUpdate; EntryLocs := TEntryLocs.Create; try for I := 0 to High(FIndexes) do begin BookIndex := FIndexes[I].Data.Index[FActiveIndexName]; if BookIndex <> Nil then EntryLocs.Merge(BookIndex.GetEntryLocs(AExpandNode.Text)); end; PopulateLocs(EntryLocs, AExpandNode); AExpandNode.Expand(False); finally EntryLocs.Free; Entries.Items.EndUpdate; end; end; procedure TMultiIndexViewer.SeeAlso(const AEntry : String); begin SetEntry(AEntry); end; procedure TMultiIndexViewer.CreateBooksMenu(const AIndexName : String); var MenuItem, SinglesSubMenu : TMenuItem; Books : TDataList; I : Integer; begin if FDataMgr.PageIndexesDict.Find(AIndexName, I) then FActiveIndexName := FDataMgr.PageIndexesDict[I] else begin ShowMessage(Format('Index "%s" not found.', [AIndexName])); Exit; end; FStatus.StatusBegin('Initializing...', True); IndexTabs.TabIndex := IndexTabs.Tabs.IndexOf(FActiveIndexName); ClearMenu(BooksMenu); Books := FDataMgr.PageIndexes[FActiveIndexName]; if Books.Count <= 0 then Exit; MenuItem := TMenuItem.Create(Self); MenuItem.Caption := 'All'; MenuItem.Tag := CombineAllBooksTag; MenuItem.OnClick := BooksMenuItemClick; BooksMenu.Items.Add(MenuItem); SinglesSubMenu := TMenuItem.Create(Self); SinglesSubMenu.Caption := 'Only'; SinglesSubMenu.Tag := SingleBookSubmenuTag; BooksMenu.Items.Add(SinglesSubMenu); BooksMenu.Items.Add(NewLine); if (Books <> Nil) and (Books.Count >= 1) then begin SetLength(FIndexes, Books.Count); for I := 0 to Books.Count-1 do begin FIndexes[I].Data := Books.Data[I]; FIndexes[I].Display := True; if Books.Count > 1 then begin MenuItem := TMenuItem.Create(Self); FIndexes[I].MenuItem := MenuItem; MenuItem.Tag := I; MenuItem.Caption := FIndexes[I].Data.Name; MenuItem.Checked := FIndexes[I].Display; MenuItem.OnClick := BooksMenuItemClick; BooksMenu.Items.Add(MenuItem); MenuItem := TMenuItem.Create(Self); MenuItem.Tag := -I-1; MenuItem.Caption := FIndexes[I].Data.Name; MenuItem.OnClick := BooksMenuItemClick; SinglesSubMenu.Add(MenuItem); end; end; end; FStatus.StatusEnd; end; procedure TMultiIndexViewer.MergeEntries(const AIndexName : String); var B, I : Integer; BookIndex : TPageIndex; BookIdxEntries : TObjDict; //BookIdxEntriesData : TStringList; NewNode : TTreeNode; begin Assert(FDataMgr <> Nil); FActiveIndexName := AIndexName; FindEdit.Text := ''; FStatus.StatusBegin('Populating index entries...', True); Entries.Items.BeginUpdate; Entries.Items.Clear; Entries.Items.Add(Nil, 'Populating entries...'); Entries.Items.EndUpdate; Application.ProcessMessages; ClearLocsList; if FMergedEntries = Nil then begin FMergedEntries := TStringList.Create; FMergedEntries.Sorted := True; FMergedEntries.Duplicates := dupIgnore; end else FMergedEntries.Clear; if Length(FIndexes) > 0 then begin for B := 0 to High(FIndexes) do begin if FIndexes[B].Display then begin BookIndex := FIndexes[B].Data.Index[FActiveIndexName]; if BookIndex <> Nil then begin BookIdxEntries := BookIndex.Entries; //BookIdxEntriesData := BookIndex.EntriesData; for I := 0 to BookIdxEntries.Count-1 do begin // for now the entriesData only has counts FMergedEntries.Add(BookIdxEntries[I]); end; end; end; end; end; Entries.Items.BeginUpdate; Entries.Items.Clear; if FMergedEntries.Count > 0 then begin for I := 0 to FMergedEntries.Count-1 do begin NewNode := Entries.Items.Add(Nil, FMergedEntries[I]); FMergedEntries.Objects[I] := NewNode; end; end; Entries.Items.EndUpdate; FStatus.StatusEnd; end; procedure TMultiIndexViewer.SetIndexName(const ANewName : String); var ChangeTo : String; begin if (ANewName = '') and (FDataMgr.PageIndexesDict.Count > 0) then begin if FDataMgr.PageIndexesDict.IndexOf('Subjects') >= 0 then ChangeTo := 'Subjects' else ChangeTo := FDataMgr.PageIndexesDict[0]; end else ChangeTo := ANewName; if CompareText(ChangeTo, FActiveIndexName) <> 0 then begin CreateBooksMenu(ChangeTo); MergeEntries(ChangeTo); end; end; procedure TMultiIndexViewer.EntriesClick(Sender: TObject); begin if (Entries.Selected <> Nil) and (Entries.Selected.Data = Nil) then FindEdit.Text := ''; end; procedure TMultiIndexViewer.LocationsCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean); var IsSeeAlso : Boolean; begin IsSeeAlso := (Node.Data <> Nil) and (PLocRec(Node.Data).Kind = ekAlias); if (Node.Text = SeeAlsoCaption) or IsSeeAlso then Sender.Canvas.Font.Style := Sender.Canvas.Font.Style + [fsBold]; end; procedure TMultiIndexViewer.IndexTabsChange(Sender: TObject); var NewIndexName : String; begin NewIndexName := IndexTabs.Tabs[IndexTabs.TabIndex]; if NewIndexName <> FActiveIndexName then ActiveIndexName := NewIndexName; end; procedure TMultiIndexViewer.EntriesDblClick(Sender: TObject); var SelItem : TTreeNode; LocRec : PLocRec; LinkData : String; begin Assert(FAddrMgr <> Nil); SelItem := Entries.Selected; if Entries.Selected <> Nil then begin if SelItem.Data = Nil then ExpandNode(SelItem) else begin LocRec := PLocRec(SelItem.Data); LinkData := LocRec.LinkData^; if LocRec.Kind = ekAlias then SeeAlso(LinkData) else FAddrMgr.SetAddress(LinkData) end; end; end; procedure TMultiIndexViewer.FindEditChange(Sender: TObject); var X : Integer; FindLen : Integer; FindString : String; begin FStatus.StatusBegin('Searching', True); FindString := FindEdit.Text; FindLen := Length(FindString); if FindLen > 0 then begin for X := 0 to FMergedEntries.Count-1 do begin if CompareText(Copy(FMergedEntries[X], 1, FindLen), FindString) = 0 then begin Entries.Selected := FMergedEntries.Objects[X] as TTreeNode; Entries.TopItem := Entries.Selected; FStatus.StatusEnd; Exit; end; end; end; FStatus.StatusEnd; end; procedure TMultiIndexViewer.FindEditEnter(Sender: TObject); begin Entries.HideSelection := False; end; procedure TMultiIndexViewer.FindEditExit(Sender: TObject); begin Entries.HideSelection := True; end; procedure TMultiIndexViewer.EntriesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_RETURN) and (Entries.Selected <> Nil) then begin if Entries.Selected.Count > 0 then Entries.Selected.Expanded := not Entries.Selected.Expanded else EntriesDblClick(Sender); end; end; end.
unit uFrmExport; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, dximctrl, cxGrid; type TFrmExport = class(TFrmParentAll) btnSave: TButton; Label1: TLabel; cbxLanguage: TdxImageComboBox; SD: TSaveDialog; procedure btnSaveClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btCloseClick(Sender: TObject); private { Private declarations } MyGrid : TcxGrid; sSource : String; public { Public declarations } function Start(Grid: TcxGrid; Source: String):Boolean; end; implementation uses uDMGlobal, uMsgBox, uMsgConstant, cxExportGrid4Link; {$R *.DFM} function TFrmExport.Start(Grid: TcxGrid; Source: String):Boolean; begin MyGrid := Grid; sSource := Source; ShowModal; end; procedure TFrmExport.btnSaveClick(Sender: TObject); var sFilter, sExt : String; begin inherited; if cbxLanguage.ItemIndex = -1 then begin MsgBox(MSG_CRT_NO_VALID_SELECTION, vbInformation + vbOKOnly); cbxLanguage.SetFocus; Exit; end; Case cbxLanguage.ItemIndex of 0 : begin sFilter := 'Microsoft Excel 4.0 Worksheet (*.xls)|*.xls'; sExt := 'xls'; end; 1 : begin sFilter := 'HTML File (*.htm; *.html)|*.htm'; sExt := 'htm'; end; 2 : begin sFilter := 'XML File (*.xml)|*.xml'; sExt := 'xml'; end; 3 : begin sFilter := 'Text document (*.txt)|*.txt'; sExt := 'txt'; end; end; with SD do begin DefaultExt := sExt; Filter := sFilter; FileName := sSource+' in '+FormatDateTime('dd-mm-yy', Date)+'.'+sExt; if Execute then begin Case cbxLanguage.ItemIndex of 0 : ExportGrid4ToExcel(FileName, MyGrid, True, True, False); 1 : ExportGrid4ToHTML(FileName, MyGrid, True, True); 2 : ExportGrid4ToXML(FileName, MyGrid, True, True); 3 : ExportGrid4ToText(FileName, MyGrid, True, True, '','',''); end; Close; end; end; end; procedure TFrmExport.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TFrmExport.btCloseClick(Sender: TObject); begin inherited; Close; end; end.
unit uLockedFileNotifications; interface uses System.Types, System.Classes, System.SyncObjs, System.SysUtils, uMemory; type TLockedFile = class(TObject) public DateOfUnLock: TDateTime; FileName: string; end; TLockFiles = class(TObject) private FFiles: TList; FSync: TCriticalSection; public constructor Create; class function Instance : TLockFiles; destructor Destroy; override; function AddLockedFile(FileName: string; LifeTimeMs: Integer): TLockedFile; function RemoveLockedFile(FileName: string): Boolean; function IsFileLocked(FileName: string): Boolean; end; implementation var LockedFiles: TLockFiles = nil; { TLockFiles } function TLockFiles.AddLockedFile(FileName: string; LifeTimeMs: Integer): TLockedFile; var I: Integer; FFile: TLockedFile; begin FileName := AnsiLowerCase(FileName); FSync.Enter; try for I := FFiles.Count - 1 downto 0 do begin FFile := TLockedFile(FFiles[I]); if FFile.FileName = FileName then begin FFile.DateOfUnLock := Now + LifeTimeMs / (1000 * 60 * 60 * 24); Result := FFile; Exit; end; end; Result := TLockedFile.Create; Result.FileName := FileName; Result.DateOfUnLock := Now + LifeTimeMs / (1000 * 60 * 60 * 24); FFiles.Add(Result); finally FSync.Leave; end; end; constructor TLockFiles.Create; begin FFiles := TList.Create; FSync := TCriticalSection.Create; end; destructor TLockFiles.Destroy; begin FreeList(FFiles); F(FSync); inherited; end; class function TLockFiles.Instance: TLockFiles; begin if LockedFiles = nil then LockedFiles := TLockFiles.Create; Result := LockedFiles; end; function TLockFiles.IsFileLocked(FileName: string): Boolean; var I: Integer; FFile: TLockedFile; ANow: TDateTime; begin Result := False; ANow := Now; FileName := AnsiLowerCase(FileName); FSync.Enter; try for I := FFiles.Count - 1 downto 0 do begin FFile := TLockedFile(FFiles[I]); if FFile.DateOfUnLock < ANow then begin FFiles.Remove(FFile); F(FFile); Continue; end; if AnsiLowerCase(FFile.FileName) = FileName then begin Result := True; Break; end; end; finally FSync.Leave; end; end; function TLockFiles.RemoveLockedFile(FileName: string): Boolean; var I: Integer; FFile: TLockedFile; begin Result := False; FileName := AnsiLowerCase(FileName); FSync.Enter; try for I := FFiles.Count - 1 downto 0 do begin FFile := TLockedFile(FFiles[I]); if AnsiLowerCase(FFile.FileName) = FileName then begin FFiles.Remove(FFile); F(FFile); Result := True; Break; end; end; finally FSync.Leave; end; end; initialization finalization F(LockedFiles); end.
Program PlayGame; { Purpose Implement Tic-Tac-Toe on the Computer Author Bruce F. Webster Last UpDate 12 Dec 1987 -- 100 mst } Uses Crt, TicTac, Moves, GameIO; Procedure StartGame(Var TheGame:Game); { Purpose Set up a new Game Pre None Post G,Cflag,Cmove have been initialized no moves have been made The TicTacToe Grid has been drawn on the screen } Var Ans : Char; Begin ClrScr; ReadChar(Ans,'Who Moves First: H)uman or C)omputer? ',['H','C']); If Ans = 'C' Then CFlag := 0 Else CFlag := 1; ReadChar(Ans,'Do You Wish to be X or O? ',['X','O']); If Ans = 'X' Then CMove := O Else CMove := X; If CFlag <> 0 Then NewGame(TheGame,Opposite(CMove)) Else NewGame(TheGame,CMove); DrawGrid; DisplayGame(TheGame); End; { Procedure Initialize } Procedure GetMove(TheGame:Game;Var L:Location); { Purpose Select the next move for the game Pre G has been Initialized 0 or more moves have been made, The Game is not yet over Post L contains a value from 1..9 GetLoc(G,L) is Blank } Var I : Integer; Begin If (MovesMade(TheGame) mod 2) = CFlag Then GenerateMove(TheGame,L) Else Begin Repeat ReadInt(I,'Enter Move ',1,9); If GetLoc(TheGAme,I) <> Blank Then Write(^G) Until GetLoc(TheGame,I) = Blank; L := I; End; End; { Procedure GetMove } Procedure ShowResults(Var TheGame : Game); { Purpose Show Results of TicTacToe Game Pre G Has been initialized, 5 or more moves have been made, The game is not yet over. Post The results of the game are displayed on the screen } Var M : Move; Begin M := Winner(TheGame); GoToXY(1,1); ClrEol; Case M of Blank : Write('The Game was a Draw! '); X : Write('X is the Winner! '); O : Write('O is the Winner! '); End; Write(' -- Press Any Key to Continue ( Q to Quit ) '); End; { Procedure ShowResults } { Procedure CleanUp ? } Var TheGame : Game; Next : Location; Ch : Char; Begin { Main body of Program } Repeat StartGame(TheGame); Repeat GetMove(TheGame,Next); DoMove(TheGame,Next); DisplayGame(TheGame); Until GameOver(TheGame); ShowResults(TheGame); Ch := ReadKey; Until (Ch in ['Q','q']); ClrScr; End. { Program TicTacToe } 
unit UnitWep; interface uses windows, uWEPUtils; var Pass: string; xDelimitador: String; function ObtainWirelessPasswords(Delimitador: string): string; implementation function ConvertDataToAscii(Buffer: pointer; Length: Word): string; var Iterator: integer; AsciiBuffer: string; begin if Buffer = nil then exit; if Length = 0 then exit; SetString(Result,pchar(Buffer),Length); end; function GetDataCallBack(DataType: Cardinal; Data: Pointer; DataSize: Cardinal): Boolean; begin case DataType of 1: //GUID della WiFi Network Interface begin Pass := Pass + PChar(Data) + xDelimitador; end; 2: //nome dell'HOT-SPOT begin Pass := Pass + PChar(Data) + xDelimitador; end; 3: //Wep Key dell'HOT-SPOT begin Pass := Pass + ConvertDataToAscii(Data, DataSize) + xDelimitador + #13#10; end; end; end; function ObtainWirelessPasswords(Delimitador: string): string; begin xDelimitador := Delimitador; Pass := ''; GetWZCSVCData(@GetDataCallBack); Result := Pass; end; end.
// // EE_TRANSFER -- File copy procedures and functions // unit ee_transfer; {$MODE OBJFPC} interface uses Crt, Classes, DateUtils, // For SecondsBetween Process, SysUtils, USupportLibrary, UTextFile, ee_global; function RobocopyMove(const sPathSource: string; sFolderDest: string): integer; implementation function RobocopyMove(const sPathSource: string; sFolderDest: string): integer; // // Use Robocopy.exe to move a file. // Create folders that are needed is done by Robocopy. // // sPathSource D:\folder\folder\file.ext // sFolderDest D:\foldernew // // Returns the error level of robocopy.exe execution // An error level > 15 is an error. // var p: TProcess; c: string; sFilename: string; sFolderSource: string; r: integer; extension: string; // Branch: Issue4 begin if FileExists(sPathSource) = true then begin sFilename := ExtractFileName(sPathSource); sFolderSource := FixFolderRemove(ExtractFilePath(sPathSource)); sFolderDest := FixFolderRemove(sFolderDest); extension := ExtractFileExt(sPathSource); WriteLn('ROBOCOPYMOVE()'); WriteLn(' Moving file: ', sFilename); WriteLn(' from folder: ', sFolderSource); WriteLn(' to folder: ', sFolderDest); WriteLn(' Extension: ', extension); // Issue4 //c := 'robocopy.exe ' + EncloseDoubleQuote(sFolderSource) + ' ' + EncloseDoubleQuote(sFolderDest) + ' ' + EncloseDoubleQuote(sFilename) + ' /mov'; // Branch: Issue4 c := 'robocopy.exe ' + EncloseDoubleQuote(sFolderSource) + ' ' + EncloseDoubleQuote(sFolderDest) + ' ' + EncloseDoubleQuote('*' + extension) + ' /mov /r:10 /w:10'; WriteLn; WriteLn('Running command:'); WriteLn(c); WriteLn; // Setup the process to be executed. p := TProcess.Create(nil); p.Executable := 'cmd.exe'; p.Parameters.Add('/c ' + c); //p.Options := [poWaitOnExit]; p.Options := [poWaitOnExit, poNoConsole]; // Branch: test //p.Options := [poWaitOnExit, poUsePipes]; // Run the sub process. p.Execute; // Get the return code from the process. r := p.ExitStatus; WriteLn('Returned error level code: ', r); end else begin WriteLn('RobocopyMove(): Warning, can''t find file ', sPathSource); end; RobocopyMove := r; end; // of function RobocopyMove. end. // of unit ee_transfer
{------------------------------------------------------------------------------- Copyright 2012 Ethea S.r.l. 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 Kitto.Ext.Base; {$I Kitto.Defines.inc} interface uses SysUtils, Classes, Generics.Collections, ExtPascal, ExtPascalUtils, Ext, ExtForm, ExtUx, EF.Intf, EF.Tree, EF.ObserverIntf, EF.Classes, Kitto.Ext.Controller, Kitto.Metadata.Views; const DEFAULT_WINDOW_WIDTH = 600; DEFAULT_WINDOW_HEIGHT = 400; DEFAULT_WINDOW_TOOL_WIDTH = 400; DEFAULT_WINDOW_TOOL_HEIGHT = 200; type TKExtContainerHelper = class helper for TExtContainer public procedure Apply(const AProc: TProc<TExtObject>); end; /// <summary> /// Base Ext window with subject, observer and controller capabilities. /// </summary> TKExtWindowControllerBase = class(TExtWindow, IInterface, IEFInterface, IEFSubject, IEFObserver, IKExtController) strict private FSubjObserverImpl: TEFSubjectAndObserver; FView: TKView; FConfig: TEFNode; FContainer: TExtContainer; function GetView: TKView; function GetConfig: TEFNode; strict protected procedure SetView(const AValue: TKView); procedure DoDisplay; virtual; function GetContainer: TExtContainer; procedure SetContainer(const AValue: TExtContainer); procedure InitDefaults; override; function GetControllerToRemove: TObject; virtual; function CreateSubController: IKExtController; virtual; procedure InitSubController(const AController: IKExtController); virtual; public destructor Destroy; override; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function AsObject: TObject; procedure AttachObserver(const AObserver: IEFObserver); virtual; procedure DetachObserver(const AObserver: IEFObserver); virtual; procedure NotifyObservers(const AContext: string = ''); virtual; procedure UpdateObserver(const ASubject: IEFSubject; const AContext: string = ''); virtual; class function SupportsContainer: Boolean; function IsSynchronous: Boolean; property Config: TEFNode read GetConfig; /// <summary> /// Reads the Width, Height, FullScreen properties under <APath> from ATree /// and sets its size accordingly. Returns True if auto-sizing is in effect /// (no explicit width and height) and False otherwise. /// </summry> function SetSizeFromTree(const ATree: TEFTree; const APath: string): Boolean; property View: TKView read GetView write SetView; procedure Display; function AsExtComponent: TExtComponent; published procedure PanelClosed; procedure WindowClosed; end; /// <summary> /// A modal window used to host panels. /// </summary> TKExtModalWindow = class(TKExtWindowControllerBase) protected procedure InitDefaults; override; public /// <summary> /// Call this after adding the panel so that the window can hook its /// beforeclose event and close itself. /// <summary> procedure HookPanel(const APanel: TExtComponent); published procedure PanelClosed; end; /// <summary> /// Base ext viewport with subject, observer and controller capabilities. /// </summary> TKExtViewportControllerBase = class(TExtViewport, IInterface, IEFInterface, IEFSubject, IEFObserver, IKExtController) private FSubjObserverImpl: TEFSubjectAndObserver; FView: TKView; FConfig: TEFNode; FContainer: TExtContainer; function GetView: TKView; function GetConfig: TEFNode; procedure CreateSubController; protected procedure SetView(const AValue: TKView); procedure DoDisplay; virtual; function GetContainer: TExtContainer; procedure SetContainer(const AValue: TExtContainer); procedure InitDefaults; override; public destructor Destroy; override; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function AsObject: TObject; procedure AttachObserver(const AObserver: IEFObserver); virtual; procedure DetachObserver(const AObserver: IEFObserver); virtual; procedure NotifyObservers(const AContext: string = ''); virtual; procedure UpdateObserver(const ASubject: IEFSubject; const AContext: string = ''); virtual; class function SupportsContainer: Boolean; property Config: TEFNode read GetConfig; function IsSynchronous: Boolean; property View: TKView read GetView write SetView; procedure Display; function AsExtComponent: TExtComponent; end; /// <summary> /// Implemented by controllers that host panels and are able to close them /// on request, such as the TabPanel controller. /// </summary> IKExtPanelHost = interface(IEFInterface) ['{F1DCE0C8-1CD9-4F97-9315-7FB2AC9CAADC}'] procedure ClosePanel(const APanel: TExtComponent); end; TKExtButton = class; TKExtToolbar = class(TExtToolbar) strict private FButtonScale: string; private function GetVisibleButtonCount: Integer; public property ButtonScale: string read FButtonScale write FButtonScale; function FindButton(const AUniqueId: string): TKExtButton; property VisibleButtonCount: Integer read GetVisibleButtonCount; end; /// <summary> /// Base Ext panel with subject and observer capabilities. /// </summary> TKExtPanelBase = class(TExtPanel, IInterface, IEFInterface, IEFSubject, IEFObserver, IKExtActivable) strict private FSubjObserverImpl: TEFSubjectAndObserver; FConfig: TEFNode; strict protected function GetConfig: TEFNode; // Closes the hosting window or tab. procedure CloseHostContainer; virtual; function FindHostWindow: TExtWindow; procedure InitDefaults; override; procedure LoadHtml(const AFileName: string; const APostProcessor: TFunc<string, string> = nil); public destructor Destroy; override; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function AsObject: TObject; procedure AttachObserver(const AObserver: IEFObserver); virtual; procedure DetachObserver(const AObserver: IEFObserver); virtual; procedure NotifyObservers(const AContext: string = ''); virtual; procedure UpdateObserver(const ASubject: IEFSubject; const AContext: string = ''); virtual; procedure Activate; virtual; property Config: TEFNode read GetConfig; end; TKExtButton = class(TExtButton, IEFSubject, IEFObserver) strict private FSubjObserverImpl: TEFSubjectAndObserver; FUniqueId: string; strict protected function FindOwnerToolbar: TKExtToolbar; function GetOwnerToolbar: TKExtToolbar; protected procedure InitDefaults; override; public destructor Destroy; override; function AsObject: TObject; procedure AttachObserver(const AObserver: IEFObserver); virtual; procedure DetachObserver(const AObserver: IEFObserver); virtual; procedure NotifyObservers(const AContext: string = ''); virtual; procedure UpdateObserver(const ASubject: IEFSubject; const AContext: string = ''); virtual; // Unique Id of the button in its toolbar (if any). property UniqueId: string read FUniqueId write FUniqueId; procedure SetIconAndScale(const AIconName: string; const AScale: string = ''); end; TKExtActionButton = class(TKExtButton) strict private FView: TKView; FActionObserver: IEFObserver; FOnInitController: TProc<IKExtController>; strict protected procedure InitController(const AController: IKExtController); virtual; procedure SetView(const AValue: TKView); virtual; procedure PerformBeforeExecute; class procedure ExecuteHandler(const AButton: TKExtButton); public property View: TKView read FView write SetView; property ActionObserver: IEFObserver read FActionObserver write FActionObserver; property OnInitController: TProc<IKExtController> read FOnInitController write FOnInitController; published procedure ExecuteButtonAction; virtual; end; TKExtActionButtonClass = class of TKExtActionButton; TKExtPanelControllerBase = class(TKExtPanelBase, IKExtController) strict private FView: TKView; FContainer: TExtContainer; FTopToolbar: TKExtToolbar; procedure CreateTopToolbar; procedure EnsureAllSupportFiles; strict protected procedure PerformDelayedClick(const AButton: TExtButton); procedure ExecuteNamedAction(const AActionName: string); virtual; function GetConfirmCall(const AMessage: string; const AMethod: TExtProcedure): string; function GetDefaultSplit: Boolean; virtual; function GetView: TKView; procedure SetView(const AValue: TKView); procedure DoDisplay; virtual; function GetContainer: TExtContainer; procedure SetContainer(const AValue: TExtContainer); property Container: TExtContainer read GetContainer write SetContainer; procedure InitSubController(const AController: IKExtController); virtual; property TopToolbar: TKExtToolbar read FTopToolbar; procedure BeforeCreateTopToolbar; virtual; procedure AfterCreateTopToolbar; virtual; /// <summary> /// Adds built-in buttons to the top toolbar. /// </summary> procedure AddTopToolbarButtons; virtual; /// <summary>Adds ToolView buttons to the top toolbar. Called after /// AddTopToolbarButtons so that these stay at the end.</summary> procedure AddTopToolbarToolViewButtons; virtual; /// <summary>Adds to the specified toolbar buttons for any ToolViews /// configured in the specified node.</summary> /// <param name="AConfigNode">ToolViews node. If nil or childrenless, no /// buttons are added.</param> /// <param name="AToolbar">Destination toolbar.</param> procedure AddToolViewButtons(const AConfigNode: TEFNode; const AToolbar: TKExtToolbar); /// <summary> /// Adds an action button representing the specified tool view to /// the specified toolbar. Override this method to create action buttons of /// classes inherited from the base TKExtActionButton. /// </summary> function AddActionButton(const AUniqueId: string; const AView: TKView; const AToolbar: TKExtToolbar): TKExtActionButton; virtual; public destructor Destroy; override; function IsSynchronous: Boolean; property View: TKView read GetView write SetView; procedure Display; function AsExtComponent: TExtComponent; end; /// <summary> /// Base class for controllers that don't have a specific visual /// representation, yet can be used to render views, such as custom action /// controllers. /// </summary> TKExtControllerBase = class(TExtComponent, IInterface, IEFInterface, IKExtController, IEFSubject, IEFObserver) private FSubjObserverImpl: TEFSubjectAndObserver; FView: TKView; FContainer: TExtContainer; FConfig: TEFNode; protected function GetView: TKView; procedure SetView(const AValue: TKView); procedure DoDisplay; virtual; function GetContainer: TExtContainer; procedure SetContainer(const AValue: TExtContainer); procedure InitDefaults; override; property Container: TExtContainer read GetContainer write SetContainer; function GetConfig: TEFNode; public destructor Destroy; override; function AsObject: TObject; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function IsSynchronous: Boolean; virtual; property View: TKView read GetView write SetView; procedure Display; function AsExtComponent: TExtComponent; property Config: TEFNode read GetConfig; procedure Apply(const AProc: TProc<IKExtController>); virtual; procedure AttachObserver(const AObserver: IEFObserver); virtual; procedure DetachObserver(const AObserver: IEFObserver); virtual; procedure NotifyObservers(const AContext: string = ''); virtual; procedure UpdateObserver(const ASubject: IEFSubject; const AContext: string = ''); virtual; end; /// <summary> /// Base class for tool controllers. /// </summary> TKExtToolController = class(TKExtControllerBase) strict protected function GetDisplayLabel: string; procedure ExecuteTool; virtual; // Called after ExecuteTool. The default implementation calls AfterExecuteTool. // Override this with an empty method if you plan to call AfterExecuteTool at // a different time. procedure DoAfterExecuteTool; virtual; procedure AfterExecuteTool; virtual; procedure DoDisplay; override; public class function GetDefaultImageName: string; virtual; class function SupportsContainer: Boolean; function IsSynchronous: Boolean; override; property DisplayLabel: string read GetDisplayLabel; end; TExtToolControllerClass = class of TKExtToolController; /// <summary> /// Base class for tool controllers that display a (modal) window with /// a set of ok/cancel buttons. /// </summary> TKExtWindowToolController = class(TKExtWindowControllerBase) strict private FConfirmButton: TKExtButton; FCancelButton: TKExtButton; FSubController: IKExtController; procedure CreateButtons; strict protected procedure SetWindowSize; virtual; procedure InitDefaults; override; procedure DoDisplay; override; function GetConfirmJSCode: string; virtual; function GetConfirmJsonData: string; virtual; procedure AfterExecuteTool; virtual; procedure InitSubController(const AController: IKExtController); override; property SubController: IKExtController read FSubController; public procedure UpdateObserver(const ASubject: IEFSubject; const AContext: string = ''); override; published procedure Confirm; virtual; procedure Cancel; virtual; end; TKExtFormComboBox = class(TExtFormComboBox, IInterface, IEFInterface, IEFSubject) private FSubjObserverImpl: TEFSubjectAndObserver; protected procedure InitDefaults; override; function GetEncodedValue: TExtFunction; public destructor Destroy; override; function AsObject: TObject; inline; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; procedure AttachObserver(const AObserver: IEFObserver); virtual; procedure DetachObserver(const AObserver: IEFObserver); virtual; procedure NotifyObservers(const AContext: string = ''); virtual; end; TKExtFormTextField = class(TExtFormTextField, IInterface, IEFInterface, IEFSubject) private FSubjObserverImpl: TEFSubjectAndObserver; protected procedure InitDefaults; override; public destructor Destroy; override; function AsObject: TObject; inline; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; procedure AttachObserver(const AObserver: IEFObserver); virtual; procedure DetachObserver(const AObserver: IEFObserver); virtual; procedure NotifyObservers(const AContext: string = ''); virtual; end; TKExtFormDateField = class(TExtFormDateField, IInterface, IEFInterface, IEFSubject) private FSubjObserverImpl: TEFSubjectAndObserver; protected procedure InitDefaults; override; public destructor Destroy; override; function AsObject: TObject; inline; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; procedure AttachObserver(const AObserver: IEFObserver); virtual; procedure DetachObserver(const AObserver: IEFObserver); virtual; procedure NotifyObservers(const AContext: string = ''); virtual; end; TKExtFormCheckBoxField = class(TExtFormCheckBox, IInterface, IEFInterface, IEFSubject) private FSubjObserverImpl: TEFSubjectAndObserver; protected procedure InitDefaults; override; public destructor Destroy; override; function AsObject: TObject; inline; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; procedure AttachObserver(const AObserver: IEFObserver); virtual; procedure DetachObserver(const AObserver: IEFObserver); virtual; procedure NotifyObservers(const AContext: string = ''); virtual; end; TKExtFormNumberField = class(TExtFormNumberField, IInterface, IEFInterface, IEFSubject) private FSubjObserverImpl: TEFSubjectAndObserver; protected procedure InitDefaults; override; public destructor Destroy; override; function AsObject: TObject; inline; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; procedure AttachObserver(const AObserver: IEFObserver); virtual; procedure DetachObserver(const AObserver: IEFObserver); virtual; procedure NotifyObservers(const AContext: string = ''); virtual; end; TKExtStatusBar = class(TExtUxStatusBar) public procedure SetErrorStatus(const AText: string); procedure ClearStatus; virtual; end; TKExtLinkButton = class(TKExtButton) private FHRef: string; procedure SetHRef(const AValue: string); public class function JSClassName: string; override; property HRef: string read FHRef write SetHRef; end; function OptionAsLabelAlign(const AAlign: string): TExtContainerLabelAlign; function OptionAsGridColumnAlign(const AAlign: string): TExtGridColumnAlign; implementation uses StrUtils, EF.StrUtils, EF.Types, EF.Localization, EF.Macros, Kitto.AccessControl, Kitto.Ext.Utils, Kitto.Ext.Session; function OptionAsGridColumnAlign(const AAlign: string): TExtGridColumnAlign; begin //alLeft, alRight, alCenter if SameText(AAlign, 'Left') then Result := caLeft else if SameText(AAlign, 'Right') then Result := caRight else if SameText(AAlign, 'Center') then Result := caCenter else raise EEFError.CreateFmt(_('Invalid value %s. Valid values: "Left", "Right", "Center".'), [AAlign]); end; function OptionAsLabelAlign(const AAlign: string): TExtContainerLabelAlign; begin if SameText(AAlign, 'Left') then Result := laLeft else if SameText(AAlign, 'Top') then Result := laTop else if SameText(AAlign, 'Right') then Result := laRight else raise EEFError.CreateFmt(_('Invalid value %s. Valid values: "Left", "Top", "Right".'), [AAlign]); end; { TKExtWindowControllerBase } function TKExtWindowControllerBase.AsExtComponent: TExtComponent; begin Result := Self; end; function TKExtWindowControllerBase.AsObject: TObject; begin Result := Self; end; procedure TKExtWindowControllerBase.AttachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.AttachObserver(AObserver); end; function TKExtWindowControllerBase.CreateSubController: IKExtController; var LSubView: TKView; LNode: TEFNode; begin Assert(Assigned(View)); Result := nil; LNode := View.FindNode('Controller/SubView'); if Assigned(LNode) then begin LSubView := Session.Config.Views.FindViewByNode(LNode); if Assigned(LSubView) then begin Result := TKExtControllerFactory.Instance.CreateController(Self, LSubView, Self); InitSubController(Result); Result.Display; end; end; end; destructor TKExtWindowControllerBase.Destroy; begin FreeAndNil(FSubjObserverImpl); FreeAndNil(FConfig); Session.RemoveController(Self); inherited; end; procedure TKExtWindowControllerBase.DetachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.DetachObserver(AObserver); end; procedure TKExtWindowControllerBase.Display; begin DoDisplay; On('render', DoLayout); end; procedure TKExtWindowControllerBase.DoDisplay; var LStyle: TEFNode; begin Session.EnsureSupportFiles(TKExtControllerRegistry.Instance.FindClassId(Self.ClassType)); Session.EnsureViewSupportFiles(View); LStyle := Config.FindNode('Style'); if Assigned(LStyle) and (LStyle.AsString <> '') then Style := LStyle.AsExpandedString; CreateSubController; Show; end; function TKExtWindowControllerBase.GetConfig: TEFNode; begin if not Assigned(FConfig) then FConfig := TEFNode.Create; Result := FConfig; end; function TKExtWindowControllerBase.GetContainer: TExtContainer; begin Result := FContainer; end; function TKExtWindowControllerBase.GetView: TKView; begin Result := FView; end; procedure TKExtWindowControllerBase.InitDefaults; begin inherited; FSubjObserverImpl := TEFSubjectAndObserver.Create; Layout := lyFit; if Session.IsMobileBrowser then Maximized := True; Border := False; Plain := True; On('close', Ajax(WindowClosed, ['Window', JSName])); end; procedure TKExtWindowControllerBase.InitSubController(const AController: IKExtController); begin end; function TKExtWindowControllerBase.IsSynchronous: Boolean; begin Result := False; end; procedure TKExtWindowControllerBase.NotifyObservers(const AContext: string); begin FSubjObserverImpl.NotifyObserversOnBehalfOf(Self, AContext); end; procedure TKExtWindowControllerBase.PanelClosed; begin NotifyObservers('Closed'); end; procedure TKExtWindowControllerBase.SetContainer(const AValue: TExtContainer); begin FContainer := AValue; end; function TKExtWindowControllerBase.SetSizeFromTree(const ATree: TEFTree; const APath: string): Boolean; var LWidth: Integer; LHeight: Integer; LFullScreen: Boolean; begin LWidth := ATree.GetInteger(APath + 'Width'); LHeight := ATree.GetInteger(APath + 'Height'); LFullScreen := ATree.GetBoolean(APath + 'FullScreen', Session.IsMobileBrowser); Result := False; if LFullScreen then begin Maximized := True; Border := not Maximized; end else if (LWidth > 0) and (LHeight > 0) then begin Width := LWidth; Height := LHeight; end else Result := True; end; procedure TKExtWindowControllerBase.SetView(const AValue: TKView); begin FView := AValue; end; class function TKExtWindowControllerBase.SupportsContainer: Boolean; begin Result := False; end; procedure TKExtWindowControllerBase.UpdateObserver(const ASubject: IEFSubject; const AContext: string); begin end; procedure TKExtWindowControllerBase.WindowClosed; begin Session.RemoveController(GetControllerToRemove); end; function TKExtWindowControllerBase.GetControllerToRemove: TObject; begin Result := Self; end; function TKExtWindowControllerBase._AddRef: Integer; begin Result := -1; end; function TKExtWindowControllerBase._Release: Integer; begin Result := -1; end; { TKExtPanelBase } procedure TKExtPanelBase.Activate; begin end; function TKExtPanelBase.AsObject: TObject; begin Result := Self; end; procedure TKExtPanelBase.AttachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.AttachObserver(AObserver); end; destructor TKExtPanelBase.Destroy; begin FreeAndNil(FSubjObserverImpl); FreeAndNil(FConfig); inherited; end; procedure TKExtPanelBase.DetachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.DetachObserver(AObserver); end; function TKExtPanelBase.GetConfig: TEFNode; begin if not Assigned(FConfig) then FConfig := TEFNode.Create; Result := FConfig; end; procedure TKExtPanelBase.NotifyObservers(const AContext: string); begin FSubjObserverImpl.NotifyObserversOnBehalfOf(Self, AContext); end; procedure TKExtPanelBase.UpdateObserver(const ASubject: IEFSubject; const AContext: string); begin end; function TKExtPanelBase._AddRef: Integer; begin Result := -1; end; function TKExtPanelBase._Release: Integer; begin Result := -1; end; function TKExtPanelBase.FindHostWindow: TExtWindow; begin Result := Config.GetObject('Sys/HostWindow') as TExtWindow; end; procedure TKExtPanelBase.InitDefaults; begin inherited; FSubjObserverImpl := TEFSubjectAndObserver.Create; Region := rgCenter; end; procedure TKExtPanelBase.LoadHtml(const AFileName: string; const APostProcessor: TFunc<string, string>); var LFullFileName: string; LHtml: string; begin LFullFileName := Session.Config.FindResourcePathName(AFileName); if LFullFileName <> '' then begin LHtml := TextFileToString(LFullFileName, TEncoding.UTF8); TEFMacroExpansionEngine.Instance.Expand(LHtml); end else LHtml := ''; if Assigned(APostProcessor) then LHtml := APostProcessor(LHtml); Html := LHtml; end; procedure TKExtPanelBase.CloseHostContainer; var LHostWindow: TExtWindow; LIntf: IKExtPanelHost; begin { TODO : Perhaps we could unify the behaviour here by implementing IKExtPanelHost in a custom window class. } LHostWindow := FindHostWindow; if Assigned(LHostWindow) then LHostWindow.Close else if Supports(Owner, IKExtPanelHost, LIntf) then LIntf.ClosePanel(Self); end; { TKExtViewportControllerBase } function TKExtViewportControllerBase.AsExtComponent: TExtComponent; begin Result := Self; end; function TKExtViewportControllerBase.AsObject: TObject; begin Result := Self; end; procedure TKExtViewportControllerBase.AttachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.AttachObserver(AObserver); end; destructor TKExtViewportControllerBase.Destroy; begin FreeAndNil(FSubjObserverImpl); FreeAndNil(FConfig); Session.RemoveController(Self); inherited; end; procedure TKExtViewportControllerBase.DetachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.DetachObserver(AObserver); end; procedure TKExtViewportControllerBase.Display; begin DoDisplay; On('render', DoLayout); end; procedure TKExtViewportControllerBase.DoDisplay; begin Session.EnsureSupportFiles(TKExtControllerRegistry.Instance.FindClassId(Self.ClassType)); Session.EnsureViewSupportFiles(View); CreateSubController; Show; end; function TKExtViewportControllerBase.GetConfig: TEFNode; begin if not Assigned(FConfig) then FConfig := TEFNode.Create; Result := FConfig; end; function TKExtViewportControllerBase.GetContainer: TExtContainer; begin Result := FContainer; end; function TKExtViewportControllerBase.GetView: TKView; begin Result := FView; end; procedure TKExtViewportControllerBase.InitDefaults; begin inherited; FSubjObserverImpl := TEFSubjectAndObserver.Create; Layout := lyBorder; end; function TKExtViewportControllerBase.IsSynchronous: Boolean; begin Result := False; end; procedure TKExtViewportControllerBase.NotifyObservers(const AContext: string); begin FSubjObserverImpl.NotifyObserversOnBehalfOf(Self, AContext); end; procedure TKExtViewportControllerBase.SetContainer(const AValue: TExtContainer); begin FContainer := AValue; end; procedure TKExtViewportControllerBase.SetView(const AValue: TKView); begin FView := AValue; end; class function TKExtViewportControllerBase.SupportsContainer: Boolean; begin Result := False; end; procedure TKExtViewportControllerBase.UpdateObserver(const ASubject: IEFSubject; const AContext: string); begin end; function TKExtViewportControllerBase._AddRef: Integer; begin Result := -1; end; function TKExtViewportControllerBase._Release: Integer; begin Result := -1; end; procedure TKExtViewportControllerBase.CreateSubController; var LSubView: TKView; LController: IKExtController; LNode: TEFNode; begin Assert(Assigned(View)); LNode := View.FindNode('Controller/SubView'); if Assigned(LNode) then begin LSubView := Session.Config.Views.FindViewByNode(LNode); if Assigned(LSubView) then begin LController := TKExtControllerFactory.Instance.CreateController(Self, LSubView, Self); LController.Display; end; end; end; { TKExtModalWindow } procedure TKExtModalWindow.HookPanel(const APanel: TExtComponent); begin Assert(Assigned(APanel)); APanel.On('close', Ajax(PanelClosed, ['Panel', APanel.JSName])); APanel.On('beforedestroy', Ajax(PanelClosed, ['Panel', APanel.JSName])); end; procedure TKExtModalWindow.InitDefaults; begin inherited; Width := Session.Config.Config.GetInteger('Defaults/Window/Width', DEFAULT_WINDOW_WIDTH); Height := Session.Config.Config.GetInteger('Defaults/Window/Height', DEFAULT_WINDOW_HEIGHT); Closable := False; Modal := True; end; procedure TKExtModalWindow.PanelClosed; begin Close; end; { TKExtFormComboBox } function TKExtFormComboBox.AsObject: TObject; begin Result := Self; end; procedure TKExtFormComboBox.AttachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.AttachObserver(AObserver); end; destructor TKExtFormComboBox.Destroy; begin FreeAndNil(FSubjObserverImpl); inherited; end; procedure TKExtFormComboBox.DetachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.DetachObserver(AObserver); end; function TKExtFormComboBox.GetEncodedValue: TExtFunction; begin ExtSession.ResponseItems.ExecuteJSCode(Self, Format('encodeURI(%s.getValue())', [JSName])); Result := Self; end; procedure TKExtFormComboBox.InitDefaults; begin inherited; FSubjObserverImpl := TEFSubjectAndObserver.Create; end; procedure TKExtFormComboBox.NotifyObservers(const AContext: string); begin FSubjObserverImpl.NotifyObserversOnBehalfOf(Self, AContext); end; function TKExtFormComboBox._AddRef: Integer; begin Result := -1; end; function TKExtFormComboBox._Release: Integer; begin Result := -1; end; { TKExtPanelControllerBase } destructor TKExtPanelControllerBase.Destroy; begin Session.RemoveController(Self); inherited; end; procedure TKExtPanelControllerBase.Display; begin if Container <> nil then begin if Config.GetBoolean('AllowClose', True) then begin Closable := True; On('close', Container.Ajax('PanelClosed', ['Panel', JSName])); end else Closable := False; end; DoDisplay; end; procedure TKExtPanelControllerBase.EnsureAllSupportFiles; var LClassType: TClass; begin LClassType := ClassType; Session.EnsureSupportFiles(TKExtControllerRegistry.Instance.FindClassId(LClassType)); while LClassType.ClassParent <> nil do begin LClassType := LClassType.ClassParent; Session.EnsureSupportFiles(TKExtControllerRegistry.Instance.FindClassId(LClassType)); end; Session.EnsureViewSupportFiles(View); end; procedure TKExtPanelControllerBase.DoDisplay; var LWidth: Integer; LSplit: TEFNode; LCollapsible: TEFNode; LCollapsed: TEFNode; LBorder: TEFNode; LHeight: Integer; LHeader: TEFNode; LWidthStr: string; LHeightStr: string; LView: TKView; LBodyStyle: string; LStyle: TEFNode; begin EnsureAllSupportFiles; if Title = '' then begin LView := View; if Assigned(LView) then Title := _(Config.GetExpandedString('Title', LView.DisplayLabel)); end; LWidthStr := Config.GetString('Width'); if TryStrToInt(LWidthStr, LWidth) then begin if LWidth > 0 then begin Width := LWidth; MinWidth := LWidth; end else if LWidth = -1 then AutoWidth := True; end else if LWidthStr <> '' then WidthString := LWidthStr; LHeightStr := Config.GetString('Height'); if TryStrToInt(LHeightStr, LHeight) then begin if LHeight > 0 then Height := LHeight else if LHeight = -1 then AutoHeight := True; end else if LHeightStr <> '' then HeightString := LHeightStr; LSplit := Config.FindNode('Split'); if Assigned(LSplit) then Split := LSplit.AsBoolean else Split := GetDefaultSplit; LBorder := Config.FindNode('Border'); if Assigned(LBorder) then Border := LBorder.AsBoolean else Border := False; LCollapsible := Config.FindNode('Collapsible'); if Assigned(LCollapsible) then Collapsible := LCollapsible.AsBoolean else Collapsible := False; LCollapsed := Config.FindNode('Collapsed'); if Assigned(LCollapsed) then Collapsed := LCollapsed.AsBoolean else Collapsed := False; LHeader := Config.FindNode('Header'); if Assigned(LHeader) then Header := LHeader.AsBoolean else Header := False; CreateTopToolbar; LBodyStyle := Config.GetExpandedString('BodyStyle'); if LBodyStyle <> '' then BodyStyle := LBodyStyle; LStyle := Config.FindNode('Style'); if Assigned(LStyle) and (LStyle.AsString <> '') then Style := LStyle.AsExpandedString; end; procedure TKExtPanelControllerBase.ExecuteNamedAction(const AActionName: string); var LToolButton: TKExtButton; begin LToolButton := FTopToolbar.FindButton(AActionName); if Assigned(LToolButton) then PerformDelayedClick(LToolButton); end; procedure TKExtPanelControllerBase.AddTopToolbarButtons; begin end; function TKExtPanelControllerBase.AddActionButton(const AUniqueId: string; const AView: TKView; const AToolbar: TKExtToolbar): TKExtActionButton; var LConfirmationMessage: string; LConfirmationJS: string; begin Assert(Assigned(AView)); Assert(Assigned(AToolbar)); Result := TKExtActionButton.CreateAndAddTo(AToolbar.Items); Result.Hidden := not AView.GetBoolean('IsVisible', True); Result.UniqueId := AUniqueId; Result.View := AView; Result.ActionObserver := Self; // A Tool may or may not have a confirmation message. LConfirmationMessage := AView.GetExpandedString('Controller/ConfirmationMessage'); // Cleanup Linebreaks with <br> tag ReplaceAllCaseSensitive(LConfirmationMessage, sLineBreak, '<br>'); LConfirmationJS := GetConfirmCall(LConfirmationMessage, Result.ExecuteButtonAction); if LConfirmationMessage <> '' then Result.On('click', JSFunction(LConfirmationJS)) else Result.On('click', Ajax(Result.ExecuteButtonAction, [])); end; procedure TKExtPanelControllerBase.AddToolViewButtons( const AConfigNode: TEFNode; const AToolbar: TKExtToolbar); var I: Integer; LView: TKView; LNode: TEFNode; begin Assert(Assigned(AToolbar)); if Assigned(AConfigNode) and (AConfigNode.ChildCount > 0) then begin TExtToolbarSeparator.CreateAndAddTo(AToolbar.Items); for I := 0 to AConfigNode.ChildCount - 1 do begin LNode := AConfigNode.Children[I]; LView := Session.Config.Views.ViewByNode(LNode); if LView.IsAccessGranted(ACM_VIEW) then AddActionButton(LNode.Name, LView, AToolbar); end; end; end; function TKExtPanelControllerBase.GetConfirmCall(const AMessage: string; const AMethod: TExtProcedure): string; begin Result := Format('confirmCall("%s", "%s", ajaxSimple, {methodURL: "%s"});', [_('Confirm operation'), AMessage, MethodURI(AMethod)]); end; procedure TKExtPanelControllerBase.AfterCreateTopToolbar; begin end; function TKExtPanelControllerBase.AsExtComponent: TExtComponent; begin Result := Self; end; procedure TKExtPanelControllerBase.BeforeCreateTopToolbar; begin end; procedure TKExtPanelControllerBase.AddTopToolbarToolViewButtons; begin AddToolViewButtons(Config.FindNode('ToolViews'), TopToolbar); end; procedure TKExtPanelControllerBase.CreateTopToolbar; begin BeforeCreateTopToolbar; FTopToolbar := TKExtToolbar.Create(Self); try FTopToolbar.ButtonScale := Config.GetString('ToolButtonScale', IfThen(Session.IsMobileBrowser, 'large', 'small')); FTopToolbar.AutoScroll := Session.IsMobileBrowser; AddTopToolbarButtons; AddTopToolbarToolViewButtons; except FreeAndNil(FTopToolbar); raise; end; if FTopToolbar.Items.Count = 0 then FreeAndNil(FTopToolbar) else begin if FTopToolbar.VisibleButtonCount = 0 then FTopToolbar.Hidden := True; Tbar := FTopToolbar; end; AfterCreateTopToolbar; end; function TKExtPanelControllerBase.GetDefaultSplit: Boolean; begin Result := False; end; function TKExtPanelControllerBase.GetContainer: TExtContainer; begin Result := FContainer; end; function TKExtPanelControllerBase.GetView: TKView; begin Result := FView; end; procedure TKExtPanelControllerBase.InitSubController(const AController: IKExtController); var LSysConfigNode: TEFNode; begin Assert(Assigned(AController)); LSysConfigNode := Config.FindNode('Sys'); if Assigned(LSysConfigNode) then AController.Config.GetNode('Sys', True).Assign(LSysConfigNode); end; function TKExtPanelControllerBase.IsSynchronous: Boolean; begin Result := False; end; procedure TKExtPanelControllerBase.PerformDelayedClick(const AButton: TExtButton); begin if Assigned(AButton) then AButton.On('render', JSFunction(AButton.PerformClick)); end; procedure TKExtPanelControllerBase.SetContainer(const AValue: TExtContainer); begin FContainer := AValue; end; procedure TKExtPanelControllerBase.SetView(const AValue: TKView); begin FView := AValue; end; { TKExtFormTextField } function TKExtFormTextField.AsObject: TObject; begin Result := Self; end; procedure TKExtFormTextField.AttachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.AttachObserver(AObserver); end; destructor TKExtFormTextField.Destroy; begin FreeAndNil(FSubjObserverImpl); inherited; end; procedure TKExtFormTextField.DetachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.DetachObserver(AObserver); end; procedure TKExtFormTextField.InitDefaults; begin inherited; FSubjObserverImpl := TEFSubjectAndObserver.Create; end; procedure TKExtFormTextField.NotifyObservers(const AContext: string); begin FSubjObserverImpl.NotifyObserversOnBehalfOf(Self, AContext); end; function TKExtFormTextField._AddRef: Integer; begin Result := -1; end; function TKExtFormTextField._Release: Integer; begin Result := -1; end; { TKExtFormDateField } function TKExtFormDateField.AsObject: TObject; begin Result := Self; end; procedure TKExtFormDateField.AttachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.AttachObserver(AObserver); end; destructor TKExtFormDateField.Destroy; begin FreeAndNil(FSubjObserverImpl); inherited; end; procedure TKExtFormDateField.DetachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.DetachObserver(AObserver); end; procedure TKExtFormDateField.InitDefaults; begin inherited; FSubjObserverImpl := TEFSubjectAndObserver.Create; end; procedure TKExtFormDateField.NotifyObservers(const AContext: string); begin FSubjObserverImpl.NotifyObserversOnBehalfOf(Self, AContext); end; function TKExtFormDateField._AddRef: Integer; begin Result := -1; end; function TKExtFormDateField._Release: Integer; begin Result := -1; end; { TKExtFormCheckBoxField } function TKExtFormCheckBoxField.AsObject: TObject; begin Result := Self; end; procedure TKExtFormCheckBoxField.AttachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.AttachObserver(AObserver); end; destructor TKExtFormCheckBoxField.Destroy; begin FreeAndNil(FSubjObserverImpl); inherited; end; procedure TKExtFormCheckBoxField.DetachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.DetachObserver(AObserver); end; procedure TKExtFormCheckBoxField.InitDefaults; begin inherited; FSubjObserverImpl := TEFSubjectAndObserver.Create; end; procedure TKExtFormCheckBoxField.NotifyObservers(const AContext: string); begin FSubjObserverImpl.NotifyObserversOnBehalfOf(Self, AContext); end; function TKExtFormCheckBoxField._AddRef: Integer; begin Result := -1; end; function TKExtFormCheckBoxField._Release: Integer; begin Result := -1; end; { TKExtStatusBar } procedure TKExtStatusBar.ClearStatus; begin inherited ClearStatus; end; procedure TKExtStatusBar.SetErrorStatus(const AText: string); begin SetStatus(JSObject(Format('text: "%s", iconCls:"x-status-error",clear:true', [AText]))); end; { TKExtControllerBase } procedure TKExtControllerBase.Apply(const AProc: TProc<IKExtController>); begin Assert(Assigned(AProc)); AProc(Self); end; function TKExtControllerBase.AsExtComponent: TExtComponent; begin Result := Self; end; function TKExtControllerBase.AsObject: TObject; begin Result := Self; end; procedure TKExtControllerBase.AttachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.AttachObserver(AObserver); end; destructor TKExtControllerBase.Destroy; begin FreeAndNil(FSubjObserverImpl); FreeAndNil(FConfig); Session.RemoveController(Self); inherited; end; procedure TKExtControllerBase.DetachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.DetachObserver(AObserver); end; procedure TKExtControllerBase.Display; begin DoDisplay; end; procedure TKExtControllerBase.DoDisplay; begin Session.EnsureSupportFiles(TKExtControllerRegistry.Instance.FindClassId(Self.ClassType)); Session.EnsureViewSupportFiles(View); end; function TKExtControllerBase.GetConfig: TEFNode; begin if not Assigned(FConfig) then FConfig := TEFNode.Create; Result := FConfig; end; function TKExtControllerBase.GetContainer: TExtContainer; begin Result := FContainer; end; function TKExtControllerBase.GetView: TKView; begin Result := FView; end; procedure TKExtControllerBase.InitDefaults; begin inherited; FSubjObserverImpl := TEFSubjectAndObserver.Create; end; function TKExtControllerBase.IsSynchronous: Boolean; begin Result := False; end; procedure TKExtControllerBase.NotifyObservers(const AContext: string); begin FSubjObserverImpl.NotifyObserversOnBehalfOf(Self, AContext); end; procedure TKExtControllerBase.SetContainer(const AValue: TExtContainer); begin FContainer := AValue; end; procedure TKExtControllerBase.SetView(const AValue: TKView); begin FView := AValue; end; procedure TKExtControllerBase.UpdateObserver(const ASubject: IEFSubject; const AContext: string); begin end; function TKExtControllerBase._AddRef: Integer; begin Result := 0; end; function TKExtControllerBase._Release: Integer; begin Result := 0; end; { TKExtActionController } procedure TKExtToolController.ExecuteTool; begin end; function TKExtToolController.GetDisplayLabel: string; begin if Assigned(View) then Result := Config.GetExpandedString('Title', View.DisplayLabel) else Result := ''; end; function TKExtToolController.IsSynchronous: Boolean; begin Result := True; end; class function TKExtToolController.SupportsContainer: Boolean; begin Result := False; end; class function TKExtToolController.GetDefaultImageName: string; begin Result := 'tool_exec'; end; procedure TKExtToolController.AfterExecuteTool; begin end; procedure TKExtToolController.DoAfterExecuteTool; begin AfterExecuteTool; end; procedure TKExtToolController.DoDisplay; begin inherited; ExecuteTool; DoAfterExecuteTool; //NotifyObservers('Closed'); end; { TKExtContainerHelper } procedure TKExtContainerHelper.Apply(const AProc: TProc<TExtObject>); var I: Integer; begin Assert(Assigned(AProc)); for I := 0 to Items.Count - 1 do begin AProc(Items[I]); if Items[I] is TExtContainer then TExtContainer(Items[I]).Apply(AProc); end; end; { TKExtActionButton } procedure TKExtActionButton.ExecuteButtonAction; var LController: IKExtController; begin Assert(Assigned(FView)); Assert(Assigned(FActionObserver)); if View.IsPersistent then Session.DisplayView(View, FActionObserver) else begin LController := TKExtControllerFactory.Instance.CreateController( Session.ObjectCatalog, FView, nil, nil, FActionObserver); InitController(LController); LController.Display; end; end; class procedure TKExtActionButton.ExecuteHandler(const AButton: TKExtButton); var LResponseItemBranch: TExtResponseItems; begin if AButton is TKExtActionButton then begin LResponseItemBranch := AButton.Session.BranchResponseItems; try TKExtActionButton(AButton).ExecuteButtonAction; finally AButton.Session.UnbranchResponseItems(LResponseItemBranch, False); // throw away end; end; end; procedure TKExtActionButton.InitController(const AController: IKExtController); begin if Assigned(FOnInitController) then FOnInitController(AController); end; procedure TKExtActionButton.PerformBeforeExecute; var LUniqueId: string; LBeforeExecuteNode, LChildNode: TEFNode; I: Integer; LButton: TKExtButton; begin LBeforeExecuteNode := View.FindNode('BeforeExecute'); if Assigned(LBeforeExecuteNode) then begin for I := 0 to LBeforeExecuteNode.ChildCount-1 do begin LChildNode := LBeforeExecuteNode.Children[I]; if SameText(LChildNode.Name, 'ToolView') then begin LUniqueId := LChildNode.AsString; if LUniqueId <> '' then begin LButton := GetOwnerToolbar.FindButton(LUniqueId); if Assigned(LButton) then ExecuteHandler(LButton as TKExtActionButton); end; end; end; end; end; procedure TKExtActionButton.SetView(const AValue: TKView); var LTooltip, LIconName: string; begin Assert(Assigned(AValue)); FView := AValue; Text := _(FView.DisplayLabel); LIconName := FView.GetString('ImageName'); if LIconName = '' then LIconName := CallViewControllerStringMethod(FView, 'GetDefaultImageName', ''); if LIconName = '' then LIconName := FView.ImageName; SetIconAndScale(LIconName); LTooltip := FView.GetExpandedString('Hint'); if LTooltip <> '' then Tooltip := LTooltip; end; { TKExtWindowToolController } procedure TKExtWindowToolController.AfterExecuteTool; begin NotifyObservers('ToolConfirmed'); Close; end; procedure TKExtWindowToolController.Cancel; begin NotifyObservers('ToolCanceled'); Close; end; procedure TKExtWindowToolController.Confirm; begin AfterExecuteTool; end; procedure TKExtWindowToolController.CreateButtons; begin FConfirmButton := TKExtButton.CreateAndAddTo(Buttons); FConfirmButton.SetIconAndScale('accept', Config.GetString('ButtonScale', 'medium')); FConfirmButton.FormBind := True; FConfirmButton.Text := Config.GetString('ConfirmButton/Caption', _('Confirm')); FConfirmButton.Tooltip := Config.GetString('ConfirmButton/Tooltip', _('Confirm action and close window')); FConfirmButton.Handler := JSFunction(GetConfirmJSCode()); FCancelButton := TKExtButton.CreateAndAddTo(Buttons); FCancelButton.SetIconAndScale('cancel', Config.GetString('ButtonScale', 'medium')); FCancelButton.Text := _('Cancel'); FCancelButton.Tooltip := _('Cancel changes'); FCancelButton.Handler := Ajax(Cancel); end; procedure TKExtWindowToolController.DoDisplay; begin inherited; Title := View.DisplayLabel; SetWindowSize; if not Config.GetBoolean('HideButtons') then CreateButtons; end; function TKExtWindowToolController.GetConfirmJSCode: string; begin Result := GetPOSTAjaxCode(Confirm, [], GetConfirmJsonData); end; function TKExtWindowToolController.GetConfirmJsonData: string; begin Result := '{}'; end; procedure TKExtWindowToolController.InitDefaults; begin inherited; Modal := True; Closable := False; Layout := lyFit; end; procedure TKExtWindowToolController.InitSubController(const AController: IKExtController); var LSubject: IEFSubject; begin inherited; FSubController := AController; if Supports(FSubController.AsObject, IEFSubject, LSubject) then LSubject.AttachObserver(Self); end; procedure TKExtWindowToolController.SetWindowSize; begin Width := Config.GetInteger('WindowWidth', DEFAULT_WINDOW_TOOL_WIDTH); Height := Config.GetInteger('WindowHeight', DEFAULT_WINDOW_TOOL_HEIGHT); Resizable := False; end; procedure TKExtWindowToolController.UpdateObserver(const ASubject: IEFSubject; const AContext: string); begin inherited; if (ASubject.AsObject = FSubController.AsObject) then begin if AContext = 'Confirmed' then Confirm else if AContext = 'Canceled' then Cancel; end; end; { TKExtButton } function TKExtButton.AsObject: TObject; begin Result := Self; end; procedure TKExtButton.AttachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.AttachObserver(AObserver); end; destructor TKExtButton.Destroy; begin FreeAndNil(FSubjObserverImpl); inherited; end; procedure TKExtButton.DetachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.DetachObserver(AObserver); end; function TKExtButton.FindOwnerToolbar: TKExtToolbar; begin if (Owner is TExtObjectList) and (TExtObjectList(Owner).Owner is TKExtToolbar) then Result := TKExtToolbar(TExtObjectList(Owner).Owner) else Result := nil; end; function TKExtButton.GetOwnerToolbar: TKExtToolbar; begin Result := FindOwnerToolbar; if Result = nil then raise Exception.Create('Owner Toolbar not found'); end; procedure TKExtButton.InitDefaults; begin inherited; FSubjObserverImpl := TEFSubjectAndObserver.Create; end; procedure TKExtButton.NotifyObservers(const AContext: string); begin FSubjObserverImpl.NotifyObserversOnBehalfOf(Self, AContext); end; procedure TKExtButton.SetIconAndScale(const AIconName: string; const AScale: string); var LIconURL: string; LToolbar: TKExtToolbar; begin LToolbar := FindOwnerToolbar; if AScale <> '' then Scale := AScale else if Assigned(LToolbar) and (LToolbar.ButtonScale <> '') then Scale := LToolbar.ButtonScale else Scale := 'small'; if AIconName <> '' then begin LIconURL := Session.Config.FindImageURL(SmartConcat(AIconName, '_', Scale)); if LIconURL = '' then LIconURL := Session.Config.FindImageURL(AIconName); Icon := LIconURL; end; end; procedure TKExtButton.UpdateObserver(const ASubject: IEFSubject; const AContext: string); begin end; { TKExtToolbar } function TKExtToolbar.FindButton(const AUniqueId: string): TKExtButton; var I: Integer; begin Result := nil; for I := 0 to Items.Count - 1 do begin if (Items[I] is TKExtButton) and SameText(TKExtButton(Items[I]).UniqueId, AUniqueId) then begin Result := TKExtButton(Items[I]); Break; end; end; end; function TKExtToolbar.GetVisibleButtonCount: Integer; var I: Integer; begin Result := 0; for I := 0 to Items.Count - 1 do begin if Items[I] is TKExtButton and not (TKExtButton(Items[I]).Hidden) then Inc(Result); end; end; { TExtLinkButton } class function TKExtLinkButton.JSClassName: string; begin //Result := 'Ext.ux.LinkButton'; Result := 'Ext.LinkButton'; end; { TKExtFormNumberField } function TKExtFormNumberField.AsObject: TObject; begin Result := Self; end; procedure TKExtFormNumberField.AttachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.AttachObserver(AObserver); end; destructor TKExtFormNumberField.Destroy; begin FreeAndNil(FSubjObserverImpl); inherited; end; procedure TKExtFormNumberField.DetachObserver(const AObserver: IEFObserver); begin FSubjObserverImpl.DetachObserver(AObserver); end; procedure TKExtFormNumberField.InitDefaults; begin inherited; FSubjObserverImpl := TEFSubjectAndObserver.Create; end; procedure TKExtFormNumberField.NotifyObservers(const AContext: string); begin FSubjObserverImpl.NotifyObserversOnBehalfOf(Self, AContext); end; function TKExtFormNumberField._AddRef: Integer; begin Result := -1; end; function TKExtFormNumberField._Release: Integer; begin Result := -1; end; procedure TKExtLinkButton.SetHRef(const AValue: string); begin FHRef := AValue; ExtSession.ResponseItems.SetConfigItem(Self, 'href', 'setHref', [AValue]); end; end.
unit UExportImagesForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UIconEngine, USettings, Vcl.StdCtrls, Vcl.ExtCtrls, UCaptionFrame, System.Actions, Vcl.ActnList; type TExportImagesForm = class(TForm) edOptimizePng: TCheckBox; OptionsPanel: TPanel; LogFrame: TPanel; LogCaption: TCaptionFrame; LogMemoMain: TMemo; CommandsPanel: TPanel; GoButton: TButton; Actions: TActionList; ActionGo: TAction; ActionExit: TAction; CancelButton: TButton; ConfigurationCaption: TCaptionFrame; ConfigurationPanel: TPanel; edMasterIconFolder: TLabeledEdit; btnOpenMasterInExplorer: TButton; btnOpenGeneratedInExplorer: TButton; edGeneratedIconFolder: TLabeledEdit; ActionsConfig: TActionList; ActionOpenMasterInExplorer: TAction; ActionOpenGeneratedInExplorer: TAction; LogMemoOptimize: TMemo; LogMemoResize: TMemo; Log2Panel: TPanel; SplitterLogs1: TSplitter; Splitter1: TSplitter; cbGenerateIphone: TCheckBox; cbGenerateIpad: TCheckBox; cbGenerateAndroid: TCheckBox; cbOnlyRequired: TCheckBox; BackColorDialog: TColorDialog; PanelBkColor: TPanel; cbCreateNewFiles: TCheckBox; procedure ActionExitExecute(Sender: TObject); procedure ActionGoExecute(Sender: TObject); procedure edMasterIconFolderChange(Sender: TObject); procedure edGeneratedIconFolderChange(Sender: TObject); procedure ActionOpenMasterInExplorerExecute(Sender: TObject); procedure ActionOpenGeneratedInExplorerExecute(Sender: TObject); procedure PanelBkColorClick(Sender: TObject); private FIconEngine: TIconEngine; procedure OpenExplorer(const dir: string); procedure UpdateSettings; procedure LoadSettings; procedure EnableScreen(const enable: boolean); function TotalCount: integer; function CommandLineSettings: TSettings; function GetString(const p, cmd: string; out s: string): boolean; procedure SetPanelBackColor(const colr: TColor); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property IconEngine: TIconEngine read FIconEngine write FIconEngine; end; var ExportImagesForm: TExportImagesForm; implementation uses IOUtils, ShellAPI, ULogger, Threading, ActiveX, UPredefinedSizes, StrUtils; {$R *.dfm} function TExportImagesForm.CommandLineSettings: TSettings; var i: Integer; r: Boolean; p, d: string; begin Result := TSettings.Create(true); for i := 1 to ParamCount - 1 do begin p := Trim(ParamStr(i)); if (p.Length = 0) then continue; if p.Chars[0] = '+' then r := true else if p.Chars[0] = '-' then r := false else raise Exception.Create('Parameters must start with + or -'); p := p.Substring(1); if SameText(p, 'SAVESETTINGS') then begin; Result.Persist := r; continue; end; if SameText(p, 'IPHONE') then begin; Result.GenerateIPhone := r; continue; end; if SameText(p, 'IPAD') then begin; Result.GenerateIPad := r; continue; end; if SameText(p, 'ANDROID') then begin; Result.GenerateAndroid := r; continue; end; if SameText(p, 'REQUIRED') then begin; Result.OnlyGenerateRequired := r; continue; end; if SameText(p, 'OPTIMIZE') then begin; Result.OptimizePng := r; continue; end; if SameText(p, 'NEWFILES') then begin; Result.CreateNewFiles := r; continue; end; if GetString(p, 'MASTERFOLDER', d) then begin; Result.MasterFolder := d; continue; end; if GetString(p, 'GENERATEDFOLDER', d) then begin; Result.GeneratedFolder := d; continue; end; if GetString(p, 'OUTPUTFPATTERN', d) then begin; Result.OutputPattern := d; continue; end; if GetString(p, 'OUTPUTFPATTERNONDISK', d) then begin; Result.OutputPatternOnDisk := d; continue; end; if GetString(p, 'BACKCOLOR', d) then begin; Result.ImgBackColor := StrToInt(d); continue; end; if GetString(p, 'OPTIMIZER', d) then begin; Result.CmdOptimizer := d; continue; end; if GetString(p, 'RESIZER', d) then begin; Result.CmdResizer := d; continue; end; raise Exception.Create('Invalid parameter: ' + ParamStr(i)); end; end; function TExportImagesForm.GetString(const p: string; const cmd: string; out s: string): boolean; var k: string; begin s := ''; if not p.StartsWith(cmd) then exit(false); if p.Length <= cmd.Length then exit(false); k := p.Substring(cmd.Length).Trim; if (k.Length < 2) then exit(false); if k.Chars[0] <> '=' then exit(false); s := k.Substring(1).Trim; Result := true; end; constructor TExportImagesForm.Create(AOwner: TComponent); var DProj: string; begin inherited; if ParamCount < 1 then begin ShowMessage('No Project specified. Configure Tools in Rad Studio and pass $Project as parameter'); Application.Terminate; exit; end; DProj := ParamStr(ParamCount); Caption := 'Icon Spread: ' + TPath.GetFileName(DProj); IconEngine := TIconEngine.Create(DProj, CommandLineSettings, procedure(Channel: TLogChannel; s: string) begin case Channel of TLogChannel.Main: TThread.Queue(nil, procedure begin LogMemoMain.Lines.Add(s); end); TLogChannel.Resize: TThread.Queue(nil, procedure begin LogMemoResize.Lines.Add(s); end); TLogChannel.Optimize: TThread.Queue(nil, procedure begin LogMemoOptimize.Lines.Add(s); end); TLogChannel.Count: TThread.Queue(nil, procedure begin LogCaption.Caption.Caption := 'Log: Processed ' + s + ' images from ' + IntToStr(TotalCount); end); end; end); LoadSettings; end; destructor TExportImagesForm.Destroy; begin if (IconEngine <> nil) then IconEngine.SaveSettings(false); IconEngine.Free; inherited; end; procedure TExportImagesForm.SetPanelBackColor(const colr: TColor); var cl: Integer; begin PanelBkColor.Color := colr; cl := ColorToRGB(colr); if GetRValue(cl) + GetGValue(cl) + GetBValue(cl) < 127 * 3 then PanelBkColor.Font.Color := clWhite else PanelBkColor.Font.Color := clBlack; end; procedure TExportImagesForm.edGeneratedIconFolderChange(Sender: TObject); begin IconEngine.Settings.GeneratedFolder := edGeneratedIconFolder.Text; if TDirectory.Exists(IconEngine.FullGeneratedFolder) then edGeneratedIconFolder.Font.Color := clBlack else edGeneratedIconFolder.Font.Color := clRed; end; procedure TExportImagesForm.edMasterIconFolderChange(Sender: TObject); begin IconEngine.Settings.MasterFolder := edMasterIconFolder.Text; if TDirectory.Exists(IconEngine.FullMasterFolder) then edMasterIconFolder.Font.Color := clBlack else edMasterIconFolder.Font.Color := clRed; end; procedure TExportImagesForm.ActionExitExecute(Sender: TObject); begin Close; end; procedure TExportImagesForm.ActionGoExecute(Sender: TObject); begin UpdateSettings; IconEngine.SaveSettings(true); //only create the ini if the user tried to run the app. We don't want to pollute the disk with ini files. LogMemoMain.Lines.Clear; LogMemoOptimize.Lines.Clear; LogMemoResize.Lines.Clear; EnableScreen(false); TTask.Run( procedure var Ok: boolean; begin Ok := true; CoInitialize(nil); try try IconEngine.GenerateFiles(); except on ex: Exception do begin ShowMessage('ERROR: ' + ex.Message); Ok := false; end; end; finally CoUninitialize; end; TThread.Queue(nil, procedure begin if (Ok) then ShowMessage('Done!'); EnableScreen(True); end) end); end; procedure TExportImagesForm.EnableScreen(const enable: boolean); begin ActionExit.Enabled := enable; ActionGo.Enabled := enable; edMasterIconFolder.Enabled := enable; edGeneratedIconFolder.Enabled := enable; OptionsPanel.Enabled := enable; end; procedure TExportImagesForm.LoadSettings; begin edMasterIconFolder.Text := IconEngine.Settings.MasterFolder; edGeneratedIconFolder.Text := IconEngine.Settings.GeneratedFolder; edOptimizePng.Checked := IconEngine.Settings.OptimizePng; cbGenerateIphone.Checked := IconEngine.Settings.GenerateIPhone; cbGenerateIpad.Checked := IconEngine.Settings.GenerateIPad; cbGenerateAndroid.Checked := IconEngine.Settings.GenerateAndroid; cbOnlyRequired.Checked := IconEngine.Settings.OnlyGenerateRequired; cbCreateNewFiles.Checked := IconEngine.Settings.CreateNewFiles; SetPanelBackColor(TColor(IconEngine.Settings.ImgBackColor)); BackColorDialog.Color := TColor(IconEngine.Settings.ImgBackColor); end; procedure TExportImagesForm.UpdateSettings; begin IconEngine.Settings.MasterFolder := edMasterIconFolder.Text; IconEngine.Settings.GeneratedFolder := edGeneratedIconFolder.Text; IconEngine.Settings.OptimizePng := edOptimizePng.Checked; IconEngine.Settings.GenerateIPhone := cbGenerateIphone.Checked; IconEngine.Settings.GenerateIPad := cbGenerateIpad.Checked; IconEngine.Settings.GenerateAndroid := cbGenerateAndroid.Checked; IconEngine.Settings.OnlyGenerateRequired := cbOnlyRequired.Checked; IconEngine.Settings.CreateNewFiles := cbCreateNewFiles.Checked; IconEngine.Settings.ImgBackColor := integer(PanelBkColor.Color); IconEngine.SaveSettings(false); end; procedure TExportImagesForm.OpenExplorer(const dir: string); begin if not TDirectory.Exists(dir) then begin ShowMessage('Directory doesn''t exist: ' + dir); exit; end; ShellExecute(Application.Handle, 'open', PWideChar(dir), '', '', SW_SHOWNORMAL); end; procedure TExportImagesForm.PanelBkColorClick(Sender: TObject); begin BackColorDialog.Execute; SetPanelBackColor(BackColorDialog.Color); UpdateSettings; end; function TExportImagesForm.TotalCount: integer; begin Result := 0; if cbGenerateAndroid.Checked then Inc(Result, AndroidImageCount); if cbGenerateIphone.Checked then Inc(Result, iPhoneImageCount); if cbGenerateIpad.Checked then Inc(Result, iPadImageCount); end; procedure TExportImagesForm.ActionOpenGeneratedInExplorerExecute( Sender: TObject); begin UpdateSettings; OpenExplorer(IconEngine.FullGeneratedFolder); end; procedure TExportImagesForm.ActionOpenMasterInExplorerExecute(Sender: TObject); begin UpdateSettings; OpenExplorer(IconEngine.FullMasterFolder); end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Shader code editor. } // TODO: decide how to load templates from external file, // update it without package recompilation unit FShaderMemo; interface uses System.Win.Registry, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Layouts, FMX.Menus, FMX.Memo, FMX.ScrollBox, FMX.Controls.Presentation; type TVXShaderMemoForm = class(TForm) ToolBar1: TToolBar; Panel1: TPanel; ButtonOK: TButton; ImageOK: TImage; ButtonCancel: TButton; ImageCancel: TImage; CheckButton: TSpeedButton; CompilatorLog: TMemo; SBOpen: TSpeedButton; Image1: TImage; SBSave: TSpeedButton; Image2: TImage; SBHelp: TSpeedButton; Image3: TImage; GLSLMemo: TMemo; procedure FormCreate(Sender: TObject); end; function VKShaderEditorForm: TVXShaderMemoForm; procedure ReleaseGLShaderEditor; //===================================================================== implementation //===================================================================== {$R *.fmx} const cRegistryKey = 'Software\VXScene\VXSceneShaderEdit'; var vShaderEditor: TVXShaderMemoForm; function VKShaderEditorForm: TVXShaderMemoForm; begin if not Assigned(vShaderEditor) then vShaderEditor := TVXShaderMemoForm.Create(nil); Result := vShaderEditor; end; procedure ReleaseGLShaderEditor; begin if Assigned(vShaderEditor) then begin vShaderEditor.Free; vShaderEditor := nil; end; end; function ReadRegistryInteger(reg: TRegistry; const name: string; defaultValue: Integer): Integer; begin if reg.ValueExists(name) then Result := reg.ReadInteger(name) else Result := defaultValue; end; procedure TVXShaderMemoForm.FormCreate(Sender: TObject); var reg: TRegistry; No: Integer; item: TMenuItem; begin reg := TRegistry.Create; try if reg.OpenKey(cRegistryKey, True) then begin Left := ReadRegistryInteger(reg, 'Left', Left); Top := ReadRegistryInteger(reg, 'Top', Top); Width := ReadRegistryInteger(reg, 'Width', 500); Height := ReadRegistryInteger(reg, 'Height', 640); end; finally reg.Free; end; { TODO : Replace with FMX.Memo routines } (* No := GLSLMemo.Styles.Add(TColors.Red, TColors.White, []); GLSLMemo.AddWord(No, GLSLDirectives); No := GLSLMemo.Styles.Add(TColors.Purple, TColors.White, [TFontStyle.fsBold]); GLSLMemo.AddWord(No, GLSLQualifiers); No := GLSLMemo.Styles.Add(TColors.Blue, TColors.White, [TFontStyle.fsBold]); GLSLMemo.AddWord(No, GLSLTypes); No := GLSLMemo.Styles.Add(TColors.Gray, TColors.White, [TFontStyle.fsBold]); GLSLMemo.AddWord(No, GLSLBuildIn); No := GLSLMemo.Styles.Add(TColors.Green, TColors.White, [TFontStyle.fsItalic]); GLSLMemo.AddWord(No, GLSLFunctions); No := GLSLMemo.Styles.Add(TColors.Yellow, TColors.Silver, [TFontStyle.fsItalic]); GLSLMemo.AddWord(No, GLSLFunctions); FLightLineStyle := GLSLMemo.Styles.Add(TColors.Black, TColors.LtGray, []); GLSLMemo.MultiCommentLeft := '/*'; GLSLMemo.MultiCommentRight := '*/'; GLSLMemo.LineComment := '//'; GLSLMemo.CaseSensitive := True; GLSLMemo.DelErase := True; item := NewItem('Attribute block', 0, False, True, OnTemplateClick, 0, ''); item.Tag := 5; GLSL120.Add(item); item := NewItem('Basic vertex program', 0, False, True, OnTemplateClick, 0, ''); item.Tag := 0; GLSL120.Add(item); item := NewItem('Basic vertex program with TBN pass', 0, False, True, OnTemplateClick, 0, ''); item.Tag := 1; GLSL120.Add(item); item := NewItem('Basic fragment program, Phong lighting', 0, False, True, OnTemplateClick, 0, ''); item.Tag := 2; GLSL120.Add(item); item := NewItem('Fragment program, normal mapping', 0, False, True, OnTemplateClick, 0, ''); item.Tag := 3; GLSL120.Add(item); item := NewItem('Attribute block', 0, False, True, OnTemplateClick, 0, ''); item.Tag := 6; GLSL330.Add(item); item := NewItem('Geometry program, edge detection', 0, False, True, OnTemplateClick, 0, ''); item.Tag := 4; GLSL330.Add(item); *) end; end.
unit Objekt.SepaBSPosList; interface uses SysUtils, Classes, Objekt.SepaBSPos, Contnrs; type TSepaBSPosList = class private function GetCount: Integer; function getSepaBSPos(Index: Integer): TSepaBSPos; protected fList: TObjectList; public constructor Create; destructor Destroy; override; property Count: Integer read GetCount; property Item[Index: Integer]: TSepaBSPos read getSepaBSPos; function Add: TSepaBSPos; end; implementation { TSepaBSPosList } constructor TSepaBSPosList.Create; begin fList := TObjectList.Create; end; destructor TSepaBSPosList.Destroy; begin FreeAndNil(fList); inherited; end; function TSepaBSPosList.GetCount: Integer; begin Result := fList.Count; end; function TSepaBSPosList.getSepaBSPos(Index: Integer): TSepaBSPos; begin Result := nil; if Index > fList.Count -1 then exit; Result := TSepaBSPos(fList[Index]); end; function TSepaBSPosList.Add: TSepaBSPos; begin Result := TSepaBSPos.Create; fList.Add(Result); end; end.
unit ThWebControl; interface uses Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils, Types, ThStructuredHtml, ThStyledCtrl, ThAttributeList, ThStyleList, ThTag, ThJavaScript, ThInterfaces, ThMessages; type TThOnTag = procedure(inSender: TObject; inTag: TThTag) of object; // TThWebControl = class(TThWebControlBase, IThHtmlSource, IThJavaScriptable) private FOnTag: TThOnTag; FJavaScript: TThJavaScriptEvents; FDesignOnly: Boolean; protected function GetJavaScript: TThJavaScriptEvents; //:$ <br>Generate HTML for this control. //:: Default implementation calls GetTagHtml to generate HTML. //:: Subclasses may override. function GetHtmlAsString: string; virtual; //:$ <br>Generate HTML for this control. function GetHtml: string; //:$ <br>Use a tag to generate HTML. //:: Uses DoTag and Tag methods to generate HTML. //:: The default implementation of GetHtml simply returns the value of //:: this method. //:: Subclasses may override. function GetTagHtml: string; //:$ <br>Assemble HTML tag for the <td> cell containing this control. //:: Fills tag object with HTML representative of the <td> cell //:: containing the control. The standard HTML generator uses a //:: table-layout and places every control inside of a <td> cell. //:: Customize the <td> tag by overriding this method, customize the cell's //:: contents by overriding the Tag method. procedure CellTag(inTag: TThTag); virtual; //:$ <br>Invokes the OnTag event. //:: Invokes the OnTag event, if assigned. GetTagHtml calls this //:: method immediately after calling the Tag method. procedure DoTag(inTag: TThTag); procedure SetJavaScript(const Value: TThJavaScriptEvents); //:$ <br>Copy style information to an HTML tag. //:: Fills tag object with style information. Specifically, the //:: StyleClass is copied into the <class> attribute, and the Style //:: object fills the <style> attribute. procedure StylizeTag(inTag: TThTag); //:$ <br>Assemble HTML tag. //:: Fills tag object with HTML representative of the control. //:: Calls StylizeTag and ListJsAttributes. Subclasses override //:: this method to provide custom HTML. //:: This HTML from this method is used as the content for the <td> cell //:: generated by the CellTag method. Customize the <td> tag by overriding //:: CellTag; customize the cell's contents by overriding this method. procedure Tag(inTag: TThTag); virtual; public constructor Create(inOwner: TComponent); override; destructor Destroy; override; //:$ <br>Add style margins. //:: Add box margins from the control's Style property to the input //:: margin rect. Each element of the rect represents the width //:: of the margin on the corresponding side. procedure AdjustMargins(var ioRect: TRect); virtual; //:$ <br>Copy JavaScript information to an attribute list. //:: Fills list object with JavaScript information. Specifically, the //:: object in the JavaScript property is asked to compose event data into //:: HTML attributes and add them to the list. procedure ListJsAttributes(inAttrs: TThAttributeList); virtual; //:$ <br>Modify an HTML document. //:: Outputs HTML into a document. Default implementation //:: simply adds the value of the Html property to the body of the //:: document. Subclasses override this method in provide custom processing //:: when an object is published. procedure Publish(inDoc: TThStructuredHtml); virtual; public //:$ <br>HTML generated to represent this control. //:: HTML representing this control is generated and returned as a //:: string. property Html: string read GetHtml; //:$ <br>Event fired after a tag is prepared for this control. property OnTag: TThOnTag read FOnTag write FOnTag; published property DesignOnly: Boolean read FDesignOnly write FDesignOnly; //:$ <br>Collection of JavaScript events. property JavaScript: TThJavaScriptEvents read GetJavaScript write SetJavaScript; end; // TThWebGraphicControl = class(TThStyledGraphicControl, IThHtmlSource, IThJavaScriptable) private FOnTag: TThOnTag; FJavaScript: TThJavaScriptEvents; FDesignOnly: Boolean; protected //:$ <br>Generate HTML for this control. //:: Default implementation calls GetTagHtml to generate HTML. //:: Subclasses may override. function GetHtmlAsString: string; virtual; //:$ <br>Generate HTML for this control. function GetHtml: string; function GetJavaScript: TThJavaScriptEvents; //:$ <br>Use a tag to generate HTML. //:: Uses DoTag and Tag methods to generate HTML. //:: The default implementation of GetHtml simply returns the value of //:: this method. //:: Subclasses may override. function GetTagHtml: string; //:$ <br>Assemble HTML tag for the <td> cell containing this control. //:: Fills tag object with HTML representative of the <td> cell //:: containing the control. The standard HTML generator uses a //:: table-layout and places every control inside of a <td> cell. //:: Customize the <td> tag by overriding this method, customize the cell's //:: contents by overriding the Tag method. procedure CellTag(inTag: TThTag); virtual; //:$ <br>Invokes the OnTag event. //:: Invokes the OnTag event, if assigned. GetTagHtml calls this //:: method immediately after calling the Tag method. procedure DoTag(inTag: TThTag); virtual; procedure SetJavaScript(const Value: TThJavaScriptEvents); //:$ <br>Copy style information to an HTML tag. //:: Fills tag object with style information. Specifically, the //:: StyleClass is copied into the <class> attribute, and the Style //:: object fills the <style> attribute. procedure StylizeTag(inTag: TThTag); //:$ <br>Assemble HTML tag. //:: Fills tag object with HTML representative of the control. //:: Calls StylizeTag and ListJsAttributes. Subclasses override //:: this method to provide custom HTML. //:: This HTML from this method is used as the content for the <td> cell //:: generated by the CellTag method. Customize the <td> tag by overriding //:: CellTag; customize the cell's contents by overriding this method. procedure Tag(inTag: TThTag); virtual; public constructor Create(inOwner: TComponent); override; destructor Destroy; override; //:$ <br>Copy JavaScript information to an attribute list. //:: Fills list object with JavaScript information. Specifically, the //:: object in the JavaScript property is asked to compose event data into //:: HTML attributes and add them to the list. procedure ListJsAttributes(inAttrs: TThAttributeList); virtual; //:$ <br>Modify an HTML document. //:: Outputs HTML into a document. Default implementation //:: simply adds the value of the Html property to the body of the //:: document. Subclasses override this method in provide custom processing //:: when an object is published. procedure Publish(inDoc: TThStructuredHtml); virtual; public //:$ <br>HTML generated to represent this control. //:: HTML representing this control is generated and returned as a //:: string. property Html: string read GetHtml; //:$ <br>Event fired after a tag is prepared for this control. property OnTag: TThOnTag read FOnTag write FOnTag; published property DesignOnly: Boolean read FDesignOnly write FDesignOnly; //:$ <br>Collection of JavaScript events. property JavaScript: TThJavaScriptEvents read GetJavaScript write SetJavaScript; end; function ThAttr(const inName, inValue: string): string; overload; function ThAttr(const inName: string; inValue: Integer): string; overload; //function ThGetHeightAttributeValue(inCtrl: TControl): string; //function ThGetHeightStyleValue(inCtrl: TControl): string; procedure ThPaintOutline(inCanvas: TCanvas; const inRect: TRect; inColor: TColor = clBlack; inPenStyle: TPenStyle = psDash; inPenWidth: Integer = 1); implementation function ThAttr(const inName, inValue: string): string; begin if (inValue = '') then Result := '' else Result := ' ' + inName + '="' + inValue + '"'; end; function ThAttr(const inName: string; inValue: Integer): string; begin Result := ThAttr(inName, IntToStr(inValue)); end; { function ThGetHeightAttributeValue(inCtrl: TControl): string; begin case inCtrl.Align of alLeft, alClient, alRight: Result := '100%'; else Result := Format('%d', [ inCtrl.Height ]); end; end; function ThGetHeightStyleValue(inCtrl: TControl): string; begin case inCtrl.Align of alLeft, alClient, alRight: Result := '100%'; else Result := Format('%dpx', [ inCtrl.Height ]); end; end; } procedure ThPaintOutline(inCanvas: TCanvas; const inRect: TRect; inColor: TColor = clBlack; inPenStyle: TPenStyle = psDash; inPenWidth: Integer = 1); begin inCanvas.Pen.Width := inPenWidth; inCanvas.Pen.Color := inColor; inCanvas.Pen.Style := inPenStyle; inCanvas.Brush.Style := bsClear; inCanvas.Rectangle(inRect); end; { TThWebControl } constructor TThWebControl.Create(inOwner: TComponent); begin inherited; FJavaScript := TThJavaScriptEvents.Create(Self); end; destructor TThWebControl.Destroy; begin FJavaScript.Free; inherited; end; procedure TThWebControl.AdjustMargins(var ioRect: TRect); begin with CtrlStyle do begin Inc(ioRect.Left, GetBoxLeft); Inc(ioRect.Top, GetBoxTop); Inc(ioRect.Right, GetBoxRight); Inc(ioRect.Bottom, GetBoxBottom); end; end; procedure TThWebControl.ListJsAttributes(inAttrs: TThAttributeList); begin JavaScript.ListAttributes(Name, inAttrs); end; procedure TThWebControl.StylizeTag(inTag: TThTag); begin inTag.Add('id', Name); Style.ListStyles(inTag.Styles); inTag.Add('class', StyleClass); end; procedure TThWebControl.Tag(inTag: TThTag); begin StylizeTag(inTag); ListJsAttributes(inTag.Attributes); end; procedure TThWebControl.DoTag(inTag: TThTag); begin if Assigned(FOnTag) then FOnTag(Self, inTag); end; function TThWebControl.GetTagHtml: string; begin with TThTag.Create do try Tag(ThisTag); DoTag(ThisTag); Result := Html; finally Free; end; end; function TThWebControl.GetHtmlAsString: string; begin Result := GetTagHtml; end; function TThWebControl.GetHtml: string; begin if DesignOnly then Result := '' else Result := GetHtmlAsString; end; procedure TThWebControl.CellTag(inTag: TThTag); begin with inTag do begin case Align of alLeft, alClient, alRight: Add('height', '100%'); else Add('height', Height); end; case Align of alTop, alClient, alBottom: ; else Add('width', Width); end; Add('valign', 'top'); end; end; procedure TThWebControl.SetJavaScript(const Value: TThJavaScriptEvents); begin FJavaScript.Assign(Value); end; procedure TThWebControl.Publish(inDoc: TThStructuredHtml); begin inDoc.Body.Add(Html); end; function TThWebControl.GetJavaScript: TThJavaScriptEvents; begin Result := FJavaScript; end; { TThWebGraphicControl } constructor TThWebGraphicControl.Create(inOwner: TComponent); begin inherited; FJavaScript := TThJavaScriptEvents.Create(Self); end; destructor TThWebGraphicControl.Destroy; begin FJavaScript.Free; inherited; end; procedure TThWebGraphicControl.StylizeTag(inTag: TThTag); begin Style.ListStyles(inTag.Styles); inTag.Add('class', StyleClass); end; procedure TThWebGraphicControl.ListJsAttributes(inAttrs: TThAttributeList); begin JavaScript.ListAttributes(Name, inAttrs); end; procedure TThWebGraphicControl.Tag(inTag: TThTag); begin StylizeTag(inTag); ListJsAttributes(inTag.Attributes); end; procedure TThWebGraphicControl.DoTag(inTag: TThTag); begin if Assigned(FOnTag) then FOnTag(Self, inTag); end; function TThWebGraphicControl.GetTagHtml: string; begin with TThTag.Create do try Tag(ThisTag); DoTag(ThisTag); Result := Html; finally Free; end; end; function TThWebGraphicControl.GetHtmlAsString: string; begin Result := GetTagHtml; end; function TThWebGraphicControl.GetHtml: string; begin if DesignOnly then Result := '' else Result := GetHtmlAsString; end; procedure TThWebGraphicControl.CellTag(inTag: TThTag); begin with inTag do begin case Align of alLeft, alClient, alRight: Add('height', '100%'); else Add('height', Height); end; case Align of alTop, alClient, alBottom: ; else Add('width', Width); end; Add('valign', 'top'); end; end; procedure TThWebGraphicControl.SetJavaScript(const Value: TThJavaScriptEvents); begin FJavaScript.Assign(Value); end; procedure TThWebGraphicControl.Publish(inDoc: TThStructuredHtml); begin inDoc.Body.Add(Html); end; function TThWebGraphicControl.GetJavaScript: TThJavaScriptEvents; begin Result := FJavaScript; end; end.
unit testinstagram; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testregistry, InstagramScrapper, fpjson, IniFiles; type { TTestInstagramBase } TTestInstagramBase= class(TTestCase) private FConf: TMemIniFile; FInstagramParser: TInstagramParser; FTargetMediaShortCode: String; FTargetUrl: String; FTargetUserName: String; procedure SaveJSONObject(AData: TJSONData; const AFileName: String); protected procedure SetUp; override; procedure TearDown; override; public procedure AccountProperties(const aFileName: String = '~AccountProperties.txt'); procedure MediaProperties(const aFileName: String = '~MediaProperties.txt'); property TargetUsername: String read FTargetUserName; property TargetMedia: String read FTargetMediaShortCode; property TargetUrl: String read FTargetUrl; end; { TTestInstagram } TTestInstagram=class(TTestInstagramBase) published procedure TestGetParseJSONAccount; procedure TestGetParseJSONMedia; procedure TestGetParseComments; procedure TestGetParseUrl; procedure TestGetParseMultiple; end; { TTestInstagramWithProxy } { It is not working when using fphttpclient } TTestInstagramWithProxy=class(TTestInstagram) protected procedure SetUp; override; end; { TTestAuthorize } TTestAuthorize = class(TTestInstagramBase) protected procedure SetUp; override; published procedure Authorise; procedure TestGetStories; end; implementation uses FileUtil, eventlog, URIParser, strutils ; const s_SampleAccount='natgeo'; s_SampleMedia='BqRpCX2gfsq'; S_SampleUrl='https://www.instagram.com/p/CAMgaUoj3b3/'; s_NotParsed='Not parsed'; s_NotUrl='This not instagram url'; s_NilJSON='JSON data is nil!'; s_ConfTarget='Target'; s_Media='Media'; s_Url='Url'; s_Username='Username'; s_Session='Session'; s_Password='Password'; s_Proxy='Proxy'; s_Host='Host'; s_Port='Port'; s_Uri='Uri'; { TTestInstagramWithProxy } procedure TTestInstagramWithProxy.SetUp; var AHost, AUsername, APassword: String; APort: Word; URI: TURI; begin inherited SetUp; AHost:= FConf.ReadString(s_Proxy, s_Host, EmptyStr); AUsername:=FConf.ReadString(s_Proxy, s_Username, EmptyStr); APassword:=FConf.ReadString(s_Proxy, s_Password, EmptyStr); APort:= FConf.ReadInteger(s_Proxy, s_Port, 0); if AHost=EmptyStr then begin URI:=URIParser.ParseURI('https://'+FConf.ReadString(s_Proxy, s_Uri, EmptyStr)); AHost:=URI.Host; APort:=URI.Port; AUsername:=URI.Username; APassword:=URI.Password; end; FInstagramParser.HTTPClient.HTTPProxyHost:=AHost; FInstagramParser.HTTPClient.HTTPProxyPort:=APort; FInstagramParser.HTTPClient.HTTPProxyUsername:=AUsername; FInstagramParser.HTTPClient.HTTPProxyPassword:=APassword; end; { TTestInstagram } procedure TTestInstagram.TestGetParseJSONAccount; begin AssertTrue(s_NotParsed, FInstagramParser.ParseGetAccount(TargetUsername)); SaveJSONObject(FInstagramParser.jsonUser, '~account.json'); AccountProperties; end; procedure TTestInstagram.TestGetParseJSONMedia; begin FInstagramParser.ParseComments:=True; FInstagramParser.Url:=FInstagramParser.GetPostUrl(TargetMedia); AssertTrue(s_NotParsed, FInstagramParser.GetDataFromUrl); SaveJSONObject(FInstagramParser.jsonPost, '~media.json'); MediaProperties; end; procedure TTestInstagram.TestGetParseComments; begin FInstagramParser.Url:=FInstagramParser.UrlFromShortcode(TargetMedia); FInstagramParser.GetCommentsFromUrl; // We must get gisToken and End_Cursor for futher requests Sleep(1000); FInstagramParser.Shortcode:=TargetMedia; while FInstagramParser.CommentHasPrev do begin if not FInstagramParser.getMediaCommentsByCodeHash(FInstagramParser.EndCursor) then Fail('Failed to retrieve the data'); Sleep(3000); end; SaveJSONObject(FInstagramParser.CommentList, '~comments.json'); end; procedure TTestInstagram.TestGetParseUrl; var aJSON: TJSONObject; begin aJSON:=nil; AssertTrue(s_NotUrl, FInstagramParser.IsInstagramUrl(TargetUrl)); AssertTrue(s_NotParsed, FInstagramParser.GetDataFromUrl); if AnsiContainsStr(TargetUrl, '/p/') or AnsiContainsStr(TargetUrl, '/tv/') then begin MediaProperties('~Url_MediaProperties.txt'); aJSON:=FInstagramParser.jsonPost end else if AnsiContainsStr(TargetUrl, 'https://www.instagram.com/') then begin AccountProperties('~Url_AccountProperties.txt'); aJSON:=FInstagramParser.jsonUser; end; SaveJSONObject(aJSON, '~UrlJSONData.json'); end; procedure TTestInstagram.TestGetParseMultiple; begin TestGetParseJSONAccount; Sleep(300); TestGetParseJSONMedia; end; { TTestAuthorize } procedure TTestAuthorize.SetUp; var AFileName: String; begin inherited SetUp; FInstagramParser.SessionUserName:=FConf.ReadString(s_Session, s_Username, ''); FInstagramParser.SessionPassword:=FConf.ReadString(s_Session, s_Password, ''); AssertTrue('Username or password not specified! See readme.md', (FInstagramParser.SessionUserName<>EmptyStr) and (FInstagramParser.SessionPassword<>EmptyStr)); AFileName:='~cookies_'+FInstagramParser.SessionUserName+'.txt'; FInstagramParser.HTTPClient.UserAgent:='Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0'; if FileExists(AFileName) then FInstagramParser.UserSession.LoadFromFile(AFileName); // No need authorise every test... FInstagramParser._Login(); FInstagramParser.UserSession.SaveToFile(AFileName); AssertTrue('Login is not succesful!', FInstagramParser.Logged); Sleep(1000); // to avoid ban from Instagram end; procedure TTestAuthorize.Authorise; begin // Just only authorise end; procedure TTestAuthorize.TestGetStories; var jsonStories: TJSONArray; begin FInstagramParser.ParseGetAccount(TargetUsername); jsonStories:=FInstagramParser._getStoriesForUser(FInstagramParser.UserID); if Assigned(jsonStories) then begin SaveJSONObject(jsonStories, '~Stories.json'); jsonStories.Free; end else Fail('json stories array is nil!'); end; procedure TTestInstagramBase.AccountProperties(const aFileName: String); var AProperties: TStringList; i: Integer; begin AProperties:=TStringList.Create; try AProperties.Values['biography']:=FInstagramParser.Biography; AProperties.Values['HomePage']:=FInstagramParser.HomePage; AProperties.Values['followed_by']:=IntToStr(FInstagramParser.FollowedBy); AProperties.Values['follows']:=IntToStr(FInstagramParser.Follows); AProperties.Values['FullName']:=FInstagramParser.FullName; AProperties.Values['Username']:=FInstagramParser.Username; AProperties.Values['UserID']:=IntToStr(FInstagramParser.UserID); AProperties.Values['ProfilePic']:=IntToStr(FInstagramParser.UserID); for i:=0 to FInstagramParser.Images.Count-1 do AProperties.Values['Image'+IntToStr(i)]:=FInstagramParser.Images[i]; for i:=0 to FInstagramParser.Videos.Count-1 do AProperties.Values['Video'+IntToStr(i)]:=FInstagramParser.Videos[i]; AProperties.SaveToFile(aFileName); AssertTrue('Empty account properties', FInstagramParser.Username<>EmptyStr); finally AProperties.Free; end; end; procedure TTestInstagramBase.MediaProperties(const aFileName: String); var AProperties: TStringList; i: Integer; begin AProperties:=TStringList.Create; try AProperties.Values['text']:=FInstagramParser.PostCaption; AProperties.Values['CommentCount']:=IntToStr(FInstagramParser.CommentCount); AProperties.Values['Likes']:=IntToStr(FInstagramParser.Likes); // properties of owner of the media post AProperties.Values['biography']:=FInstagramParser.Biography; AProperties.Values['HomePage']:=FInstagramParser.HomePage; AProperties.Values['followed_by']:=IntToStr(FInstagramParser.FollowedBy); AProperties.Values['follows']:=IntToStr(FInstagramParser.Follows); AProperties.Values['FullName']:=FInstagramParser.FullName; AProperties.Values['Username']:=FInstagramParser.Username; AProperties.Values['UserID']:=IntToStr(FInstagramParser.UserID); AProperties.Values['ProfilePic']:=IntToStr(FInstagramParser.UserID); for i:=0 to FInstagramParser.Images.Count-1 do AProperties.Values['Image'+IntToStr(i)]:=FInstagramParser.Images[i]; for i:=0 to FInstagramParser.Videos.Count-1 do AProperties.Values['Video'+IntToStr(i)]:=FInstagramParser.Videos[i]; AProperties.SaveToFile(aFileName); CheckNotEquals(FInstagramParser.Images.Count+FInstagramParser.Videos.Count, 0, 'Empty media content'); SaveJSONObject(FInstagramParser.CommentList, '~comments.json'); finally AProperties.Free; end; end; procedure TTestInstagramBase.SaveJSONObject(AData: TJSONData; const AFileName: String); var AStrings: TStringList; begin if not Assigned(AData) then begin Fail(s_NilJSON); Exit; end; AStrings:=TStringList.Create; try AStrings.Text:=AData.FormatJSON; AStrings.SaveToFile(AFileName); finally AStrings.Free; end; end; procedure TTestInstagramBase.SetUp; begin FConf:=TMemIniFile.Create('testinstagram.ini'); FInstagramParser:=TInstagramParser.Create; FInstagramParser.Logger:=TEventLog.Create(nil); FInstagramParser.Logger.AppendContent:=True; FInstagramParser.Logger.LogType:=ltFile; FInstagramParser.Logger.Active:=True; FInstagramParser.HTTPClient.UserAgent:='Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0'; FTargetUserName:=FConf.ReadString(s_ConfTarget, s_Username, s_SampleAccount); FTargetMediaShortCode:=FConf.ReadString(s_ConfTarget, s_Media, s_SampleMedia); FTargetUrl:=FConf.ReadString(s_ConfTarget, s_Url, S_SampleUrl); Sleep(1000); // to avoid ban from Instagram end; procedure TTestInstagramBase.TearDown; begin FreeAndNil(FConf); FInstagramParser.Logger.Free; FInstagramParser.Logger:=nil; FreeAndNil(FInstagramParser); end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { A simple component written by request from someone at the www.glscene.ru forums. Allows to view the FPS and do the usual Zoom and MoveAroundTarget stuff that all demos usually have in themselves. All that is just by dropping this component on the form. } unit VXS.SimpleNavigation; interface {$I VXScene.inc} uses System.Types, System.Classes, System.SysUtils, System.TypInfo, System.Math, FMX.Forms, FMX.Controls, FMX.ExtCtrls, FMX.Types, VXS.VectorGeometry, VXS.Scene, VXS.Win64Viewer, VXS.Strings; type TVXSimpleNavigationOption = ( snoInvertMoveAroundX, snoInvertMoveAroundY, // MoveAroundTarget. snoInvertZoom, snoInvertMouseWheel, // Zoom. snoInvertRotateX, snoInvertRotateY, // RotateTarget. snoMouseWheelHandled, // MouseWheel. snoShowFPS // Show FPS ); TVXSimpleNavigationOptions = set of TVXSimpleNavigationOption; TVXSimpleNavigationAction = (snaNone, snaMoveAroundTarget, snaZoom, snaRotateTarget, snaCustom); TVXSimpleNavigationKeyCombination = class; TSimpleNavigationCustomActionEvent = procedure(Sender: TVXSimpleNavigationKeyCombination; Shift: TShiftState; X, Y: Single) of object; TVXSimpleNavigationKeyCombination = class(TCollectionItem) private FExitOnMatch: Boolean; FAction: TVXSimpleNavigationAction; FOnCustomAction: TSimpleNavigationCustomActionEvent; FShiftState: TShiftState; protected function GetDisplayName: string; override; procedure DoOnCustomAction(Shift: TShiftState; X, Y: Single); virtual; public constructor Create(Collection: TCollection); override; procedure Assign(Source: TPersistent); override; published property ShiftState: TShiftState read FShiftState write FShiftState default []; property ExitOnMatch: Boolean read FExitOnMatch write FExitOnMatch default True; property Action: TVXSimpleNavigationAction read FAction write FAction default snaNone; property OnCustomAction: TSimpleNavigationCustomActionEvent read FOnCustomAction write FOnCustomAction; end; TVXSimpleNavigationKeyCombinations = class(TOwnedCollection) private function GetItems(Index: Integer): TVXSimpleNavigationKeyCombination; procedure SetItems(Index: Integer; const Value: TVXSimpleNavigationKeyCombination); public function Add: TVXSimpleNavigationKeyCombination; overload; function Add(const AShiftState: TShiftState; const AAction: TVXSimpleNavigationAction; const AExitOnMatch: Boolean = True): TVXSimpleNavigationKeyCombination; overload; property Items[Index: Integer]: TVXSimpleNavigationKeyCombination read GetItems write SetItems; default; end; TVXSimpleNavigation = class(TComponent) private FTimer: TTimer; FForm: TCustomForm; FVXSceneViewer: TVXSceneViewer; FOldX, FOldY: Single; FFormCaption: string; FMoveAroundTargetSpeed: Single; FZoomSpeed: Single; FOptions: TVXSimpleNavigationOptions; FKeyCombinations: TVXSimpleNavigationKeyCombinations; FRotateTargetSpeed: Single; FOnMouseMove: TMouseMoveEvent; procedure ShowFPS(Sender: TObject); procedure ViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); procedure ViewerMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); procedure SetVXSceneViewer(const Value: TVXSceneViewer); procedure SetForm(const Value: TCustomForm); function StoreFormCaption: Boolean; function StoreMoveAroundTargetSpeed: Boolean; function StoreZoomSpeed: Boolean; procedure SetKeyCombinations(const Value: TVXSimpleNavigationKeyCombinations); function StoreRotateTargetSpeed: Boolean; procedure SetOptions(const Value: TVXSimpleNavigationOptions); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; published property Form: TCustomForm read FForm write SetForm; property VXSceneViewer: TVXSceneViewer read FVXSceneViewer write SetVXSceneViewer; property ZoomSpeed: Single read FZoomSpeed write FZoomSpeed stored StoreZoomSpeed; property MoveAroundTargetSpeed: Single read FMoveAroundTargetSpeed write FMoveAroundTargetSpeed stored StoreMoveAroundTargetSpeed; property RotateTargetSpeed: Single read FRotateTargetSpeed write FRotateTargetSpeed stored StoreRotateTargetSpeed; property FormCaption: string read FFormCaption write FFormCaption stored StoreFormCaption; property Options: TVXSimpleNavigationOptions read FOptions write SetOptions default [snoMouseWheelHandled, snoShowFPS]; property KeyCombinations: TVXSimpleNavigationKeyCombinations read FKeyCombinations write SetKeyCombinations; property OnMouseMove: TMouseMoveEvent read FOnMouseMove write FOnMouseMove; end; implementation const vFPSString = '%FPS'; EPS = 0.001; { TVXSimpleNavigation } procedure TVXSimpleNavigation.Assign(Source: TPersistent); begin if Source is TVXSimpleNavigation then begin { Don't do that, because that might overide the original component's event handlers SetForm(TVXSimpleNavigation(Source).FForm); SetVXSceneViewer(TVXSimpleNavigation(Source).FVXSceneViewer); } FZoomSpeed := TVXSimpleNavigation(Source).FZoomSpeed; FMoveAroundTargetSpeed := TVXSimpleNavigation(Source).FMoveAroundTargetSpeed; FRotateTargetSpeed := TVXSimpleNavigation(Source).FRotateTargetSpeed; FFormCaption := TVXSimpleNavigation(Source).FFormCaption; FOptions := TVXSimpleNavigation(Source).FOptions; FKeyCombinations.Assign(TVXSimpleNavigation(Source).FKeyCombinations); end else inherited; // Die! end; constructor TVXSimpleNavigation.Create(AOwner: TComponent); var I: Integer; begin inherited; FKeyCombinations := TVXSimpleNavigationKeyCombinations.Create(Self, TVXSimpleNavigationKeyCombination); FKeyCombinations.Add([ssLeft, ssRight], snaZoom, True); FKeyCombinations.Add([ssLeft], snaMoveAroundTarget, True); FKeyCombinations.Add([ssRight], snaMoveAroundTarget, True); FMoveAroundTargetSpeed := 1; FRotateTargetSpeed := 1; FZoomSpeed := 1.5; FOptions := [snoMouseWheelHandled, snoShowFPS]; FFormCaption := vFPSString; FTimer := TTimer.Create(nil); FTimer.OnTimer := ShowFPS; FOnMouseMove := nil; //Detect form if AOwner is TCustomForm then SetForm(TCustomForm(AOwner)); //Detect SceneViewer if FForm <> nil then begin if FForm.ComponentCount <> 0 then for I := 0 to FForm.ComponentCount - 1 do if FForm.Components[I] is TVXSceneViewer then begin SetVXSceneViewer(TVXSceneViewer(FForm.Components[I])); Exit; end; end; end; destructor TVXSimpleNavigation.Destroy; begin FTimer.Free; FKeyCombinations.Free; if FForm <> nil then TForm(FForm).OnMouseWheel := nil; if FVXSceneViewer <> nil then FVXSceneViewer.OnMouseMove := nil; inherited; end; procedure TVXSimpleNavigation.ViewerMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); var Sign: SmallInt; begin if (csDesigning in ComponentState) or (WheelDelta = 0) then Exit; if snoInvertMouseWheel in FOptions then Sign := 1 else Sign := -1; if FVXSceneViewer <> nil then if FVXSceneViewer.Camera <> nil then FVXSceneViewer.Camera.AdjustDistanceToTarget( Power(FZoomSpeed, Sign * WheelDelta div Abs(WheelDelta))); Handled := snoMouseWheelHandled in FOptions; end; procedure TVXSimpleNavigation.ViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); procedure DoZoom; var Sign: SmallInt; begin if snoInvertZoom in FOptions then Sign := -1 else Sign := 1; FVXSceneViewer.Camera.AdjustDistanceToTarget( Power(FZoomSpeed, Sign * (Y - FOldY) / 20)); end; procedure DoMoveAroundTarget; var SignX: SmallInt; SignY: SmallInt; begin if snoInvertMoveAroundX in FOptions then SignX := -1 else SignX := 1; if snoInvertMoveAroundY in FOptions then SignY := -1 else SignY := 1; FVXSceneViewer.Camera.MoveAroundTarget(SignX * FMoveAroundTargetSpeed * (FOldY - Y), SignY * FMoveAroundTargetSpeed * (FOldX - X)); end; procedure DoRotateTarget; var SignX: SmallInt; SignY: SmallInt; begin if snoInvertRotateX in FOptions then SignX := -1 else SignX := 1; if snoInvertRotateY in FOptions then SignY := -1 else SignY := 1; FVXSceneViewer.Camera.RotateTarget(SignY * FRotateTargetSpeed * (FOldY - Y), SignX * FRotateTargetSpeed * (FOldX - X)); end; var I: Integer; begin if csDesigning in ComponentState then exit; if FVXSceneViewer <> nil then if FVXSceneViewer.Camera <> nil then begin if FKeyCombinations.Count <> 0 then for I := 0 to FKeyCombinations.Count - 1 do if FKeyCombinations[I].FShiftState <= Shift then begin case FKeyCombinations[I].FAction of snaNone: ; //Ignore. snaMoveAroundTarget: DoMoveAroundTarget; snaZoom: DoZoom; snaRotateTarget: DoRotateTarget; snaCustom: FKeyCombinations[I].DoOnCustomAction(Shift, X, Y); else Assert(False, strErrorEx + strUnknownType); end; if FKeyCombinations[I].FExitOnMatch then Break; end; end; FOldX := X; FOldY := Y; if Assigned(FOnMouseMove) then FOnMouseMove(Self, Shift, X, Y); end; procedure TVXSimpleNavigation.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (AComponent = FVXSceneViewer) and (Operation = opRemove) then FVXSceneViewer := nil; if (AComponent = FForm) and (Operation = opRemove) then FForm := nil; end; procedure TVXSimpleNavigation.SetKeyCombinations( const Value: TVXSimpleNavigationKeyCombinations); begin FKeyCombinations.Assign(Value); end; procedure TVXSimpleNavigation.SetForm(const Value: TCustomForm); begin if FForm <> nil then begin FForm.RemoveFreeNotification(Self); TForm(FForm).OnMouseWheel := nil; TForm(FForm).OnMouseMove := nil; if FFormCaption = vFPSString then FFormCaption := FForm.Caption + ' - ' + vFPSString; FForm.FreeNotification(Self); end; FForm := Value; end; procedure TVXSimpleNavigation.SetVXSceneViewer( const Value: TVXSceneViewer); begin if FVXSceneViewer <> nil then begin FVXSceneViewer.RemoveFreeNotification(Self); FVXSceneViewer.OnMouseMove := nil; end; FVXSceneViewer := Value; if FVXSceneViewer <> nil then begin FVXSceneViewer.OnMouseMove := ViewerMouseMove; FVXSceneViewer.FreeNotification(Self); end; end; procedure TVXSimpleNavigation.ShowFPS(Sender: TObject); var Index: Integer; Temp: string; begin if (FVXSceneViewer <> nil) and (FForm <> nil) and not(csDesigning in ComponentState) and (snoShowFPS in FOptions) then begin Temp := FFormCaption; Index := Pos(vFPSString, Temp); if Index <> 0 then begin Delete(Temp, Index, Length(vFPSString)); Insert(FVXSceneViewer.FramesPerSecondText, Temp, Index); end; FForm.Caption := Temp; FVXSceneViewer.ResetPerformanceMonitor; end; end; function TVXSimpleNavigation.StoreFormCaption: Boolean; begin Result := (FFormCaption <> vFPSString); end; function TVXSimpleNavigation.StoreMoveAroundTargetSpeed: Boolean; begin Result := Abs(FMoveAroundTargetSpeed - 1) > EPS; end; function TVXSimpleNavigation.StoreZoomSpeed: Boolean; begin Result := Abs(FZoomSpeed - 1.5) > EPS; end; function TVXSimpleNavigation.StoreRotateTargetSpeed: Boolean; begin Result := Abs(FRotateTargetSpeed - 1) > EPS; end; procedure TVXSimpleNavigation.SetOptions( const Value: TVXSimpleNavigationOptions); begin if FOptions <> Value then begin FOptions := Value; end; end; { TVXSimpleNavigationKeyCombination } procedure TVXSimpleNavigationKeyCombination.Assign(Source: TPersistent); begin if Source is TVXSimpleNavigationKeyCombination then begin FExitOnMatch := TVXSimpleNavigationKeyCombination(Source).FExitOnMatch; FAction := TVXSimpleNavigationKeyCombination(Source).FAction; FOnCustomAction := TVXSimpleNavigationKeyCombination(Source).FOnCustomAction; FShiftState := TVXSimpleNavigationKeyCombination(Source).FShiftState; end else inherited; // Die! end; constructor TVXSimpleNavigationKeyCombination.Create(Collection: TCollection); begin inherited; FAction := snaNone; FExitOnMatch := True; end; procedure TVXSimpleNavigationKeyCombination.DoOnCustomAction( Shift: TShiftState; X, Y: Single); begin if Assigned(FOnCustomAction) then FOnCustomAction(Self, Shift, X, Y); end; function TVXSimpleNavigationKeyCombination.GetDisplayName: string; begin Result := GetSetProp(Self, 'ShiftState', True) + ' - ' + GetEnumName(TypeInfo(TVXSimpleNavigationAction), Integer(FAction)); end; { TVXSimpleNavigationKeyCombinations } function TVXSimpleNavigationKeyCombinations.Add: TVXSimpleNavigationKeyCombination; begin Result := TVXSimpleNavigationKeyCombination(inherited Add); end; function TVXSimpleNavigationKeyCombinations.Add( const AShiftState: TShiftState; const AAction: TVXSimpleNavigationAction; const AExitOnMatch: Boolean): TVXSimpleNavigationKeyCombination; begin Result := Add; with Result do begin FShiftState := AShiftState; FAction := AAction; FExitOnMatch := AExitOnMatch; end; end; function TVXSimpleNavigationKeyCombinations.GetItems( Index: Integer): TVXSimpleNavigationKeyCombination; begin Result := TVXSimpleNavigationKeyCombination(inherited GetItem(Index)); end; procedure TVXSimpleNavigationKeyCombinations.SetItems(Index: Integer; const Value: TVXSimpleNavigationKeyCombination); begin inherited SetItem(Index, Value); end; end.
{*****************************************************************} { } { CodeGear Delphi Runtime Library } { EVR9.pas interface unit } { } { Copyright (c) 2007 Sebastian Zierer } { Converted 20 Feb 2007 Sebastian Zierer } { Last modified 16 May 2008 Sebastian Zierer } { Version 1.0a } { } {*****************************************************************} {*****************************************************************} { } { 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/MPL-1.1.html } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or } { implied. See the License for the specific language governing } { rights and limitations under the License. } { } { The original files are: } { evr.idl } { } { The original code is: EVR9.pas, released 20 January 2007 } { } { The initial developer of the Pascal code is } { Sebastian Zierer. } { } { Portions created by Microsoft are } { Copyright (C) 1995-2006 Microsoft Corporation. } { } { Portions created by Sebastian Zierer are } { Copyright (C) 2007 Sebastian Zierer } { All Rights Reserved. } { } { Contributor(s): } { } { Notes: } { } { Modification history: } { } { Known Issues: } { } {*****************************************************************} unit EVR9; interface uses Windows, ActiveX, DirectShow9; {$MINENUMSIZE 4} {$IFNDEF conditionalexpressions} {$DEFINE norecprocs} // Delphi 5 or less {$ENDIF} {$IFDEF conditionalexpressions} // Delphi 6+ {$IF compilerversion < 18} // Delphi 2005 or less {$DEFINE norecprocs} {$IFEND} {$ENDIF} //============================================================================= // Description: // // Service GUID used by IMFGetService::GetService to retrieve interfaces from // the renderer or the presenter. // const SID_IMFVideoProcessor = '{6AB0000C-FECE-4d1f-A2AC-A9573530656E}'; SID_IMFVideoMixerBitmap = '{814C7B20-0FDB-4eec-AF8F-F957C8F69EDC}'; SID_IMFStreamSink = '{6ef2a660-47c0-4666-b13d-cbb717f2fa2c}'; SID_IEVRFilterConfig = '{83E91E85-82C1-4EA7-801D-85DC50B75086}'; SID_IMFVideoDisplayControl = '{A490B1E4-AB84-4D31-A1B2-181E03B1077A}'; SID_IMFDesiredSample = '{56C294D0-753E-4260-8D61-A3D8820B1D54}'; SID_IMFVideoPositionMapper = '{1F6A9F17-E70B-4E24-8AE4-0B2C3BA7A4AE}'; SID_IMFVideoDeviceID = '{A38D9567-5A9C-4F3C-B293-8EB415B279BA}'; SID_IMFVideoMixerControl = '{A5C6C53F-C202-4AA5-9695-175BA8C508A5}'; SID_IMFGetService = '{FA993888-4383-415A-A930-DD472A8CF6F7}'; SID_IMFVideoRenderer = '{DFDFD197-A9CA-43D8-B341-6AF3503792CD}'; SID_IMFTrackedSample = '{245BF8E9-0755-40F7-88A5-AE0F18D55E17}'; SID_IMFTopologyServiceLookup = '{fa993889-4383-415a-a930-dd472a8cf6f7}'; SID_IMFTopologyServiceLookupClient = '{fa99388a-4383-415a-a930-dd472a8cf6f7}'; SID_IEVRTrustedVideoPlugin = '{83A4CE40-7710-494b-A893-A472049AF630}'; var IID_IMFTrackedSample: TGUID = SID_IMFTrackedSample; IID_IMFVideoDisplayControl: TGUID = SID_IMFVideoDisplayControl; // GetService MR_VIDEO_RENDER_SERVICE IID_IMFVideoPresenter: TGUID = '{29AFF080-182A-4A5D-AF3B-448F3A6346CB}'; IID_IMFVideoPositionMapper: TGUID = SID_IMFVideoPositionMapper; // GetService MR_VIDEO_RENDER_SERVICE IID_IMFDesiredSample: TGUID = SID_IMFDesiredSample; IID_IMFVideoMixerControl: TGUID = SID_IMFVideoMixerControl; // GetService MR_VIDEO_MIXER_SERVICE IID_IMFVideoRenderer: TGUID = SID_IMFVideoRenderer; IID_IMFVideoDeviceID: TGUID = SID_IMFVideoDeviceID; IID_IEVRFilterConfig: TGUID = SID_IEVRFilterConfig; IID_IMFTopologyServiceLookup: TGUID = SID_IMFTopologyServiceLookup; IID_IMFTopologyServiceLookupClient: TGUID = SID_IMFTopologyServiceLookupClient; IID_IEVRTrustedVideoPlugin: TGUID = SID_IEVRTrustedVideoPlugin; CLSID_EnhancedVideoRenderer: TGUID = '{FA10746C-9B63-4B6C-BC49-FC300EA5F256}'; CLSID_MFVideoMixer9: TGUID = '{E474E05A-AB65-4f6A-827C-218B1BAAF31F}'; CLSID_MFVideoPresenter9: TGUID = '{98455561-5136-4D28-AB08-4CEE40EA2781}'; CLSID_EVRTearlessWindowPresenter9: TGUID = '{A0A7A57B-59B2-4919-A694-ADD0A526C373}'; MR_VIDEO_RENDER_SERVICE: TGUID = '{1092A86c-AB1A-459A-A336-831FBC4D11FF}'; MR_VIDEO_MIXER_SERVICE: TGUID = '{073cd2fc-6cf4-40b7-8859-e89552c841f8}'; MR_VIDEO_ACCELERATION_SERVICE: TGUID = '{efef5175-5c7d-4ce2-bbbd-34ff8bca6554}'; MR_BUFFER_SERVICE: TGUID = '{a562248c-9ac6-4ffc-9fba-3af8f8ad1a4d}'; VIDEO_ZOOM_RECT: TGUID = '{7aaa1638-1b7f-4c93-bd89-5b9c9fb6fcf0}'; type IMFVideoPositionMapper = interface(IUnknown) [SID_IMFVideoPositionMapper] function MapOutputCoordinateToInputStream( xOut: Single; yOut: Single; dwOutputStreamIndex: DWORD; dwInputStreamIndex: DWORD; out pxIn: Single; out pyIn: Single): HResult; stdcall; end; IMFVideoDeviceID = interface(IUnknown) [SID_IMFVideoDeviceID] function GetDeviceID(out pDeviceID: TIID): HResult; stdcall; end; const MFVideoARMode_None = $00000000; MFVideoARMode_PreservePicture = $00000001; MFVideoARMode_PreservePixel = $00000002; MFVideoARMode_NonLinearStretch = $00000004; MFVideoARMode_Mask = $00000007; //============================================================================= // Description: // // The rendering preferences used by the video presenter object. // const // MFVideoRenderPrefs // Do not paint color keys (default off) MFVideoRenderPrefs_DoNotRenderBorder = $00000001; // Do not clip to monitor that has largest amount of video (default off) MFVideoRenderPrefs_DoNotClipToDevice = $00000002; MFVideoRenderPrefs_Mask = $00000003; type PMFVideoNormalizedRect = ^TMFVideoNormalizedRect; TMFVideoNormalizedRect = record left: Single; top: Single; right: Single; bottom: Single; {$IFNDEF norecprocs} procedure Init(ALeft, ATop, ARight, ABottom: Single); {$ENDIF} end; type IMFVideoDisplayControl = interface(IUnknown) [SID_IMFVideoDisplayControl] function GetNativeVideoSize({unique} out pszVideo: TSIZE; {unique} out pszARVideo: TSIZE): HResult; stdcall; function GetIdealVideoSize({unique} out pszMin: TSIZE; {unique} out pszMax: TSIZE): HResult; stdcall; function SetVideoPosition({unique} pnrcSource: PMFVideoNormalizedRect; {unique} prcDest: PRECT): HResult; stdcall; function GetVideoPosition(out pnrcSource: TMFVideoNormalizedRect; out prcDest: TRECT): HResult; stdcall; function SetAspectRatioMode(dwAspectRatioMode: DWORD): HResult; stdcall; function GetAspectRatioMode(out pdwAspectRatioMode: DWORD): HResult; stdcall; function SetVideoWindow(hwndVideo: HWND): HResult; stdcall; function GetVideoWindow(out phwndVideo: HWND): HResult; stdcall; function RepaintVideo: HResult; stdcall; function GetCurrentImage(pBih: PBITMAPINFOHEADER; out lpDib; out pcbDib: DWORD; {unique} pTimeStamp: PInt64): HResult; stdcall; function SetBorderColor(Clr: COLORREF): HResult; stdcall; function GetBorderColor(out pClr: COLORREF): HResult; stdcall; function SetRenderingPrefs(dwRenderFlags: DWORD): HResult; stdcall; // a combination of MFVideoRenderPrefs function GetRenderingPrefs(out pdwRenderFlags: DWORD): HResult; stdcall; function SetFullscreen(fFullscreen: Boolean): HResult; stdcall; function GetFullscreen(out pfFullscreen: Boolean): HResult; stdcall; end; //============================================================================= // Description: // // The different message types that can be passed to the video presenter via // IMFVideoPresenter::ProcessMessage. // TMFVP_MESSAGE_TYPE = ( // Called by the video renderer when a flush request is received on the // reference video stream. In response, the presenter should clear its // queue of samples waiting to be presented. // ulParam is unused and should be set to zero. MFVP_MESSAGE_FLUSH = $00000000, // Indicates to the presenter that the current output media type on the // mixer has changed. In response, the presenter may now wish to renegotiate // the media type of the video mixer. // Return Values: // S_OK - successful completion // MF_E_INVALIDMEDIATYPE - The presenter and mixer could not agree on // a media type. // ulParam is unused and should be set to zero. MFVP_MESSAGE_INVALIDATEMEDIATYPE = $00000001, // Indicates that a sample has been delivered to the video mixer object, // and there may now be a sample now available on the mixer's output. In // response, the presenter may want to draw frames out of the mixer's // output. // ulParam is unused and should be set to zero. MFVP_MESSAGE_PROCESSINPUTNOTIFY = $00000002, // Called when streaming is about to begin. In // response, the presenter should allocate any resources necessary to begin // streaming. // ulParam is unused and should be set to zero. MFVP_MESSAGE_BEGINSTREAMING = $00000003, // Called when streaming has completed. In // response, the presenter should release any resources that were // previously allocated for streaming. // ulParam is unused and should be set to zero. MFVP_MESSAGE_ENDSTREAMING = $00000004, // Indicates that the end of this segment has been reached. // When the last frame has been rendered, EC_COMPLETE should be sent // on the IMediaEvent interface retrieved from the renderer // during IMFTopologyServiceLookupClient::InitServicePointers method. // ulParam is unused and should be set to zero. MFVP_MESSAGE_ENDOFSTREAM = $00000005, // The presenter should step the number frames indicated by the lower DWORD // of ulParam. // The first n-1 frames should be skipped and only the nth frame should be // shown. Note that this message should only be received while in the pause // state or while in the started state when the rate is 0. // Otherwise, MF_E_INVALIDREQUEST should be returned. // When the nth frame has been shown EC_STEP_COMPLETE // should be sent on the IMediaEvent interface. // Additionally, if stepping is being done while the rate is set to 0 // (a.k.a. "scrubbing"), the frame should be displayed immediately when // it is received, and EC_SCRUB_TIME should be sent right away after // sending EC_STEP_COMPLETE. MFVP_MESSAGE_STEP = $00000006, // The currently queued step operation should be cancelled. The presenter // should remain in the pause state following the cancellation. // ulParam is unused and should be set to zero. MFVP_MESSAGE_CANCELSTEP = $00000007); // IMFVideoPresenter = interface(IMFClockStateSink) // ['{29AFF080-182A-4a5d-AF3B-448F3A6346CB}'] // function ProcessMessage(eMessage: TMFVP_MESSAGE_TYPE; ulParam: ULONG_PTR); // function GetCurrentMediaType(out ppMediaType: IMFVideoMediaType); // end; IMFDesiredSample = interface(IUnknown) [SID_IMFDesiredSample] function GetDesiredSampleTimeAndDuration(out phnsSampleTime: Int64; out phnsSampleDuration: Int64): HResult; stdcall; function SetDesiredSampleTimeAndDuration(hnsSampleTime: Int64; hnsSampleDuration: Int64): HResult; stdcall; procedure Clear; stdcall; end; // IMFTrackedSample = interface(IUnknown) // [SID_IMFTrackedSample] // function SetAllocator(pSampleAllocator: IMFAsyncCallback; {unique} pUnkState: IUnknown); // end; IMFVideoMixerControl = interface(IUnknown) [SID_IMFVideoMixerControl] function SetStreamZOrder(dwStreamID: DWORD; dwZ: DWORD): HResult; stdcall; function GetStreamZOrder(dwStreamID: DWORD; out pdwZ: DWORD): HResult; stdcall; function SetStreamOutputRect(dwStreamID: DWORD; pnrcOutput: PMFVideoNormalizedRect): HResult; stdcall; function GetStreamOutputRect(dwStreamID: DWORD; out pnrcOutput: TMFVideoNormalizedRect): HResult; stdcall; end; // IMFVideoRenderer = interface(IUnknown) // [SID_IMFVideoRenderer] // function InitializeRenderer({unique, nil} pVideoMixer: IMFTransform; // {unique, nil} pVideoPresenter: IMFVideoPresenter); // end; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// type MF_SERVICE_LOOKUP_TYPE = ( MF_SERVICE_LOOKUP_UPSTREAM, MF_SERVICE_LOOKUP_UPSTREAM_DIRECT, MF_SERVICE_LOOKUP_DOWNSTREAM, MF_SERVICE_LOOKUP_DOWNSTREAM_DIRECT, MF_SERVICE_LOOKUP_ALL, // lookup service on any components of the graph MF_SERVICE_LOOKUP_GLOBAL); // lookup global objects IMFTopologyServiceLookup = interface(IUnknown) [SID_IMFTopologyServiceLookup] function LookupService(_Type: MF_SERVICE_LOOKUP_TYPE; dwIndex: DWORD; const guidService: TIID; {in} const riid: TIID; out ppvObjects; var pnObjects: DWORD): HResult; stdcall; end; IMFTopologyServiceLookupClient = interface(IUnknown) [SID_IMFTopologyServiceLookupClient] function InitServicePointers(pLookup: IMFTopologyServiceLookup): HResult; stdcall; end; IEVRTrustedVideoPlugin = interface(IUnknown) [SID_IEVRTrustedVideoPlugin] function IsInTrustedVideoMode(out pYes: BOOL): HResult; stdcall; function CanConstrict (out pYes: BOOL): HResult; stdcall; function SetConstriction(dwKPix: DWORD): HResult; stdcall; function DisableImageExport(bDisable: BOOL): HResult; stdcall; end; type IEVRFilterConfig = interface(IUnknown) [SID_IEVRFilterConfig] function SetNumberOfStreams(dwMaxStreams: DWORD): HResult; stdcall; function GetNumberOfStreams(out pdwMaxStreams: DWORD): HResult; stdcall; end; IMFGetService = interface(IUnknown) [SID_IMFGetService] function GetService(const guidService: TGUID; const IID: TIID; out ppvObject): HResult; stdcall; end; type D3DPOOL = DWord; TDXVA2_Fixed32 = record {$IFNDEF norecprocs} procedure Dummy; class operator Implicit(Fixed32: TDXVA2_Fixed32): Double; class operator Implicit(ADouble: Double): TDXVA2_Fixed32; {$ENDIF} case Integer of 0: (Fraction: Word; //USHORT; (Unsigned SmallInt = Word) Value: SHORT); 1: (ll: LongInt) end; TDXVA2_VideoProcessorCaps = record DeviceCaps: UINT; // see DXVA2_VPDev_Xxxx InputPool: D3DPOOL; NumForwardRefSamples: UINT; NumBackwardRefSamples: UINT; Reserved: UINT; DeinterlaceTechnology: UINT; // see DXVA2_DeinterlaceTech_Xxxx ProcAmpControlCaps: UINT; // see DXVA2_ProcAmp_Xxxx VideoProcessorOperations: UINT; // see DXVA2_VideoProcess_Xxxx NoiseFilterTechnology: UINT; // see DXVA2_NoiseFilterTech_Xxxx DetailFilterTechnology: UINT; // see DXVA2_DetailFilterTech_Xxxx end; TDXVA2_ValueRange = record MinValue: TDXVA2_Fixed32; MaxValue: TDXVA2_Fixed32; DefaultValue: TDXVA2_Fixed32; StepSize: TDXVA2_Fixed32; end; TDXVA2_ProcAmpValues = record Brightness: TDXVA2_Fixed32; Contrast: TDXVA2_Fixed32; Hue: TDXVA2_Fixed32; Saturation: TDXVA2_Fixed32; end; const DXVA2_ProcAmp_None = $0000; DXVA2_ProcAmp_Brightness = $0001; DXVA2_ProcAmp_Contrast = $0002; DXVA2_ProcAmp_Hue = $0004; DXVA2_ProcAmp_Saturation = $0008; DXVA2_ProcAmp_Mask = $000F; DXVA2_VideoProcProgressiveDevice: TGUID = '{5a54a0c9-c7ec-4bd9-8ede-f3c75dc4393b}'; DXVA2_VideoProcBobDevice : TGUID = '{335aa36e-7884-43a4-9c91-7f87faf3e37e}'; DXVA2_VideoProcSoftwareDevice : TGUID = '{4553d47f-ee7e-4e3f-9475-dbf1376c4810}'; type IMFVideoProcessor = interface(IUnknown) [SID_IMFVideoProcessor] function GetAvailableVideoProcessorModes(var lpdwNumProcessingModes: UINT; { [size_is][size_is][out] } out ppVideoProcessingModes {Pointer to Array of GUID}): HResult; stdcall; function GetVideoProcessorCaps(lpVideoProcessorMode: PGUID; { [out] } out lpVideoProcessorCaps: TDXVA2_VideoProcessorCaps): HResult; stdcall; function GetVideoProcessorMode(out lpMode: TGUID): HResult; stdcall; function SetVideoProcessorMode(lpMode: PGUID): HResult; stdcall; function GetProcAmpRange(dwProperty: DWORD; out pPropRange: TDXVA2_ValueRange): HResult; stdcall; function GetProcAmpValues(dwFlags: DWORD; out Values: TDXVA2_ProcAmpValues): HResult; stdcall; function SetProcAmpValues(dwFlags: DWORD; {in} const pValues: TDXVA2_ProcAmpValues): HResult; stdcall; function GetFilteringRange(dwProperty: DWORD; out pPropRange: TDXVA2_ValueRange): HResult; stdcall; function GetFilteringValue(dwProperty: DWORD; out pValue: TDXVA2_Fixed32): HResult; stdcall; function SetFilteringValue(dwProperty: DWORD; const pValue: TDXVA2_Fixed32): HResult; stdcall; function GetBackgroundColor(out lpClrBkg: COLORREF): HResult; stdcall; function SetBackgroundColor(ClrBkg: COLORREF): HResult; stdcall; end; // TMFVideoAlphaBitmapFlags = ( const MFVideoAlphaBitmap_EntireDDS = $1; MFVideoAlphaBitmap_SrcColorKey = $2; MFVideoAlphaBitmap_SrcRect = $4; MFVideoAlphaBitmap_DestRect = $8; MFVideoAlphaBitmap_FilterMode = $10; MFVideoAlphaBitmap_Alpha = $20; MFVideoAlphaBitmap_BitMask = $3f; type TMFVideoAlphaBitmapParams = record dwFlags: DWORD; clrSrcKey: COLORREF; rcSrc: TRECT; nrcDest: TMFVideoNormalizedRect; fAlpha: Single; dwFilterMode: DWORD; end; IDirect3DSurface9 = Pointer; // TODO (for now use a pointer to avoid dependencies to DirectX 9 units) TMFVideoAlphaBitmap = record GetBitmapFromDC: Boolean; case Boolean of True: (hdc: HDC; params: TMFVideoAlphaBitmapParams); False: (pDDS: IDirect3DSurface9; params2: TMFVideoAlphaBitmapParams;); end; IMFVideoMixerBitmap = interface(IUnknown) [SID_IMFVideoMixerBitmap] function SetAlphaBitmap(const pBmpParms: TMFVideoAlphaBitmap): HResult; stdcall; function ClearAlphaBitmap: HResult; stdcall; function UpdateAlphaBitmapParameters(const pBmpParms: TMFVideoAlphaBitmapParams): HResult; stdcall; function GetAlphaBitmapParameters(out pBmpParms: TMFVideoAlphaBitmapParams): HResult; stdcall; end; function MFVideoNormalizedRect(const ALeft, ATop, ARight, ABottom: Single): TMFVideoNormalizedRect; implementation function MFVideoNormalizedRect(const ALeft, ATop, ARight, ABottom: Single): TMFVideoNormalizedRect; begin Result.left := ALeft; Result.top := ATop; Result.right := ARight; Result.bottom := ABottom; end; { TMFVideoNormalizedRect } {$IFNDEF norecprocs} procedure TMFVideoNormalizedRect.Init(ALeft, ATop, ARight, ABottom: Single); begin left := ALeft; top := ATop; right := ARight; bottom := ABottom; end; {$ENDIF} { TDXVA2_Fixed32 } {$IFNDEF norecprocs} procedure TDXVA2_Fixed32.Dummy; begin // this is just to make delphi 2007 class completion happy end; class operator TDXVA2_Fixed32.Implicit(Fixed32: TDXVA2_Fixed32): Double; begin with Fixed32 do Result := Value + Fraction / $10000; end; class operator TDXVA2_Fixed32.Implicit(ADouble: Double): TDXVA2_Fixed32; begin Result.Fraction := Trunc(Frac(ADouble) * $10000); Result.Value := Trunc(ADouble); end; {$ENDIF} end.
unit MulOpTest; {$mode objfpc}{$H+} interface uses fpcunit, testregistry, uEnums, uIntXLibTypes, uIntX, uConstants; type { TTestMulOp } TTestMulOp = class(TTestCase) published procedure PureIntX(); procedure PureIntXSign(); procedure IntAndIntX(); procedure Zero(); procedure Big(); procedure Big2(); procedure Big3(); procedure Performance(); protected procedure SetUp; override; end; implementation procedure TTestMulOp.PureIntX(); begin AssertTrue(TIntX.Create(3) * TIntX.Create(5) = TIntX.Create(15)); end; procedure TTestMulOp.PureIntXSign(); begin AssertTrue(TIntX.Create(-3) * TIntX.Create(5) = TIntX.Create(-15)); end; procedure TTestMulOp.IntAndIntX(); begin AssertTrue(TIntX.Create(3) * 5 = 15); end; procedure TTestMulOp.Zero(); begin AssertTrue(0 * TIntX.Create(3) = 0); end; procedure TTestMulOp.Big(); var temp1, temp2, tempRes: TIntXLibUInt32Array; int1, int2, intRes: TIntX; begin SetLength(temp1, 2); temp1[0] := 1; temp1[1] := 1; SetLength(temp2, 2); temp2[0] := 1; temp2[1] := 1; SetLength(tempRes, 3); tempRes[0] := 1; tempRes[1] := 2; tempRes[2] := 1; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, False); intRes := TIntX.Create(tempRes, False); AssertTrue(int1 * int2 = intRes); end; procedure TTestMulOp.Big2(); var temp1, temp2, tempRes: TIntXLibUInt32Array; int1, int2, intRes: TIntX; begin SetLength(temp1, 2); temp1[0] := 1; temp1[1] := 1; SetLength(temp2, 1); temp2[0] := 2; SetLength(tempRes, 2); tempRes[0] := 2; tempRes[1] := 2; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, False); intRes := TIntX.Create(tempRes, False); AssertTrue(intRes = int1 * int2); AssertTrue(intRes = int2 * int1); end; procedure TTestMulOp.Big3(); var temp1, temp2, tempRes: TIntXLibUInt32Array; int1, int2, intRes: TIntX; begin SetLength(temp1, 2); temp1[0] := TConstants.MaxUInt32Value; temp1[1] := TConstants.MaxUInt32Value; SetLength(temp2, 2); temp2[0] := TConstants.MaxUInt32Value; temp2[1] := TConstants.MaxUInt32Value; SetLength(tempRes, 4); tempRes[0] := 1; tempRes[1] := 0; tempRes[2] := TConstants.MaxUInt32Value - 1; tempRes[3] := TConstants.MaxUInt32Value; int1 := TIntX.Create(temp1, False); int2 := TIntX.Create(temp2, False); intRes := TIntX.Create(tempRes, False); AssertTrue(int1 * int2 = intRes); end; procedure TTestMulOp.Performance(); var i: integer; temp1: TIntXLibUInt32Array; IntX, intX2: TIntX; begin SetLength(temp1, 2); temp1[0] := 0; temp1[1] := 1; IntX := TIntX.Create(temp1, False); intX2 := IntX; i := 0; while i <= Pred(1000) do begin intX2 := intX2 * IntX; Inc(i); end; end; procedure TTestMulOp.SetUp; begin inherited SetUp; TIntX.GlobalSettings.MultiplyMode := TMultiplyMode.mmClassic; end; initialization RegisterTest(TTestMulOp); end.
unit API_MVC; interface uses Vcl.Forms ,Vcl.Dialogs ,System.Classes ,System.SysUtils ,System.Generics.Collections ,API_DBases; type ////////////////////////////////////////////////////////////////////////////// // событие модели TEvent = procedure(EventName: string; EventData :TDictionary<string,variant>) of object; ////////////////////////////////////////////////////////////////////////////// // модель TModelAbstract = class abstract private FEvent: TEvent; FGlobals: TObjectDictionary<string,TObject>; protected FControllerMessage: string; FDBEngine: TDBEngine; FEventData: TDictionary<string,variant>; FData: TDictionary<string,variant>; FObjData: TObjectDictionary<string,TObject>; procedure GenerateEvent(EventCode: string); // переопределяется в потомках procedure InputDataParce; virtual; public constructor Create(Data: TDictionary<string,variant>; ObjData, aGlobals: TObjectDictionary<string,TObject>); overload; destructor Destroy; override; // реализация в потомках procedure Execute; virtual; abstract; procedure ModelInitForThreads; virtual; public property Event: TEvent read FEvent write FEvent; property ControllerMessage: string read FControllerMessage write FControllerMessage; end; TModelClass = class of TModelAbstract; TModelMethod = procedure of object; ////////////////////////////////////////////////////////////////////////////// // контроллер TControllerAbstract = class abstract protected FDBEngine: TDBEngine; FSettingFileName: String; FSettings: TStringList; FGlobals: TObjectDictionary<string, TObject>; FData: TDictionary<string, variant>; FObjData: TObjectDictionary<string, TObject>; FModel: TModelAbstract; procedure CallModel(aModelClass: TModelClass); virtual; // реализация в потомках procedure EventListener(aEventName: string; aEventData: TDictionary<string,variant>); virtual; abstract; procedure InitController; virtual; abstract; procedure PrepareModel(aMessage: string); virtual; abstract; public constructor Create; overload; procedure SendViewMessage(aMessage: string); destructor Destroy; override; property Model: TModelAbstract read FModel write FModel; end; TControllerClass = class of TControllerAbstract; ////////////////////////////////////////////////////////////////////////////// // представление TViewAbstract = class abstract(TForm) private procedure DeInitMVC; protected FisMainForm: Boolean; FisReleased: Boolean; FController: TControllerAbstract; FControllerClass: TControllerClass; // реализация в потомках procedure InitMVC; virtual; abstract; procedure AfterControllerCreate; virtual; procedure SendViewMessage(aMsg: string); public constructor Create(AOwner: TComponent); override; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); property ControllerClass: TControllerClass read FControllerClass write FControllerClass; property isReleased: Boolean read FisReleased write FisReleased; end; implementation procedure TViewAbstract.AfterControllerCreate; begin end; procedure TModelAbstract.ModelInitForThreads; begin end; procedure TModelAbstract.InputDataParce; begin FDBEngine:=FGlobals.Items['DBEngine'] as TDBEngine; end; destructor TModelAbstract.Destroy; begin inherited; FEventData.Free; end; procedure TModelAbstract.GenerateEvent(EventCode: string); begin FControllerMessage:=''; if Assigned(FEvent) then FEvent(EventCode, FEventData); end; constructor TViewAbstract.Create(AOwner: TComponent); begin inherited; if AOwner is TViewAbstract then Self.FController:=TViewAbstract(AOwner).FController; Self.OnCreate:=FormCreate; Self.OnDestroy:=FormDestroy; end; constructor TModelAbstract.Create(Data: TDictionary<System.string,Variant>; ObjData, aGlobals: TObjectDictionary<string,System.TObject>); begin Self.FData:=Data; Self.FObjData:=ObjData; Self.FGlobals:=aGlobals; Self.InputDataParce; FEventData:=TDictionary<string,variant>.Create; end; destructor TControllerAbstract.Destroy; begin FSettings.Free; if Assigned(FDBEngine) then FDBEngine.Free; FGlobals.Free; FObjData.Free; FData.Free; inherited; end; constructor TControllerAbstract.Create; begin try inherited; Self.InitController; FSettings:=TStringList.Create; if not FSettingFileName.IsEmpty then FSettings.LoadFromFile(FSettingFileName); FGlobals:=TObjectDictionary<string,TObject>.Create; if Assigned(FDBEngine) then FGlobals.Add('DBEngine', FDBEngine); FData:=TDictionary<string,variant>.Create; FObjData:=TObjectDictionary<string,TObject>.Create([doOwnsValues]); except On E : Exception do begin ShowMessage('Ошибка создания контроллера:'+E.Message); RunError; end; end; end; procedure TControllerAbstract.SendViewMessage(aMessage: string); begin try // формируем данные для модели Self.FData.Clear; Self.FObjData.Clear; Self.PrepareModel(aMessage); except On E : Exception do ShowMessage('Ошибка в сообщении вида "'+aMessage+'" :'+E.Message); end; end; procedure TControllerAbstract.CallModel(aModelClass: TModelClass); begin FModel:=aModelClass.Create(Self.FData, Self.FObjData, Self.FGlobals); try FModel.Event:=Self.EventListener; FModel.Execute; finally FreeAndNil(FModel); end; end; procedure TViewAbstract.DeInitMVC; begin FController.Free; end; procedure TViewAbstract.FormCreate(Sender: TObject); begin if not Assigned(FController) then begin Self.InitMVC; FController:=FControllerClass.Create; FisMainForm:=True; AfterControllerCreate; end; end; procedure TViewAbstract.FormDestroy(Sender: TObject); begin if FisMainForm then Self.DeInitMVC; end; procedure TViewAbstract.SendViewMessage(aMsg: string); begin FController.SendViewMessage(aMsg); end; end.
unit uFrmSearchHold; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, cxLookAndFeelPainters, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, StdCtrls, cxButtons, ExtCtrls, ADODB, DBClient, Provider; type TFrmSearchHold = class(TForm) grdHolds: TcxGrid; grdHoldsDB: TcxGridDBTableView; grdHoldsLevel: TcxGridLevel; dsSearchHold: TDataSource; qrySearchHold: TADOQuery; pnlBottom: TPanel; btnOk: TcxButton; btnCancel: TcxButton; pnlFilter: TPanel; edtDataIni: TcxDateEdit; edtDataFim: TcxDateEdit; qrySearchHoldSaleCode: TStringField; qrySearchHoldPreSaleDate: TDateTimeField; qrySearchHoldPessoa: TStringField; qrySearchHoldIDPreSale: TIntegerField; grdHoldsDBIDPreSale: TcxGridDBColumn; grdHoldsDBSaleCode: TcxGridDBColumn; grdHoldsDBPreSaleDate: TcxGridDBColumn; grdHoldsDBPessoa: TcxGridDBColumn; lblDataIni: TLabel; lblDataFim: TLabel; btnProcurar: TcxButton; lblNumPedido: TLabel; edtNumPedido: TcxTextEdit; qryHasService: TADOQuery; qryHasServiceTotalService: TIntegerField; dspSearchHold: TDataSetProvider; cdsSearchHold: TClientDataSet; cdsSearchHoldIDPreSale: TIntegerField; cdsSearchHoldSaleCode: TStringField; cdsSearchHoldPreSaleDate: TDateTimeField; cdsSearchHoldPessoa: TStringField; qryHasChange: TADOQuery; qryHasChangeTotalChange: TIntegerField; procedure btnProcurarClick(Sender: TObject); procedure grdHoldsDBDblClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure cdsSearchHoldAfterOpen(DataSet: TDataSet); private function HasService: Boolean; function HasChange: Boolean; public function Start: Integer; end; implementation uses uFrmMain, DateUtils, uStringFunctions; {$R *.dfm} { TFrmSearchHold } function TFrmSearchHold.Start: Integer; begin Result := -1; ShowModal; if (ModalResult = mrOk) and (not cdsSearchHold.IsEmpty) then Result := cdsSearchHoldIDPreSale.AsInteger; end; procedure TFrmSearchHold.btnProcurarClick(Sender: TObject); var sSQL: String; begin sSQL := 'SELECT ' + ' I.IDPreSale, ' + ' I.SaleCode, ' + ' I.PreSaleDate, ' + ' P.Pessoa ' + 'FROM ' + ' Invoice I ' + ' JOIN Pessoa P ON (I.IDCustomer = P.IDPessoa) ' + 'WHERE ' + ' I.IDInvoice IS NULL ';// + //' AND I.DeliverConfirmation = 1 '; with qrySearchHold do begin if edtNumPedido.Text <> '' then sSQL := sSQL + ' AND SaleCode = ' + QuotedStr(edtNumPedido.Text) else sSQL := sSQL + ' AND DeliverDate >= ' + QuotedStr(FormatDateTime('yyyymmdd', Trunc(edtDataIni.Date))) + ' AND DeliverDate <= ' + QuotedStr(FormatDateTime('yyyymmdd', Trunc(IncDay(edtDataFim.Date)))); SQL.Text := sSQL; end; with cdsSearchHold do begin if Active then Close; Open; end; end; procedure TFrmSearchHold.grdHoldsDBDblClick(Sender: TObject); begin btnOkClick(Sender); end; procedure TFrmSearchHold.FormCreate(Sender: TObject); begin edtDataIni.Date := Date; edtDataFim.Date := Date; end; function TFrmSearchHold.HasService: Boolean; begin with qryHasService do begin if Active then Close; Parameters.ParamByName('IDPreSale').Value := cdsSearchHoldIDPreSale.AsInteger; Open; Result := FieldByName('TotalService').AsInteger > 0; Close; end; end; procedure TFrmSearchHold.btnOkClick(Sender: TObject); begin if cdsSearchHold.IsEmpty then MessageDlg('Nenhum pedido foi selecionado.', mtWarning, [mbOK], 0) else if HasService then MessageDlg('Este pedido possui serviço(s) e não pode ser faturado.', mtWarning, [mbOK], 0) else ModalResult := mrOk; end; procedure TFrmSearchHold.cdsSearchHoldAfterOpen(DataSet: TDataSet); begin with cdsSearchHold do try DisableControls; First; while not Eof do begin if HasChange then Delete else Next; end; First; finally EnableControls; end; end; function TFrmSearchHold.HasChange: Boolean; begin with qryHasChange do begin if Active then Close; Parameters.ParamByName('IDPreSale').Value := cdsSearchHoldIDPreSale.AsInteger; Open; Result := FieldByName('TotalChange').AsInteger > 0; Close; end; end; end.
unit uHydrometerType_AE; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,ibase, cxControls, cxContainer, cxEdit, cxTextEdit, StdCtrls, cxLookAndFeelPainters, cxButtons, cxMemo, cxGroupBox, uConsts; type TfrmHydrometerType_AE = class(TForm) NameLabel: TLabel; cxGroupBox1: TcxGroupBox; NameEdit: TcxTextEdit; CalibrLabel: TLabel; CalibrEdit: TcxTextEdit; MeasCalibrLabel: TLabel; MeasCalibrEdit: TcxTextEdit; CapacityLabel: TLabel; CapacityEdit: TcxTextEdit; AccuracyLabel: TLabel; AccuracyEdit: TcxTextEdit; NoteMemo: TcxMemo; NoteLabel: TLabel; FactoryLabel: TLabel; FactoryEdit: TcxTextEdit; OkButton: TcxButton; CancelButton: TcxButton; procedure CancelButtonClick(Sender: TObject); procedure OkButtonClick(Sender: TObject); procedure CalibrEditKeyPress(Sender: TObject; var Key: Char); procedure MeasCalibrEditKeyPress(Sender: TObject; var Key: Char); private PLanguageIndex : byte; procedure FormIniLanguage(); public ID_NAME : int64; DB_Handle : TISC_DB_HANDLE; constructor Create(AOwner:TComponent; LanguageIndex : byte);reintroduce; end; implementation {$R *.dfm} constructor TfrmHydrometerType_AE.Create(AOwner:TComponent; LanguageIndex : byte); begin Screen.Cursor:=crHourGlass; inherited Create(AOwner); PLanguageIndex:= LanguageIndex; FormIniLanguage(); Screen.Cursor:=crDefault; DecimalSeparator := ','; end; procedure TfrmHydrometerType_AE.FormIniLanguage; begin NameLabel.caption := uConsts.bs_name_hydrometer_type[PLanguageIndex]; CalibrLabel.caption := uConsts.bs_caliber_hydrometer[PLanguageIndex]; MeasCalibrLabel.caption := uConsts.bs_id_unit_meas[PLanguageIndex]; CapacityLabel.caption := uConsts.bs_capacity_hydrometer[PLanguageIndex]; AccuracyLabel.caption := uConsts.bs_accuracy_hydrometer[PLanguageIndex]; NoteLabel.caption := uConsts.bs_note_hydrometer[PLanguageIndex]; FactoryLabel.caption := uConsts.bs_factory_hydrometer[PLanguageIndex]; OkButton.Caption := uConsts.bs_Accept[PLanguageIndex]; CancelButton.Caption := uConsts.bs_Cancel[PLanguageIndex]; end; procedure TfrmHydrometerType_AE.CancelButtonClick(Sender: TObject); begin close; end; procedure TfrmHydrometerType_AE.OkButtonClick(Sender: TObject); begin if (NameEdit.text = '') then begin ShowMessage('Необхідно заповнити назву типу водоміра !'); NameEdit.SetFocus; exit; end; if (CalibrEdit.text = '') then begin ShowMessage('Необхідно заповнити одиниці калібр водоміра!'); CalibrEdit.SetFocus; exit; end; if (MeasCalibrEdit.text = '') then begin ShowMessage('Необхідно заповнити одиниці виміру калібру водоміра!'); MeasCalibrEdit.SetFocus; exit; end; if (CapacityEdit.text = '') then begin ShowMessage('Необхідно заповнити розрядність водоміра!'); CapacityEdit.SetFocus; exit; end; if (AccuracyEdit.text = '') then begin ShowMessage('Необхідно заповнити точність водоміра!'); AccuracyEdit.SetFocus; exit; end; if (FactoryEdit.text = '') then begin ShowMessage('Необхідно заповнити виробнкиа водоміра!'); FactoryEdit.SetFocus; exit; end; {if (NoteMemo.text = '') then begin ShowMessage('Необхідно заповнити усі поля!'); NoteMemo.SetFocus; exit; end; } ModalResult:=mrOk; end; procedure TfrmHydrometerType_AE.CalibrEditKeyPress(Sender: TObject; var Key: Char); begin if Key = '.' then Key := DecimalSeparator; if ((Ord(Key) < 48) or (Ord(Key) > 57)) and (Ord(Key) <> 8) and (Ord(Key) <> VK_DELETE) and (Key <> DecimalSeparator) then Key := Chr(0); end; procedure TfrmHydrometerType_AE.MeasCalibrEditKeyPress(Sender: TObject; var Key: Char); begin if ((Ord(Key) < 48) or (Ord(Key) > 57)) and (Ord(Key) <> 8) and (Ord(Key) <> VK_DELETE) then Key := Chr(0); end; end.
unit ContaReceberRepository; interface uses BasicRepository, PessoaVO, System.SysUtils, Generics.Collections, RecebimentoContaVO, RecebimentoContaParcelaVO, RecebimentoContaRecebimentoVO, CartaoRecebimentoVO; type TContaReceberRepository = class(TBasicRepository) class function getPessoaById(idOfPessoa: Integer): TPessoaVO; class procedure RecebimentoContaInserir(Recebimento: TRecebimentoContaVO); class procedure RecebimentoContaParcelaInserir(idOfRecebimentoConta: Integer; ParcelasReceber: TObjectList<TRecebimentoContaParcelaVO>); class procedure RecebimentoContaRecebimentoInserir(idOfRecebimentoConta: Integer; Recementos: TObjectList<TRecebimentoContaRecebimentoVO>); class procedure CartaoRecebimentoInserir(idOfRecebimentoConta: Integer; CartaoRecebimentos: TObjectList<TCartaoRecebimentoVO>); class procedure AtualizarContas(idOfPessoa: Integer); end; implementation { TContaReceberRepository } class procedure TContaReceberRepository.AtualizarContas(idOfPessoa: Integer); var Comando: string; begin Comando:= 'execute procedure conta_recebertoabater(' + IntToStr(idOfPessoa) + ')'; ComandoSQL(Comando); end; class procedure TContaReceberRepository.CartaoRecebimentoInserir( idOfRecebimentoConta: Integer; CartaoRecebimentos: TObjectList<TCartaoRecebimentoVO>); var I: Integer; begin for I := 0 to Pred(CartaoRecebimentos.Count) do begin CartaoRecebimentos.Items[i].IdRecebimentoConta:= idOfRecebimentoConta; Inserir(CartaoRecebimentos.Items[i]); end; end; class function TContaReceberRepository.getPessoaById( idOfPessoa: Integer): TPessoaVO; var Filtro: string; begin Filtro:= 'ID = ' + IntToStr(idOfPessoa); Result:= ConsultarUmObjeto<TPessoaVO>(Filtro,True); end; class procedure TContaReceberRepository.RecebimentoContaInserir( Recebimento: TRecebimentoContaVO); begin Recebimento.Id:= Inserir(Recebimento); end; class procedure TContaReceberRepository.RecebimentoContaParcelaInserir( idOfRecebimentoConta: Integer; ParcelasReceber: TObjectList<TRecebimentoContaParcelaVO>); var I: Integer; begin for I := 0 to Pred(ParcelasReceber.Count) do begin ParcelasReceber.Items[i].IdRecebimentoConta:= idOfRecebimentoConta; Inserir(ParcelasReceber.Items[i]); end; end; class procedure TContaReceberRepository.RecebimentoContaRecebimentoInserir( idOfRecebimentoConta: Integer; Recementos: TObjectList<TRecebimentoContaRecebimentoVO>); var I: Integer; begin for I := 0 to Pred(Recementos.Count) do begin Recementos.Items[i].IdRecebimentoConta:= idOfRecebimentoConta; Inserir(Recementos.Items[i]); end; end; end.
{----------------------------------------------------------------------------- Unit Name: frmFileExplorer Author: Kiriakos Vlahos Purpose: File Explorer Window History: -----------------------------------------------------------------------------} unit frmFileExplorer; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, JvComponent, JvDockControlForm, VirtualTrees, VirtualExplorerTree, VirtualShellUtilities, Menus, frmIDEDockWin, ActnList, VirtualShellHistory, TBX, TB2Item, TB2Dock, TB2Toolbar, JvComponentBase; const WM_EXPLOREHERE = WM_USER + 1000; type TFileExplorerWindow = class(TIDEDockWindow) FileExplorerTree: TVirtualExplorerTree; VirtualShellHistory: TVirtualShellHistory; FileExplorerActions: TActionList; actGoForward: TAction; actGoBack: TAction; actGoUp: TAction; actRefresh: TAction; actEnableFilter: TAction; ExplorerDock: TTBXDock; ExplorerToolbar: TTBXToolbar; TBXItem3: TTBXItem; TBXItem5: TTBXItem; TBXSubmenuItem1: TTBXSubmenuItem; TBXItem6: TTBXItem; TBXItemBack: TTBXSubmenuItem; TBXItemForward: TTBXSubmenuItem; TBXSeparatorItem1: TTBXSeparatorItem; ExplorerPopUp: TTBXPopupMenu; Back1: TTBXItem; About1: TTBXItem; Up1: TTBXItem; N1: TTBXSeparatorItem; BrowsePath: TTBXSubmenuItem; Desktop: TTBXItem; MyComputer: TTBXItem; MyDocuments: TTBXItem; CurrentDirectory: TTBXItem; PythonPath1: TTBXItem; N2: TTBXSeparatorItem; EnableFilter: TTBXItem; ChangeFilter: TTBXItem; N3: TTBXSeparatorItem; Refresh1: TTBXItem; TBXPythonPath: TTBXSubmenuItem; ShellContextPopUp: TPopupMenu; TBSubmenuItem1: TTBXSubmenuItem; ExploreHere: TMenuItem; actSearchPath: TAction; SearchPath1: TMenuItem; TBXSeparatorItem2: TTBXSeparatorItem; TBXItem1: TTBXItem; ActiveScript: TTBXItem; actExploreHere: TAction; actManageFavourites: TAction; actAddToFavourites: TAction; TBXSeparatorItem3: TTBXSeparatorItem; mnFavourites: TTBXSubmenuItem; TBXItem2: TTBXItem; TBXItem7: TTBXItem; TBXSeparatorItem5: TTBXSeparatorItem; N4: TMenuItem; AddToFavourites1: TMenuItem; TBXSeparatorItem6: TTBXSeparatorItem; TBXSubmenuItem2: TTBXSubmenuItem; TBXSubmenuItem3: TTBXSubmenuItem; actNewFolder: TAction; TBXSeparatorItem4: TTBXSeparatorItem; TBXItem8: TTBXItem; N5: TMenuItem; CreateNewFolder1: TMenuItem; TBXItem10: TTBXItem; procedure VirtualShellHistoryChange(Sender: TBaseVirtualShellPersistent; ItemIndex: Integer; ChangeType: TVSHChangeType); procedure FileExplorerTreeKeyPress(Sender: TObject; var Key: Char); procedure ActiveScriptClick(Sender: TObject); procedure FileExplorerTreeEnumFolder( Sender: TCustomVirtualExplorerTree; Namespace: TNamespace; var AllowAsChild: Boolean); procedure DesktopClick(Sender: TObject); procedure MyComputerClick(Sender: TObject); procedure MyDocumentsClick(Sender: TObject); procedure CurrentDirectoryClick(Sender: TObject); procedure ChangeFilterClick(Sender: TObject); procedure FileExplorerTreeDblClick(Sender: TObject); procedure ExploreHereClick(Sender: TObject); procedure actGoBackExecute(Sender: TObject); procedure FileExplorerActionsUpdate(Action: TBasicAction; var Handled: Boolean); procedure actGoForwardExecute(Sender: TObject); procedure actGoUpExecute(Sender: TObject); procedure actRefreshExecute(Sender: TObject); procedure actEnableFilterExecute(Sender: TObject); procedure FormActivate(Sender: TObject); procedure TBXItemBackPopup(Sender: TTBCustomItem; FromLink: Boolean); procedure TBXItemForwardPopup(Sender: TTBCustomItem; FromLink: Boolean); procedure BrowsePathPopup(Sender: TTBCustomItem; FromLink: Boolean); procedure actSearchPathExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actManageFavouritesExecute(Sender: TObject); procedure actAddToFavouritesExecute(Sender: TObject); procedure mnFavouritesPopup(Sender: TTBCustomItem; FromLink: Boolean); procedure actNewFolderExecute(Sender: TObject); private fFavourites: TStringList; { Private declarations } procedure PathItemClick(Sender: TObject); procedure WMExploreHere(var Message: TMessage); message WM_EXPLOREHERE; function GetExplorerPath: string; procedure SetExplorerPath(const Value: string); public { Public declarations } procedure UpdateWindow; property Favourites : TStringList read fFavourites; property ExplorerPath : string read GetExplorerPath write SetExplorerPath; end; var FileExplorerWindow: TFileExplorerWindow; implementation uses frmPyIDEMain, uEditAppIntfs, dmCommands, VarPyth, SHlObj, cFindInFiles, frmFindResults, VirtualPIDLTools, JvDockGlobals, dlgDirectoryList, StringResources, VirtualWideStrings; {$R *.dfm} procedure TFileExplorerWindow.UpdateWindow; begin end; procedure TFileExplorerWindow.FileExplorerTreeEnumFolder( Sender: TCustomVirtualExplorerTree; Namespace: TNamespace; var AllowAsChild: Boolean); Var FileExt: WideString; Begin FileExt := UpperCase(ExtractFileExt(Namespace.NameParseAddress)); if not Namespace.Folder { Don't filter folders } and actEnableFilter.Checked and (Pos(FileExt, UpperCase(CommandsDataModule.PyIDEOptions.FileExplorerFilter)) = 0) then AllowAsChild := False else AllowAsChild := True; end; procedure TFileExplorerWindow.DesktopClick(Sender: TObject); begin FileExplorerTree.RootFolder := rfDeskTop; end; procedure TFileExplorerWindow.MyComputerClick(Sender: TObject); begin FileExplorerTree.RootFolder := rfDrives; end; procedure TFileExplorerWindow.MyDocumentsClick(Sender: TObject); begin FileExplorerTree.RootFolder := rfPersonal; end; procedure TFileExplorerWindow.CurrentDirectoryClick(Sender: TObject); begin FileExplorerTree.RootFolderCustomPath := GetCurrentDir; end; procedure TFileExplorerWindow.ActiveScriptClick(Sender: TObject); var Editor : IEditor; FileName : string; begin Editor := PyIDEMainForm.GetActiveEditor; if Assigned(Editor) then begin FileName := Editor.FileName; if FileName <> '' then FileExplorerTree.RootFolderCustomPath := ExtractFileDir(FileName); end; end; procedure TFileExplorerWindow.ChangeFilterClick(Sender: TObject); begin CommandsDataModule.PyIDEOptions.FileExplorerFilter := InputBox('File Explorer Filter', 'Enter Filter:', CommandsDataModule.PyIDEOptions.FileExplorerFilter); FileExplorerTree.RefreshTree; end; procedure TFileExplorerWindow.PathItemClick(Sender: TObject); begin if Sender is TTBCustomItem then FileExplorerTree.RootFolderCustomPath := TTBCustomItem(Sender).Caption; end; procedure TFileExplorerWindow.FileExplorerTreeDblClick(Sender: TObject); Var NameSpace : TNameSpace; NameSpaceArray : TNameSpaceArray; begin NameSpaceArray := FileExplorerTree.SelectedToNamespaceArray; if Length(NameSpaceArray) > 0 then begin NameSpace := NameSpaceArray[Low(NameSpaceArray)]; if not NameSpace.Folder and NameSpace.FileSystem then PyIDEMainForm.DoOpenFile(NameSpace.NameForParsing); end; end; procedure TFileExplorerWindow.ExploreHereClick(Sender: TObject); Var NameSpaceArray : TNameSpaceArray; begin NameSpaceArray := FileExplorerTree.SelectedToNamespaceArray; if (Length(NameSpaceArray) > 0) and NameSpaceArray[Low(NameSpaceArray)].Folder then begin PostMessage(Handle, WM_EXPLOREHERE, 0, Integer(NameSpaceArray[Low(NameSpaceArray)].AbsolutePIDL)); end; end; procedure TFileExplorerWindow.actSearchPathExecute(Sender: TObject); Var NameSpaceArray : TNameSpaceArray; begin NameSpaceArray := FileExplorerTree.SelectedToNamespaceArray; if (Length(NameSpaceArray) > 0) and NameSpaceArray[Low(NameSpaceArray)].Folder then begin AddMRUString(NameSpaceArray[Low(NameSpaceArray)].NameForParsing, FindInFilesExpert.DirList, True); FindInFilesExpert.GrepSearch := 2; //Directory if Assigned(FindResultsWindow) then FindResultsWindow.Execute(False) end; end; procedure TFileExplorerWindow.WMExploreHere(var Message: TMessage); Var PIDL: PItemIDList; begin PIDL := PItemIDList(Message.LParam); if Assigned(PIDL) then begin FileExplorerTree.RootFolderCustomPIDL := PIDL; //VirtualShellHistory.Clear; end; end; function TFileExplorerWindow.GetExplorerPath: string; begin With FileExplorerTree.RootFolderNamespace do if IsDesktop or IsMyComputer or not FileSystem then Result := '' else Result := NameForParsing; end; procedure TFileExplorerWindow.mnFavouritesPopup(Sender: TTBCustomItem; FromLink: Boolean); var i : integer; Item : TTBXItem; begin while mnFavourites.Count > 3 do mnFavourites.Items[0].Free; if fFavourites.Count = 0 then begin Item := TTBXItem.Create(mnFavourites); Item.Caption := SEmptyList; mnFavourites.Insert(0, Item); end else for i := 0 to fFavourites.Count - 1 do begin Item := TTBXItem.Create(mnFavourites); Item.Caption := fFavourites[i]; Item.OnClick := PathItemClick; mnFavourites.Insert(0, Item); end; end; procedure TFileExplorerWindow.SetExplorerPath(const Value: string); begin try FileExplorerTree.RootFolderCustomPath := Value; except FileExplorerTree.RootFolder := rfDrives; end; //VirtualShellHistory.Clear; end; procedure TFileExplorerWindow.actGoBackExecute(Sender: TObject); begin VirtualShellHistory.Back; end; procedure TFileExplorerWindow.actGoForwardExecute(Sender: TObject); begin VirtualShellHistory.Next; end; procedure TFileExplorerWindow.actGoUpExecute(Sender: TObject); Var PIDL: PItemIDList; begin if FileExplorerTree.RootFolderNamespace.IsDesktop then Exit; // No parent! PIDL := PIDLMgr.CopyPIDL(FileExplorerTree.RootFolderNamespace.AbsolutePIDL); try PIDLMgr.StripLastID(PIDL); FileExplorerTree.RootFolderCustomPIDL := PIDL; finally PIDLMgr.FreePIDL(PIDL); end; end; procedure TFileExplorerWindow.actAddToFavouritesExecute(Sender: TObject); Var NameSpaceArray : TNameSpaceArray; Path : string; begin NameSpaceArray := FileExplorerTree.SelectedToNamespaceArray; if (Length(NameSpaceArray) > 0) and NameSpaceArray[Low(NameSpaceArray)].Folder then begin Path := NameSpaceArray[Low(NameSpaceArray)].NameForParsing; if fFavourites.IndexOf(Path) < 0 then begin fFavourites.Add(Path); // Todo update Favourites Menu end; end; end; procedure TFileExplorerWindow.actEnableFilterExecute(Sender: TObject); begin FileExplorerTree.RefreshTree; end; procedure TFileExplorerWindow.actManageFavouritesExecute(Sender: TObject); begin EditFolderList(fFavourites, 'File Explorer Favourites'); end; procedure TFileExplorerWindow.actNewFolderExecute(Sender: TObject); Var NameSpaceArray : TNameSpaceArray; Node : PVirtualNode; TargetPath : string; begin NameSpaceArray := FileExplorerTree.SelectedToNamespaceArray; if (Length(NameSpaceArray) > 0) and NameSpaceArray[Low(NameSpaceArray)].Folder then begin TargetPath := NameSpaceArray[Low(NameSpaceArray)].NameForParsing + PathDelim + SNewFolder; TargetPath := UniqueDirName(TargetPath); CreateDirectory(PChar(TargetPath), nil); SHChangeNotify(SHCNE_MKDIR, SHCNF_PATH, PChar(TargetPath), nil); FileExplorerTree.RefreshNode(FileExplorerTree.GetFirstSelected); Node := FileExplorerTree.FindNode(TargetPath); if Assigned(Node) then begin FileExplorerTree.ClearSelection; FileExplorerTree.FocusedNode := Node; FileExplorerTree.EditNode(Node, -1); end; end; end; procedure TFileExplorerWindow.actRefreshExecute(Sender: TObject); begin FileExplorerTree.RefreshTree(True); end; procedure TFileExplorerWindow.FileExplorerActionsUpdate( Action: TBasicAction; var Handled: Boolean); Var NameSpaceArray : TNameSpaceArray; begin NameSpaceArray := FileExplorerTree.SelectedToNamespaceArray; actSearchPath.Enabled := (Length(NameSpaceArray) > 0) and NameSpaceArray[Low(NameSpaceArray)].Folder; actAddToFavourites.Enabled := actSearchPath.Enabled; actNewFolder.Enabled := actSearchPath.Enabled; actExploreHere.Enabled := actSearchPath.Enabled; actGoBack.Enabled := VirtualShellHistory.ItemIndex > 0; actGoForward.Enabled := VirtualShellHistory.ItemIndex < VirtualShellHistory.Count-1; end; procedure TFileExplorerWindow.FormActivate(Sender: TObject); begin inherited; if not HasFocus then begin FGPanelEnter(Self); PostMessage(FileExplorerTree.Handle, WM_SETFOCUS, 0, 0); end; end; procedure TFileExplorerWindow.FormCreate(Sender: TObject); begin inherited; fFavourites := TStringList.Create; fFavourites.Duplicates := dupIgnore; fFavourites.Sorted := True; end; procedure TFileExplorerWindow.FormDestroy(Sender: TObject); begin inherited; fFavourites.Free; end; procedure TFileExplorerWindow.TBXItemBackPopup(Sender: TTBCustomItem; FromLink: Boolean); begin VirtualShellHistory.FillPopupMenu_TB2000(TBXItemBack, TTBXItem, fpdNewestToOldest); end; procedure TFileExplorerWindow.TBXItemForwardPopup(Sender: TTBCustomItem; FromLink: Boolean); begin VirtualShellHistory.FillPopupMenu_TB2000(TBXItemForward, TTBXItem, fpdOldestToNewest); end; procedure TFileExplorerWindow.BrowsePathPopup(Sender: TTBCustomItem; FromLink: Boolean); var i : integer; Item : TTBXItem; begin TBXPythonPath.Clear; for i := 0 to Len(SysModule.path) - 1 do begin Item := TTBXItem.Create(TBXPythonPath); Item.Caption := SysModule.path.GetItem(i); Item.OnClick := PathItemClick; TBXPythonPath.Add(Item); end; end; procedure TFileExplorerWindow.FileExplorerTreeKeyPress(Sender: TObject; var Key: Char); begin if Key = Char(VK_Return) then FileExplorerTreeDblClick(Sender); end; procedure TFileExplorerWindow.VirtualShellHistoryChange( Sender: TBaseVirtualShellPersistent; ItemIndex: Integer; ChangeType: TVSHChangeType); begin if not Assigned(VirtualShellHistory.VirtualExplorerTree) then exit; if ChangeType = hctSelected then begin if not ILIsParent(FileExplorerTree.RootFolderNamespace.AbsolutePIDL, VirtualShellHistory.Items[ItemIndex].AbsolutePIDL, False) then begin VirtualShellHistory.VirtualExplorerTree := nil; FileExplorerTree.RootFolderCustomPIDL := VirtualShellHistory.Items[ItemIndex].AbsolutePIDL; VirtualShellHistory.VirtualExplorerTree := FileExplorerTree; end; end; end; end.
{** @abstract(This unit provides a wrapper around the standard fpc dom unit) see TTreeParserDOM *} unit simplexmltreeparserfpdom; { Copyright (C) 2008 - 2012 Benito van der Zander (BeniBela) benito@benibela.de www.benibela.de This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } {$mode objfpc}{$H+} interface uses Classes, SysUtils, simplehtmltreeparser, DOM, XMLRead; type { TTreeParserDOM } {** Base class for TTreeParserDOM *} TTreeParserDOMBase = class(TTreeParser) //** Create a tree document from a standard fpc dom document function import(dom: TDOMDocument): TTreeDocument; //** Reads a tree document from a string, using the standard fpc dom functions to parse it function parseDOM(const document: String; const uri: string = ''): TTreeDocument; //** Loads a tree document from a file, using the standard fpc dom functions to parse it function parseDOMFromFile(const filename: string): TTreeDocument; end; {** This class provides wrapper methods around the standard fpc DOM functions, to convert the TDOMDocument class created by fpc to the TTreeDocument class used by the XQuery engine. *} TTreeParserDOM = class(TTreeParserDOMBase) //** Reads a tree document from a string, using the standard fpc dom functions to parse it function parseTree(html: string; uri: string = ''; contentType: string = ''): TTreeDocument; override; //** Loads a tree document from a file, using the standard fpc dom functions to parse it function parseTreeFromFile(filename: string): TTreeDocument; override; end; EXMLReadError = XMLRead.EXMLReadError; implementation { TTreeParserDOM } function TTreeParserDOMBase.import(dom: TDOMDocument): TTreeDocument; var doc: TTreeDocument; namespaces: TNamespaceList; function getNamespace(const url, prefix: string): INamespace; begin if namespaces.hasNamespacePrefix(prefix, result) then //not tested, but should work like this if result.getURL = url then exit; result := TNamespace.create(url, prefix); namespaces.add(result); end; procedure importNode(parent: TTreeNode; node: TDOMNode); var i: Integer; new: TTreeNode; nscount: Integer; begin nscount := namespaces.Count; if node is TDOMElement then begin new := TTreeNode.createElementPair(UTF8Encode(node.NodeName)); if node.HasAttributes then for i := 0 to node.Attributes.Length - 1 do begin new.addAttribute(UTF8Encode(node.Attributes[i].NodeName), UTF8Encode(node.Attributes[i].NodeValue)); if node.Attributes[i].NamespaceURI <> '' then new.attributes.Items[new.attributes.count - 1].namespace := getNamespace(UTF8Encode(node.Attributes[i].NamespaceURI), UTF8Encode(node.Attributes[i].Prefix)); end; for i := 0 to node.ChildNodes.Count - 1 do importNode(new, node.ChildNodes[i]); end else begin if (node is TDOMText) or (node is TDOMCDATASection) then new := TTreeNode.create(tetText, UTF8Encode(node.NodeValue)) else if node is TDOMComment then new := TTreeNode.create(tetComment, UTF8Encode(node.NodeValue)) else if node is TDOMProcessingInstruction then begin new := TTreeNode.create(tetProcessingInstruction, UTF8Encode(node.NodeName)); new.addAttribute('', UTF8Encode(node.NodeValue)); end else exit; end; if node.NamespaceURI <> '' then new.namespace := getNamespace(UTF8Encode(node.NamespaceURI), UTF8Encode(node.Prefix)); parent.addChild(new); namespaces.DeleteFrom(nscount); end; var i: Integer; temp: TTreeNode; offset: Integer; a: TTreeAttribute; begin namespaces:= TNamespaceList.Create; doc := TTreeDocument.create(self); doc.baseURI:=dom.baseURI; doc.documentURI:=dom.baseURI; doc.document := doc; doc.reverse := TTreeNode.create(tetClose); doc.reverse.reverse := doc; doc.next := doc.reverse; doc.next.previous := doc; doc.reverse.document := doc; for i := 0 to dom.ChildNodes.Count - 1 do importNode(doc, dom.ChildNodes[i]); temp := doc; offset := 1; while temp <> nil do begin temp.offset := offset; offset += 1; if temp.attributes <> nil then begin for a in temp.attributes do begin a.offset := offset; offset += 1; end; end; temp := temp.next; end; FTrees.Add(doc); FCurrentTree := doc; namespaces.free; result := doc; end; function TTreeParserDOMBase.parseDOM(const document: String; const uri: string): TTreeDocument; var temp: TXMLDocument; stringStream: TStringStream; begin stringStream := TStringStream.Create(document); ReadXMLFile(temp, stringStream); result := import(temp); result.baseURI:=uri; result.documentURI:=uri; stringStream.Free; temp.Free; end; function TTreeParserDOMBase.parseDOMFromFile(const filename: string): TTreeDocument; var temp: TXMLDocument; begin ReadXMLFile(temp, filename); result := import(temp); temp.Free; end; function TTreeParserDOM.parseTree(html: string; uri: string; contentType: string): TTreeDocument; begin Result:=parseDOM(html, uri); end; function TTreeParserDOM.parseTreeFromFile(filename: string): TTreeDocument; begin Result:=parseDOMFromFile(filename); end; end.
unit uFrmLog; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, DBClient, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit, StdCtrls, ExtCtrls, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid, cxLookAndFeelPainters, cxButtons; type TFrmLog = class(TForm) dsLog: TDataSource; grdLogDBTableView: TcxGridDBTableView; grdLogLevel: TcxGridLevel; grdLog: TcxGrid; pnlTop: TPanel; pnlBottom: TPanel; cbxLogFile: TcxComboBox; cdsLogs: TClientDataSet; cdsLogsID: TIntegerField; cdsLogsMsgError: TStringField; cdsLogsDateTime: TDateTimeField; grdLogDBTableViewID: TcxGridDBColumn; grdLogDBTableViewMsgError: TcxGridDBColumn; grdLogDBTableViewDateTime: TcxGridDBColumn; lblLog: TLabel; btnClose: TcxButton; btnEmail: TcxButton; procedure cbxLogFilePropertiesChange(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnEmailClick(Sender: TObject); private procedure LoadLogFile; public { Public declarations } end; var FrmLog: TFrmLog; implementation uses uDM; {$R *.dfm} procedure TFrmLog.cbxLogFilePropertiesChange(Sender: TObject); begin LoadLogFile; end; procedure TFrmLog.LoadLogFile; begin if cdsLogs.Active then cdsLogs.Close; cdsLogs.LoadFromFile(Application.GetNamePath + cbxLogFile.Text); end; procedure TFrmLog.btnCloseClick(Sender: TObject); begin Close; end; procedure TFrmLog.FormShow(Sender: TObject); var iReturn: Integer; SearchRec: TSearchRec; begin cbxLogFile.Properties.Items.Clear; iReturn := FindFirst(Application.GetNamePath + '*.xml', faAnyFile, SearchRec); try while iReturn = 0 do begin cbxLogFile.Properties.Items.Add(SearchRec.Name); iReturn := FindNext(SearchRec); end; finally FindClose(SearchRec); end; if DM.FLastLogFileName <> '' then cbxLogFile.Text := DM.FLastLogFileName; end; procedure TFrmLog.btnEmailClick(Sender: TObject); begin if cbxLogFile.Text <> '' then DM.SendEmailLogText(DM.ECommerceInfo.FURL, 'Log de erro', Application.GetNamePath + cbxLogFile.Text); end; end.
unit uPochasDisAdd; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, uSpravControl, uDateControl, uFControl, uLabeledFControl, uCharControl, uIntControl, uFormControl, uInvisControl, uBoolControl, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, FIBDataSet, pFIBDataSet, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, uMemoControl; type TfrmAddPochasDis = class(TForm) GroupBox1: TGroupBox; DateDismission: TqFDateControl; DismissionReason: TqFCharControl; NameDismission: TqFSpravControl; cbAll: TqFBoolControl; btnOk: TBitBtn; btnCancel: TBitBtn; NoteEdit: TqFMemoControl; ManEdit: TqFSpravControl; procedure NameDismissionOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: string); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure ManEditOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: string); private { Private declarations } public { Public declarations } end; implementation uses uCommonSp, uPochasDis, qfTools, uSelPochas; {$R *.dfm} procedure TfrmAddPochasDis.NameDismissionOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: string); var sp: TSprav; begin // создать справочник sp := GetSprav('asup\SpDismission'); if sp <> nil then begin // заполнить входные параметры sp.Input.Append; sp.Input.FieldValues['DBHandle'] := Integer(TfrmPochasDisOrder(owner).Database.Handle); sp.Input.FieldValues['FormStyle'] := fsNormal; sp.Input.Post; // показать справочник и проанализировать результат (выбор одного подр.) sp.Show; if (sp.Output <> nil) and not sp.Output.IsEmpty then begin Value := sp.Output['Id_Dismission']; DisplayText := sp.Output['Name_Dismission']; if not VarIsNull(sp.Output['Kzot_St']) then DisplayText := DisplayText + ' ' + sp.Output['Kzot_St']; end; sp.Free; end; end; procedure TfrmAddPochasDis.FormCreate(Sender: TObject); begin DateDismission.Value := date; end; procedure TfrmAddPochasDis.FormShow(Sender: TObject); begin DismissionReason.SetFocus; end; procedure TfrmAddPochasDis.btnOkClick(Sender: TObject); begin if TfrmPochasDisOrder(Owner).Input['mode'] = 3 then Close; if qFCheckAll(Self) then ModalResult := mrOk; end; procedure TfrmAddPochasDis.ManEditOpenSprav(Sender: TObject; var Value: Variant; var DisplayText: string); var frm: TSelPochasForm; begin try frm := TSelPochasForm.Create(self); frm.date_search := DateDismission.Value; frm.DSetPochas.Close; frm.DSetPochas.SQLs.SelectSQL.Text := 'select * from UP_DT_POCHAS_PLAN_S(:IN_DATE)'; frm.DSetPochas.parambyname('IN_DATE').AsDate := frm.date_search; frm.DSetPochas.Open; except on e: exception do showmessage(e.message); end; if frm.ShowModal = mrOk then begin Value := frm.DSetPochas['ID_POCHAS_PLAN']; if VarIsNull(frm.DSetPochas['NUM_ORDER']) then DisplayText := frm.DSetPochas['FIO'] else DisplayText := '№ ' + frm.DSetPochas['NUM_ORDER'] + ', ' + frm.DSetPochas['FIO']; end; frm.DSetPochas.Close; frm.Free; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLBaseMeshSilhouette<p> Silhouette classes for GLBaseMesh and FaceGroups.<p> <b>History : </b><font size=-1><ul> <li>30/03/07 - DaStr - Added $I GLScene.inc <li>25/03/07 - DaStr - Renamed parameters in some methods (thanks Burkhard Carstens) (Bugtracker ID = 1678658) <li>23/03/07 - DaStr - Added explicit pointer dereferencing (thanks Burkhard Carstens) (Bugtracker ID = 1678644) <li>09/02/04 - MF - Fixed bug where vertices weren't freed when owned <li>24/06/03 - MF - Created file from parts of GLShilouette </ul></font> } unit GLBaseMeshSilhouette; interface {$I GLScene.inc} uses Classes, GLVectorGeometry, GLVectorLists, GLVectorFileObjects, GLSilhouette; type // TFaceGroupConnectivity // TFaceGroupConnectivity = class(TConnectivity) private FMeshObject : TMeshObject; FOwnsVertices : boolean; procedure SetMeshObject(const Value: TMeshObject); public procedure Clear; override; {: Builds the connectivity information. } procedure RebuildEdgeList; property MeshObject : TMeshObject read FMeshObject write SetMeshObject; constructor Create(APrecomputeFaceNormal : boolean); override; constructor CreateFromMesh(aMeshObject : TMeshObject; APrecomputeFaceNormal : Boolean); destructor Destroy; override; end; // TGLBaseMeshConnectivity // TGLBaseMeshConnectivity = class(TBaseConnectivity) private FGLBaseMesh : TGLBaseMesh; FFaceGroupConnectivityList : TList; function GetFaceGroupConnectivity(i: integer): TFaceGroupConnectivity; function GetConnectivityCount: integer; procedure SetGLBaseMesh(const Value: TGLBaseMesh); protected function GetEdgeCount: integer; override; function GetFaceCount: integer; override; public property ConnectivityCount : integer read GetConnectivityCount; property FaceGroupConnectivity[i : integer] : TFaceGroupConnectivity read GetFaceGroupConnectivity; property GLBaseMesh : TGLBaseMesh read FGLBaseMesh write SetGLBaseMesh; procedure Clear(SaveFaceGroupConnectivity : boolean); {: Builds the connectivity information. } procedure RebuildEdgeList; procedure CreateSilhouette(const silhouetteParameters : TGLSilhouetteParameters; var aSilhouette : TGLSilhouette; AddToSilhouette : boolean); override; constructor Create(APrecomputeFaceNormal : boolean); override; constructor CreateFromMesh(aGLBaseMesh : TGLBaseMesh); destructor Destroy; override; end; implementation { TFaceGroupConnectivity } // ------------------ // ------------------ TFaceGroupConnectivity ------------------ // ------------------ procedure TFaceGroupConnectivity.Clear; begin if Assigned(FVertices) then begin if FOwnsVertices then FVertices.Clear else FVertices := nil; inherited; if not FOwnsVertices and Assigned(FMeshObject) then FVertices := FMeshObject.Vertices; end else inherited; end; constructor TFaceGroupConnectivity.Create(APrecomputeFaceNormal: boolean); begin inherited; FOwnsVertices := true; end; procedure TFaceGroupConnectivity.SetMeshObject(const Value: TMeshObject); begin Clear; FMeshObject := Value; if FOwnsVertices then FVertices.Free; FVertices := FMeshObject.Vertices; FOwnsVertices := false; RebuildEdgeList; end; constructor TFaceGroupConnectivity.CreateFromMesh(aMeshObject: TMeshObject; APrecomputeFaceNormal: boolean); begin Create(APrecomputeFaceNormal); MeshObject := aMeshObject; end; destructor TFaceGroupConnectivity.Destroy; begin if FOwnsVertices then FVertices.Free; FVertices := nil; inherited; end; procedure TFaceGroupConnectivity.RebuildEdgeList; var iFaceGroup, iFace, iVertex : integer; FaceGroup : TFGVertexIndexList; List : PIntegerArray; begin // Make sure that the connectivity information is empty Clear; // Create a list of edges for the meshobject for iFaceGroup := 0 to FMeshObject.FaceGroups.Count-1 do begin Assert(FMeshObject.FaceGroups[iFaceGroup] is TFGVertexIndexList, 'Method only works for descendants of TFGVertexIndexList.'); FaceGroup := TFGVertexIndexList(FMeshObject.FaceGroups[iFaceGroup]); case FaceGroup.Mode of fgmmTriangles, fgmmFlatTriangles : begin for iFace := 0 to FaceGroup.TriangleCount - 1 do begin List := @FaceGroup.VertexIndices.List[iFace * 3 + 0]; AddIndexedFace(List^[0], List^[1], List^[2]); end; end; fgmmTriangleStrip : begin for iFace:=0 to FaceGroup.VertexIndices.Count-3 do begin List := @FaceGroup.VertexIndices.List[iFace]; if (iFace and 1)=0 then AddIndexedFace(List^[0], List^[1], List^[2]) else AddIndexedFace(List^[2], List^[1], List^[0]); end; end; fgmmTriangleFan : begin List := FaceGroup.VertexIndices.List; for iVertex:=2 to FaceGroup.VertexIndices.Count-1 do AddIndexedFace(List^[0], List^[iVertex-1], List^[iVertex]) end; else Assert(false,'Not supported'); end; end; end; // ------------------ // ------------------ TGLBaseMeshConnectivity ------------------ // ------------------ procedure TGLBaseMeshConnectivity.RebuildEdgeList; var i : integer; begin for i := 0 to ConnectivityCount - 1 do FaceGroupConnectivity[i].RebuildEdgeList; end; procedure TGLBaseMeshConnectivity.Clear(SaveFaceGroupConnectivity : boolean); var i : integer; begin if SaveFaceGroupConnectivity then begin for i := 0 to ConnectivityCount - 1 do FaceGroupConnectivity[i].Clear; end else begin for i := 0 to ConnectivityCount - 1 do FaceGroupConnectivity[i].Free; FFaceGroupConnectivityList.Clear; end; end; constructor TGLBaseMeshConnectivity.Create(APrecomputeFaceNormal: boolean); begin FFaceGroupConnectivityList := TList.Create; inherited; end; constructor TGLBaseMeshConnectivity.CreateFromMesh(aGLBaseMesh: TGLBaseMesh); begin Create(not (aGLBaseMesh is TGLActor)); GLBaseMesh := aGLBaseMesh; end; procedure TGLBaseMeshConnectivity.SetGLBaseMesh(const Value: TGLBaseMesh); var i : integer; MO : TMeshObject; Connectivity : TFaceGroupConnectivity; begin Clear(False); FGLBaseMesh := Value; // Only precompute normals if the basemesh isn't an actor (because they change) FPrecomputeFaceNormal := not (Value is TGLActor); FGLBaseMesh := Value; for i := 0 to Value.MeshObjects.Count-1 do begin MO := Value.MeshObjects[i]; Connectivity := TFaceGroupConnectivity.CreateFromMesh(MO, FPrecomputeFaceNormal); FFaceGroupConnectivityList.Add(Connectivity); end; end; procedure TGLBaseMeshConnectivity.CreateSilhouette( const silhouetteParameters : TGLSilhouetteParameters; var aSilhouette : TGLSilhouette; AddToSilhouette : boolean); var i : integer; begin if aSilhouette=nil then aSilhouette:=TGLSilhouette.Create else aSilhouette.Flush; for i := 0 to ConnectivityCount-1 do FaceGroupConnectivity[i].CreateSilhouette(silhouetteParameters, aSilhouette, true); end; destructor TGLBaseMeshConnectivity.Destroy; begin Clear(false); FFaceGroupConnectivityList.Free; inherited; end; function TGLBaseMeshConnectivity.GetConnectivityCount: integer; begin result := FFaceGroupConnectivityList.Count; end; function TGLBaseMeshConnectivity.GetEdgeCount: integer; var i : integer; begin result := 0; for i := 0 to ConnectivityCount - 1 do result := result + FaceGroupConnectivity[i].EdgeCount; end; function TGLBaseMeshConnectivity.GetFaceCount: integer; var i : integer; begin result := 0; for i := 0 to ConnectivityCount - 1 do result := result + FaceGroupConnectivity[i].FaceCount; end; function TGLBaseMeshConnectivity.GetFaceGroupConnectivity( i: integer): TFaceGroupConnectivity; begin result := TFaceGroupConnectivity(FFaceGroupConnectivityList[i]); end; end.
unit ExplicitConvertOpTest; interface uses DUnitX.TestFramework, Math, SysUtils, uIntXLibTypes, uIntX; type [TestFixture] TExplicitConvertOpTest = class(TObject) public [Test] procedure ConvertToInteger(); [Test] procedure ConvertToUInt32(); [Test] procedure ConvertToInt64(); [Test] procedure ConvertToUInt64(); [Test] procedure ConvertToDouble(); [Test] procedure ConvertToWord(); procedure ConvertNullToInteger(); [Test] procedure CallConvertNullToInteger(); procedure ConvertNullToUInt32(); [Test] procedure CallConvertNullToUInt32(); procedure ConvertNullToInt64(); [Test] procedure CallConvertNullToInt64(); procedure ConvertNullToUInt64(); [Test] procedure CallConvertNullToUInt64(); procedure ConvertNullToWord(); [Test] procedure CallConvertNullToWord(); procedure ConvertNullToDouble(); [Test] procedure CallConvertNullToDouble(); end; implementation [Test] procedure TExplicitConvertOpTest.ConvertToInteger(); var temp: TIntXLibUInt32Array; n: Integer; IntX: TIntX; un: UInt32; begin n := 1234567890; IntX := n; Assert.AreEqual(n, Integer(IntX)); n := -n; IntX := n; Assert.AreEqual(n, Integer(IntX)); n := 0; IntX := n; Assert.AreEqual(n, Integer(IntX)); n := 1234567890; un := UInt32(n); SetLength(temp, 3); temp[0] := un; temp[1] := un; temp[2] := un; IntX := TIntX.Create(temp, False); Assert.AreEqual(n, Integer(IntX)); IntX := TIntX.Create(temp, True); Assert.AreEqual(-n, Integer(IntX)); end; [Test] procedure TExplicitConvertOpTest.ConvertToUInt32(); var temp: TIntXLibUInt32Array; IntX: TIntX; n: UInt32; begin n := 1234567890; IntX := n; Assert.AreEqual(n, UInt32(IntX)); n := 0; IntX := n; Assert.AreEqual(n, UInt32(IntX)); n := 1234567890; SetLength(temp, 3); temp[0] := n; temp[1] := n; temp[2] := n; IntX := TIntX.Create(temp, False); Assert.AreEqual(n, UInt32(IntX)); end; procedure TExplicitConvertOpTest.ConvertToInt64(); var temp: TIntXLibUInt32Array; IntX: TIntX; n: Int64; un: UInt32; ni: Integer; begin n := 1234567890123456789; IntX := n; Assert.AreEqual(n, Int64(IntX)); n := -n; IntX := n; Assert.AreEqual(n, Int64(IntX)); n := 0; IntX := n; Assert.AreEqual(n, Int64(IntX)); un := 1234567890; n := Int64((un or UInt64(un) shl 32)); SetLength(temp, 5); temp[0] := un; temp[1] := un; temp[2] := un; temp[3] := un; temp[4] := un; IntX := TIntX.Create(temp, False); Assert.AreEqual(n, Int64(IntX)); IntX := TIntX.Create(temp, True); Assert.AreEqual(-n, Int64(IntX)); ni := 1234567890; n := ni; IntX := ni; Assert.AreEqual(n, Int64(IntX)); end; [Test] procedure TExplicitConvertOpTest.ConvertToUInt64(); var temp: TIntXLibUInt32Array; IntX: TIntX; n: UInt64; un: UInt32; begin n := 1234567890123456789; IntX := n; Assert.AreEqual(n, UInt64(IntX)); n := 0; IntX := n; Assert.AreEqual(n, UInt64(IntX)); un := 1234567890; n := un or UInt64(un) shl 32; SetLength(temp, 5); temp[0] := un; temp[1] := un; temp[2] := un; temp[3] := un; temp[4] := un; IntX := TIntX.Create(temp, False); Assert.AreEqual(n, UInt64(IntX)); n := un; IntX := un; Assert.AreEqual(n, UInt64(IntX)); end; [Test] procedure TExplicitConvertOpTest.ConvertToDouble; var IntX: TIntX; d: Double; begin d := 1.7976931348623157E+308; IntX := TIntX.Create(d); Assert.AreEqual ('17976931348623157081452742373170435679807056752584499659891747680315726078002853876058955863276687817154045895351438246423432132688946418276846754670353751' + '6986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368', IntX.ToString()); d := Double(IntX); Assert.AreEqual('1.79769313486232E308', FloatToStr(d)); d := -1.7976931348623157E+308; IntX := TIntX.Create(d); Assert.AreEqual ('-17976931348623157081452742373170435679807056752584499659891747680315726078002853876058955863276687817154045895351438246423432132688946418276846754670353751' + '6986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368', IntX.ToString()); d := Double(IntX); Assert.AreEqual('-1.79769313486232E308', FloatToStr(d)); d := 1.7976931348623157E+308; IntX := TIntX.Create(d) + TIntX.Create(d); d := Double(IntX); Assert.IsTrue(d = Infinity); d := -1.7976931348623157E+308; IntX := TIntX.Create(d) + TIntX.Create(d); d := Double(IntX); Assert.IsTrue(d = NegInfinity); IntX := TIntX.Create(0); d := Double(IntX); Assert.IsTrue(d = 0); d := 9007199254740993; IntX := TIntX.Create(d); d := Double(IntX); Assert.IsTrue(d = 9007199254740992); end; [Test] procedure TExplicitConvertOpTest.ConvertToWord(); var n: Word; IntX: TIntX; begin n := 12345; IntX := n; Assert.AreEqual(n, Word(IntX)); n := 0; IntX := n; Assert.AreEqual(n, Word(IntX)); end; procedure TExplicitConvertOpTest.ConvertNullToInteger(); begin Integer(TIntX(Default (TIntX))); end; [Test] procedure TExplicitConvertOpTest.CallConvertNullToInteger(); var TempMethod: TTestLocalMethod; begin TempMethod := ConvertNullToInteger; Assert.WillRaise(TempMethod, EArgumentNilException); end; procedure TExplicitConvertOpTest.ConvertNullToUInt32(); begin UInt32(TIntX(Default (TIntX))); end; [Test] procedure TExplicitConvertOpTest.CallConvertNullToUInt32(); var TempMethod: TTestLocalMethod; begin TempMethod := ConvertNullToUInt32; Assert.WillRaise(TempMethod, EArgumentNilException); end; procedure TExplicitConvertOpTest.ConvertNullToInt64(); begin Int64(TIntX(Default (TIntX))); end; [Test] procedure TExplicitConvertOpTest.CallConvertNullToInt64(); var TempMethod: TTestLocalMethod; begin TempMethod := ConvertNullToInt64; Assert.WillRaise(TempMethod, EArgumentNilException); end; procedure TExplicitConvertOpTest.ConvertNullToUInt64(); begin UInt64(TIntX(Default (TIntX))); end; [Test] procedure TExplicitConvertOpTest.CallConvertNullToUInt64(); var TempMethod: TTestLocalMethod; begin TempMethod := ConvertNullToUInt64; Assert.WillRaise(TempMethod, EArgumentNilException); end; procedure TExplicitConvertOpTest.ConvertNullToWord(); begin Word(TIntX(Default (TIntX))); end; [Test] procedure TExplicitConvertOpTest.CallConvertNullToWord(); var TempMethod: TTestLocalMethod; begin TempMethod := ConvertNullToWord; Assert.WillRaise(TempMethod, EArgumentNilException); end; procedure TExplicitConvertOpTest.ConvertNullToDouble(); begin Double(TIntX(Default (TIntX))); end; [Test] procedure TExplicitConvertOpTest.CallConvertNullToDouble(); var TempMethod: TTestLocalMethod; begin TempMethod := ConvertNullToDouble; Assert.WillRaise(TempMethod, EArgumentNilException); end; initialization TDUnitX.RegisterTestFixture(TExplicitConvertOpTest); end.
unit uFrameParents; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxTextEdit, cxContainer, cxEdit, cxLabel, cxControls, cxGroupBox, cxMaskEdit,uPrK_Resources; type TFrameParents = class(TFrame) cxGroupBoxOtec: TcxGroupBox; cxLabelOtecMestoRaboti: TcxLabel; cxTextEditOtecMestoRaboti: TcxTextEdit; cxLabelOtecDoljnost: TcxLabel; cxTextEditOtecDoljnost: TcxTextEdit; cxGroupBoxMother: TcxGroupBox; cxLabelOtecFam: TcxLabel; cxTextEditOtecFam: TcxTextEdit; cxLabelOtecName: TcxLabel; cxTextEditOtecName: TcxTextEdit; cxLabelOtecOtch: TcxLabel; cxTextEditOtecOtch: TcxTextEdit; cxMaskEditOtecTel: TcxMaskEdit; cxLabelOtecTel: TcxLabel; cxLabelMotherFam: TcxLabel; cxTextEditMotherFam: TcxTextEdit; cxLabelMotherName: TcxLabel; cxTextEditMotherName: TcxTextEdit; cxLabelMotherOtch: TcxLabel; cxTextEditMotherOtch: TcxTextEdit; cxLabelMotherMestoRaboti: TcxLabel; cxTextEditMotherMestoRaboti: TcxTextEdit; cxLabelMotherDoljnost: TcxLabel; cxTextEditMotherDoljnost: TcxTextEdit; cxLabelMotherTel: TcxLabel; cxMaskEditMotherTel: TcxMaskEdit; private public procedure InicCaptionFrame; procedure InicDataFrame(rejim :RejimPrK); end; implementation uses uPRK_DT_ABIT,uConstants; {$R *.dfm} { TFrameParents } procedure TFrameParents.InicCaptionFrame; var i: integer; begin i:=TFormPRK_DT_ABIT(self.Owner).IndLangAbit; cxGroupBoxOtec.Caption :=ncxGroupBoxOtec[i]; cxLabelOtecFam.Caption :=nLabelParentFam[i]; cxLabelOtecName.Caption :=nLabelParentName[i]; cxLabelOtecOtch.Caption :=nLabelParentOtch[i]; cxLabelOtecMestoRaboti.Caption :=nLabelParentMestoRaboti[i]; cxLabelOtecDoljnost.Caption :=nLabelParentDoljnost[i]; cxLabelOtecTel.Caption :=nLabelParentTel[i]; cxGroupBoxMother.Caption :=ncxGroupBoxMother[i]; cxLabelMotherFam.Caption :=nLabelParentFam[i]; cxLabelMotherName.Caption :=nLabelParentName[i]; cxLabelMotherOtch.Caption :=nLabelParentOtch[i]; cxLabelMotherMestoRaboti.Caption :=nLabelParentMestoRaboti[i]; cxLabelMotherDoljnost.Caption :=nLabelParentDoljnost[i]; cxLabelMotherTel.Caption :=nLabelParentTel[i]; cxTextEditOtecFam.Text :=''; cxTextEditOtecName.Text :=''; cxTextEditOtecOtch.Text :=''; cxTextEditOtecMestoRaboti.Text :=''; cxTextEditOtecDoljnost.Text :=''; cxTextEditMotherFam.Text :=''; cxTextEditMotherName.Text :=''; cxTextEditMotherOtch.Text :=''; cxTextEditMotherMestoRaboti.Text :=''; cxTextEditMotherDoljnost.Text :=''; end; procedure TFrameParents.InicDataFrame(rejim: RejimPrK); begin if TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['O_FAMILIA']<>Null then cxTextEditOtecFam.Text :=TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['O_FAMILIA']; if TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['O_IMYA']<>Null then cxTextEditOtecName.Text :=TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['O_IMYA']; if TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['O_OTCHESTVO']<>Null then cxTextEditOtecOtch.Text :=TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['O_OTCHESTVO']; if TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['O_MEST_RAB']<>Null then cxTextEditOtecMestoRaboti.Text :=TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['O_MEST_RAB']; if TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['O_DOLGN_RAB']<>Null then cxTextEditOtecDoljnost.Text :=TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['O_DOLGN_RAB']; if TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['O_PHONE']<>Null then cxMaskEditOtecTel.Text :=TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['O_PHONE']; if TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['M_FAMILIA']<>Null then cxTextEditMotherFam.Text :=TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['M_FAMILIA']; if TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['M_IMYA']<>Null then cxTextEditMotherName.Text :=TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['M_IMYA']; if TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['M_OTCHESTVO']<>Null then cxTextEditMotherOtch.Text :=TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['M_OTCHESTVO']; if TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['M_MEST_RAB']<>Null then cxTextEditMotherMestoRaboti.Text :=TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['M_MEST_RAB']; if TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['M_DOLGN_RAB']<>Null then cxTextEditMotherDoljnost.Text :=TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['M_DOLGN_RAB']; if TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['M_PHONE']<>Null then cxMaskEditMotherTel.Text :=TFormPRK_DT_ABIT(self.Owner).DataSetFizlAbit.FieldValues['M_PHONE']; if rejim=ViewPrK then begin cxTextEditOtecFam.Properties.ReadOnly :=true; cxTextEditOtecName.Properties.ReadOnly :=true; cxTextEditOtecOtch.Properties.ReadOnly :=true; cxTextEditOtecMestoRaboti.Properties.ReadOnly :=true; cxTextEditOtecDoljnost.Properties.ReadOnly :=true; cxMaskEditOtecTel.Properties.ReadOnly :=true; cxTextEditMotherFam.Properties.ReadOnly :=true; cxTextEditMotherName.Properties.ReadOnly :=true; cxTextEditMotherOtch.Properties.ReadOnly :=true; cxTextEditMotherMestoRaboti.Properties.ReadOnly :=true; cxTextEditMotherDoljnost.Properties.ReadOnly :=true; cxMaskEditMotherTel.Properties.ReadOnly :=true; cxTextEditOtecFam.Style.Color :=TFormPRK_DT_ABIT(self.Owner).TextViewColor; cxTextEditOtecName.Style.Color :=TFormPRK_DT_ABIT(self.Owner).TextViewColor; cxTextEditOtecOtch.Style.Color :=TFormPRK_DT_ABIT(self.Owner).TextViewColor; cxTextEditOtecMestoRaboti.Style.Color :=TFormPRK_DT_ABIT(self.Owner).TextViewColor; cxTextEditOtecDoljnost.Style.Color :=TFormPRK_DT_ABIT(self.Owner).TextViewColor; cxMaskEditOtecTel.Style.Color :=TFormPRK_DT_ABIT(self.Owner).TextViewColor; cxTextEditMotherFam.Style.Color :=TFormPRK_DT_ABIT(self.Owner).TextViewColor; cxTextEditMotherName.Style.Color :=TFormPRK_DT_ABIT(self.Owner).TextViewColor; cxTextEditMotherOtch.Style.Color :=TFormPRK_DT_ABIT(self.Owner).TextViewColor; cxTextEditMotherMestoRaboti.Style.Color :=TFormPRK_DT_ABIT(self.Owner).TextViewColor; cxTextEditMotherDoljnost.Style.Color :=TFormPRK_DT_ABIT(self.Owner).TextViewColor; cxMaskEditMotherTel.Style.Color :=TFormPRK_DT_ABIT(self.Owner).TextViewColor; end; end; end.
unit FFoundFile; (*==================================================================== MDI window with found files ======================================================================*) interface uses SysUtils, {$ifdef mswindows} WinTypes,WinProcs, {$ELSE} LCLIntf, LCLType, LMessages, {$ENDIF} Messages, Classes, Graphics, Controls, Forms, Dialogs, Grids, Menus, PrintersDlgs, UTypes, UApiTypes, UCollections, FSettings, FMain, {FDBase,} UStringList; type TOneFLine = class // class for one found file (=line) POneFile : TPOneFile; Disk : TPQString; Dir : TPQString; ShortDesc: TPQString; Id : longint; ExtAttr : byte; constructor Create(aOneFile: TOneFile; var aDisk, aDir, aShortDesc: ShortString; aID: longint; AExtAttr: byte); destructor Destroy; override; end; { TFormFoundFileList } TFormFoundFileList = class(TForm) DrawGrid: TDrawGrid; MenuItem1: TMenuItem; MenuItem2: TMenuItem; PopupMenu: TPopupMenu; MenuGoTo: TMenuItem; MenuPrint: TMenuItem; MenuHelp: TMenuItem; MenuCopy: TMenuItem; MenuSelectAll: TMenuItem; N1: TMenuItem; MenuUnselectAll: TMenuItem; N2: TMenuItem; PrintDialog: TPrintDialog; ///PrintDialog: TPrintDialog; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormCreate(Sender: TObject); procedure DrawGridDrawCell(Sender: TObject; Col, Row: Longint; Rect: TRect; State: TGridDrawState); procedure FormDestroy(Sender: TObject); procedure DrawGridMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DrawGridDblClick(Sender: TObject); procedure MenuGoToClick(Sender: TObject); procedure MenuItem2Click(Sender: TObject); procedure MenuPrintClick(Sender: TObject); procedure MenuHelpClick(Sender: TObject); procedure DrawGridSelectCell(Sender: TObject; Col, Row: Longint; var CanSelect: Boolean); procedure DrawGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure MenuCopyClick(Sender: TObject); procedure MenuSelectAllClick(Sender: TObject); procedure MenuUnselectAllClick(Sender: TObject); procedure DrawGridMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); private ///FoundList : TQStringList; FoundList : TStringList; TimeWidth : Integer; SortArr : TSortArr; NeedReSort : boolean; {if SortArr changes, resort in idle time} ReversedSort : boolean; CanDraw : boolean; FormIsClosed : boolean; LastFileSelected : Integer; MakeSelection : boolean; MaxFileNameLength : Integer; {max. delka jmena v akt. seznamu} MaxFileNamePxLength: Integer; LastMouseMoveTime : longint; FilesHintDisplayed : boolean; LastMouseXFiles : integer; LastMouseYFiles : integer; LastHintRect : TRect; DisableHints : integer; DisableNextDoubleClick: boolean; MousePosAlreadyChecked: boolean; function GetSortString(OneLine: TOneFLine): ShortString; procedure ResortFoundList; procedure ResetFontAndSize; procedure SetFileColWidth; procedure ShowFileHint; procedure EraseFileHint; function FindOneLine(Point: TPoint; var Rect: TRect): TOneFLine; public QGlobalOptions: TGlobalOptions; ///DBaseWindow: TFormDBase; DBaseWindow: TMainForm; procedure GetList(DBaseHandle: PDBaseHandle); procedure LocalIdle; procedure LocalTimer; procedure SetNeedResort(Sort: TSort); procedure ChangeGlobalOptions; procedure SelectAll; procedure UnselectAll; procedure MakeCopy; procedure MakePrint; procedure ExportToOtherFormat; end; //--------------------------------------------------------------------------- implementation uses Clipbrd, {Printers,} UExceptions, UApi, UBaseUtils, FFindFileDlg, FProgress, FAbortPrint, {FMain,} ULang, UPrinter, FHidden, {$ifdef LOGFONT} UFont, {$endif} UExport, FFoundExport; {$R *.dfm} const ClipboardLimit = 32 * 1024 - 10; {---TOneFLine---------------------------------------------------------} constructor TOneFLine.Create(aOneFile: TOneFile; var aDisk, aDir, aShortDesc: ShortString; aID: longint; AExtAttr: byte); begin GetMemOneFile(POneFile, aOneFile); Disk := QNewStr(aDisk); Dir := QNewStr(aDir); ShortDesc := QNewStr(aShortDesc); ID := aID; ExtAttr := AExtAttr; end; //--------------------------------------------------------------------------- destructor TOneFLine.Destroy; begin FreeMemOneFile(POneFile); QDisposeStr(Disk); QDisposeStr(Dir); QDisposeStr(ShortDesc); end; //---TFormFoundList---------------------------------------------------------- procedure TFormFoundFileList.FormClose(Sender: TObject; var Action: TCloseAction); begin if FormIsClosed then Action := caFree; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := true; FormIsClosed := true; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.SetFileColWidth; begin DrawGrid.ColWidths[2] := MaxFileNamePxLength + 5; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.GetList(DBaseHandle: PDBaseHandle); var OneFile: TOneFile; Disk, Dir, ShortDesc: ShortString; OneLine: TOneFLine; Index : Integer; Total : Integer; PercentPie : Integer; ShowProgress: boolean; TmpInt : Integer; begin FoundList.Clear; MaxFileNameLength := 12; MaxFileNamePxLength := 50; try // if there is a large number of items, we should show a progress window Total := QI_GetFoundCount(DBaseHandle); ShowProgress := Total > 700; if Total < 2000 then PercentPie := Total div 10 + 1 else PercentPie := Total div 50 + 1; if ShowProgress then FormProgress.ResetAndShow(lsSorting); for Index := 0 to pred(Total) do begin if QI_GetSearchItemAt (DBaseHandle, Index, OneFile, Disk, Dir, ShortDesc) then begin if ShowProgress and ((Index mod PercentPie) = 0) then FormProgress.SetProgress((longint(Index) * 100) div Total); OneLine := TOneFLine.Create(OneFile, Disk, Dir, ShortDesc, Index, 0); FoundList.AddObject(GetSortString(OneLine), OneLine); if ShowProgress and FormProgress.StopIt then break; TmpInt := length(OneFile.LongName) + length(OneFile.Ext); if TmpInt > MaxFileNameLength then MaxFileNameLength := TmpInt; TmpInt := DrawGrid.Canvas.TextWidth(OneFile.LongName+OneFile.Ext); if TmpInt > MaxFileNamePxLength then MaxFileNamePxLength := TmpInt; end; end; DrawGrid.RowCount := FoundList.Count + 1; CanDraw := true; if ShowProgress then FormProgress.Hide; QI_ClearFoundList(DBaseHandle); SetFileColWidth; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin Close; FatalErrorMessage(EFatal.Message); end; end; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.FormCreate(Sender: TObject); begin FormIsClosed := false; ///FoundList := TQStringList.Create; FoundList := TStringList.Create; FoundList.Sorted := true; ///FoundList.Duplicates := qdupAccept; FoundList.Duplicates := dupAccept; SortArr := FormSearchFileDlg.DlgData.SortArr; NeedResort := false; ReversedSort := false; QGlobalOptions := TGlobalOptions.Create; FormSettings.GetOptions(QGlobalOptions); ResetFontAndSize; CanDraw := false; LastFileSelected := 1; MakeSelection := false; MaxFileNameLength := 12; MaxFileNamePxLength := 50; LastMouseMoveTime := $0FFFFFFF; FilesHintDisplayed := false; DisableHints := 0; SetRectEmpty(LastHintRect); DisableNextDoubleClick := false; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.DrawGridDrawCell(Sender: TObject; Col, Row: Longint; Rect: TRect; State: TGridDrawState); var S: ShortString; StartX : Integer; DosDateTime: longint; PartRect : TRect; OneLine : TOneFLine; Size : longint; Width : Integer; CutIt : boolean; begin if not CanDraw or FormIsClosed then exit; if Row <= FoundList.Count then begin case Col of 0: if Row = 0 then DrawGrid.Canvas.TextRect(Rect, Rect.Left+1, Rect.Top, lsDisk2) else begin OneLine := TOneFLine(FoundList.Objects[Row-1]); if (OneLine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGrid.Canvas.Brush.Color := clQSelectedBack; DrawGrid.Canvas.Font.Color := clQSelectedText; end; DrawGrid.Canvas.FillRect(Rect); DrawGrid.Canvas.TextRect(Rect, Rect.Left+1, Rect.Top, GetPQString(OneLine.Disk)); end; 1: if Row = 0 then DrawGrid.Canvas.TextRect(Rect, Rect.Left+2, Rect.Top, lsFolder3) else begin OneLine := TOneFLine(FoundList.Objects[Row-1]); if (OneLine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGrid.Canvas.Brush.Color := clQSelectedBack; DrawGrid.Canvas.Font.Color := clQSelectedText; end; S := GetPQString(OneLine.Dir); Width := DrawGrid.Canvas.TextWidth(S); if Width > (Rect.Right - Rect.Left - 2) then begin StartX := Rect.Right - Width - 2; CutIt := true; end else begin StartX := Rect.Left + 2; CutIt := false; end; DrawGrid.Canvas.FillRect(Rect); DrawGrid.Canvas.TextRect(Rect, StartX, Rect.Top, S); if CutIt then begin S := '< '; Width := DrawGrid.Canvas.TextWidth(S); DrawGrid.Canvas.TextRect( Classes.Rect(Rect.Left, Rect.Top, Rect.Left + Width + 2, Rect.Bottom), Rect.Left+2, Rect.Top, '< ') end; end; 2: if Row = 0 then DrawGrid.Canvas.TextRect(Rect, Rect.Left+2, Rect.Top, lsFile) else begin OneLine := TOneFLine(FoundList.Objects[Row-1]); if (OneLine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGrid.Canvas.Brush.Color := clQSelectedBack; DrawGrid.Canvas.Font.Color := clQSelectedText; end; DrawGrid.Canvas.FillRect(Rect); DrawGrid.Canvas.TextRect(Rect, Rect.Left+2, Rect.Top, OneLine.POneFile^.LongName + OneLine.POneFile^.Ext); end; 3: begin if Row = 0 then begin S := lsSize; StartX := Rect.Right - DrawGrid.Canvas.TextWidth(S) - 2; DrawGrid.Canvas.TextRect(Rect, StartX, Rect.Top, S); end else begin OneLine := TOneFLine(FoundList.Objects[Row-1]); if (OneLine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGrid.Canvas.Brush.Color := clQSelectedBack; DrawGrid.Canvas.Font.Color := clQSelectedText; end; Size := OneLine.POneFile^.Size; if OneLine.POneFile^.Attr and faDirectory = faDirectory then S := lsFolder else if (OneLine.POneFile^.Size=0) and (OneLine.POneFile^.Time=0) then S := lsDisk3 else S := FormatSize(Size, QGlobalOptions.ShowInKb); StartX := Rect.Right - DrawGrid.Canvas.TextWidth(S) - 2; DrawGrid.Canvas.FillRect(Rect); DrawGrid.Canvas.TextRect(Rect, StartX, Rect.Top, S); end; end; 4: begin if Row = 0 then begin S := lsDateTime; StartX := Rect.Right - DrawGrid.Canvas.TextWidth(S) - 2; DrawGrid.Canvas.TextRect(Rect, StartX, Rect.Top, S); end else begin OneLine := TOneFLine(FoundList.Objects[Row-1]); if (OneLine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGrid.Canvas.Brush.Color := clQSelectedBack; DrawGrid.Canvas.Font.Color := clQSelectedText; end; DrawGrid.Canvas.FillRect(Rect); DosDateTime := OneLine.POneFile^.Time; if DosDateTime <> 0 then begin S := DosTimeToStr(DosDateTime, QGlobalOptions.ShowSeconds); StartX := Rect.Right - DrawGrid.Canvas.TextWidth(S) - 2; DrawGrid.Canvas.TextRect(Rect, StartX, Rect.Top, S); S := DosDateToStr(DosDateTime); PartRect := Rect; PartRect.Right := PartRect.Right - TimeWidth; if PartRect.Right < PartRect.Left then PartRect.Right := PartRect.Left; StartX := PartRect.Right - DrawGrid.Canvas.TextWidth(S) - 2; DrawGrid.Canvas.TextRect(PartRect, StartX, Rect.Top, S); end else DrawGrid.Canvas.TextRect(Rect, Rect.Left+2, Rect.Top, ''); end; if Row > 0 then end; 5: if Row = 0 then DrawGrid.Canvas.TextRect(Rect, Rect.Left+2, Rect.Top, lsDescription) else begin OneLine := TOneFLine(FoundList.Objects[Row-1]); if (OneLine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGrid.Canvas.Brush.Color := clQSelectedBack; DrawGrid.Canvas.Font.Color := clQSelectedText; end; DrawGrid.Canvas.FillRect(Rect); DrawGrid.Canvas.TextRect(Rect, Rect.Left+2, Rect.Top, GetPQString(OneLine.ShortDesc)); end; end; end; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.FormDestroy(Sender: TObject); begin FoundList.Free; QGlobalOptions.Free; end; //--------------------------------------------------------------------------- // returns the string for sorting the lines function TFormFoundFileList.GetSortString(OneLine: TOneFLine): ShortString; var TmpL : longint; Index: Integer; begin Result := ''; for Index := 1 to 3 do with OneLine do begin case SortArr[Index] of soName: begin Result := Result + POneFile^.LongName + ' ' + POneFile^.Ext; end; soExt: begin Result := Result + POneFile^.Ext + ' ' + POneFile^.LongName; end; soTime: begin TmpL := MaxLongInt - POneFile^.Time; Result := Result + Format('%10.10d', [TmpL]) + POneFile^.Ext + POneFile^.LongName; end; soSize: begin TmpL := MaxLongInt - POneFile^.Size; Result := Result + Format('%10.10d', [TmpL]) + POneFile^.Ext + POneFile^.LongName; end; soKey: begin Result := Result + GetPQString(Disk) + ' ' + GetPQString(Dir); end; soDir: begin Result := Result + GetPQString(Dir) + ' ' + GetPQString(Disk); end; end; end; end; //--------------------------------------------------------------------------- // called from the main form when there is nothing better to do procedure TFormFoundFileList.LocalIdle; begin if NeedReSort then begin NeedReSort := false; ResortFoundList; end; end; //--------------------------------------------------------------------------- // called from the main form procedure TFormFoundFileList.LocalTimer; begin if FormIsClosed then exit; if QGlobalOptions.ShowFileHints and ((longint(GetTickCount) - LastMouseMoveTime) > defHintDelayPeriod) then ShowFileHint; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.SetNeedResort(Sort: TSort); begin if Sort <> SortArr[1] then begin SortArr[3] := SortArr[2]; SortArr[2] := SortArr[1]; SortArr[1] := Sort; ReversedSort := false; end else ReversedSort := not ReversedSort; NeedResort := true; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.DrawGridMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var i: Integer; OneColWidth, TotalWidth: Integer; begin DisableNextDoubleClick := false; with DrawGrid do if Button = mbLeft then begin if Y < DefaultRowHeight then begin TotalWidth := 0; DisableNextDoubleClick := true; for i := 0 to pred(ColCount) do begin OneColWidth := DrawGrid.ColWidths[i]; inc(TotalWidth, OneColWidth); if X < TotalWidth then begin case i of 0: SetNeedResort(soKey); 1: SetNeedResort(soDir); 2: if X > TotalWidth - OneColWidth div 2 then SetNeedResort(soExt) else SetNeedResort(soName); 3: SetNeedResort(soSize); 4: SetNeedResort(soTime); end; break; end; end; exit; end; if LastFileSelected >= DrawGrid.RowCount then LastFileSelected := pred(DrawGrid.RowCount); if ssShift in Shift then begin for i := 1 to pred(DrawGrid.RowCount) do begin with TOneFLine(FoundList.Objects[i-1]) do ExtAttr := ExtAttr and not eaSelected; end; if LastFileSelected <= DrawGrid.Row then for i := LastFileSelected to DrawGrid.Row do begin with TOneFLine(FoundList.Objects[i-1]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; end else for i := LastFileSelected downto DrawGrid.Row do begin with TOneFLine(FoundList.Objects[i-1]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; end; DrawGrid.Repaint; end; if ssCtrl in Shift then begin with TOneFLine(FoundList.Objects[DrawGrid.Row-1]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; end; end; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.ResortFoundList; var ///NewFoundList : TQStringList; NewFoundList : TStringList; Index : Integer; OneLine : TOneFLine; OneFile : TOneFile; ADisk, ADir, AShortDesc: ShortString; Total : Integer; PercentPie : Integer; ShowProgress : boolean; SaveID : longint; begin SaveID := TOneFLine(FoundList.Objects[DrawGrid.Row-1]).ID; Total := FoundList.Count; ShowProgress := Total > 700; if Total < 2000 then PercentPie := Total div 10 + 1 else PercentPie := Total div 50 + 1; if ShowProgress then FormProgress.ResetAndShow(lsSorting); ///NewFoundList := TQStringList.Create; NewFoundList := TStringList.Create; NewFoundList.Capacity := FoundList.Count; NewFoundList.Sorted := true; NewFoundList.Duplicates := dupAccept; ///NewFoundList.Reversed := ReversedSort; ///NewFoundList.Duplicates := qdupAccept; for Index := 0 to pred(Total) do with TOneFLine(FoundList.Objects[Index]) do begin if ShowProgress and ((Index mod PercentPie) = 0) then FormProgress.SetProgress((longint(Index) * 100) div Total); MoveOneFile(POneFile^, OneFile); ADisk := GetPQString(Disk); ADir := GetPQString(Dir); AShortDesc := GetPQString(ShortDesc); OneLine := TOneFLine.Create(OneFile, ADisk, ADir, AShortDesc, ID, ExtAttr); NewFoundList.AddObject(GetSortString(OneLine), OneLine); if ShowProgress and FormProgress.StopIt then break; end; if ShowProgress and FormProgress.StopIt then begin FreeObjects(NewFoundList); NewFoundList.Free; end else begin FoundList.Free; FreeObjects(FoundList); FoundList := NewFoundList; for Index := 0 to pred(Total) do if SaveID = TOneFLine(FoundList.Objects[Index]).ID then begin DrawGrid.Row := Index + 1; break; end; end; if ShowProgress then FormProgress.Hide; DrawGrid.Refresh; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.ResetFontAndSize; begin with DrawGrid do begin {$ifndef LOGFONT} ///Font.Assign (QGlobalOptions.FoundFont); ///Canvas.Font.Assign(QGlobalOptions.FoundFont); {$else} SetFontFromLogFont(Font, QGlobalOptions.FoundLogFont); SetFontFromLogFont(Canvas.Font, QGlobalOptions.FoundLogFont); {$endif} DefaultRowHeight := Canvas.TextHeight('My'); TimeWidth := Canvas.TextWidth(DosTimeToStr(longint(23) shl 11, QGlobalOptions.ShowSeconds)); TimeWidth := TimeWidth + TimeWidth div 6; ColWidths[0] := Canvas.TextWidth('Mmmmxxxx.mxx') + 2; ColWidths[1] := 2 * Canvas.TextWidth('Mmmmmxxxxx '); SetFileColWidth; ColWidths[3] := Canvas.TextWidth(FormatSize(2000000000, QGlobalOptions.ShowInKb)) + 2; if QGlobalOptions.ShowTime then ColWidths[4] := Canvas.TextWidth(' ' + DosDateToStr (694026240)) + TimeWidth + 2 else ColWidths[4] := Canvas.TextWidth(' ' + DosDateToStr (694026240)) + 2; ColWidths[5] := 25 * Canvas.TextWidth('Mmmmxxxxx '); end; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.ChangeGlobalOptions; begin FormSettings.GetOptions(QGlobalOptions); ResetFontAndSize; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.DrawGridDblClick(Sender: TObject); var LongName: ShortString; begin if DisableNextDoubleClick then exit; with TOneFLine(FoundList.Objects[DrawGrid.Row-1]) do begin LongName := POneFile^.LongName + POneFile^.Ext; DBaseWindow.BringToFront; DBaseWindow.JumpTo(GetPQString(Disk), GetPQString(Dir), LongName); DBaseWindow.PageControl1.TabIndex:=0; end; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.MenuGoToClick(Sender: TObject); begin DrawGridDblClick(Sender); end; procedure TFormFoundFileList.MenuItem2Click(Sender: TObject); begin close; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.DrawGridSelectCell(Sender: TObject; Col, Row: Longint; var CanSelect: Boolean); var i: Integer; begin if MakeSelection then begin MakeSelection := false; if LastFileSelected <= Row then for i := LastFileSelected to Row-1 do begin with TOneFLine(FoundList.Objects[i-1]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; end else for i := LastFileSelected downto Row+1 do begin with TOneFLine(FoundList.Objects[i-1]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; end; if abs(LastFileSelected - Row) > 1 then DrawGrid.Repaint; end; LastFileSelected := DrawGrid.Selection.Top; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.DrawGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = []) and ((Key = vk_Insert) or (Key = vk_Space)) then begin with TOneFLine(FoundList.Objects[pred(DrawGrid.Row)]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; if (DrawGrid.Row + 1) < DrawGrid.RowCount then DrawGrid.Row := DrawGrid.Row + 1; end; if (ssShift in Shift) and ((Key = vk_Down) or (Key = vk_Up) or (Key = vk_Prior) or (Key = vk_Next) or (Key = vk_Home) or (Key = vk_End)) then begin LastFileSelected := DrawGrid.Selection.Top; MakeSelection := true; end; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.SelectAll; var i: Integer; AlreadySelected: boolean; begin if UsePersistentBlocks then begin AlreadySelected := true; for i := 0 to pred(FoundList.Count) do with TOneFLine(FoundList.Objects[i]) do if (ExtAttr and eaSelected) = 0 then begin AlreadySelected := false; break; end; if AlreadySelected then for i := 0 to pred(FoundList.Count) do with TOneFLine(FoundList.Objects[i]) do ExtAttr := ExtAttr and not eaSelected else for i := 0 to pred(FoundList.Count) do with TOneFLine(FoundList.Objects[i]) do ExtAttr := ExtAttr or eaSelected; end else begin for i := 0 to pred(FoundList.Count) do with TOneFLine(FoundList.Objects[i]) do ExtAttr := ExtAttr or eaSelected; end; DrawGrid.Repaint; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.UnselectAll; var i: Integer; begin for i := 0 to pred(FoundList.Count) do begin with TOneFLine(FoundList.Objects[i]) do ExtAttr := ExtAttr and not eaSelected; end; DrawGrid.Repaint; end; //--------------------------------------------------------------------------- // copies selected lines to clipboard as text procedure TFormFoundFileList.MakeCopy; var CopyBuffer : PChar; hCopyBuffer: THandle; TotalLength: longint; procedure Run(CalcOnly: boolean); var i: Integer; S: ShortString; OneLine: TOneFLine; begin for i := 0 to pred(FoundList.Count) do begin OneLine := TOneFLine(FoundList.Objects[i]); if (OneLine.ExtAttr and eaSelected <> 0) or (i = pred(DrawGrid.Row)) then begin S := GetPQString(OneLine.Disk); AddToBuffer(CalcOnly, S + #9, CopyBuffer, TotalLength); S := GetPQString(OneLine.Dir); AddToBuffer(CalcOnly, S + #9, CopyBuffer, TotalLength); S := OneLine.POneFile^.LongName + OneLine.POneFile^.Ext; AddToBuffer(CalcOnly, S + #9, CopyBuffer, TotalLength); if OneLine.POneFile^.Attr and faDirectory = faDirectory then S := lsFolder else if (OneLine.POneFile^.Size=0) and (OneLine.POneFile^.Time=0) then S := lsDisk3 else S := FormatSize(OneLine.POneFile^.Size, QGlobalOptions.ShowInKb); AddToBuffer(CalcOnly, S + #9, CopyBuffer, TotalLength); if OneLine.POneFile^.Time <> 0 then S := DosDateToStr(OneLine.POneFile^.Time) + #9 + DosTimeToStr(OneLine.POneFile^.Time, QGlobalOptions.ShowSeconds) else S := #9; AddToBuffer(CalcOnly, S + #9, CopyBuffer, TotalLength); S := GetPQString(OneLine.ShortDesc); AddToBuffer(CalcOnly, S + #13#10, CopyBuffer, TotalLength); end; end; end; begin TotalLength := 0; Run(true); ///hCopyBuffer := GlobalAlloc(GMEM_MOVEABLE or GMEM_ZEROINIT, TotalLength+1); ///CopyBuffer := GlobalLock(hCopyBuffer); Run(false); ///GlobalUnlock(hCopyBuffer); ///Clipboard.SetAsHandle(CF_TEXT, hCopyBuffer); end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.MenuCopyClick(Sender: TObject); begin MakeCopy; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.MenuSelectAllClick(Sender: TObject); begin SelectAll; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.MenuUnselectAllClick(Sender: TObject); begin UnselectAll; end; //--------------------------------------------------------------------------- // implements printing of the lines procedure TFormFoundFileList.MakePrint; const NoOfColumns = 6; var AmountPrintedPx: Integer; PageCounter: Integer; ColWidthsPx: array [0..NoOfColumns-1] of Integer; TimeWidthPx: Integer; {Disk, Dir, Name, Size, Time, Desc} {------} function CanPrintOnThisPage: boolean; begin Result := true; {$ifdef mswindows} if PrintDialog.PrintRange <> prPageNums then exit; with PrintDialog do if (PageCounter >= FromPage) and (PageCounter <= ToPage) then exit; Result := false; {$endif} end; {------} procedure GoToNewPage; begin {$ifdef mswindows} if PrintDialog.PrintRange <> prPageNums then QPrinterNewPage else begin with PrintDialog do if (PageCounter >= FromPage) and (PageCounter < ToPage) then QPrinterNewPage; end; {$endif} end; {------} procedure PrintHeaderAndFooter; var OutRect : TRect; S : ShortString; begin if FormAbortPrint.Aborted then exit; {$ifdef mswindows} QPrinterSaveAndSetFont(pfsItalic); {header} OutRect.Left := LeftPrintAreaPx; OutRect.Right := RightPrintAreaPx; OutRect.Top := TopPrintAreaPx; OutRect.Bottom := OutRect.Top + LineHeightPx; if CanPrintOnThisPage then begin S := QGlobalOptions.PrintHeader; if S = '' then S := Caption; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 50)); {0.2 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Bottom + YPxPer1mm); QPrinterLineTo(RightPrintAreaPx, OutRect.Bottom + YPxPer1mm); end; {footer} OutRect.Bottom := BottomPrintAreaPx; OutRect.Top := OutRect.Bottom - LineHeightPx; if CanPrintOnThisPage then begin QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, TimePrinted); S := lsPage + IntToStr(PageCounter); OutRect.Left := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 50)); {0.2 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Top - YPxPer1mm); QPrinterLineTo(RightPrintAreaPx, OutRect.Top - YPxPer1mm); end; QPrinterRestoreFont; {$endif} end; {------} procedure PrintColumnNames; var OutRect : TRect; S : ShortString; i : Integer; StartX : Integer; begin if FormAbortPrint.Aborted then exit; {$ifdef mswindows} QPrinterSaveAndSetFont(pfsBold); OutRect.Left := LeftPrintAreaPx; OutRect.Top := AmountPrintedPx; OutRect.Bottom := OutRect.Top + LineHeightPx; for i := 0 to NoOfColumns-1 do if CanPrintOnThisPage then begin OutRect.Right := OutRect.Left + ColWidthsPx[i] - 3*XPxPer1mm; if (OutRect.Right > RightPrintAreaPx) or (i = NoOfColumns-1) then OutRect.Right := RightPrintAreaPx; if (OutRect.Left < OutRect.Right) then begin case i of 0: begin S := lsDisk2; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; 1: begin S := lsFolder3; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; 2: begin S := lsFile; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; 3: begin S := lsSize; StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 4: begin S := lsDateTime; StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 5: begin S := lsDescription; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; end; end; inc(OutRect.Left,ColWidthsPx[i]); end; inc(AmountPrintedPx, LineHeightPx + YPxPer1mm); QPrinterRestoreFont; {$endif} end; {------} function CutStringToDesiredWidth (var S: ShortString; DesiredPxWidth: Integer): Integer; // cuts the string so that it has limited length var Len, PxWidth, EstimatedCut: Integer; TmpS: ShortString; begin ///PxWidth := QPrinterGetTextWidth(S); Len := length(S); Result := DesiredPxWidth; if PxWidth <= 0 then exit; if DesiredPxWidth <= 0 then exit; if PxWidth <= DesiredPxWidth then exit; EstimatedCut := (longint(Len) * DesiredPxWidth) div PxWidth; TmpS := ShortCopy(S, Len-EstimatedCut+1, EstimatedCut); ///PxWidth := QPrinterGetTextWidth(TmpS); if PxWidth > DesiredPxWidth then begin while PxWidth > DesiredPxWidth do begin dec(EstimatedCut); if EstimatedCut = 0 then exit; TmpS := ShortCopy(S, Len-EstimatedCut+1, EstimatedCut); ///PxWidth := QPrinterGetTextWidth(TmpS); end; if EstimatedCut >= 2 then dec(EstimatedCut, 2); S := ShortCopy(S, Len-EstimatedCut+1, EstimatedCut); ///PxWidth := QPrinterGetTextWidth(S); Result := PxWidth; exit; end; if PxWidth <= DesiredPxWidth then begin while PxWidth <= DesiredPxWidth do begin inc(EstimatedCut); if EstimatedCut > Len then exit; TmpS := ShortCopy(S, Len-EstimatedCut+1, EstimatedCut); ///PxWidth := QPrinterGetTextWidth(TmpS); end; if EstimatedCut >=3 then dec(EstimatedCut, 3); S := ShortCopy(S, Len-EstimatedCut+1, EstimatedCut); ///PxWidth := QPrinterGetTextWidth(S); Result := PxWidth; exit; end; end; {------} procedure PrintOneLine(Index: Integer); const ArrowS = '« '; var OneLine: TOneFLine; OutRect : TRect; TmpRect : TRect; S : ShortString; i : Integer; StartX : Integer; PxWidth : Integer; DesiredPxWidth: Integer; CutIt : boolean; begin if FormAbortPrint.Aborted then exit; OneLine := TOneFLine(FoundList.Objects[Index]); {$ifdef mswindows} if (PrintDialog.PrintRange = prSelection) and (OneLine.ExtAttr and eaSelected = 0) and (Index <> pred(DrawGrid.Row)) then exit; OutRect.Left := LeftPrintAreaPx; OutRect.Top := AmountPrintedPx; OutRect.Bottom := OutRect.Top + LineHeightPx; for i := 0 to NoOfColumns-1 do if CanPrintOnThisPage then begin OutRect.Right := OutRect.Left + ColWidthsPx[i] - 3*XPxPer1mm; if (OutRect.Right > RightPrintAreaPx) or (i = NoOfColumns-1) then OutRect.Right := RightPrintAreaPx; if OutRect.Left >= OutRect.Right then break; case i of 0: begin S := GetPQString(OneLine.Disk); QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; 1: begin S := GetPQString(OneLine.Dir); PxWidth := QPrinterGetTextWidth(S); DesiredPxWidth := OutRect.Right - OutRect.Left; TmpRect := OutRect; if PxWidth > DesiredPxWidth then begin PxWidth := CutStringToDesiredWidth (S, DesiredPxWidth); StartX := OutRect.Right - PxWidth; CutIt := true; end else begin StartX := OutRect.Left; CutIt := false; end; if CutIt then begin QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, ArrowS); end; QPrinterTextRect(TmpRect, StartX, OutRect.Top, S); end; 2: begin S := OneLine.POneFile^.LongName + OneLine.POneFile^.Ext; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; 3: begin if OneLine.POneFile^.Attr and faDirectory = faDirectory then S := lsFolder else if (OneLine.POneFile^.Size=0) and (OneLine.POneFile^.Time=0) then S := lsDisk3 else S := FormatSize(OneLine.POneFile^.Size, QGlobalOptions.ShowInKb); StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 4: begin if OneLine.POneFile^.Time <> 0 then begin S := DosTimeToStr(OneLine.POneFile^.Time, QGlobalOptions.ShowSeconds); StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); S := DosDateToStr(OneLine.POneFile^.Time); TmpRect := OutRect; TmpRect.Right := TmpRect.Right - TimeWidthPx; if TmpRect.Right > TmpRect.Left then begin StartX := TmpRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(TmpRect, StartX, TmpRect.Top, S); end; end; end; 5: begin S := GetPQString(OneLine.ShortDesc); QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; end; inc(OutRect.Left,ColWidthsPx[i]); end; inc(AmountPrintedPx, LineHeightPx); {$endif} end; {------} var i: Integer; Ratio: double; TmpS: array[0..256] of char; Copies: Integer; begin {$ifdef mswindows} if PrintDialog.Execute then begin QPrinterReset(QGlobalOptions); AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; Ratio := QPrinterGetTextWidth('MMMAaBbCcIi') / DrawGrid.Canvas.TextWidth('MMMAaBbCcIi'); for i := 0 to NoOfColumns-1 do ColWidthsPx[i] := round(DrawGrid.ColWidths[i] * Ratio) + 3*XPxPer1mm; TimeWidthPx := QPrinterGetTextWidth(DosTimeToStr(longint(23) shl 11, QGlobalOptions.ShowSeconds)); TimeWidthPx := TimeWidthPx + TimeWidthPx div 6; FormAbortPrint.LabelProgress.Caption := lsPreparingToPrint; FormAbortPrint.Show; MainForm.Enabled :=false; try Application.ProcessMessages; for Copies := 1 to PrintDialog.Copies do begin PageCounter := 1; QPrinterBeginDoc (lsQuickDir); PrintHeaderAndFooter; PrintColumnNames; FormAbortPrint.LabelProgress.Caption := lsPrintingPage + IntToStr(PageCounter); for i := 0 to pred(FoundList.Count) do begin Application.ProcessMessages; if FormAbortPrint.Aborted then break; PrintOneLine(i); if (AmountPrintedPx + 3*LineHeightPx) > BottomPrintAreaPx then begin if not FormAbortPrint.Aborted then begin GoToNewPage; inc(PageCounter); end; FormAbortPrint.LabelProgress.Caption := lsPrintingPage + IntToStr(PageCounter); Application.ProcessMessages; AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; PrintHeaderAndFooter; PrintColumnNames; end; end; QPrinterEndDoc; if FormAbortPrint.Aborted then break; end; except on E: Exception do Application.MessageBox(StrPCopy(TmpS, E.Message), lsError, mb_Ok or mb_IconExclamation); end; MainForm.Enabled :=true; FormAbortPrint.Hide; end; {$endif} end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.MenuPrintClick(Sender: TObject); begin MakePrint; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.MenuHelpClick(Sender: TObject); begin Application.HelpContext(250); end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.DrawGridMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if (LastMouseXFiles <> X) or (LastMouseYFiles <> Y) then begin MousePosAlreadyChecked := false; EraseFileHint; LastMouseXFiles := X; LastMouseYFiles := Y; LastMouseMoveTime := GetTickCount; end; end; //--------------------------------------------------------------------------- // shows the yellow bubble hint procedure TFormFoundFileList.ShowFileHint; var Point : TPoint; Rect : TRect; HintWidth : integer; LineHeight : integer; OneLine : TOneFLine; S : ShortString; i, TmpInt : integer; PolygonPts : array[0..2] of TPoint; XPosition : integer; begin if MousePosAlreadyChecked then exit; if DisableHints <> 0 then exit; if FilesHintDisplayed then exit; MousePosAlreadyChecked := true; GetCursorPos(Point); Point := DrawGrid.ScreenToClient(Point); // is the cursor still in the window? if (LastMouseXFiles <> Point.X) or (LastMouseYFiles <> Point.Y) then exit; OneLine := FindOneLine(Point, Rect); if OneLine = nil then exit; HiddenForm.MemoForHints.Lines.Clear; S := GetPQString(OneLine.ShortDesc); if length(S) > 0 then HiddenForm.MemoForHints.Lines.Insert(0, S); if HiddenForm.MemoForHints.Lines.Count = 0 then exit; with DrawGrid.Canvas do begin HintWidth := 0; LineHeight := 0; for i := 0 to pred(HiddenForm.MemoForHints.Lines.Count) do begin TmpInt := TextWidth(HiddenForm.MemoForHints.Lines[i]); if HintWidth < TmpInt then HintWidth := TmpInt; TmpInt := TextHeight(HiddenForm.MemoForHints.Lines[i]); if LineHeight < TmpInt then LineHeight := TmpInt; end; XPosition := (Rect.Left + Rect.Right) div 2; LastHintRect.Left := XPosition - HintWidth + 5; LastHintRect.Right := XPosition + 11; if (LastHintRect.Left <= 0) then OffsetRect(LastHintRect, -LastHintRect.Left+3, 0); PolygonPts[0].X := LastHintRect.Right - 17; PolygonPts[1].X := LastHintRect.Right - 11; PolygonPts[2].X := LastHintRect.Right - 5; if Rect.Top < (DrawGrid.Height div 2) then begin LastHintRect.Top := Rect.Bottom + 3; LastHintRect.Bottom := Rect.Bottom + HiddenForm.MemoForHints.Lines.Count * LineHeight + 5; PolygonPts[0].Y := LastHintRect.Top; PolygonPts[1].Y := LastHintRect.Top - 6; PolygonPts[2].Y := LastHintRect.Top; end else begin LastHintRect.Top := Rect.Top - HiddenForm.MemoForHints.Lines.Count * LineHeight - 5; LastHintRect.Bottom := Rect.Top - 3; PolygonPts[0].Y := LastHintRect.Bottom-1; PolygonPts[1].Y := LastHintRect.Bottom + 5; PolygonPts[2].Y := LastHintRect.Bottom-1; end; Brush.Color := $CFFFFF; Font.Color := clBlack; Pen.Color := clBlack; RoundRect(LastHintRect.Left, LastHintRect.Top, LastHintRect.Right, LastHintRect.Bottom, 4, 4); Polygon(PolygonPts); Pen.Color := $CFFFFF; MoveTo(PolygonPts[0].X+1, PolygonPts[0].Y); LineTo(PolygonPts[2].X, PolygonPts[2].Y); for i := 0 to pred(HiddenForm.MemoForHints.Lines.Count) do TextOut(LastHintRect.Left+3, LastHintRect.Top+1+i*LineHeight, HiddenForm.MemoForHints.Lines[i]); end; FilesHintDisplayed := true; end; //--------------------------------------------------------------------------- // finds the line according to its coordinates function TFormFoundFileList.FindOneLine(Point: TPoint; var Rect: TRect): TOneFLine; var ACol, ARow: longint; begin DrawGrid.MouseToCell(Point.X, Point.Y, ACol, ARow); Rect := DrawGrid.CellRect(5, ARow); if IsRectEmpty(Rect) then begin Rect := DrawGrid.CellRect(ACol, ARow); Rect.Left := 0; Rect.Right := DrawGrid.Width; end; if (ARow > 0) and (ARow <= FoundList.Count) then begin Result := TOneFLine(FoundList.Objects[ARow-1]); exit; end; Result := nil; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.EraseFileHint; begin if FilesHintDisplayed then begin FilesHintDisplayed := false; InflateRect(LastHintRect, 0, 6); InvalidateRect(DrawGrid.Handle, @LastHintRect, false); end; end; //--------------------------------------------------------------------------- procedure TFormFoundFileList.ExportToOtherFormat; begin FormFoundExport.IsFileFoundList := true; FormFoundExport.FoundList := FoundList; FormFoundExport.DBaseHandle := DBaseWindow.DBaseHandle; FormFoundExport.DBaseFileName := DBaseWindow.DBaseFileName; FormFoundExport.ShowModal; end; //--------------------------------------------------------------------------- end.
unit Visu0; interface {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} uses Windows,graphics,classes,sysutils,math, util1,Dgraphic,Dtrace1,dtf0,tbe0,Dgrad1, Daffmat,Dpalette, debug0, dibG, stmDef; { TvisuInfo contient les paramètres d'affichage d'une trace ou d'une matrice } { C'est un Record plutôt qu'un objet } { Il est utilisé dans la saisie de coordonnées ==> Cood0 } { et par dataF0 } Const nbComplexMode=8; LongNomComplexMode=7; tbComplexMode:array[1..nbComplexMode] of string[LongNomComplexMode]=( 'X', 'Y', 'MDL', 'ARG', 'X/Y', 'Y/X', 'MDL/ARG', 'ARG/MDL' ); type { 16-9-99: On note TvisuInfo dans ToldVisuInfo pour pouvoir changer les configurations Dans le nouveau TvisuInfo: on supprime Title on modifie le type de cpx, cpy, cpz qui deviennent smallint } TOldVisuInfo= record Xmin,Xmax,Ymin,Ymax,Zmin,Zmax:double; gamma:single; aspect:single; ux,uy:string[10]; color:longint; twoCol:boolean; modeT,tailleT:byte; largeurTrait,styleTrait:byte; modeLogX,modeLogY,grille:boolean; cpX,cpY,cpZ:byte; title:string[80]; echX,echY:boolean; FtickX,FtickY:boolean; CompletX,completY:boolean; TickExtX,TickExtY:boolean; ScaleColor:longint; fontDesc:TfontDescriptor; font:Tfont; theta:single; inverseX,inverseY:boolean; Epduration:single; end; TWFoptions=record active:boolean; DxAff,DyAff:single; Mleft,Mtop,Mright,Mbottom:single; end; PWFoptions=^TWFoptions; TgetSelectPixel=function(i,j:integer):boolean of object; type TvisuFlagIndex=( VF_Xmin, VF_Xmax, VF_Ymin, VF_Ymax, VF_Zmin, VF_Zmax, VF_gamma, VF__aspect, VF_ux, VF_uy, VF_color, VF_twoCol, VF_modeT, VF_tailleT, VF_largeurTrait, VF_styleTrait, VF_modeLogX, VF_modeLogY, VF_grille, VF_cpX, VF_cpY, VF_cpZ, VF_echX, VF_echY, VF_FtickX, VF_FtickY, VF_CompletX, VF_completY, VF_TickExtX, VF_TickExtY, VF_ScaleColor, VF_fontVisu, VF_theta, VF_inverseX, VF_inverseY, VF_Epduration, VF_ModeMat, VF_keepRatio, VF_color2, VF_CpxMode, VF_AngularMode, VF_AngularLW, VF_Cmin, VF_Cmax, VF_gammaC, VF_FscaleX0, VF_FscaleY0, VF_modeLogZ, VF_Gdisp, VF_Xdisp, VF_Ydisp, VF_FullD2, VF_toptop ); TvisuFlags=array[TvisuFlagIndex] of boolean; PvisuFlags=^TvisuFlags; const NbVisuFlags= ord(VF_toptop); type PvisuInfo=^TvisuInfo; TvisuInfo= object Xmin,Xmax,Ymin,Ymax,Zmin,Zmax:double; gamma:single; //_aspect:single; BarWidth: single; ux,uy:string[10]; color:longint; twoCol:boolean; modeT,tailleT:byte; largeurTrait,styleTrait:byte; modeLogX,modeLogY,grille:boolean; cpX,cpY,cpZ:smallint; echX,echY:boolean; FtickX,FtickY:boolean; CompletX,completY:boolean; TickExtX,TickExtY:boolean; ScaleColor:longint; fontDescA:TfontDescriptor; SmoothFactor:integer; DumTheta:single; inverseX,inverseY:boolean; Epduration:single; ModeMat:byte; keepRatio:boolean; color2:longint; getSelectPixel,getMarkedPixel:TgetSelectPixel; selectCol,MarkCol:integer; CpxMode:byte; { 0: X 1: Y 2: Mdl 3: Arg 4: X / Y 5: Y / X 6: Mdl / Arg 7: Arg / Mdl } AngularMode:byte; { 0: none 1: angle=value 2: angle=cpx arg } AngularLW:integer; { largeur trait en mode angulaire } Cmin,Cmax:double; gammaC:single; FscaleX0,FscaleY0:boolean; modeLogZ:boolean; Gdisp,Xdisp,Ydisp:double; FullD2:boolean; FvisuFlags: PvisuFlags; {Ces deux pointeurs sont mis à zéro après un chargement} fontVisu:Tfont; procedure init; procedure done; procedure InitVisuFlags; procedure assign(const visu:TvisuInfo); procedure displayScale; {getInsideT calcule la position du rectangle de tracé en fonction de la fenêtre courante pour les vecteurs, graphes et fonctions } function getInsideT:Trect; function getInsideT2(data:TdataTbB):Trect; {getInsideMat calcule la position du rectangle de tracé en fonction de la fenêtre courante pour les matrices } function getInsideMat(data:TdataTbB;wf:PwfOptions;degP:typedegre):Trect; {displayTrace0 affiche la trace seule dans la fenêtre courante} procedure displayTrace0(data:typedataB; ExternalWorld, ExtParam,logX,logY:boolean; mode,taille:integer;onDP:TonDisplayPoint; deltaY:float); {displayTrace affiche la trace et les échelles dans la fenêtre courante En sortie, la fenêtre n'est pas modifiée} procedure displayTrace(data:typedataB;onDP:TonDisplayPoint;deltaY:float); function displayEmpty:Trect; procedure displayPoints(data:typedataB;onDP:TonDisplayPoint;i1,i2:integer; inside:boolean;deltaY:float); procedure affPaveA(poly:Tpoly4;i,j:integer); procedure affPaveWire(poly:Tpoly4;i,j:integer); procedure moveWire(poly:Tpoly4;i,j:integer); procedure affPaveA3(poly:Tpoly4;i,j:integer); procedure affPaveA3bis(poly:Tpoly4;i,j:integer); procedure affPaveSel(poly:Tpoly4;i,j:integer); procedure affPavePhase(poly:Tpoly4;phase:float); procedure FastDisplayMat0(ExternalWorld:boolean;palName:AnsiString; Fcell:boolean;Acol,Arow:integer; getSel,getMark:TgetSelectPixel; const TransparentValue:double=0;Ftransparent:boolean=false); procedure DisplayMatLog0(ExternalWorld:boolean;palName:AnsiString; Fcell:boolean;Acol,Arow:integer;const TransparentValue:double=0;Ftransparent:boolean=false); procedure displayMat0(data:TdataTbB;ExternalWorld:boolean;palName:AnsiString; Fcell:boolean;Acol,Arow:integer; wf:PwfOptions;degP:typedegre; getSel,getMark:TgetSelectPixel; const TransparentValue:double=0;Ftransparent:boolean=false; ForceNotFast:boolean=false); procedure displayMat(data:TdataTbB;palName:AnsiString; Fcell:boolean;Acol,Arow:integer; wf:PwfOptions;degP:typedegre; getSel,getMark:TgetSelectPixel; const TransparentValue:double=0;Ftransparent:boolean=false); function getMatPos(data:TdataTbB;wf:PwfOptions;degP:typedegre;var x,y:integer):boolean;overload; function getMatPos(data:TdataTbB;wf:PwfOptions;degP:typedegre;var x,y:float):boolean;overload; procedure displayGraph0(data1,data2,dataS:typedataB;min,max:integer; ExternalWorld,extParam,logX,logY:boolean; mode,taille:integer); procedure displayGraph(data1,data2,dataS:typedataB;min,max:integer); procedure displayFunc0(f0:TypefonctionEE;xdeb,xfin:float;nbpt:integer; ExternalWorld,extParam,logX,logY:boolean; mode,taille:integer); procedure displayFunc(f0:TypefonctionEE;xdeb,xfin:float;nbpt:integer); procedure cadrerX(data:typeDataB); procedure cadrerY(data:typeDataB); procedure cadrerYlocal(data:typeDataB); procedure initFont; procedure freeFont; procedure CompleteLoadInfo; procedure translateCoo(plus:boolean); procedure transferOldVisu(var oldVisu:ToldVisuInfo); procedure displayColorMap0(name:AnsiString;dir,Ncol:integer); procedure displayColorMap(name:AnsiString;dir,Ncol:integer); procedure controle; procedure FontToGlb; procedure resetFontToGlb; function info(ww:AnsiString):AnsiString; function compare(visu1:TvisuInfo):boolean; procedure getIntegerBounds(data:TdataTbB;var x1,y1,x2,y2:double); function MatFastCondition(wf:PwfOptions;degP:typedegre): boolean; end; TmatColor=record col1:byte; tpPal:TpaletteType; col2:byte; bid:byte; end; {Marges minimales pour l'affichage du cadre intérieur} const DispVec_left=5; DispVec_Right=8; DispVec_Top=5; DispVec_Bottom=5; var visuModel:TvisuInfo; implementation {****************** Méthodes de TvisuInfo *********************************} var FontCnt:integer; oldFont:Tfont; FmagFont:boolean; FlagPoints:boolean; I1points,I2points:integer; procedure TvisuInfo.init; begin Xmax:=100; Ymax:=100; Zmax:=1; gamma:=1; color:=DefPenColor; modeT:=2; tailleT:=3; largeurTrait:=1; styleTrait:=1; //_aspect:=0; BarWidth:=0; echX:=true; echY:=true; FtickX:=true; FtickY:=true; CompletX:=true; completY:=true; TickExtX:=false; TickExtY:=false; ScaleColor:=DefScaleColor; inverseX:=false; inverseY:=false; fontDescA.init; fontVisu:=nil; initFont; CpxMode:=0; AngularLW:=1; Cmin:=0; Cmax:=100; gammaC:=1; Gdisp:=1; FvisuFlags:=nil; SmoothFactor:=0; end; procedure TvisuInfo.done; begin fontVisu.free; fontVisu:=nil; if assigned(FvisuFlags) then begin dispose(FvisuFlags); FvisuFlags:=nil; end; end; procedure TvisuInfo.InitVisuFlags; begin new(FvisuFlags); fillchar(FvisuFlags^,sizeof(FvisuFlags^),0); end; procedure TvisuInfo.assign(const visu:TvisuInfo); var p:pointer; begin p:=fontVisu; move(visu,Xmin,sizeof(visu)); fontVisu:=p; {conserver le pointeur font} if assigned(visu.fontVisu) then begin if not assigned(fontVisu) then fontVisu:=Tfont.Create; fontVisu.Assign(visu.fontVisu); {copier le contenu de font} end; end; procedure TvisuInfo.initFont; begin if not assigned(fontVisu) then fontVisu:=Tfont.create; DescToFont(fontDescA,fontVisu); end; procedure TvisuInfo.freeFont; begin fontVisu.free; fontVisu:=nil; end; procedure TvisuInfo.CompleteLoadInfo; begin fontvisu:=nil; FvisuFlags:=nil; SmoothFactor:=0; end; procedure TvisuInfo.DisplayScale; var grad:typeGrad; begin FontToGlb; Dgraphic.setWorld(Xmin,Ymin,Xmax,Ymax); grad:=typeGrad.create; TRY with grad do begin setUnites(uX,uY); setLog(modeLogX,modeLogY); setEch(echX,echY); setCadre(FtickX,FtickY,1); setComplet(completX,completY); setExternal(tickExtX,tickExtY); setInverse(inverseX,inverseY); setGrille(grille); setZeroAxis(FscaleX0,FscaleY0); if PRprinting and PRmonochrome then setColors(clBlack,clWhite) else setColors(scaleColor,canvasGlb.brush.color); affiche; end; FINALLY grad.free; resetFontToGlb; END; end; function duplicate(data:typedataB):typeDataB; begin if data.ClassType=typeDataCpxS then with typeDataCpxS(data) do result:=typeDataCpxS.create(p,StepSize div 8 {nbvoie},indice1,indiceMin,indiceMax) else if data.ClassType=typeDataCpxD then with typeDataCpxD(data) do result:=typeDataCpxD.create(p,StepSize div 16 {nbvoie},indice1,indiceMin,indiceMax) else if data.ClassType=typeDataCpxE then with typeDataCpxE(data) do result:=typeDataCpxE.create(p,StepSize div 20 {nbvoie},indice1,indiceMin,indiceMax) else result:=nil; if assigned(result) then begin result.ax:=data.ax; result.bx:=data.bx; result.ay:=data.ay; result.by:=data.by; end; end; procedure TvisuInfo.displayTrace0(data:typeDataB; ExternalWorld,ExtParam,logX,logY:boolean; mode,taille:integer;onDP:TonDisplayPoint; deltaY:float); var univers:TUnivers; trace:TTrace0; x1,y1,x2,y2:float; mt,tt:integer; dataY:typeDataB; begin if data=nil then exit; dataY:=duplicate(data); if not assigned(dataY) and (cpxMode>=4) then exit; univers:=Tunivers.create; if externalWorld then begin Dgraphic.getWorld(x1,y1,x2,y2); univers.setWorld(x1,y1,x2,y2); univers.setModeLog(LogX,LogY) end else begin univers.setWorld(xmin,ymin+deltaY,xmax,ymax+deltaY); univers.setModeLog(modeLogX,modeLogY); end; univers.setInverse(inverseX,inverseY); if cpxMode<4 then trace:=TtraceTableau.create(univers,data) else trace:=TTraceTableauDouble.create(univers,data,dataY,nil); with TtraceTableau(trace) do begin if PRprinting and PRmonochrome then begin setColorTrace(clBlack); setColorTrace2(clBlack); end else begin if ExtParam then begin setColorTrace(canvasGlb.pen.color); setColorTrace2(canvasGlb.pen.color); end else begin setColorTrace(self.color); setColorTrace2(self.color2); end; end; if extParam then begin if mode<>0 then mt:=mode else mt:=modeT; if taille<>0 then tt:=taille else tt:=tailleT; setStyle(mT,tT); end else setStyle(modeT,tailleT); setTrait(largeurTrait,styleTrait); setBarWidth(self.BarWidth); onDisplayPoint:=onDP; if CpxMode<4 then data.modeCpx:=CpxMode else begin data.modeCpx:=0; dataY.modeCpx:=1; end; SmoothF:=(SmoothFactor-1) div 2; if FlagPoints then afficherPoints(I1points,I2points) else afficher; end; trace.free; univers.free; data.modeCpx:=0; dataY.free; end; function TvisuInfo.getInsideT:Trect; var x1,y1,x2,y2:integer; xw1,yw1,xw2,yw2:integer; htext,ltext:integer; ratio:float; dx,dy:integer; begin FontToGlb; TRY getWindowG(x1,y1,x2,y2); htext:=canvasGlb.textHeight('1'); ltext:=canvasGlb.textWidth('1000000'); xw1:=x1+DispVec_left+ord(echY {and not FscaleY0})*ltext; yw1:=y1+DispVec_Top; xw2:=x2-DispVec_Right; yw2:=y2-ord(echX {and not FscaleX0})*htext-DispVec_Bottom; if keepRatio and (Xmax-Xmin<>0) then begin ratio:=abs((Ymax-Ymin)/(Xmax-Xmin)); dx:=xw2-xw1; dy:=yw2-yw1; if dx*ratio<dy then dy:=roundL(dx*ratio) else dx:=roundL(dy/ratio); if dx<4 then dx:=4; if dy<4 then dy:=4; xw1:=(xw1+xw2) div 2 -dx div 2; xw2:=xw1+dx ; yw1:=(yw1+yw2) div 2 -dy div 2; yw2:=yw1+dy; end; result:= rect(xw1,yw1,xw2,yw2); FINALLY resetFontToGlb; END; end; procedure TVisuInfo.displayTrace(data:typeDataB;onDP:TonDisplayPoint;deltaY:float); var x1,y1,x2,y2:integer; BKcolor:longint; rectI:Trect; begin FontToGLB; TRY BKcolor:=canvasGlb.brush.color; getWindowG(x1,y1,x2,y2); rectI:=getInsideT; with rectI do setWindow(left,top,right,bottom); displayTrace0(data,false,false,false,false,0,0,onDP,deltaY); DisplayScale; setWindow(x1,y1,x2,y2); FINALLY canvasGlb.brush.color:=BKcolor; resetFontToGLB; END; end; function TVisuInfo.displayEmpty:Trect; var x1,y1,x2,y2:integer; BKcolor:longint; rectI:Trect; begin FontToGLB; TRY BKcolor:=canvasGlb.brush.color; getWindowG(x1,y1,x2,y2); rectI:=getInsideT; result:=rectI; with rectI do setWindow(left,top,right,bottom); DisplayScale; setWindow(x1,y1,x2,y2); FINALLY canvasGlb.brush.color:=BKcolor; resetFontToGLB; END; end; procedure TVisuInfo.displayPoints(data:typeDataB;onDP:TonDisplayPoint;i1,i2:integer; inside:boolean;deltaY:float); begin if not assigned(data) then exit; FlagPoints:=true; I1points:=I1; I2points:=I2; try if not inside then displayTrace(data,onDP,deltaY) else displayTrace0(data,false,false,false,false,0,0,onDP,deltaY); finally FlagPoints:=false; end; end; procedure TvisuInfo.displayGraph0(data1,data2,dataS:typeDataB;min,max:integer; ExternalWorld,extParam,logX,logY:boolean; mode,taille:integer); var univers:TUnivers; trace:TTraceTableauDouble; x1,y1,x2,y2:float; mt,tt:integer; begin if (data1=nil) or (data2=nil) then exit; univers:=Tunivers.create; if externalWorld then begin Dgraphic.getWorld(x1,y1,x2,y2); univers.setWorld(x1,y1,x2,y2); univers.setModeLog(LogX,LogY) end else begin univers.setWorld(xmin,ymin,xmax,ymax); univers.setModeLog(modeLogX,modeLogY); end; univers.setInverse(inverseX,inverseY); trace:=TTraceTableauDouble.create(univers,data1,data2,dataS); trace.setIminImax(min,max); with trace do begin if PRprinting and PRmonochrome then begin setColorTrace(clBlack); setColorTrace2(clBlack); end else begin if ExtParam then begin setColorTrace(canvasGlb.pen.color); setColorTrace2(canvasGlb.pen.color); end else begin setColorTrace(self.color); setColorTrace2(self.color2); end; end; if extParam then begin if mode<>0 then mt:=mode else mt:=modeT; if taille<>0 then tt:=taille else tt:=tailleT; setStyle(mT,tT); end else setStyle(modeT,tailleT); setTrait(largeurTrait,styleTrait); setBarWidth(self.BarWidth); afficher; end; trace.free; univers.free; end; procedure TvisuInfo.displayGraph(data1,data2,dataS:typeDataB;min,max:integer); var x1,y1,x2,y2:integer; BKcolor:longint; rectI:Trect; const dd=5; begin FontToGlb; TRY BKcolor:=canvasGlb.brush.color; getWindowG(x1,y1,x2,y2); rectI:=getInsideT; with rectI do setWindow(left,top,right,bottom); displayGraph0(data1,data2,dataS,min,max,false,false,false,false,0,0); DisplayScale; setWindow(x1,y1,x2,y2); FINALLY canvasGlb.brush.color:=BKcolor; resetFontToGlb; END; end; procedure TvisuInfo.displayFunc0(f0:TypefonctionEE;xdeb,xfin:float;nbpt:integer; ExternalWorld,extParam,logX,logY:boolean; mode,taille:integer); var univers:TUnivers; trace:TTracefonction; x1,y1,x2,y2:float; mt,tt:integer; begin if (@f0=nil) then exit; univers:=Tunivers.create; if externalWorld then begin Dgraphic.getWorld(x1,y1,x2,y2); univers.setWorld(x1,y1,x2,y2); univers.setModeLog(LogX,LogY); end else begin univers.setWorld(xmin,ymin,xmax,ymax); univers.setModeLog(modeLogX,modeLogY); end; univers.setInverse(inverseX,inverseY); trace:=TTracefonction.create(univers); trace.setFonction(trace.identA,f0,xdeb,xfin,nbpt); with trace do begin if PRprinting and PRmonochrome then begin setColorTrace(clBlack); setColorTrace2(clBlack); end else begin if ExtParam then begin setColorTrace(canvasGlb.pen.color); setColorTrace2(canvasGlb.pen.color); end else begin setColorTrace(self.color); setColorTrace2(self.color2); end; end; if extParam then begin if mode<>0 then mt:=mode else mt:=modeT; if taille<>0 then tt:=taille else tt:=tailleT; setStyle(mT,tT); end else setStyle(modeT,tailleT); setTrait(largeurTrait,styleTrait); setBarWidth(self.BarWidth); afficher; end; trace.free; univers.free; end; procedure TvisuInfo.displayFunc(f0:TypefonctionEE;xdeb,xfin:float;nbpt:integer); var x1,y1,x2,y2:integer; BKcolor:longint; rectI:Trect; const dd=5; begin fontToGlb; TRY BKcolor:=canvasGlb.brush.color; getWindowG(x1,y1,x2,y2); rectI:=getInsideT; with rectI do setWindow(left,top,right,bottom); displayFunc0(f0,xdeb,xfin,nbpt,false,false,false,false,0,0); DisplayScale; setWindow(x1,y1,x2,y2); FINALLY canvasGlb.brush.color:=BKcolor; resetFontToGlb; END; end; var data0:TdataTbB; dpal:TDpalette; transparentColor0:integer; procedure TvisuInfo.moveWire(poly:Tpoly4;i,j:integer); var x,y,z:integer; z0:float; begin with data0 do if (i>=Imin) and (i<=Imax) and (j>=Jmin) and (j<=Jmax) then z0:=getE(i,j) else z0:=0; x:=(poly[1].x+poly[3].x) div 2; y:=(poly[1].y+poly[3].y) div 2; z:=round(z0); with canvasGlb do begin pen.color:=clBlack; moveto(x,y-z); end; end; procedure TvisuInfo.affPaveWire(poly:Tpoly4;i,j:integer); var x,y,z:integer; z0:float; begin with data0 do if (i>=Imin) and (i<=Imax) and (j>=Jmin) and (j<=Jmax) then z0:=getE(i,j) else z0:=0; x:=(poly[1].x+poly[3].x) div 2; y:=(poly[1].y+poly[3].y) div 2; z:=round(z0); with canvasGlb do begin pen.color:=clBlack; lineto(x,y-z); end; end; procedure TvisuInfo.affPavePhase(poly:Tpoly4;phase:float); var xc,yc,cosA,sinA,cos1,sin1,d1,d2:float; begin phase:=-phase; xc:=(poly[1].x+poly[3].x)/2; yc:=(poly[1].y+poly[3].y)/2; d1:=sqrt(sqr(poly[1].X-poly[2].X)+sqr(poly[1].y-poly[2].y)); d2:=sqrt(sqr(poly[3].X-poly[2].X)+sqr(poly[3].y-poly[2].y)); if (d1<1) or (d2<1) then exit; cosA:=(poly[2].X-poly[3].X)/d1; sinA:=(poly[2].Y-poly[3].Y)/d1; cos1:=cosA*cos(phase)-sinA*sin(phase); sin1:=sinA*cos(phase)+sin(phase)*cosA; if d2<d1 then d1:=d2; d1:=(d1-angularLW)/2; if d1<1 then d1:=1; with canvasGlb do begin moveto(round(xc+d1*cos1),round(yc+d1*sin1)); lineto(round(xc-d1*cos1),round(yc-d1*sin1)); end; end; procedure TvisuInfo.affPaveA(poly:Tpoly4;i,j:integer); var z:float; col:integer; w:TfloatComp; x,y:float; begin if CpxMode>=4 then begin with data0 do case modeMat of 0: w:=getCpxValA(i,j); 1: w:=getCpxSmoothValA3(i,j); 2: w:=getCpxSmoothValA3bis(i,j); end; case CpxMode of 4: begin x:=w.x; y:=w.y; end; 5: begin x:=w.y; y:=w.x; end; 6: begin x:=mdlCpx(w); y:=angleCpx(w); end; 7: begin y:=mdlCpx(w); x:=angleCpx(w); end; end; col:=Dpal.color2D(x,y); end else with data0 do begin case modeMat of 0: z:=getValA(i,j); 1: z:=getSmoothValA3(i,j); 2: z:=getSmoothValA3bis(i,j); end; col:=dpal.colorPal(z); if transparentColor0=col then exit; end; with canvasGlb do begin brush.color:=col; if col=$0100000F then col:=$0100000E; {Un bug sur la couleur 15 !} pen.color:=col; case AngularMode of 0: polyGon(poly); 1: begin canvasGlb.Pen.Width:=angularLW; affPavePhase(poly,z); end; 2: begin case modeMat of 0: w:=data0.getCpxValA(i,j); 1: w:=data0.getCpxSmoothValA3(i,j); 2: w:=data0.getCpxSmoothValA3bis(i,j); end; canvasGlb.Pen.Width:=angularLW; affPavePhase(poly,angleCpx(w)); canvasGlb.Pen.Width:=1; end; end; end; end; procedure TvisuInfo.affPaveA3(poly:Tpoly4;i,j:integer); var col:integer; begin col:=dpal.colorPal(data0.getSmoothValA3(i,j)); with canvasGlb do begin brush.color:=col; if col=$0100000F then col:=$0100000E; {Un bug sur la couleur 15 !} pen.color:=col; polyGon(poly); end; end; procedure TvisuInfo.affPaveA3bis(poly:Tpoly4;i,j:integer); var col:integer; begin col:=dpal.colorPal(data0.getSmoothValA3bis(i,j)); with canvasGlb do begin brush.color:=col; if col=$0100000F then col:=$0100000E; {Un bug sur la couleur 15 !} pen.color:=col; polyGon(poly); end; end; procedure TvisuInfo.affPaveSel(poly:Tpoly4;i,j:integer); var invX,invY:boolean; begin //invX:=inverseX and with canvasGlb do begin if getSelectPixel(i,j) then begin brush.style:=bsClear; pen.Color:=SelectCol; {polygon(poly);} if (data0.ay>0) and not getSelectPixel(i,j-1) or (data0.ay<0) and not getSelectPixel(i,j+1) then begin moveto(poly[1].x,poly[1].y); lineto(poly[2].x,poly[2].y); end; if (data0.ax>0) and not getSelectPixel(i+1,j) or (data0.ax<0) and not getSelectPixel(i-1,j) then begin moveto(poly[2].x,poly[2].y); lineto(poly[3].x,poly[3].y); end; if (data0.ay>0) and not getSelectPixel(i,j+1) or (data0.ay<0) and not getSelectPixel(i,j-1) then begin moveto(poly[3].x,poly[3].y); lineto(poly[4].x,poly[4].y); end; if (data0.ax>0) and not getSelectPixel(i-1,j) or (data0.ax<0) and not getSelectPixel(i+1,j) then begin moveto(poly[4].x,poly[4].y); lineto(poly[1].x,poly[1].y); end; end; if getMarkedPixel(i,j) then begin pen.Color:=MarkCol; moveto(poly[1].x,poly[1].y); lineto(poly[3].x,poly[3].y); moveto(poly[2].x,poly[2].y); lineto(poly[4].x,poly[4].y); end; end; end; function TvisuInfo.getInsideT2(data:TdataTbB):Trect; var x1,y1,x2,y2:integer; xw1,yw1,xw2,yw2:integer; htext,ltext:integer; ratio:float; dx,dy:integer; begin FontToGlb; TRY getWindowG(x1,y1,x2,y2); htext:=canvasGlb.textHeight('1'); ltext:=canvasGlb.textWidth('1000000'); // on réduit d'abord la fenêtre pour tenir compte des échelles xw1:=x1+DispVec_left+ord(echY)*ltext; yw1:=y1+DispVec_Top; xw2:=x2-DispVec_Right; yw2:=y2-ord(echX)*htext-DispVec_Bottom; result:= rect(xw1,yw1,xw2,yw2); // On tient compte ensuite de l'aspectratio if keepRatio and assigned(data) and (data.invConvX(Xmax)-data.invConvX(Xmin)<>0) then begin with data do //ratio:=abs(PixRatio*(invConvY(Ymax)-invConvY(Ymin))/(invConvX(Xmax)-invConvX(Xmin))); ratio:=abs(PixRatio*(Ymax-Ymin)/(Xmax-Xmin)); dx:=xw2-xw1; dy:=yw2-yw1; if dx*ratio<dy then dy:=roundL(dx*ratio) else dx:=roundL(dy/ratio); if dx<4 then dx:=4; if dy<4 then dy:=4; xw1:=(xw1+xw2) div 2 -dx div 2; xw2:=xw1+dx ; yw1:=(yw1+yw2) div 2 -dy div 2; yw2:=yw1+dy; end; result:= rect(xw1,yw1,xw2,yw2); {statuslineTxt(Estr(xw1,1)+' '+Estr(yw1,1)+' '+Estr(xw2,1)+' '+Estr(yw2,1) );} FINALLY resetFontToGlb; END; end; procedure TvisuInfo.getIntegerBounds(data:TdataTbB;var x1,y1,x2,y2:double); begin with data do if Xmin<Xmax then begin X1:=convx(floor(invconvxR(Xmin))); X2:=convx(ceil(invconvxR(Xmax))); end else begin X1:=convx(ceil(invconvxR(Xmin))); X2:=convx(floor(invconvxR(Xmax))); end; with data do if Ymin<Ymax then begin Y1:=convy(floor(invconvyR(Ymin))); Y2:=convy(ceil(invconvyR(Ymax))); end else begin Y1:=convy(ceil(invconvyR(Ymin))); Y2:=convy(floor(invconvyR(Ymax))); end; end; function TvisuInfo.getInsideMat(data:TdataTbB;wf:PwfOptions;degP:typedegre):Trect; var affMat:typeAffmat; x1,y1,x2,y2:integer; aspect:float; begin getWindowG(x1,y1,x2,y2); result:=rect(x1,y1,x2,y2); if (data=nil) or (data.Imax<data.Imin) or (data.Jmax<data.Jmin) then exit; data0:=data; aspect:=data.AspectRatio; if (Xmin=Xmax) or (Ymin=Ymax) or degP.Fuse or assigned(wf) and wf^.active then exit; result:= getInsideT2(data); with result do setWindow(left,top,right,bottom); with affMat do begin (* case modeMat of 0: begin init(data.Imin,data.Jmin,data.Imax,data.Jmax,aspect,0); affPaveU:=affPaveA; setXlimits(data.invConvX(Xmin),data.invConvX(Xmax)-1); setYlimits(data.invConvY(Ymin),data.invConvY(Ymax)-1); end; 1: begin init(data.Imin,data.Jmin, data.Imin+(data.Imax-data.Imin+1)*3,data.Jmin+(data.Jmax-data.Jmin+1)*3, aspect,0); affPaveU:=affPaveA; setXlimits(data.invConvX(Xmin)*3-2,data.invConvX(Xmax)*3-3); setYlimits(data.invConvY(Ymin)*3-2,data.invConvY(Ymax)*3-3); end; 2: begin init(data.Imin,data.Jmin, data.Imin+(data.Imax-data.Imin+1)*3,data.Jmin+(data.Jmax-data.Jmin+1)*3, aspect,0); affPaveU:=affPaveA; setXlimits(data.invConvX(Xmin)*3-2,data.invConvX(Xmax)*3-3); setYlimits(data.invConvY(Ymin)*3-2,data.invConvY(Ymax)*3-3); end; end; {Fwires:=(modeMat=3);} setInv(inverseX,inverseY); setKeepRatio(keepRatio); calculRbase; result:=getIrect; *) setWindow(x1,y1,x2,y2); end; end; procedure TvisuInfo.FastDisplayMat0(ExternalWorld:boolean;palName:AnsiString; Fcell:boolean;Acol,Arow:integer; getSel,getMark:TgetSelectPixel; const TransparentValue:double=0;Ftransparent:boolean=false); var x1e,y1e,x2e,y2e:float; x1,y1,x2,y2:integer; x1g,y1g,x2g,y2g: integer; rectS, rectS1, rectW:Trect; dib:Tbitmap; i,j,i1,j1:integer; p:PtabOctet; w:integer; w1,w2:float; dpal:TDpalette; logPal:TMaxLogPalette; TransparentIndex:integer; invX,invY: boolean; rectU:Trect; deltaX,deltaY:float; poly4: Tpoly4; sgnX,sgnY: integer; function getV(i,j:integer):float; begin with data0 do case modeMat of 0: if (i>=Imin)and (i<=Imax) and (j>=Jmin) and (j<=Jmax) then result:=getE(i,j) else result:=0; 1: result:=getSmoothValA3(i,j); 2: result:=getSmoothValA3bis(i,j); end; end; procedure getVCpx(i,j:integer;var x,y:float); var z:TFloatComp; begin with data0 do case modeMat of 0: z:=getCpxValA(i,j); 1: z:=getCpxSmoothValA3(i,j); 2: z:=getCpxSmoothValA3bis(i,j); end; case CpxMode of 4: begin x:=z.x; y:=z.y; end; 5: begin x:=z.y; y:=z.x; end; 6: begin x:=mdlCpx(z); y:=angleCpx(z); end; 7: begin y:=mdlCpx(z); x:=angleCpx(z); end; end; end; procedure CheckLeftRight; begin with rectS do begin if rectS.left>rectS.Right then swap(left,right); dec(left); inc(right); if top>bottom then swap(top,bottom); dec(Top); inc(Bottom); end; end; function cvx(x:float):integer; begin if not inverseX then result:=convWx(x) else result:=convWxInvert(x); end; function cvy(y:float):integer; begin if not inverseY then result:=convWy(y) else result:=convWyInvert(y); end; begin if Zmin=Zmax then Zmax:=Zmin+1; if externalWorld then Dgraphic.getWorld(x1e,y1e,x2e,y2e) else begin x1e:=Xmin; y1e:=Ymin; x2e:=Xmax; y2e:=Ymax; setWorld(x1e,y1e,x2e,y2e); end; invX:= (x1e>x2e) xor (data0.ax<0) xor inverseX; invY:= (y1e>y2e) xor (data0.ay<0) xor inverseY; dpal:=TDpalette.create; dpal.setColors(TmatColor(color).col1,TmatColor(color).col2,TwoCol,canvasGlb.handle); dpal.setType(palName); dpal.SetPalette(Zmin,Zmax,gamma,modeLogZ); Dib:=Tbitmap.Create; Dib.PixelFormat:= pf8bit; TRY with Dib do begin if cpxMode>=4 then begin dpal.set2DPalette(FullD2); dpal.setChrominance(Cmin,Cmax,gammaC); end; LogPal:=dpal.rgbPalette; Dib.Transparent:= FTransparent; TransparentIndex:=Dpal.ColorIndex(TransparentValue); Dib.TransparentMode:= tmFixed; with LogPal.palPalEntry[TransparentIndex] do Dib.transparentColor:=rgb(peRed,peGreen,peBlue); Palette:= CreatePalette(PlogPalette(@LogPal)^); // rectS définit la zone matrice affichée pour modemat=0 rectS:=rect(data0.invConvX(X1e),data0.invConvY(Y1e),data0.invConvX(X2e),data0.invConvY(Y2e)); checkLeftRight; rectS1:=rectS; // rectW définit la fenêtre en pixels qui doit recevoir exactement rectS // ce calcul est aussi valable pour modeMat<>0 if data0.ax>0 then begin rectW.Left:= cvx(data0.convx(rectS.left)); rectW.Right:= cvx(data0.convx(rectS.right+1)); end else begin rectW.Left:= cvx(data0.convx(rectS.right)); rectW.Right:= cvx(data0.convx(rectS.left-1)); end; if data0.ay>0 then begin rectW.top:= cvy(data0.convy(rectS.top)); rectW.bottom:= cvy(data0.convy(rectS.bottom+1)); end else begin rectW.top:= cvy(data0.convy(rectS.bottom)); rectW.bottom:= cvy(data0.convy(rectS.top-1)); end; checkRectangle(rectW); if modeMat=0 then begin //Dimensionner le dib width:= rectS.Right-rectS.Left+1; height:= rectS.bottom-rectS.top+1; //fill(0); x1:=0; y1:=0; x2:=width-1; y2:=height-1; if rectS.Left+x1<data0.Imin then x1:=data0.Imin-rectS.Left; if rectS.Left+x2>data0.Imax then x2:=data0.Imax-rectS.Left; if rectS.top+y1<data0.Jmin then y1:=data0.Jmin-rectS.top; if rectS.top+y2>data0.Jmax then y2:=data0.Jmax-rectS.top; end else begin rectS:=rect(rectS.left*3-2*data0.Imin,rectS.top*3-2*data0.Jmin, rectS.right*3-2*data0.Imin+2,rectS.bottom*3-2*data0.Jmin+2); width:= rectS.Right-rectS.Left+1; height:= rectS.bottom-rectS.top+1; x1:=0; y1:=0; x2:=width-1; y2:=height-1; end; // si la matrice n'occupe pas toute la fenêtre, on veille à remplir le fond if (x1>0) or (x1<width-1) or (y1>0) or (y1<height-1) then begin Canvas.Brush.Color:=transparentColor; Canvas.Brush.style:=bsSolid; Canvas.Pen.Color:=transparentColor; Canvas.Pen.style:=psSolid; Canvas.fillrect(rect(0,0,Width,height)); end; if cpxMode<4 then begin for j:=y1 to y2 do begin if invY then p:=scanline[j] else p:=scanline[height-1-j]; for i:=x1 to x2 do begin w:=Dpal.colorIndex(getV(rectS.Left+i,rectS.top+j)); if invX then p^[width-1-i]:=w else p^[i]:=w; end; end; end else begin for j:=y1 to y2 do begin if invY then p:=scanline[j] else p:=scanline[height-1-j]; for i:=x1 to x2 do begin getVCpx(rectS.Left+i,rectS.top+j,w1,w2); w:=Dpal.colorIndex2D(w1,w2); if invX then p^[width-1-i]:=w else p^[i]:=w; end; end; end; { statuslineTxt(Istr(rectS.left)+' '+Istr(rectS.top)+' '+Istr(rectS.right)+' '+Istr(rectS.bottom)+' '+ Istr(rectW.left)+' '+Istr(rectW.top)+' '+Istr(rectW.right)+' '+Istr(rectW.bottom) ); } end; canvasGlb.stretchDraw(rectW,Dib ); if assigned(getSel) or assigned(getMark) then begin if data0.ax>0 then sgnX:=1 else sgnX:=-1; if data0.ay>0 then sgnY:=1 else sgnY:=-1; getWorld(x1e,y1e,x2e,y2e); i:=ord(inverseX)+2*ord(inverseY); case i of 0: setWorld(X1e,Y1e,X2e,Y2e); 1: setWorld(X2e,Y1e,X1e,Y2e); 2: setWorld(X1e,Y2e,X2e,Y1e); 3: setWorld(X2e,Y2e,X1e,Y1e); end; for i:=rectS1.Left to rectS1.Right do for j:=rectS1.top to rectS1.bottom do begin if (i>=data0.Imin) and (i<=data0.Imax) and (j>=data0.Jmin) and (j<=data0.Jmax) and ( getSel(i,j) or getMark(i,j)) then begin poly4[1]:= point(convWx(data0.convx(i)),convWy(data0.convy(j))); poly4[2]:= point(convWx(data0.convx(i+sgnX)),convWy(data0.convy(j))); poly4[3]:= point(convWx(data0.convx(i+sgnX)),convWy(data0.convy(j+sgnY))); poly4[4]:= point(convWx(data0.convx(i)),convWy(data0.convy(j+sgnY))); AffPaveSel(poly4,i,j); end; end; setWorld(X1e,Y1e,X2e,Y2e); end; FINALLY dib.Free; dpal.Free; data0.modeCpx:=0; {ISPend;} END; end; procedure TvisuInfo.DisplayMatLog0(ExternalWorld:boolean;palName:AnsiString; Fcell:boolean;Acol,Arow:integer; const TransparentValue:double=0;Ftransparent:boolean=false); var x1e,y1e,x2e,y2e:float; x1,y1,x2,y2:float; i1,j1,i2,j2:integer; i1r,j1r,i2r,j2r:integer; i,j:integer; xb:float; w:integer; w1,w2:float; dpal:TDpalette; function getV(i,j:integer):float; begin with data0 do case modeMat of 0: result:=getE(i,j); 1: result:=getSmoothValA3(i,j); 2: result:=getSmoothValA3bis(i,j); end; end; procedure getVCpx(i,j:integer;var x,y:float); var z:TFloatComp; begin with data0 do case modeMat of 0: z:=getCpxValA(i,j); 1: z:=getCpxSmoothValA3(i,j); 2: z:=getCpxSmoothValA3bis(i,j); end; case CpxMode of 4: begin x:=z.x; y:=z.y; end; 5: begin x:=z.y; y:=z.x; end; 6: begin x:=mdlCpx(z); y:=angleCpx(z); end; 7: begin y:=mdlCpx(z); x:=angleCpx(z); end; end; end; begin if Zmin=Zmax then Zmax:=Zmin+1; if externalWorld then Dgraphic.getWorld(x1e,y1e,x2e,y2e) else begin x1e:=Xmin; y1e:=Ymin; x2e:=Xmax; y2e:=Ymax; end; dpal:=TDpalette.create; dpal.setColors(TmatColor(color).col1,TmatColor(color).col2,TwoCol,canvasGlb.handle); dpal.setType(palName); dpal.SetPalette(Zmin,Zmax,gamma,modeLogZ); try if cpxMode>=4 then begin dpal.set2DPalette(FullD2); dpal.setChrominance(Cmin,Cmax,gammaC); end; if modeMat=0 then begin i1:=data0.invConvX(X1e); j1:=data0.invConvY(Y1e); i2:=data0.invConvX(X2e)-1; j2:=data0.invConvY(Y2e)-1; if i1<data0.Imin then i1:=data0.Imin; if i2>data0.Imax then i2:=data0.Imax; if j1<data0.Jmin then j1:=data0.Jmin; if j2>data0.Jmax then j2:=data0.Jmax; end else begin i1:=data0.invConvX(X1e)*3-2; j1:=data0.invConvY(Y1e)*3-2; i2:=data0.invConvX(X2e)*3-3; j2:=data0.invConvY(Y2e)*3-3; x1e:=3*x1e; x2e:=3*x2e; y1e:=3*y1e; y2e:=3*y2e; end; if modeLogX then begin x1:=log10(x1e); x2:=log10(x2e); end else begin x1:=x1e; x2:=x2e; end; if modeLogY then begin y1:=log10(y1e); y2:=log10(y2e); end else begin y1:=y1e; y2:=y2e; end; if inverseX then begin xb:=x1; x1:=x2; x2:=xb; end; if inverseY then begin xb:=y1; y1:=y2; y2:=xb; end; Dgraphic.setWorld(x1,y1,x2,y2); for j:=j1 to j2 do for i:=i1 to i2 do begin if cpxMode<4 then canvasGlb.Pen.color:=Dpal.ColorPal(getV(i,j)) else begin getVCpx(i,j,w1,w2); canvasGlb.Pen.color:=Dpal.color2D(w1,w2); end; canvasGlb.brush.color:=canvasGlb.pen.color; if modeLogX then begin i1r:=convWx(log10(data0.convx(i))); i2r:=convWx(log10(data0.convx(i+1))); end else begin i1r:=convWx(data0.convx(i)); i2r:=convWx(data0.convx(i+1)); end; if modeLogY then begin j1r:=convWy(log10(data0.convy(j))); j2r:=convWy(log10(data0.convy(j+1))); end else begin j1r:=convWy(data0.convy(j)); j2r:=convWy(data0.convy(j+1)); end; if i1r>i2r then swap(i1r,i2r); if j1r>j2r then swap(j1r,j2r); inc(i2r); inc(j2r); canvasGlb.rectangle(i1r,j1r,i2r,j2r); end; FINALLY dpal.Free; data0.modeCpx:=0; {ISPend;} END; end; function TvisuInfo.MatFastCondition(wf:PwfOptions;degP:typedegre): boolean; begin result:= (not degP.Fuse) and ((wf=nil) or not wf.active ) and (Angularmode=0) and not (PRprinting and PRsplitMatrix) end; procedure TvisuInfo.displayMat0(data:TdataTbB;externalWorld:boolean;palName:AnsiString; Fcell:boolean;Acol,Arow:integer; wf:PwfOptions;degP:typedegre; getSel,getMark:TgetSelectPixel; const TransparentValue:double=0;Ftransparent:boolean=false; ForceNotFast:boolean=false); var i:integer; affMat:typeAffmat; x1e,y1e,x2e,y2e:float; x1,y1,x2,y2:integer; Mtop1,Mbottom1,Mleft1,Mright1:integer; aspect:float; theta1:float; degPix:typedegre; poly: typePoly5R; xminA,yminA,xmaxA,ymaxA,dxmax,dymax:float; di,dj:integer; R:float; begin if (data=nil) or (data.aspectRatio=0) or (data.Imax<data.Imin) or (data.Jmax<data.Jmin) then exit; if (Xmin=Xmax) or (Ymin=Ymax) then exit; data0:=data; aspect:= data0.AspectRatio; if degP.Fuse then // Affichage multigraph avec params position begin if (degP.dx<=0) or (degP.dy<=0) then exit; theta1:= degP.theta; degToPolyR(degP,poly); xminA:= 1E100; xmaxA:=-1E100; yminA:= 1E100; ymaxA:=-1E100; for i:=1 to 4 do begin if poly[i].x < xminA then xminA:=poly[i].x; if poly[i].x > xmaxA then xmaxA:=poly[i].x; if poly[i].y < yminA then yminA:=poly[i].y; if poly[i].y > ymaxA then ymaxA:=poly[i].y; end; dxmax:=xmaxA-xminA; dymax:=ymaxA-yminA; di:=x2act-x1act; dj:=y2act-y1act; if dymax/dxmax>dj/di then R:=dymax/dj else R:=dxmax/di; degPix.x:= (x1act+x2act)/2 ; degPix.y:= (y1act+y2act)/2; degPix.dx:= degP.dx/R; degPix.dy:= degP.dy/R; degPix.theta:= degP.theta; end else if degP.Fcontrol then // Affichage controle avec params position theta1:= degP.theta else theta1:=0; getSelectPixel:=getSel; getMarkedPixel:=getMark; data0.modeCpx:=CpxMode mod 4; if externalWorld then Dgraphic.getWorld(x1e,y1e,x2e,y2e) else begin x1e:=Xmin; y1e:=Ymin; x2e:=Xmax; y2e:=Ymax; end; if modeLogX or modeLogY then DisplayMatLog0(ExternalWorld,palName,Fcell,Acol,Arow) else if MatFastCondition(wf,degP) and not ForceNotFast then begin FastDisplayMat0(ExternalWorld,palName,Fcell,Acol,Arow, getSel,getMark, TransparentValue, Ftransparent); exit; end else with affMat do begin case modeMat of 0: begin init(data.Imin,data.Jmin,data.Imax,data.Jmax,aspect, theta1); affPaveU:=affPaveA; setXlimits(data.invConvX(X1e),data.invConvX(X2e)-1); setYlimits(data.invConvY(Y1e),data.invConvY(Y2e)-1); end; 1: begin init(data.Imin,data.Jmin, data.Imin+(data.Imax-data.Imin+1)*3,data.Jmin+(data.Jmax-data.Jmin+1)*3, aspect, theta1); affPaveU:=affPaveA; setXlimits(data.invConvX(X1e)*3-2,data.invConvX(X2e)*3-3); setYlimits(data.invConvY(Y1e)*3-2,data.invConvY(Y2e)*3-3); end; 2: begin init(data.Imin,data.Jmin, data.Imin+(data.Imax-data.Imin+1)*3,data.Jmin+(data.Jmax-data.Jmin+1)*3, aspect, theta1); affPaveU:=affPaveA; setXlimits(data.invConvX(X1e)*3-2,data.invConvX(X2e)*3-3); setYlimits(data.invConvY(Y1e)*3-2,data.invConvY(Y2e)*3-3); end; end; {Fwires:=(modeMat=3);} dpal:=TDpalette.create; dpal.setColors(TmatColor(color).col1,TmatColor(color).col2,TwoCol,canvasGlb.handle); dpal.setType(palName); dpal.SetPalette(Zmin,Zmax,gamma,modeLogZ); if Ftransparent then TransparentColor0:=Dpal.ColorPal(TransparentValue) else TransparentColor0:= -1; if cpxMode>=4 then begin dpal.set2DPalette(FullD2); dpal.setChrominance(Cmin,Cmax,gammaC); end; setInv(inverseX,inverseY); setKeepRatio(keepRatio); if assigned(wf) and wf^.active and not degP.Fuse then with wf^ do begin getWindowG(x1,y1,x2,y2); Mtop1:=round((y2-y1)*Mtop/100); Mleft1:=round((x2-x1)*Mleft/100); Mbottom1:=round((y2-y1)*Mbottom/100); Mright1:=round((x2-x1)*Mright/100); setClipRegion(x1,y1,x2,y2); setWindow(x1+Mleft1,y1+Mtop1,x2-Mright1,y2-Mbottom1); setDxAffDyAff(dxAff,dyAff); end; if Fcell then afficheCell(Acol,Arow) else if degP.Fuse then With DegPix do displayInRect(x,y,dx,dy,theta) else if degP.Fcontrol then With DegP do displayInRect(x,y,dx,dy,theta) else affiche; dpal.free; end; if assigned(getSel) or assigned(getMark) then with affMat do begin init(data.Imin,data.Jmin,data.Imax,data.Jmax,aspect,theta1); setXlimits(data.invConvX(X1e),data.invConvX(X2e)-1); setYlimits(data.invConvY(Y1e),data.invConvY(Y2e)-1); setInv(inverseX,inverseY); setKeepRatio(keepRatio); if assigned(wf) and wf^.active and not degP.Fuse then with wf^ do begin getWindowG(x1,y1,x2,y2); Mtop1:=round((y2-y1)*Mtop/100); Mleft1:=round((x2-x1)*Mleft/100); Mbottom1:=round((y2-y1)*Mbottom/100); Mright1:=round((x2-x1)*Mright/100); setWindow(x1+Mleft1,y1+Mtop1,x2-Mright1,y2-Mbottom1); setDxAffDyAff(dxAff,dyAff); end; affPaveU:=affPaveSel; if not degP.Fuse then affiche else with degPix do displayInRect(x,y,dx,dy,theta); {drawBorder(clWhite);} with getIrect do setWindow(left,top,right,bottom); end; data.modeCpx:=0; end; procedure TvisuInfo.displayMat(data:TdataTbB;palName:AnsiString; Fcell:boolean;Acol,Arow:integer; wf:PwfOptions;degP:typedegre; getSel,getMark:TgetSelectPixel; const TransparentValue:double=0;Ftransparent:boolean=false); var x1,y1,x2,y2:integer; BKcolor:longint; withWF:boolean; begin fontToGlb; TRY BKcolor:=canvasGlb.brush.color; withWF:=assigned(wf) and wf^.active; getWindowG(x1,y1,x2,y2); if not withWF then with getInsideMat(data,wf,degP) do setWindow(left,top,right,bottom); displayMat0(data,false,palName,Fcell,Acol,Arow,wf,degP,getSel,getMark, TransparentValue, Ftransparent); if (not degP.Fuse) {and not Fcell} and not(assigned(wf) and wf^.active) {and (modeMat<>3)} then DisplayScale; setWindow(x1,y1,x2,y2); FINALLY canvasGlb.brush.color:=BKcolor; resetFontToGlb; END; end; function TvisuInfo.getMatPos(data:TdataTbB;wf:PwfOptions;degP:typedegre;var x,y:integer):boolean; var x1,y1,x2,y2:integer; withWF:boolean; Mtop1,Mbottom1,Mleft1,Mright1:integer; affMat:typeAffmat; aspect:float; theta1:float; Xr,Yr: float; i:integer; begin result:=false; if data=nil then exit; getWindowG(x1,y1,x2,y2); if MatFastCondition(wf,degP) then begin with getInsideT2(data) do setWindow(left,top,right,bottom,true); i:=ord(inverseX)+2*ord(inverseY); case i of 0: setWorld(Xmin,Ymin,Xmax,Ymax); 1: setWorld(Xmax,Ymin,Xmin,Ymax); 2: setWorld(Xmin,Ymax,Xmax,Ymin); 3: setWorld(Xmax,Ymax,Xmin,Ymin); end; Xr:= invconvWx(x); Yr:= invconvWy(y); with data do begin if (ax<0) then x:= ceil((Xr-bx)/ax) else x:= floor((Xr-bx)/ax); if (ay<0) then y:= ceil((Yr-by)/ax) else y:= floor((Yr-by)/ay); result:= (x>=Imin) and (x<=Imax) and (y>=Jmin) and (y<=Jmax); end; setWindow(x1,y1,x2,y2); exit; end; if degP.Fuse then theta1:=degP.theta else theta1:=0; fontToGlb; TRY withWF:=assigned(wf) and wf^.active; if not withWF and not degP.Fuse then with getInsideT2(data) do setWindow(left,top,right,bottom); aspect:=data.aspectRatio; with affMat do begin init(data.Imin,data.Jmin,data.Imax,data.Jmax,aspect,theta1); setXlimits(data.invConvX(Xmin),data.invConvX(Xmax)-1); setYlimits(data.invConvY(Ymin),data.invConvY(Ymax)-1); setInv(inverseX,inverseY); setKeepRatio(keepRatio); if withWF then with wf^ do begin getWindowG(x1,y1,x2,y2); Mtop1:=round((y2-y1)*Mtop/100); Mleft1:=round((x2-x1)*Mleft/100); Mbottom1:=round((y2-y1)*Mbottom/100); Mright1:=round((x2-x1)*Mright/100); setWindow(x1+Mleft1,y1+Mtop1,x2-Mright1,y2-Mbottom1); setDxAffDyAff(dxAff,dyAff); end; result:=getPixelPos(x,y); end; FINALLY setWindow(x1,y1,x2,y2); resetFontToGlb; END; end; function TvisuInfo.getMatPos(data:TdataTbB;wf:PwfOptions;degP:typedegre;var x,y:float):boolean; var x1,y1,x2,y2:integer; withWF:boolean; Mtop1,Mbottom1,Mleft1,Mright1:integer; affMat:typeAffmat; aspect:float; theta1:float; Xr,Yr: float; i:integer; begin result:=false; if data=nil then exit; getWindowG(x1,y1,x2,y2); if MatFastCondition(wf,degP) then begin with getInsideT2(data) do setWindow(left,top,right,bottom,true); i:=ord(inverseX)+2*ord(inverseY); case i of 0: setWorld(Xmin,Ymin,Xmax,Ymax); 1: setWorld(Xmax,Ymin,Xmin,Ymax); 2: setWorld(Xmin,Ymax,Xmax,Ymin); 3: setWorld(Xmax,Ymax,Xmin,Ymin); end; Xr:= invconvWx(round(x)); Yr:= invconvWy(round(y)); with data do begin x:= (Xr-bx)/ax; y:= (Yr-by)/ax; result:= (x>=Imin) and (x<=Imax) and (y>=Jmin) and (y<=Jmax); end; setWindow(x1,y1,x2,y2); exit; end; fontToGlb; TRY if degP.Fuse then theta1:=degP.theta else theta1:=0; withWF:=assigned(wf) and wf^.active; getWindowG(x1,y1,x2,y2); if not withWF and not degP.Fuse then with getInsideT2(data) do setWindow(left,top,right,bottom); aspect:=data.aspectRatio; with affMat do begin init(data.Imin,data.Jmin,data.Imax,data.Jmax,aspect,theta1); setXlimits(data.invConvX(Xmin),data.invConvX(Xmax)-1); setYlimits(data.invConvY(Ymin),data.invConvY(Ymax)-1); setInv(inverseX,inverseY); setKeepRatio(keepRatio); if withWF then with wf^ do begin getWindowG(x1,y1,x2,y2); Mtop1:=round((y2-y1)*Mtop/100); Mleft1:=round((x2-x1)*Mleft/100); Mbottom1:=round((y2-y1)*Mbottom/100); Mright1:=round((x2-x1)*Mright/100); setWindow(x1+Mleft1,y1+Mtop1,x2-Mright1,y2-Mbottom1); setDxAffDyAff(dxAff,dyAff); end; result:=getPixelPos(x,y); end; FINALLY setWindow(x1,y1,x2,y2); resetFontToGlb; END; end; procedure TvisuInfo.cadrerX(data:typeDataB); var min,max:float; begin if data=nil then exit; if CpxMode>=4 then data.LimitesY(min,max,0,0) else begin if modeT=DM_evt1 then begin if EpDuration>0 then begin min:=0; max:=EpDuration; end else data.limitesY(min,max,0,0); end else data.limitesX(min,max); end; if min<=max then begin Xmin:=min; Xmax:=max; end; end; procedure TvisuInfo.cadrerY(data:typeDataB); var min,max:float; begin if data=nil then exit; if CpxMode>=4 then begin data.modeCpx:=1; data.LimitesY(min,max,0,0); end else begin data.modeCpx:=CpxMode; if modeT=DM_evt1 then begin min:=-100; max:=100; end else data.limitesY(min,max,0,0); end; if min<=max then begin Ymin:=min; Ymax:=max; end; data.modeCpx:=0; end; procedure TvisuInfo.cadrerYlocal(data:typeDataB); var min,max,delta:float; begin if data=nil then exit; if cpxMode<4 then data.modeCpx:=CpxMode; if modeT=DM_evt1 then begin min:=-100; max:=100; end else begin data.limitesY(min,max,data.invconvx(Xmin),data.invconvx(Xmax)); end; delta:=max-min; Ymin:=min-delta/10; Ymax:=max+delta/10; data.modeCpx:=0; end; procedure TvisuInfo.translateCoo(plus:boolean); var d:float; begin d:=Xmax-Xmin; if plus then begin Xmin:=Xmin+d; Xmax:=Xmax+d; end else begin Xmin:=Xmin-d; Xmax:=Xmax-d; end; end; procedure TvisuInfo.transferOldVisu(var oldVisu:ToldVisuInfo); begin Xmin:=oldVisu.Xmin; Xmax:=oldVisu.Xmax; Ymin:=oldVisu.Ymin; Ymax:=oldVisu.Ymax; Zmin:=oldVisu.Zmin; Zmax:=oldVisu.Zmax; gamma:=oldVisu.gamma; //_aspect:=oldVisu.aspect; ux:=oldVisu.ux; uy:=oldVisu.uy; color:=oldVisu.color; twoCol:=oldVisu.twoCol; modeT:=oldVisu.modeT; tailleT:=oldVisu.tailleT; largeurTrait:=oldVisu.largeurTrait; styleTrait:=oldVisu.styleTrait; modeLogX:=oldVisu.modeLogX; modeLogY:=oldVisu.modeLogY; grille:=oldVisu.grille; cpX:=oldVisu.cpx; cpY:=oldVisu.cpy; cpZ:=oldVisu.cpz; echX:=oldVisu.echX; echY:=oldVisu.echY; FtickX:=oldVisu.FtickX; FtickY:=oldVisu.FtickY; CompletX:=oldVisu.completX; completY:=oldVisu.completY; TickExtX:=oldVisu.TickExtX; TickExtY:=oldVisu.TickExtY; ScaleColor:=oldVisu.ScaleColor; fontDescA:=oldVisu.fontDesc; initFont; //theta:=oldVisu.theta; inverseX:=false; inverseY:=false; Epduration:=oldVisu.EpDuration; end; procedure TvisuInfo.displayColorMap0(name:AnsiString;dir,Ncol:integer); var i:integer; x1,x2:integer; dp:TDpalette; k,w,h:integer; begin dp:=TDpalette.create; dp.setColors(TmatColor(color).col1,TmatColor(color).col2,TwoCol,canvasGlb.handle); dp.setType(Name); dp.SetPalette(Zmin,Zmax,gamma,modeLogZ); with canvasGlb do begin w:=x2act-x1act+1; h:=y2act-y1act+1; brush.style:=bsSolid; pen.style:=psSolid; case dir of 0:for i:=0 to nCol-1 do begin x1:=x1act+round(w/nCol*i); x2:=x1act+round(w/nCol*(i+1)); k:=dp.ColorPal(Zmin+i*(Zmax-Zmin)/(nCol-1)); brush.color:=k; pen.color:=k; rectangle(x1-1,y1act,x2+1,y2act+2); end; 1:for i:=0 to nCol-1 do begin x2:=y2act-round(h/nCol*i); x1:=y2act-round(h/nCol*(i+1)); k:=dp.ColorPal(Zmin+i*(Zmax-Zmin)/(nCol-1)); brush.color:=k; pen.color:=k; rectangle(x1act,x1-1,x2act+1,x2+1); end; 2:for i:=0 to nCol-1 do begin x2:=x2act-round(w/nCol*i); x1:=x2act-round(w/nCol*(i+1)); k:=dp.ColorPal(Zmin+i*(Zmax-Zmin)/(nCol-1)); brush.color:=k; pen.color:=k; rectangle(x1-1,y1act,x2+1,y2act+2); end; 3:for i:=0 to nCol-1 do begin x1:=y1act+round(h/nCol*i); x2:=y1act+round(h/nCol*(i+1)); k:=dp.ColorPal(Zmin+i*(Zmax-Zmin)/(nCol-1)); brush.color:=k; pen.color:=k; rectangle(x1act,x1-1,x2act+1,x2+1); end; end; end; dp.free; end; procedure TvisuInfo.displayColorMap(name:AnsiString;dir,Ncol:integer); var x1,y1,x2,y2:integer; BKcolor:longint; rectI:Trect; begin FontToGlb; TRY BKcolor:=canvasGlb.brush.color; getWindowG(x1,y1,x2,y2); rectI:=getInsideT; with rectI do setWindow(left,top,right,bottom); displayColorMap0(name,dir,Ncol); DisplayScale; setWindow(x1,y1,x2,y2); Finally canvasGlb.brush.color:=BKcolor; resetFontToGlb; End; end; procedure TvisuInfo.controle; begin if Xmin=Xmax then begin Xmin:=0; Xmax:=100; end; if Ymin=Ymax then begin Ymin:=0; Ymax:=100; end; if (modeT<1) or (modeT>nbStyleTrace) then begin modeT:=1; end; if (gamma<=0) then begin gamma:=1; end; end; procedure TvisuInfo.FontToGlb; begin if not assigned(canvasGlb) then exit; if fontvisu=nil then initFont; if FontCnt=0 then begin oldFont:=canvasGlb.font; canvasGlb.font:=fontVisu; if PRprinting and not FmagFont then begin canvasGlb.font.size:=round(canvasGlb.font.size*PRfontMag); FmagFont:=true; end; end; inc(FontCnt); end; procedure TvisuInfo.resetFontToGlb; begin if not assigned(canvasGlb) then exit; dec(fontCnt); if FontCnt=0 then begin if FmagFont then canvasGlb.font.size:=round(canvasGlb.font.size/PRfontMag); FmagFont:=false; canvasGlb.Font:=oldFont; end; end; function TvisuInfo.info(ww:AnsiString): AnsiString; begin result:=ww+'MinMax='+Estr(Xmin,3)+','+Estr(Xmax,3)+',' +Estr(Ymin,3)+','+Estr(Ymax,3)+',' +Estr(Zmin,3)+','+Estr(Zmax,3)+CRLF+ ww+'gamma='+Estr(gamma,3)+CRLF+ {ww+'aspect='+Estr(aspect,3)+CRLF+} ww+'Ux='+ux+CRLF+ ww+'Uy='+uy+CRLF+ ww+'color='+Istr(color)+CRLF+ ww+'twoCol='+Bstr(twocol)+CRLF+ ww+'modeT='+Istr(modeT)+CRLF+ ww+'tailleT='+Istr(tailleT)+CRLF+ ww+'lineWidth='+Istr(largeurTrait)+CRLF+ ww+'StyleT='+Istr(styleTrait)+CRLF+ ww+'logX='+Bstr(modeLogX)+CRLF+ ww+'logY='+Bstr(modeLogY)+CRLF+ ww+'Grid='+Bstr(grille)+CRLF+ ww+'CP='+Istr(cpX)+','+Istr(cpY)+','+Istr(cpZ)+CRLF+ ww+'Ech='+Bstr(echX)+','+Bstr(echY)+CRLF+ ww+'Ftick='+Bstr(FtickX)+','+Bstr(FtickY)+CRLF+ ww+'Complet='+Bstr(completX)+','+Bstr(completY)+CRLF+ ww+'TickExt='+Bstr(TickExtX)+','+Bstr(TickExtY)+CRLF+ ww+'ScaleColor='+Istr(scaleColor)+CRLF+ ww+'fontDesc='+fontDescA.info+Crlf+ ww+'font='+Istr(intG(fontVisu))+CRLF+ //ww+'theta='+Estr(theta,3)+CRLF+ ww+'inverse='+Bstr(inverseX)+','+Bstr(inverseY)+CRLF+ ww+'Epduration='+Estr(EpDuration,3)+CRLF+ ww+'ModeMat='+Istr(modeMat)+CRLF+ ww+'keepRatio='+Bstr(keepRatio)+CRLF+ ww+'color2='+Istr(color2)+CRLF+ ww+'getS='+Istr(intG(@@getselectPixel))+','+Istr(intG(@@getMarkedPixel))+CRLF+ ww+'selectCol='+Istr(selectCol)+CRLF+ ww+'MarkCol='+Istr(MarkCol); end; function TvisuInfo.compare(visu1:TvisuInfo):boolean; var p1,p2:pointer; begin result:=(fontVisu.name=visu1.fontVisu.name) and (fontVisu.size=visu1.fontVisu.size) and (fontVisu.Style=visu1.fontVisu.style) and (fontVisu.Color=visu1.fontVisu.color); if result then begin p1:=fontVisu; p2:=visu1.fontVisu; fontVisu:=nil; visu1.fontVisu:=nil; result:=comparemem(@self,@visu1,sizeof(TvisuInfo)); fontVisu:=p1; visu1.fontVisu:=p2; end; end; Initialization AffDebug('Initialization visu0',0); visuModel.init; end.
unit Aurelius.Schema.Utils; {$I Aurelius.Inc} interface uses Generics.Collections, Aurelius.Sql.Metadata; type TSchemaUtils = class public class function GetReferencingForeignKeys(Database: TDatabaseMetadata; ReferencedTable: TTableMetadata): TArray<TForeignKeyMetadata>; class function FindTable(Database: TDatabaseMetadata; const TableName, TableSchema: string): TTableMetadata; class function GetTable(Database: TDatabaseMetadata; const TableName, TableSchema: string): TTableMetadata; class function FindSequence(Database: TDatabaseMetadata; const SequenceName: string): TSequenceMetadata; class function FindColumn(Table: TTableMetadata; const ColumnName: string): TColumnMetadata; class function GetColumn(Table: TTableMetadata; const ColumnName: string): TColumnMetadata; class function FindForeignKey(Table: TTableMetadata; const ForeignKeyName: string): TForeignKeyMetadata; class function FindUniqueKey(Table: TTableMetadata; const UniqueKeyName: string): TUniqueKeyMetadata; end; implementation uses SysUtils, Aurelius.Schema.Exceptions; { TSchemaUtils } class function TSchemaUtils.FindColumn(Table: TTableMetadata; const ColumnName: string): TColumnMetadata; var Column: TColumnMetadata; begin for Column in Table.Columns do if SameText(Column.Name, ColumnName) then Exit(Column); Result := nil; end; class function TSchemaUtils.FindForeignKey(Table: TTableMetadata; const ForeignKeyName: string): TForeignKeyMetadata; var ForeignKey: TForeignKeyMetadata; begin for ForeignKey in Table.ForeignKeys do if SameText(ForeignKey.Name, ForeignKeyName) then Exit(ForeignKey); Result := nil; end; class function TSchemaUtils.FindSequence(Database: TDatabaseMetadata; const SequenceName: string): TSequenceMetadata; var Sequence: TSequenceMetadata; begin for Sequence in Database.Sequences do if SameText(Sequence.Name, SequenceName) then Exit(Sequence); Result := nil; end; class function TSchemaUtils.FindTable(Database: TDatabaseMetadata; const TableName, TableSchema: string): TTableMetadata; var Table: TTableMetadata; begin for Table in Database.Tables do if SameText(Table.Name, TableName) and SameText(Table.Schema, TableSchema) then Exit(Table); Result := nil; end; class function TSchemaUtils.FindUniqueKey(Table: TTableMetadata; const UniqueKeyName: string): TUniqueKeyMetadata; var UniqueKey: TUniqueKeyMetadata; begin for UniqueKey in Table.UniqueKeys do if SameText(UniqueKey.Name, UniqueKeyName) then Exit(UniqueKey); Result := nil; end; class function TSchemaUtils.GetColumn(Table: TTableMetadata; const ColumnName: string): TColumnMetadata; begin Result := FindColumn(Table, ColumnName); if Result = nil then raise EColumnMetadataNotFound.Create(ColumnName, Table.Name); end; class function TSchemaUtils.GetReferencingForeignKeys(Database: TDatabaseMetadata; ReferencedTable: TTableMetadata): TArray<TForeignKeyMetadata>; var Table: TTableMetadata; ForeignKey: TForeignKeyMetadata; ForeignKeys: TList<TForeignKeyMetadata>; {$IFNDEF DELPHIXE_LVL} I: integer; {$ENDIF} begin ForeignKeys := TList<TForeignKeyMetadata>.Create; try for Table in Database.Tables do for ForeignKey in Table.ForeignKeys do begin if SameText(ForeignKey.ToTable.Name, ReferencedTable.Name) and SameText(ForeignKey.ToTable.Schema, ReferencedTable.Schema) then ForeignKeys.Add(ForeignKey); end; {$IFDEF DELPHIXE_LVL} Result := ForeignKeys.ToArray; {$ELSE} SetLength(Result, ForeignKeys.Count); for I := 0 to ForeignKeys.Count - 1 do Result[I] := ForeignKeys[I]; {$ENDIF} finally ForeignKeys.Free; end; end; class function TSchemaUtils.GetTable(Database: TDatabaseMetadata; const TableName, TableSchema: string): TTableMetadata; begin Result := FindTable(Database, TableName, TableSchema); if Result = nil then raise ETableMetadataNotFound.Create(TableName, TableSchema); end; end.
{ ****************************************************************************** } { * Core cipher Library ,writen by QQ 600585@qq.com * } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } (* update history 2017-11-26 fixed fastMD5,THashMD5 calculate x64 and x86,ARM platform more than 4G memory Support QQ600585 change name TMD5Class as THashMD5 Added global DefaultParallelDepth 2017-12-6 added supported hash elf64 2017-12-7 added System default key 2018-5-16 remove pasmp 2018-9 fixed rc6 with arm Linux *) unit CoreCipher; { core cipher engine. create by qq600585 } {$INCLUDE zDefine.inc} // debug used // {$UNDEF RangeCheck} // {$UNDEF OverflowCheck} {$O+} interface uses Types, SysUtils, Math, TypInfo, {$IFDEF FastMD5} Fast_MD5, {$ENDIF} CoreClasses, UnicodeMixedLib, MemoryStream64, PascalStrings, ListEngine; {$REGION 'BaseDefine'} const { largest structure that can be created } MaxStructSize = MaxInt; { 2G } cIntSize = 4; cKeyDWORDSize = 4; cKey2DWORDSize = 8; cKey64Size = 8; cKey128Size = 16; cKey192Size = 24; cKey256Size = 32; type PDWORD = ^DWORD; { general structures } PDWordArray = ^TDWordArray; TDWordArray = array [0 .. MaxStructSize div SizeOf(DWORD) - 1] of DWORD; TCCByteArray = array [0 .. MaxStructSize div SizeOf(Byte) - 1] of Byte; PCCByteArray = ^TCCByteArray; TInt32 = packed record case Byte of 1: (Lo: Word; Hi: Word); 2: (LoLo: Byte; LoHi: Byte; HiLo: Byte; HiHi: Byte); 3: (i: Integer); 4: (u: DWORD); end; TInt64 = packed record case Byte of 0: (Lo: Integer; Hi: Integer); 1: (LoLo: Word; LoHi: Word; HiLo: Word; HiHi: Word); 2: (LoLoLo: Byte; LoLoHi: Byte; LoHiLo: Byte; LoHiHi: Byte; HiLoLo: Byte; HiLoHi: Byte; HiHiLo: Byte; HiHiHi: Byte); 3: (i: Int64); 4: (u: UInt64); end; { encryption key types } type PKey64 = ^TKey64; { !!.03 } TKey64 = array [0 .. 7] of Byte; PKey128 = ^TKey128; { !!.03 } TKey128 = array [0 .. 15] of Byte; PKey256 = ^TKey256; { !!.03 } TKey256 = array [0 .. 31] of Byte; { encryption block types } PLBCBlock = ^TLBCBlock; TLBCBlock = array [0 .. 3] of DWORD; { LBC block } PDESBlock = ^TDESBlock; TDESBlock = array [0 .. 7] of Byte; { DES block } PLQCBlock = ^TLQCBlock; TLQCBlock = array [0 .. 1] of DWORD; { Quick Cipher,no LBC key generate } PBFBlock = ^TBFBlock; TBFBlock = array [0 .. 1] of DWORD; { BlowFish } PXXTEABlock = ^TXXTEABlock; TXXTEABlock = array [0 .. 63] of Byte; { XXTEA } TDesConverter = packed record case Byte of 0: (Bytes: array [0 .. 7] of Byte); 1: (DWords: array [0 .. 1] of DWORD) end; P128Bit = ^T128Bit; T128Bit = array [0 .. 3] of DWORD; P256Bit = ^T256Bit; T256Bit = array [0 .. 7] of DWORD; TTransformOutput = array [0 .. 3] of DWORD; PTransformInput = ^TTransformInput; TTransformInput = array [0 .. 15] of DWORD; { context type constants } const BFRounds = 16; { 16 blowfish rounds } { block cipher context types } type { Blowfish } PBFContext = ^TBFContext; TBFContext = packed record PBox: array [0 .. (BFRounds + 1)] of DWORD; SBox: array [0 .. 3, 0 .. 255] of DWORD; end; { DES } PDESContext = ^TDESContext; TDESContext = packed record TransformedKey: array [0 .. 31] of DWORD; Encrypt: Boolean; end; { 3 DES } PTripleDESContext = ^TTripleDESContext; TTripleDESContext = array [0 .. 1] of TDESContext; PTripleDESContext3Key = ^TTripleDESContext3Key; TTripleDESContext3Key = array [0 .. 2] of TDESContext; { !!.01 } { LBC Cipher context } PLBCContext = ^TLBCContext; TLBCContext = packed record Encrypt: Boolean; Dummy: array [0 .. 2] of Byte; { filler } Rounds: Integer; case Byte of 0: (SubKeys64: array [0 .. 15] of TKey64); 1: (SubKeysInts: array [0 .. 3, 0 .. 7] of DWORD); end; { LSC stream cipher } PLSCContext = ^TLSCContext; TLSCContext = packed record index: Integer; Accumulator: Integer; SBox: array [0 .. 255] of Byte; end; { random number stream ciphers } PRNG32Context = ^TRNG32Context; TRNG32Context = array [0 .. 3] of Byte; PRNG64Context = ^TRNG64Context; TRNG64Context = array [0 .. 7] of Byte; { message digest blocks } PMD5Digest = ^TMD5Digest; TMD5Digest = TMD5; { 128 bits - MD5 } TMD5Key = TMD5Digest; PSHA1Digest = ^TSHA1Digest; TSHA1Digest = array [0 .. 19] of Byte; { 160 bits - SHA-1 } TSHA1Key = TSHA1Digest; PSHA256Digest = ^TSHA256Digest; TSHA256Digest = array [0 .. 31] of Byte; { 256 bits - SHA-256 } TSHA256Key = TSHA256Digest; PSHA512Digest = ^TSHA512Digest; TSHA512Digest = array [0 .. 63] of Byte; { 512 bits - SHA-512 } TSHA512Key = TSHA512Digest; PSHA3_224_Digest = ^TSHA3_224_Digest; PSHA3_256_Digest = ^TSHA3_256_Digest; PSHA3_384_Digest = ^TSHA3_384_Digest; PSHA3_512_Digest = ^TSHA3_512_Digest; TSHA3_224_Digest = array [0 .. 224 div 8 - 1] of Byte; TSHA3_256_Digest = array [0 .. 256 div 8 - 1] of Byte; TSHA3_384_Digest = array [0 .. 384 div 8 - 1] of Byte; TSHA3_512_Digest = array [0 .. 512 div 8 - 1] of Byte; { message digest context types } TLMDContext = packed record DigestIndex: Integer; Digest: array [0 .. 255] of Byte; KeyIndex: Integer; case Byte of 0: (KeyInts: array [0 .. 3] of DWORD); 1: (key: TKey128); end; PMD5Context = ^TMD5Context; TMD5Context = packed record { MD5 } Count: array [0 .. 1] of DWORD; { number of bits handled mod 2^64 } State: TTransformOutput; { scratch buffer } Buf: array [0 .. 63] of Byte; { input buffer } end; TSHA1Context = packed record { SHA-1 } sdHi: DWORD; sdLo: DWORD; sdIndex: NativeUInt; sdHash: array [0 .. 4] of DWORD; sdBuf: array [0 .. 63] of Byte; end; {$ENDREGION 'BaseDefine'} type { key style and auto Encrypt } TCipherSecurity = (csNone, csDES64, csDES128, csDES192, csBlowfish, csLBC, csLQC, csRNG32, csRNG64, csLSC, // mini cipher csXXTea512, // NIST cipher csRC6, csSerpent, csMars, csRijndael, csTwoFish); TCipherSecuritys = set of TCipherSecurity; TCipherSecurityArray = array of TCipherSecurity; TCipherKeyStyle = (cksNone, cksKey64, cks3Key64, cksKey128, cksKey256, cks2IntKey, cksIntKey, ckyDynamicKey); PCipherKeyBuffer = ^TCipherKeyBuffer; TCipherKeyBuffer = TBytes; THashSecurity = ( hsNone, hsFastMD5, hsMD5, hsSHA1, hsSHA256, hsSHA512, hsSHA3_224, hsSHA3_256, hsSHA3_384, hsSHA3_512, hs256, hs128, hs64, hs32, hs16, hsELF, hsELF64, hsMix128, hsCRC16, hsCRC32); THashSecuritys = set of THashSecurity; TCipher = class(TCoreClassObject) public const CAllHash: THashSecuritys = [ hsNone, hsFastMD5, hsMD5, hsSHA1, hsSHA256, hsSHA512, hsSHA3_224, hsSHA3_256, hsSHA3_384, hsSHA3_512, hs256, hs128, hs64, hs32, hs16, hsELF, hsELF64, hsMix128, hsCRC16, hsCRC32]; CHashName: array [THashSecurity] of SystemString = ( 'None', 'FastMD5', 'MD5', 'SHA1', 'SHA256', 'SHA512', 'SHA3_224', 'SHA3_256', 'SHA3_384', 'SHA3_512', '256', '128', '64', '32', '16', 'ELF', 'ELF64', 'Mix128', 'CRC16', 'CRC32'); CCipherSecurityName: array [TCipherSecurity] of SystemString = ('None', 'DES64', 'DES128', 'DES192', 'Blowfish', 'LBC', 'LQC', 'RNG32', 'RNG64', 'LSC', 'XXTea512', 'RC6', 'Serpent', 'Mars', 'Rijndael', 'TwoFish'); cCipherKeyStyle: array [TCipherSecurity] of TCipherKeyStyle = ( cksNone, // csNone cksKey64, // csDES64 cksKey128, // csDES128 cks3Key64, // csDES192 cksKey128, // csBlowfish cksKey128, // csLBC cksKey128, // csLQC cksIntKey, // csRNG32 cks2IntKey, // csRNG64 ckyDynamicKey, // csLSC cksKey128, // csXXTea512 ckyDynamicKey, // csRC6 ckyDynamicKey, // csSerpent ckyDynamicKey, // csMars ckyDynamicKey, // csRijndael ckyDynamicKey // csTwoFish ); public class function AllCipher: TCipherSecurityArray; class function NameToHashSecurity(n: SystemString; var hash: THashSecurity): Boolean; class function BuffToString(buff: Pointer; Size: NativeInt): TPascalString; overload; class function StringToBuff(const Hex: TPascalString; var Buf; BufSize: Cardinal): Boolean; overload; class procedure HashToString(hash: Pointer; Size: NativeInt; var output: TPascalString); overload; class procedure HashToString(hash: TSHA3_224_Digest; var output: TPascalString); overload; class procedure HashToString(hash: TSHA3_256_Digest; var output: TPascalString); overload; class procedure HashToString(hash: TSHA3_384_Digest; var output: TPascalString); overload; class procedure HashToString(hash: TSHA3_512_Digest; var output: TPascalString); overload; class procedure HashToString(hash: TSHA512Digest; var output: TPascalString); overload; class procedure HashToString(hash: TSHA256Digest; var output: TPascalString); overload; class procedure HashToString(hash: TSHA1Digest; var output: TPascalString); overload; class procedure HashToString(hash: TMD5Digest; var output: TPascalString); overload; class procedure HashToString(hash: TBytes; var output: TPascalString); overload; class procedure HashToString(hash: TBytes; var output: SystemString); overload; class function CompareHash(h1, h2: TSHA3_224_Digest): Boolean; overload; class function CompareHash(h1, h2: TSHA3_256_Digest): Boolean; overload; class function CompareHash(h1, h2: TSHA3_384_Digest): Boolean; overload; class function CompareHash(h1, h2: TSHA3_512_Digest): Boolean; overload; class function CompareHash(h1, h2: TSHA512Digest): Boolean; overload; class function CompareHash(h1, h2: TSHA256Digest): Boolean; overload; class function CompareHash(h1, h2: TSHA1Digest): Boolean; overload; class function CompareHash(h1, h2: TMD5Digest): Boolean; overload; class function CompareHash(h1, h2: Pointer; Size: NativeInt): Boolean; overload; class function CompareHash(h1, h2: TBytes): Boolean; overload; class function CompareKey(k1, k2: TCipherKeyBuffer): Boolean; overload; class function GenerateSHA3_224Hash(sour: Pointer; Size: NativeInt): TSHA3_224_Digest; class function GenerateSHA3_256Hash(sour: Pointer; Size: NativeInt): TSHA3_256_Digest; class function GenerateSHA3_384Hash(sour: Pointer; Size: NativeInt): TSHA3_384_Digest; class function GenerateSHA3_512Hash(sour: Pointer; Size: NativeInt): TSHA3_512_Digest; class function GenerateSHA512Hash(sour: Pointer; Size: NativeInt): TSHA512Digest; class function GenerateSHA256Hash(sour: Pointer; Size: NativeInt): TSHA256Digest; class function GenerateSHA1Hash(sour: Pointer; Size: NativeInt): TSHA1Digest; class function GenerateMD5Hash(sour: Pointer; Size: NativeInt): TMD5Digest; class procedure GenerateMDHash(sour: Pointer; Size: NativeInt; OutHash: Pointer; HashSize: NativeInt); class procedure GenerateHashByte(hs: THashSecurity; sour: Pointer; Size: NativeInt; var output: TBytes); class function GenerateHashString(hs: THashSecurity; sour: Pointer; Size: NativeInt): TPascalString; class function BufferToHex(const Buf; BufSize: Cardinal): TPascalString; class function HexToBuffer(const Hex: TPascalString; var Buf; BufSize: Cardinal): Boolean; class function CopyKey(const k: TCipherKeyBuffer): TCipherKeyBuffer; class procedure GenerateNoneKey(var output: TCipherKeyBuffer); class procedure GenerateKey64(const s: TPascalString; var output: TCipherKeyBuffer); overload; class procedure GenerateKey64(sour: Pointer; Size: NativeInt; var output: TCipherKeyBuffer); overload; class procedure GenerateKey128(const s: TPascalString; var output: TCipherKeyBuffer); overload; class procedure GenerateKey128(sour: Pointer; Size: NativeInt; var output: TCipherKeyBuffer); overload; class procedure GenerateKey256(const s: TPascalString; var output: TCipherKeyBuffer); overload; class procedure GenerateKey256(sour: Pointer; Size: NativeInt; var output: TCipherKeyBuffer); overload; class procedure Generate3Key64(const s: TPascalString; var output: TCipherKeyBuffer); overload; class procedure Generate3Key64(sour: Pointer; Size: NativeInt; var output: TCipherKeyBuffer); overload; class procedure Generate2IntKey(const s: TPascalString; var output: TCipherKeyBuffer); overload; class procedure Generate2IntKey(sour: Pointer; Size: NativeInt; var output: TCipherKeyBuffer); overload; class procedure GenerateIntKey(const s: TPascalString; var output: TCipherKeyBuffer); overload; class procedure GenerateIntKey(sour: Pointer; Size: NativeInt; var output: TCipherKeyBuffer); overload; class procedure GenerateBytesKey(const s: TPascalString; KeySize: DWORD; var output: TCipherKeyBuffer); overload; class procedure GenerateBytesKey(sour: Pointer; Size, KeySize: DWORD; var output: TCipherKeyBuffer); overload; class procedure GenerateKey64(const k: TKey64; var output: TCipherKeyBuffer); overload; class procedure GenerateKey128(const k1, k2: TKey64; var output: TCipherKeyBuffer); overload; class procedure GenerateKey(const k: TKey64; var output: TCipherKeyBuffer); overload; class procedure GenerateKey(const k1, k2, k3: TKey64; var output: TCipherKeyBuffer); overload; class procedure GenerateKey(const k: TKey128; var output: TCipherKeyBuffer); overload; class procedure GenerateKey(const k: TKey256; var output: TCipherKeyBuffer); overload; class procedure GenerateKey(const k1, k2: DWORD; var output: TCipherKeyBuffer); overload; class procedure GenerateKey(const k: DWORD; var output: TCipherKeyBuffer); overload; class procedure GenerateKey(const key: PByte; Size: DWORD; var output: TCipherKeyBuffer); overload; class procedure GenerateKey(cs: TCipherSecurity; buffPtr: Pointer; Size: NativeInt; var output: TCipherKeyBuffer); overload; class procedure GenerateKey(cs: TCipherSecurity; s: TPascalString; var output: TCipherKeyBuffer); overload; class function GetKeyStyle(const p: PCipherKeyBuffer): TCipherKeyStyle; overload; class function GetKey(const KeyBuffPtr: PCipherKeyBuffer; var k: TKey64): Boolean; overload; class function GetKey(const KeyBuffPtr: PCipherKeyBuffer; var k1, k2, k3: TKey64): Boolean; overload; class function GetKey(const KeyBuffPtr: PCipherKeyBuffer; var k: TKey128): Boolean; overload; class function GetKey(const KeyBuffPtr: PCipherKeyBuffer; var k: TKey256): Boolean; overload; class function GetKey(const KeyBuffPtr: PCipherKeyBuffer; var k1, k2: DWORD): Boolean; overload; class function GetKey(const KeyBuffPtr: PCipherKeyBuffer; var k: DWORD): Boolean; overload; class function GetKey(const KeyBuffPtr: PCipherKeyBuffer; var key: TBytes): Boolean; overload; class procedure EncryptTail(TailPtr: Pointer; TailSize: NativeInt); class function DES64(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; class function DES128(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; class function DES192(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; class function Blowfish(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; class function LBC(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; class function LQC(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; class function RNG32(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer): Boolean; class function RNG64(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer): Boolean; class function LSC(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer): Boolean; class function XXTea512(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; class function RC6(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; class function Serpent(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; class function Mars(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; class function Rijndael(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; class function TwoFish(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; class procedure BlockCBC(sour: Pointer; Size: NativeInt; boxBuff: Pointer; boxSiz: NativeInt); class function EncryptBuffer(cs: TCipherSecurity; sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; class function EncryptBufferCBC(cs: TCipherSecurity; sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; end; {$IFDEF Parallel} TParallelCipher = class(TCoreClassObject) private type TParallelCipherFunc = procedure(Job, buff, key: Pointer; Size: NativeInt) of object; PParallelCipherJobData = ^TParallelCipherJobData; TParallelCipherJobData = record cipherFunc: TParallelCipherFunc; KeyBuffer: Pointer; OriginBuffer: Pointer; BlockLen: NativeInt; TotalBlock: NativeInt; CompletedBlock: NativeInt; Encrypt: Boolean; end; protected procedure DES64_Parallel(Job, buff, key: Pointer; Size: NativeInt); procedure DES128_Parallel(Job, buff, key: Pointer; Size: NativeInt); procedure DES192_Parallel(Job, buff, key: Pointer; Size: NativeInt); procedure Blowfish_Parallel(Job, buff, key: Pointer; Size: NativeInt); procedure LBC_Parallel(Job, buff, key: Pointer; Size: NativeInt); procedure LQC_Parallel(Job, buff, key: Pointer; Size: NativeInt); procedure TwoFish_Parallel(Job, buff, key: Pointer; Size: NativeInt); procedure XXTea512_Parallel(Job, buff, key: Pointer; Size: NativeInt); procedure RC6_Parallel(Job, buff, key: Pointer; Size: NativeInt); procedure Serpent_Parallel(Job, buff, key: Pointer; Size: NativeInt); procedure Mars_Parallel(Job, buff, key: Pointer; Size: NativeInt); procedure Rijndael_Parallel(Job, buff, key: Pointer; Size: NativeInt); procedure BlockCBC_Parallel(Job, buff, key: Pointer; Size: NativeInt); procedure ParallelCipherCall(const JobData: PParallelCipherJobData; const FromIndex, ToIndex: Integer); procedure RunParallel(const JobData: PParallelCipherJobData; const Total, Depth: Integer); public BlockDepth: Integer; constructor Create; destructor Destroy; override; function DES64(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; function DES128(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; function DES192(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; function Blowfish(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; function LBC(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; function LQC(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; function XXTea512(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; function RC6(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; function Serpent(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; function Mars(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; function Rijndael(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; function TwoFish(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; procedure BlockCBC(sour: Pointer; Size: NativeInt; boxBuff: Pointer; boxSiz: NativeInt); function EncryptBuffer(cs: TCipherSecurity; sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; function EncryptBufferCBC(cs: TCipherSecurity; sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; end; {$ENDIF} var { system default cbc refrence } SystemCBC: TBytes; {$IFDEF Parallel} { system default Parallel depth } DefaultParallelDepth: Integer; // default cpucount * 2 ParallelTriggerCondition: Integer; // default 1024 {$ENDIF} procedure InitSysCBCAndDefaultKey(rand: Int64); function SequEncryptWithDirect(const cs: TCipherSecurity; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; overload; function SequEncryptWithDirect(const ca: TCipherSecurityArray; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; overload; {$IFDEF Parallel} function SequEncryptWithParallel(const cs: TCipherSecurity; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; overload; function SequEncryptWithParallel(const ca: TCipherSecurityArray; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; overload; {$ENDIF} function SequEncrypt(const ca: TCipherSecurityArray; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; overload; function SequEncrypt(const cs: TCipherSecurity; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; overload; function SequEncryptCBCWithDirect(const cs: TCipherSecurity; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; overload; function SequEncryptCBCWithDirect(const ca: TCipherSecurityArray; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; overload; {$IFDEF Parallel} function SequEncryptCBCWithParallel(const cs: TCipherSecurity; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; overload; function SequEncryptCBCWithParallel(const ca: TCipherSecurityArray; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; overload; {$ENDIF} function SequEncryptCBC(const ca: TCipherSecurityArray; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; overload; function SequEncryptCBC(const cs: TCipherSecurity; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; overload; function GenerateSequHash(hssArry: THashSecuritys; sour: Pointer; Size: NativeInt): TPascalString; overload; procedure GenerateSequHash(hssArry: THashSecuritys; sour: Pointer; Size: NativeInt; output: TListPascalString); overload; procedure GenerateSequHash(hssArry: THashSecuritys; sour: Pointer; Size: NativeInt; output: TCoreClassStream); overload; function CompareSequHash(HashVL: THashStringList; sour: Pointer; Size: NativeInt): Boolean; overload; function CompareSequHash(hashData: TPascalString; sour: Pointer; Size: NativeInt): Boolean; overload; function CompareSequHash(hashData: TListPascalString; sour: Pointer; Size: NativeInt): Boolean; overload; function CompareSequHash(hashData: TCoreClassStream; sour: Pointer; Size: NativeInt): Boolean; overload; function GenerateMemoryHash(hssArry: THashSecuritys; sour: Pointer; Size: NativeInt): TPascalString; function CompareMemoryHash(sour: Pointer; Size: NativeInt; const hashBuff: TPascalString): Boolean; function GeneratePasswordHash(hssArry: THashSecuritys; const passwd: TPascalString): TPascalString; function ComparePasswordHash(const passwd, hashBuff: TPascalString): Boolean; function GeneratePassword(const ca: TCipherSecurityArray; const passwd: TPascalString): TPascalString; overload; function ComparePassword(const ca: TCipherSecurityArray; const passwd, passwdDataSource: TPascalString): Boolean; overload; function GeneratePassword(const cs: TCipherSecurity; const passwd: TPascalString): TPascalString; overload; function ComparePassword(const cs: TCipherSecurity; const passwd, passwdDataSource: TPascalString): Boolean; overload; { QuantumCryptographyPassword: used sha-3 shake256 cryptography as 512 bits password SHA-3 (Secure Hash Algorithm 3) is the latest member of the Secure Hash Algorithm family of standards, released by NIST on August 5, 2015.[4][5] Although part of the same series of standards, SHA-3 is internally quite different from the MD5-like structure of SHA-1 and SHA-2. Keccak is based on a novel approach called sponge construction. Sponge construction is based on a wide random function or random permutation, and allows inputting ("absorbing" in sponge terminology) any amount of data, and outputting ("squeezing") any amount of data, while acting as a pseudorandom function with regard to all previous inputs. This leads to great flexibility. NIST does not currently plan to withdraw SHA-2 or remove it from the revised Secure Hash Standard. The purpose of SHA-3 is that it can be directly substituted for SHA-2 in current applications if necessary, and to significantly improve the robustness of NIST's overall hash algorithm toolkit ref wiki https://en.wikipedia.org/wiki/SHA-3 } function GenerateQuantumCryptographyPassword(const passwd: TPascalString): TPascalString; function CompareQuantumCryptographyPassword(const passwd, passwdDataSource: TPascalString): Boolean; // QuantumCryptography for Stream support: used sha-3-512 cryptography as 512 bits password procedure QuantumEncrypt(input, output: TCoreClassStream; SecurityLevel: Integer; key: TCipherKeyBuffer); function QuantumDecrypt(input, output: TCoreClassStream; key: TCipherKeyBuffer): Boolean; {$REGION 'cryptAndHash'} type { Blowfish Cipher } TBlowfish = class(TCoreClassObject) public class procedure EncryptBF(const Context: TBFContext; var Block: TBFBlock; Encrypt: Boolean); class procedure InitEncryptBF(key: TKey128; var Context: TBFContext); end; { DES Cipher } TDES = class(TCoreClassObject) strict private class procedure JoinBlock(const l, r: DWORD; var Block: TDESBlock); class procedure SplitBlock(const Block: TDESBlock; var l, r: DWORD); private public class procedure EncryptDES(const Context: TDESContext; var Block: TDESBlock); class procedure EncryptTripleDES(const Context: TTripleDESContext; var Block: TDESBlock); class procedure EncryptTripleDES3Key(const Context: TTripleDESContext3Key; var Block: TDESBlock); class procedure InitEncryptDES(const key: TKey64; var Context: TDESContext; Encrypt: Boolean); class procedure InitEncryptTripleDES(const key: TKey128; var Context: TTripleDESContext; Encrypt: Boolean); class procedure InitEncryptTripleDES3Key(const Key1, Key2, Key3: TKey64; var Context: TTripleDESContext3Key; Encrypt: Boolean); class procedure ShrinkDESKey(var key: TKey64); end; { SHA1 } TSHA1 = class(TCoreClassObject) strict private class procedure SHA1Clear(var Context: TSHA1Context); class procedure SHA1Hash(var Context: TSHA1Context); class function SHA1SwapByteOrder(n: DWORD): DWORD; class procedure SHA1UpdateLen(var Context: TSHA1Context; Len: DWORD); public class procedure SHA1(var Digest: TSHA1Digest; const Buf; BufSize: NativeUInt); class procedure ByteBuffSHA1(var Digest: TSHA1Digest; const Bytes_: TBytes); class procedure InitSHA1(var Context: TSHA1Context); class procedure UpdateSHA1(var Context: TSHA1Context; const Buf; BufSize: NativeUInt); class procedure FinalizeSHA1(var Context: TSHA1Context; var Digest: TSHA1Digest); end; { SHA-2-SHA256 } TSHA256 = class(TCoreClassObject) private class procedure SwapDWORD(var a: DWORD); class procedure Compute(var Digest: TSHA256Digest; const buff: Pointer); public class procedure SHA256(var Digest: TSHA256Digest; const Buf; BufSize: NativeUInt); end; { SHA-2-SHA512 } TSHA512 = class(TCoreClassObject) private class procedure SwapQWORD(var a: UInt64); class procedure Compute(var Digest: TSHA512Digest; const buff: Pointer); public class procedure SHA512(var Digest: TSHA512Digest; const Buf; BufSize: UInt64); end; { SHA-3:SHA224,SHA256,SHA384,SHA512,SHAKE128,SHAKE256 } TSHA3 = class(TCoreClassObject) private type TSHA3Context = record HashLength: DWORD; BlockLen: DWORD; Buffer: array of Byte; BufSize: DWORD; a, b: array [0 .. 24] of UInt64; c, d: array [0 .. 4] of UInt64; end; private const // Round constants RC: array [0 .. 23] of UInt64 = ( $0000000000000001, $0000000000008082, $800000000000808A, $8000000080008000, $000000000000808B, $0000000080000001, $8000000080008081, $8000000000008009, $000000000000008A, $0000000000000088, $0000000080008009, $000000008000000A, $000000008000808B, $800000000000008B, $8000000000008089, $8000000000008003, $8000000000008002, $8000000000000080, $000000000000800A, $800000008000000A, $8000000080008081, $8000000000008080, $0000000080000001, $8000000080008008); // Rotation offsets RO: array [0 .. 24] of Integer = (0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8, 18, 2, 61, 56, 14); private class function ComputeX(const x: Integer): Integer; inline; class function ComputeXY(const x, y: Integer): Integer; inline; class procedure BlockSHA3(var Context: TSHA3Context); class procedure InitializeSHA3(var Context: TSHA3Context; HashLength: Integer); class procedure SHA3(var Context: TSHA3Context; Chunk: PByte; Size: NativeInt); class procedure FinalizeSHA3(var Context: TSHA3Context; const output: PCCByteArray); class procedure FinalizeSHAKE(var Context: TSHA3Context; Limit: Integer; const output: PCCByteArray); public class procedure SHA224(var Digest: TSHA3_224_Digest; Buf: PByte; BufSize: NativeInt); class procedure SHA256(var Digest: TSHA3_256_Digest; Buf: PByte; BufSize: NativeInt); class procedure SHA384(var Digest: TSHA3_384_Digest; Buf: PByte; BufSize: NativeInt); class procedure SHA512(var Digest: TSHA3_512_Digest; Buf: PByte; BufSize: NativeInt); class procedure SHAKE128(const Digest: PCCByteArray; Buf: PByte; BufSize: NativeInt; Limit: Integer); class procedure SHAKE256(const Digest: PCCByteArray; Buf: PByte; BufSize: NativeInt; Limit: Integer); end; { LBC Cipher } TLBC = class(TCoreClassObject) public class procedure EncryptLBC(const Context: TLBCContext; var Block: TLBCBlock); class procedure EncryptLQC(const key: TKey128; var Block: TLQCBlock; Encrypt: Boolean); class procedure InitEncryptLBC(const key: TKey128; var Context: TLBCContext; Rounds: Integer; Encrypt: Boolean); end; { MD5 } THashMD5 = class(TCoreClassObject) public class procedure GenerateMD5Key(var key: TKey128; const Bytes_: TBytes); class procedure HashMD5(var Digest: TMD5Digest; const Buf; BufSize: NativeInt); class procedure ByteBuffHashMD5(var Digest: TMD5Digest; const Bytes_: TBytes); class procedure InitMD5(var Context: TMD5Context); class procedure UpdateMD5(var Context: TMD5Context; const Buf; BufSize: NativeInt); class procedure FinalizeMD5(var Context: TMD5Context; var Digest: TMD5Digest); end; { message digest } THashMD = class(TCoreClassObject) public class procedure GenerateLMDKey(var key; KeySize: Integer; const Bytes_: TBytes); class procedure HashLMD(var Digest; DigestSize: Integer; const Buf; BufSize: NativeInt); class procedure ByteBuffHashLMD(var Digest; DigestSize: Integer; const Bytes_: TBytes); class procedure InitLMD(var Context: TLMDContext); class procedure UpdateLMD(var Context: TLMDContext; const Buf; BufSize: NativeInt); class procedure FinalizeLMD(var Context: TLMDContext; var Digest; DigestSize: Integer); end; { Random Number Cipher } TRNG = class(TCoreClassObject) public class procedure EncryptRNG32(var Context: TRNG32Context; var Buf; BufSize: Integer); class procedure EncryptRNG64(var Context: TRNG64Context; var Buf; BufSize: Integer); class procedure InitEncryptRNG32(key: DWORD; var Context: TRNG32Context); class procedure InitEncryptRNG64(KeyHi, KeyLo: DWORD; var Context: TRNG64Context); end; { LSC Stream Cipher } TLSC = class(TCoreClassObject) public class procedure EncryptLSC(var Context: TLSCContext; var Buf; BufSize: Integer); class procedure InitEncryptLSC(const key; KeySize: Integer; var Context: TLSCContext); end; { Miscellaneous algorithms } { Misc public utilities } TMISC = class(TCoreClassObject) public class procedure Mix128(var x: T128Bit); static; class function Ran0Prim(var Seed: Integer; IA, IQ, IR: Integer): Integer; static; class function Random64(var Seed: TInt64): Integer; static; class procedure Transform(var OutputBuffer: TTransformOutput; var InBuf: TTransformInput); static; class procedure GenerateRandomKey(var key; KeySize: Integer); static; class procedure HashELF(var Digest: DWORD; const Buf; BufSize: NativeUInt); static; class procedure HashELF64(var Digest: Int64; const Buf; BufSize: NativeUInt); static; class procedure HashMix128(var Digest: DWORD; const Buf; BufSize: NativeInt); static; class function Ran01(var Seed: Integer): Integer; static; class function Ran02(var Seed: Integer): Integer; static; class function Ran03(var Seed: Integer): Integer; static; class function Random32Byte(var Seed: Integer): Byte; static; class function Random64Byte(var Seed: TInt64): Byte; static; class function RolX(i, c: DWORD): DWORD; static; class procedure ByteBuffHashELF(var Digest: DWORD; const Bytes_: TBytes); static; class procedure ByteBuffHashMix128(var Digest: DWORD; const Bytes_: TBytes); static; class procedure XorMem(var Mem1; const Mem2; Count: NativeInt); static; end; { TEA } procedure XXTEAEncrypt(var key: TKey128; var Block: TXXTEABlock); procedure XXTEADecrypt(var key: TKey128; var Block: TXXTEABlock); const { RC6 } cRC6_NumRounds = 20; { number of rounds must be between 16-24 } type PRC6Key = ^TRC6Key; TRC6Key = array [0 .. ((cRC6_NumRounds * 2) + 3)] of DWORD; PRC6Block = ^TRC6Block; TRC6Block = array [0 .. 15] of Byte; TRC6 = class(TCoreClassObject) public class function LRot32(x, c: DWORD): DWORD; class function RRot32(x, c: DWORD): DWORD; class procedure InitKey(buff: Pointer; Size: Integer; var KeyContext: TRC6Key); class procedure Encrypt(var KeyContext: TRC6Key; var Data: TRC6Block); class procedure Decrypt(var KeyContext: TRC6Key; var Data: TRC6Block); end; type { Serpent } PSerpentkey = ^TSerpentkey; TSerpentkey = array [0 .. 131] of DWORD; PSerpentBlock = ^TSerpentBlock; TSerpentBlock = array [0 .. 15] of Byte; TSerpent = class(TCoreClassObject) public class procedure InitKey(buff: Pointer; Size: Integer; var KeyContext: TSerpentkey); class procedure Encrypt(var KeyContext: TSerpentkey; var Data: TSerpentBlock); class procedure Decrypt(var KeyContext: TSerpentkey; var Data: TSerpentBlock); end; type { Mars } PMarskey = ^TMarskey; TMarskey = array [0 .. 39] of DWORD; PMarsBlock = ^TMarsBlock; TMarsBlock = array [0 .. 15] of Byte; TMars = class(TCoreClassObject) public class procedure gen_mask(var x, m: DWORD); class procedure InitKey(buff: Pointer; Size: Integer; var KeyContext: TMarskey); class procedure Encrypt(var KeyContext: TMarskey; var Data: TMarsBlock); class procedure Decrypt(var KeyContext: TMarskey; var Data: TMarsBlock); end; type { Rijndael } PRijndaelkey = ^TRijndaelkey; TRijndaelkey = packed record NumRounds: DWORD; rk, drk: array [0 .. 14, 0 .. 7] of DWORD; end; PRijndaelBlock = ^TRijndaelBlock; TRijndaelBlock = array [0 .. 15] of Byte; TRijndael = class(TCoreClassObject) private const {$REGION 'RijndaelDefine'} T1: array [0 .. 255, 0 .. 3] of Byte = ( ($C6, $63, $63, $A5), ($F8, $7C, $7C, $84), ($EE, $77, $77, $99), ($F6, $7B, $7B, $8D), ($FF, $F2, $F2, $0D), ($D6, $6B, $6B, $BD), ($DE, $6F, $6F, $B1), ($91, $C5, $C5, $54), ($60, $30, $30, $50), ($02, $01, $01, $03), ($CE, $67, $67, $A9), ($56, $2B, $2B, $7D), ($E7, $FE, $FE, $19), ($B5, $D7, $D7, $62), ($4D, $AB, $AB, $E6), ($EC, $76, $76, $9A), ($8F, $CA, $CA, $45), ($1F, $82, $82, $9D), ($89, $C9, $C9, $40), ($FA, $7D, $7D, $87), ($EF, $FA, $FA, $15), ($B2, $59, $59, $EB), ($8E, $47, $47, $C9), ($FB, $F0, $F0, $0B), ($41, $AD, $AD, $EC), ($B3, $D4, $D4, $67), ($5F, $A2, $A2, $FD), ($45, $AF, $AF, $EA), ($23, $9C, $9C, $BF), ($53, $A4, $A4, $F7), ($E4, $72, $72, $96), ($9B, $C0, $C0, $5B), ($75, $B7, $B7, $C2), ($E1, $FD, $FD, $1C), ($3D, $93, $93, $AE), ($4C, $26, $26, $6A), ($6C, $36, $36, $5A), ($7E, $3F, $3F, $41), ($F5, $F7, $F7, $02), ($83, $CC, $CC, $4F), ($68, $34, $34, $5C), ($51, $A5, $A5, $F4), ($D1, $E5, $E5, $34), ($F9, $F1, $F1, $08), ($E2, $71, $71, $93), ($AB, $D8, $D8, $73), ($62, $31, $31, $53), ($2A, $15, $15, $3F), ($08, $04, $04, $0C), ($95, $C7, $C7, $52), ($46, $23, $23, $65), ($9D, $C3, $C3, $5E), ($30, $18, $18, $28), ($37, $96, $96, $A1), ($0A, $05, $05, $0F), ($2F, $9A, $9A, $B5), ($0E, $07, $07, $09), ($24, $12, $12, $36), ($1B, $80, $80, $9B), ($DF, $E2, $E2, $3D), ($CD, $EB, $EB, $26), ($4E, $27, $27, $69), ($7F, $B2, $B2, $CD), ($EA, $75, $75, $9F), ($12, $09, $09, $1B), ($1D, $83, $83, $9E), ($58, $2C, $2C, $74), ($34, $1A, $1A, $2E), ($36, $1B, $1B, $2D), ($DC, $6E, $6E, $B2), ($B4, $5A, $5A, $EE), ($5B, $A0, $A0, $FB), ($A4, $52, $52, $F6), ($76, $3B, $3B, $4D), ($B7, $D6, $D6, $61), ($7D, $B3, $B3, $CE), ($52, $29, $29, $7B), ($DD, $E3, $E3, $3E), ($5E, $2F, $2F, $71), ($13, $84, $84, $97), ($A6, $53, $53, $F5), ($B9, $D1, $D1, $68), ($00, $00, $00, $00), ($C1, $ED, $ED, $2C), ($40, $20, $20, $60), ($E3, $FC, $FC, $1F), ($79, $B1, $B1, $C8), ($B6, $5B, $5B, $ED), ($D4, $6A, $6A, $BE), ($8D, $CB, $CB, $46), ($67, $BE, $BE, $D9), ($72, $39, $39, $4B), ($94, $4A, $4A, $DE), ($98, $4C, $4C, $D4), ($B0, $58, $58, $E8), ($85, $CF, $CF, $4A), ($BB, $D0, $D0, $6B), ($C5, $EF, $EF, $2A), ($4F, $AA, $AA, $E5), ($ED, $FB, $FB, $16), ($86, $43, $43, $C5), ($9A, $4D, $4D, $D7), ($66, $33, $33, $55), ($11, $85, $85, $94), ($8A, $45, $45, $CF), ($E9, $F9, $F9, $10), ($04, $02, $02, $06), ($FE, $7F, $7F, $81), ($A0, $50, $50, $F0), ($78, $3C, $3C, $44), ($25, $9F, $9F, $BA), ($4B, $A8, $A8, $E3), ($A2, $51, $51, $F3), ($5D, $A3, $A3, $FE), ($80, $40, $40, $C0), ($05, $8F, $8F, $8A), ($3F, $92, $92, $AD), ($21, $9D, $9D, $BC), ($70, $38, $38, $48), ($F1, $F5, $F5, $04), ($63, $BC, $BC, $DF), ($77, $B6, $B6, $C1), ($AF, $DA, $DA, $75), ($42, $21, $21, $63), ($20, $10, $10, $30), ($E5, $FF, $FF, $1A), ($FD, $F3, $F3, $0E), ($BF, $D2, $D2, $6D), ($81, $CD, $CD, $4C), ($18, $0C, $0C, $14), ($26, $13, $13, $35), ($C3, $EC, $EC, $2F), ($BE, $5F, $5F, $E1), ($35, $97, $97, $A2), ($88, $44, $44, $CC), ($2E, $17, $17, $39), ($93, $C4, $C4, $57), ($55, $A7, $A7, $F2), ($FC, $7E, $7E, $82), ($7A, $3D, $3D, $47), ($C8, $64, $64, $AC), ($BA, $5D, $5D, $E7), ($32, $19, $19, $2B), ($E6, $73, $73, $95), ($C0, $60, $60, $A0), ($19, $81, $81, $98), ($9E, $4F, $4F, $D1), ($A3, $DC, $DC, $7F), ($44, $22, $22, $66), ($54, $2A, $2A, $7E), ($3B, $90, $90, $AB), ($0B, $88, $88, $83), ($8C, $46, $46, $CA), ($C7, $EE, $EE, $29), ($6B, $B8, $B8, $D3), ($28, $14, $14, $3C), ($A7, $DE, $DE, $79), ($BC, $5E, $5E, $E2), ($16, $0B, $0B, $1D), ($AD, $DB, $DB, $76), ($DB, $E0, $E0, $3B), ($64, $32, $32, $56), ($74, $3A, $3A, $4E), ($14, $0A, $0A, $1E), ($92, $49, $49, $DB), ($0C, $06, $06, $0A), ($48, $24, $24, $6C), ($B8, $5C, $5C, $E4), ($9F, $C2, $C2, $5D), ($BD, $D3, $D3, $6E), ($43, $AC, $AC, $EF), ($C4, $62, $62, $A6), ($39, $91, $91, $A8), ($31, $95, $95, $A4), ($D3, $E4, $E4, $37), ($F2, $79, $79, $8B), ($D5, $E7, $E7, $32), ($8B, $C8, $C8, $43), ($6E, $37, $37, $59), ($DA, $6D, $6D, $B7), ($01, $8D, $8D, $8C), ($B1, $D5, $D5, $64), ($9C, $4E, $4E, $D2), ($49, $A9, $A9, $E0), ($D8, $6C, $6C, $B4), ($AC, $56, $56, $FA), ($F3, $F4, $F4, $07), ($CF, $EA, $EA, $25), ($CA, $65, $65, $AF), ($F4, $7A, $7A, $8E), ($47, $AE, $AE, $E9), ($10, $08, $08, $18), ($6F, $BA, $BA, $D5), ($F0, $78, $78, $88), ($4A, $25, $25, $6F), ($5C, $2E, $2E, $72), ($38, $1C, $1C, $24), ($57, $A6, $A6, $F1), ($73, $B4, $B4, $C7), ($97, $C6, $C6, $51), ($CB, $E8, $E8, $23), ($A1, $DD, $DD, $7C), ($E8, $74, $74, $9C), ($3E, $1F, $1F, $21), ($96, $4B, $4B, $DD), ($61, $BD, $BD, $DC), ($0D, $8B, $8B, $86), ($0F, $8A, $8A, $85), ($E0, $70, $70, $90), ($7C, $3E, $3E, $42), ($71, $B5, $B5, $C4), ($CC, $66, $66, $AA), ($90, $48, $48, $D8), ($06, $03, $03, $05), ($F7, $F6, $F6, $01), ($1C, $0E, $0E, $12), ($C2, $61, $61, $A3), ($6A, $35, $35, $5F), ($AE, $57, $57, $F9), ($69, $B9, $B9, $D0), ($17, $86, $86, $91), ($99, $C1, $C1, $58), ($3A, $1D, $1D, $27), ($27, $9E, $9E, $B9), ($D9, $E1, $E1, $38), ($EB, $F8, $F8, $13), ($2B, $98, $98, $B3), ($22, $11, $11, $33), ($D2, $69, $69, $BB), ($A9, $D9, $D9, $70), ($07, $8E, $8E, $89), ($33, $94, $94, $A7), ($2D, $9B, $9B, $B6), ($3C, $1E, $1E, $22), ($15, $87, $87, $92), ($C9, $E9, $E9, $20), ($87, $CE, $CE, $49), ($AA, $55, $55, $FF), ($50, $28, $28, $78), ($A5, $DF, $DF, $7A), ($03, $8C, $8C, $8F), ($59, $A1, $A1, $F8), ($09, $89, $89, $80), ($1A, $0D, $0D, $17), ($65, $BF, $BF, $DA), ($D7, $E6, $E6, $31), ($84, $42, $42, $C6), ($D0, $68, $68, $B8), ($82, $41, $41, $C3), ($29, $99, $99, $B0), ($5A, $2D, $2D, $77), ($1E, $0F, $0F, $11), ($7B, $B0, $B0, $CB), ($A8, $54, $54, $FC), ($6D, $BB, $BB, $D6), ($2C, $16, $16, $3A)); T2: array [0 .. 255, 0 .. 3] of Byte = ( ($A5, $C6, $63, $63), ($84, $F8, $7C, $7C), ($99, $EE, $77, $77), ($8D, $F6, $7B, $7B), ($0D, $FF, $F2, $F2), ($BD, $D6, $6B, $6B), ($B1, $DE, $6F, $6F), ($54, $91, $C5, $C5), ($50, $60, $30, $30), ($03, $02, $01, $01), ($A9, $CE, $67, $67), ($7D, $56, $2B, $2B), ($19, $E7, $FE, $FE), ($62, $B5, $D7, $D7), ($E6, $4D, $AB, $AB), ($9A, $EC, $76, $76), ($45, $8F, $CA, $CA), ($9D, $1F, $82, $82), ($40, $89, $C9, $C9), ($87, $FA, $7D, $7D), ($15, $EF, $FA, $FA), ($EB, $B2, $59, $59), ($C9, $8E, $47, $47), ($0B, $FB, $F0, $F0), ($EC, $41, $AD, $AD), ($67, $B3, $D4, $D4), ($FD, $5F, $A2, $A2), ($EA, $45, $AF, $AF), ($BF, $23, $9C, $9C), ($F7, $53, $A4, $A4), ($96, $E4, $72, $72), ($5B, $9B, $C0, $C0), ($C2, $75, $B7, $B7), ($1C, $E1, $FD, $FD), ($AE, $3D, $93, $93), ($6A, $4C, $26, $26), ($5A, $6C, $36, $36), ($41, $7E, $3F, $3F), ($02, $F5, $F7, $F7), ($4F, $83, $CC, $CC), ($5C, $68, $34, $34), ($F4, $51, $A5, $A5), ($34, $D1, $E5, $E5), ($08, $F9, $F1, $F1), ($93, $E2, $71, $71), ($73, $AB, $D8, $D8), ($53, $62, $31, $31), ($3F, $2A, $15, $15), ($0C, $08, $04, $04), ($52, $95, $C7, $C7), ($65, $46, $23, $23), ($5E, $9D, $C3, $C3), ($28, $30, $18, $18), ($A1, $37, $96, $96), ($0F, $0A, $05, $05), ($B5, $2F, $9A, $9A), ($09, $0E, $07, $07), ($36, $24, $12, $12), ($9B, $1B, $80, $80), ($3D, $DF, $E2, $E2), ($26, $CD, $EB, $EB), ($69, $4E, $27, $27), ($CD, $7F, $B2, $B2), ($9F, $EA, $75, $75), ($1B, $12, $09, $09), ($9E, $1D, $83, $83), ($74, $58, $2C, $2C), ($2E, $34, $1A, $1A), ($2D, $36, $1B, $1B), ($B2, $DC, $6E, $6E), ($EE, $B4, $5A, $5A), ($FB, $5B, $A0, $A0), ($F6, $A4, $52, $52), ($4D, $76, $3B, $3B), ($61, $B7, $D6, $D6), ($CE, $7D, $B3, $B3), ($7B, $52, $29, $29), ($3E, $DD, $E3, $E3), ($71, $5E, $2F, $2F), ($97, $13, $84, $84), ($F5, $A6, $53, $53), ($68, $B9, $D1, $D1), ($00, $00, $00, $00), ($2C, $C1, $ED, $ED), ($60, $40, $20, $20), ($1F, $E3, $FC, $FC), ($C8, $79, $B1, $B1), ($ED, $B6, $5B, $5B), ($BE, $D4, $6A, $6A), ($46, $8D, $CB, $CB), ($D9, $67, $BE, $BE), ($4B, $72, $39, $39), ($DE, $94, $4A, $4A), ($D4, $98, $4C, $4C), ($E8, $B0, $58, $58), ($4A, $85, $CF, $CF), ($6B, $BB, $D0, $D0), ($2A, $C5, $EF, $EF), ($E5, $4F, $AA, $AA), ($16, $ED, $FB, $FB), ($C5, $86, $43, $43), ($D7, $9A, $4D, $4D), ($55, $66, $33, $33), ($94, $11, $85, $85), ($CF, $8A, $45, $45), ($10, $E9, $F9, $F9), ($06, $04, $02, $02), ($81, $FE, $7F, $7F), ($F0, $A0, $50, $50), ($44, $78, $3C, $3C), ($BA, $25, $9F, $9F), ($E3, $4B, $A8, $A8), ($F3, $A2, $51, $51), ($FE, $5D, $A3, $A3), ($C0, $80, $40, $40), ($8A, $05, $8F, $8F), ($AD, $3F, $92, $92), ($BC, $21, $9D, $9D), ($48, $70, $38, $38), ($04, $F1, $F5, $F5), ($DF, $63, $BC, $BC), ($C1, $77, $B6, $B6), ($75, $AF, $DA, $DA), ($63, $42, $21, $21), ($30, $20, $10, $10), ($1A, $E5, $FF, $FF), ($0E, $FD, $F3, $F3), ($6D, $BF, $D2, $D2), ($4C, $81, $CD, $CD), ($14, $18, $0C, $0C), ($35, $26, $13, $13), ($2F, $C3, $EC, $EC), ($E1, $BE, $5F, $5F), ($A2, $35, $97, $97), ($CC, $88, $44, $44), ($39, $2E, $17, $17), ($57, $93, $C4, $C4), ($F2, $55, $A7, $A7), ($82, $FC, $7E, $7E), ($47, $7A, $3D, $3D), ($AC, $C8, $64, $64), ($E7, $BA, $5D, $5D), ($2B, $32, $19, $19), ($95, $E6, $73, $73), ($A0, $C0, $60, $60), ($98, $19, $81, $81), ($D1, $9E, $4F, $4F), ($7F, $A3, $DC, $DC), ($66, $44, $22, $22), ($7E, $54, $2A, $2A), ($AB, $3B, $90, $90), ($83, $0B, $88, $88), ($CA, $8C, $46, $46), ($29, $C7, $EE, $EE), ($D3, $6B, $B8, $B8), ($3C, $28, $14, $14), ($79, $A7, $DE, $DE), ($E2, $BC, $5E, $5E), ($1D, $16, $0B, $0B), ($76, $AD, $DB, $DB), ($3B, $DB, $E0, $E0), ($56, $64, $32, $32), ($4E, $74, $3A, $3A), ($1E, $14, $0A, $0A), ($DB, $92, $49, $49), ($0A, $0C, $06, $06), ($6C, $48, $24, $24), ($E4, $B8, $5C, $5C), ($5D, $9F, $C2, $C2), ($6E, $BD, $D3, $D3), ($EF, $43, $AC, $AC), ($A6, $C4, $62, $62), ($A8, $39, $91, $91), ($A4, $31, $95, $95), ($37, $D3, $E4, $E4), ($8B, $F2, $79, $79), ($32, $D5, $E7, $E7), ($43, $8B, $C8, $C8), ($59, $6E, $37, $37), ($B7, $DA, $6D, $6D), ($8C, $01, $8D, $8D), ($64, $B1, $D5, $D5), ($D2, $9C, $4E, $4E), ($E0, $49, $A9, $A9), ($B4, $D8, $6C, $6C), ($FA, $AC, $56, $56), ($07, $F3, $F4, $F4), ($25, $CF, $EA, $EA), ($AF, $CA, $65, $65), ($8E, $F4, $7A, $7A), ($E9, $47, $AE, $AE), ($18, $10, $08, $08), ($D5, $6F, $BA, $BA), ($88, $F0, $78, $78), ($6F, $4A, $25, $25), ($72, $5C, $2E, $2E), ($24, $38, $1C, $1C), ($F1, $57, $A6, $A6), ($C7, $73, $B4, $B4), ($51, $97, $C6, $C6), ($23, $CB, $E8, $E8), ($7C, $A1, $DD, $DD), ($9C, $E8, $74, $74), ($21, $3E, $1F, $1F), ($DD, $96, $4B, $4B), ($DC, $61, $BD, $BD), ($86, $0D, $8B, $8B), ($85, $0F, $8A, $8A), ($90, $E0, $70, $70), ($42, $7C, $3E, $3E), ($C4, $71, $B5, $B5), ($AA, $CC, $66, $66), ($D8, $90, $48, $48), ($05, $06, $03, $03), ($01, $F7, $F6, $F6), ($12, $1C, $0E, $0E), ($A3, $C2, $61, $61), ($5F, $6A, $35, $35), ($F9, $AE, $57, $57), ($D0, $69, $B9, $B9), ($91, $17, $86, $86), ($58, $99, $C1, $C1), ($27, $3A, $1D, $1D), ($B9, $27, $9E, $9E), ($38, $D9, $E1, $E1), ($13, $EB, $F8, $F8), ($B3, $2B, $98, $98), ($33, $22, $11, $11), ($BB, $D2, $69, $69), ($70, $A9, $D9, $D9), ($89, $07, $8E, $8E), ($A7, $33, $94, $94), ($B6, $2D, $9B, $9B), ($22, $3C, $1E, $1E), ($92, $15, $87, $87), ($20, $C9, $E9, $E9), ($49, $87, $CE, $CE), ($FF, $AA, $55, $55), ($78, $50, $28, $28), ($7A, $A5, $DF, $DF), ($8F, $03, $8C, $8C), ($F8, $59, $A1, $A1), ($80, $09, $89, $89), ($17, $1A, $0D, $0D), ($DA, $65, $BF, $BF), ($31, $D7, $E6, $E6), ($C6, $84, $42, $42), ($B8, $D0, $68, $68), ($C3, $82, $41, $41), ($B0, $29, $99, $99), ($77, $5A, $2D, $2D), ($11, $1E, $0F, $0F), ($CB, $7B, $B0, $B0), ($FC, $A8, $54, $54), ($D6, $6D, $BB, $BB), ($3A, $2C, $16, $16)); T3: array [0 .. 255, 0 .. 3] of Byte = ( ($63, $A5, $C6, $63), ($7C, $84, $F8, $7C), ($77, $99, $EE, $77), ($7B, $8D, $F6, $7B), ($F2, $0D, $FF, $F2), ($6B, $BD, $D6, $6B), ($6F, $B1, $DE, $6F), ($C5, $54, $91, $C5), ($30, $50, $60, $30), ($01, $03, $02, $01), ($67, $A9, $CE, $67), ($2B, $7D, $56, $2B), ($FE, $19, $E7, $FE), ($D7, $62, $B5, $D7), ($AB, $E6, $4D, $AB), ($76, $9A, $EC, $76), ($CA, $45, $8F, $CA), ($82, $9D, $1F, $82), ($C9, $40, $89, $C9), ($7D, $87, $FA, $7D), ($FA, $15, $EF, $FA), ($59, $EB, $B2, $59), ($47, $C9, $8E, $47), ($F0, $0B, $FB, $F0), ($AD, $EC, $41, $AD), ($D4, $67, $B3, $D4), ($A2, $FD, $5F, $A2), ($AF, $EA, $45, $AF), ($9C, $BF, $23, $9C), ($A4, $F7, $53, $A4), ($72, $96, $E4, $72), ($C0, $5B, $9B, $C0), ($B7, $C2, $75, $B7), ($FD, $1C, $E1, $FD), ($93, $AE, $3D, $93), ($26, $6A, $4C, $26), ($36, $5A, $6C, $36), ($3F, $41, $7E, $3F), ($F7, $02, $F5, $F7), ($CC, $4F, $83, $CC), ($34, $5C, $68, $34), ($A5, $F4, $51, $A5), ($E5, $34, $D1, $E5), ($F1, $08, $F9, $F1), ($71, $93, $E2, $71), ($D8, $73, $AB, $D8), ($31, $53, $62, $31), ($15, $3F, $2A, $15), ($04, $0C, $08, $04), ($C7, $52, $95, $C7), ($23, $65, $46, $23), ($C3, $5E, $9D, $C3), ($18, $28, $30, $18), ($96, $A1, $37, $96), ($05, $0F, $0A, $05), ($9A, $B5, $2F, $9A), ($07, $09, $0E, $07), ($12, $36, $24, $12), ($80, $9B, $1B, $80), ($E2, $3D, $DF, $E2), ($EB, $26, $CD, $EB), ($27, $69, $4E, $27), ($B2, $CD, $7F, $B2), ($75, $9F, $EA, $75), ($09, $1B, $12, $09), ($83, $9E, $1D, $83), ($2C, $74, $58, $2C), ($1A, $2E, $34, $1A), ($1B, $2D, $36, $1B), ($6E, $B2, $DC, $6E), ($5A, $EE, $B4, $5A), ($A0, $FB, $5B, $A0), ($52, $F6, $A4, $52), ($3B, $4D, $76, $3B), ($D6, $61, $B7, $D6), ($B3, $CE, $7D, $B3), ($29, $7B, $52, $29), ($E3, $3E, $DD, $E3), ($2F, $71, $5E, $2F), ($84, $97, $13, $84), ($53, $F5, $A6, $53), ($D1, $68, $B9, $D1), ($00, $00, $00, $00), ($ED, $2C, $C1, $ED), ($20, $60, $40, $20), ($FC, $1F, $E3, $FC), ($B1, $C8, $79, $B1), ($5B, $ED, $B6, $5B), ($6A, $BE, $D4, $6A), ($CB, $46, $8D, $CB), ($BE, $D9, $67, $BE), ($39, $4B, $72, $39), ($4A, $DE, $94, $4A), ($4C, $D4, $98, $4C), ($58, $E8, $B0, $58), ($CF, $4A, $85, $CF), ($D0, $6B, $BB, $D0), ($EF, $2A, $C5, $EF), ($AA, $E5, $4F, $AA), ($FB, $16, $ED, $FB), ($43, $C5, $86, $43), ($4D, $D7, $9A, $4D), ($33, $55, $66, $33), ($85, $94, $11, $85), ($45, $CF, $8A, $45), ($F9, $10, $E9, $F9), ($02, $06, $04, $02), ($7F, $81, $FE, $7F), ($50, $F0, $A0, $50), ($3C, $44, $78, $3C), ($9F, $BA, $25, $9F), ($A8, $E3, $4B, $A8), ($51, $F3, $A2, $51), ($A3, $FE, $5D, $A3), ($40, $C0, $80, $40), ($8F, $8A, $05, $8F), ($92, $AD, $3F, $92), ($9D, $BC, $21, $9D), ($38, $48, $70, $38), ($F5, $04, $F1, $F5), ($BC, $DF, $63, $BC), ($B6, $C1, $77, $B6), ($DA, $75, $AF, $DA), ($21, $63, $42, $21), ($10, $30, $20, $10), ($FF, $1A, $E5, $FF), ($F3, $0E, $FD, $F3), ($D2, $6D, $BF, $D2), ($CD, $4C, $81, $CD), ($0C, $14, $18, $0C), ($13, $35, $26, $13), ($EC, $2F, $C3, $EC), ($5F, $E1, $BE, $5F), ($97, $A2, $35, $97), ($44, $CC, $88, $44), ($17, $39, $2E, $17), ($C4, $57, $93, $C4), ($A7, $F2, $55, $A7), ($7E, $82, $FC, $7E), ($3D, $47, $7A, $3D), ($64, $AC, $C8, $64), ($5D, $E7, $BA, $5D), ($19, $2B, $32, $19), ($73, $95, $E6, $73), ($60, $A0, $C0, $60), ($81, $98, $19, $81), ($4F, $D1, $9E, $4F), ($DC, $7F, $A3, $DC), ($22, $66, $44, $22), ($2A, $7E, $54, $2A), ($90, $AB, $3B, $90), ($88, $83, $0B, $88), ($46, $CA, $8C, $46), ($EE, $29, $C7, $EE), ($B8, $D3, $6B, $B8), ($14, $3C, $28, $14), ($DE, $79, $A7, $DE), ($5E, $E2, $BC, $5E), ($0B, $1D, $16, $0B), ($DB, $76, $AD, $DB), ($E0, $3B, $DB, $E0), ($32, $56, $64, $32), ($3A, $4E, $74, $3A), ($0A, $1E, $14, $0A), ($49, $DB, $92, $49), ($06, $0A, $0C, $06), ($24, $6C, $48, $24), ($5C, $E4, $B8, $5C), ($C2, $5D, $9F, $C2), ($D3, $6E, $BD, $D3), ($AC, $EF, $43, $AC), ($62, $A6, $C4, $62), ($91, $A8, $39, $91), ($95, $A4, $31, $95), ($E4, $37, $D3, $E4), ($79, $8B, $F2, $79), ($E7, $32, $D5, $E7), ($C8, $43, $8B, $C8), ($37, $59, $6E, $37), ($6D, $B7, $DA, $6D), ($8D, $8C, $01, $8D), ($D5, $64, $B1, $D5), ($4E, $D2, $9C, $4E), ($A9, $E0, $49, $A9), ($6C, $B4, $D8, $6C), ($56, $FA, $AC, $56), ($F4, $07, $F3, $F4), ($EA, $25, $CF, $EA), ($65, $AF, $CA, $65), ($7A, $8E, $F4, $7A), ($AE, $E9, $47, $AE), ($08, $18, $10, $08), ($BA, $D5, $6F, $BA), ($78, $88, $F0, $78), ($25, $6F, $4A, $25), ($2E, $72, $5C, $2E), ($1C, $24, $38, $1C), ($A6, $F1, $57, $A6), ($B4, $C7, $73, $B4), ($C6, $51, $97, $C6), ($E8, $23, $CB, $E8), ($DD, $7C, $A1, $DD), ($74, $9C, $E8, $74), ($1F, $21, $3E, $1F), ($4B, $DD, $96, $4B), ($BD, $DC, $61, $BD), ($8B, $86, $0D, $8B), ($8A, $85, $0F, $8A), ($70, $90, $E0, $70), ($3E, $42, $7C, $3E), ($B5, $C4, $71, $B5), ($66, $AA, $CC, $66), ($48, $D8, $90, $48), ($03, $05, $06, $03), ($F6, $01, $F7, $F6), ($0E, $12, $1C, $0E), ($61, $A3, $C2, $61), ($35, $5F, $6A, $35), ($57, $F9, $AE, $57), ($B9, $D0, $69, $B9), ($86, $91, $17, $86), ($C1, $58, $99, $C1), ($1D, $27, $3A, $1D), ($9E, $B9, $27, $9E), ($E1, $38, $D9, $E1), ($F8, $13, $EB, $F8), ($98, $B3, $2B, $98), ($11, $33, $22, $11), ($69, $BB, $D2, $69), ($D9, $70, $A9, $D9), ($8E, $89, $07, $8E), ($94, $A7, $33, $94), ($9B, $B6, $2D, $9B), ($1E, $22, $3C, $1E), ($87, $92, $15, $87), ($E9, $20, $C9, $E9), ($CE, $49, $87, $CE), ($55, $FF, $AA, $55), ($28, $78, $50, $28), ($DF, $7A, $A5, $DF), ($8C, $8F, $03, $8C), ($A1, $F8, $59, $A1), ($89, $80, $09, $89), ($0D, $17, $1A, $0D), ($BF, $DA, $65, $BF), ($E6, $31, $D7, $E6), ($42, $C6, $84, $42), ($68, $B8, $D0, $68), ($41, $C3, $82, $41), ($99, $B0, $29, $99), ($2D, $77, $5A, $2D), ($0F, $11, $1E, $0F), ($B0, $CB, $7B, $B0), ($54, $FC, $A8, $54), ($BB, $D6, $6D, $BB), ($16, $3A, $2C, $16)); T4: array [0 .. 255, 0 .. 3] of Byte = ( ($63, $63, $A5, $C6), ($7C, $7C, $84, $F8), ($77, $77, $99, $EE), ($7B, $7B, $8D, $F6), ($F2, $F2, $0D, $FF), ($6B, $6B, $BD, $D6), ($6F, $6F, $B1, $DE), ($C5, $C5, $54, $91), ($30, $30, $50, $60), ($01, $01, $03, $02), ($67, $67, $A9, $CE), ($2B, $2B, $7D, $56), ($FE, $FE, $19, $E7), ($D7, $D7, $62, $B5), ($AB, $AB, $E6, $4D), ($76, $76, $9A, $EC), ($CA, $CA, $45, $8F), ($82, $82, $9D, $1F), ($C9, $C9, $40, $89), ($7D, $7D, $87, $FA), ($FA, $FA, $15, $EF), ($59, $59, $EB, $B2), ($47, $47, $C9, $8E), ($F0, $F0, $0B, $FB), ($AD, $AD, $EC, $41), ($D4, $D4, $67, $B3), ($A2, $A2, $FD, $5F), ($AF, $AF, $EA, $45), ($9C, $9C, $BF, $23), ($A4, $A4, $F7, $53), ($72, $72, $96, $E4), ($C0, $C0, $5B, $9B), ($B7, $B7, $C2, $75), ($FD, $FD, $1C, $E1), ($93, $93, $AE, $3D), ($26, $26, $6A, $4C), ($36, $36, $5A, $6C), ($3F, $3F, $41, $7E), ($F7, $F7, $02, $F5), ($CC, $CC, $4F, $83), ($34, $34, $5C, $68), ($A5, $A5, $F4, $51), ($E5, $E5, $34, $D1), ($F1, $F1, $08, $F9), ($71, $71, $93, $E2), ($D8, $D8, $73, $AB), ($31, $31, $53, $62), ($15, $15, $3F, $2A), ($04, $04, $0C, $08), ($C7, $C7, $52, $95), ($23, $23, $65, $46), ($C3, $C3, $5E, $9D), ($18, $18, $28, $30), ($96, $96, $A1, $37), ($05, $05, $0F, $0A), ($9A, $9A, $B5, $2F), ($07, $07, $09, $0E), ($12, $12, $36, $24), ($80, $80, $9B, $1B), ($E2, $E2, $3D, $DF), ($EB, $EB, $26, $CD), ($27, $27, $69, $4E), ($B2, $B2, $CD, $7F), ($75, $75, $9F, $EA), ($09, $09, $1B, $12), ($83, $83, $9E, $1D), ($2C, $2C, $74, $58), ($1A, $1A, $2E, $34), ($1B, $1B, $2D, $36), ($6E, $6E, $B2, $DC), ($5A, $5A, $EE, $B4), ($A0, $A0, $FB, $5B), ($52, $52, $F6, $A4), ($3B, $3B, $4D, $76), ($D6, $D6, $61, $B7), ($B3, $B3, $CE, $7D), ($29, $29, $7B, $52), ($E3, $E3, $3E, $DD), ($2F, $2F, $71, $5E), ($84, $84, $97, $13), ($53, $53, $F5, $A6), ($D1, $D1, $68, $B9), ($00, $00, $00, $00), ($ED, $ED, $2C, $C1), ($20, $20, $60, $40), ($FC, $FC, $1F, $E3), ($B1, $B1, $C8, $79), ($5B, $5B, $ED, $B6), ($6A, $6A, $BE, $D4), ($CB, $CB, $46, $8D), ($BE, $BE, $D9, $67), ($39, $39, $4B, $72), ($4A, $4A, $DE, $94), ($4C, $4C, $D4, $98), ($58, $58, $E8, $B0), ($CF, $CF, $4A, $85), ($D0, $D0, $6B, $BB), ($EF, $EF, $2A, $C5), ($AA, $AA, $E5, $4F), ($FB, $FB, $16, $ED), ($43, $43, $C5, $86), ($4D, $4D, $D7, $9A), ($33, $33, $55, $66), ($85, $85, $94, $11), ($45, $45, $CF, $8A), ($F9, $F9, $10, $E9), ($02, $02, $06, $04), ($7F, $7F, $81, $FE), ($50, $50, $F0, $A0), ($3C, $3C, $44, $78), ($9F, $9F, $BA, $25), ($A8, $A8, $E3, $4B), ($51, $51, $F3, $A2), ($A3, $A3, $FE, $5D), ($40, $40, $C0, $80), ($8F, $8F, $8A, $05), ($92, $92, $AD, $3F), ($9D, $9D, $BC, $21), ($38, $38, $48, $70), ($F5, $F5, $04, $F1), ($BC, $BC, $DF, $63), ($B6, $B6, $C1, $77), ($DA, $DA, $75, $AF), ($21, $21, $63, $42), ($10, $10, $30, $20), ($FF, $FF, $1A, $E5), ($F3, $F3, $0E, $FD), ($D2, $D2, $6D, $BF), ($CD, $CD, $4C, $81), ($0C, $0C, $14, $18), ($13, $13, $35, $26), ($EC, $EC, $2F, $C3), ($5F, $5F, $E1, $BE), ($97, $97, $A2, $35), ($44, $44, $CC, $88), ($17, $17, $39, $2E), ($C4, $C4, $57, $93), ($A7, $A7, $F2, $55), ($7E, $7E, $82, $FC), ($3D, $3D, $47, $7A), ($64, $64, $AC, $C8), ($5D, $5D, $E7, $BA), ($19, $19, $2B, $32), ($73, $73, $95, $E6), ($60, $60, $A0, $C0), ($81, $81, $98, $19), ($4F, $4F, $D1, $9E), ($DC, $DC, $7F, $A3), ($22, $22, $66, $44), ($2A, $2A, $7E, $54), ($90, $90, $AB, $3B), ($88, $88, $83, $0B), ($46, $46, $CA, $8C), ($EE, $EE, $29, $C7), ($B8, $B8, $D3, $6B), ($14, $14, $3C, $28), ($DE, $DE, $79, $A7), ($5E, $5E, $E2, $BC), ($0B, $0B, $1D, $16), ($DB, $DB, $76, $AD), ($E0, $E0, $3B, $DB), ($32, $32, $56, $64), ($3A, $3A, $4E, $74), ($0A, $0A, $1E, $14), ($49, $49, $DB, $92), ($06, $06, $0A, $0C), ($24, $24, $6C, $48), ($5C, $5C, $E4, $B8), ($C2, $C2, $5D, $9F), ($D3, $D3, $6E, $BD), ($AC, $AC, $EF, $43), ($62, $62, $A6, $C4), ($91, $91, $A8, $39), ($95, $95, $A4, $31), ($E4, $E4, $37, $D3), ($79, $79, $8B, $F2), ($E7, $E7, $32, $D5), ($C8, $C8, $43, $8B), ($37, $37, $59, $6E), ($6D, $6D, $B7, $DA), ($8D, $8D, $8C, $01), ($D5, $D5, $64, $B1), ($4E, $4E, $D2, $9C), ($A9, $A9, $E0, $49), ($6C, $6C, $B4, $D8), ($56, $56, $FA, $AC), ($F4, $F4, $07, $F3), ($EA, $EA, $25, $CF), ($65, $65, $AF, $CA), ($7A, $7A, $8E, $F4), ($AE, $AE, $E9, $47), ($08, $08, $18, $10), ($BA, $BA, $D5, $6F), ($78, $78, $88, $F0), ($25, $25, $6F, $4A), ($2E, $2E, $72, $5C), ($1C, $1C, $24, $38), ($A6, $A6, $F1, $57), ($B4, $B4, $C7, $73), ($C6, $C6, $51, $97), ($E8, $E8, $23, $CB), ($DD, $DD, $7C, $A1), ($74, $74, $9C, $E8), ($1F, $1F, $21, $3E), ($4B, $4B, $DD, $96), ($BD, $BD, $DC, $61), ($8B, $8B, $86, $0D), ($8A, $8A, $85, $0F), ($70, $70, $90, $E0), ($3E, $3E, $42, $7C), ($B5, $B5, $C4, $71), ($66, $66, $AA, $CC), ($48, $48, $D8, $90), ($03, $03, $05, $06), ($F6, $F6, $01, $F7), ($0E, $0E, $12, $1C), ($61, $61, $A3, $C2), ($35, $35, $5F, $6A), ($57, $57, $F9, $AE), ($B9, $B9, $D0, $69), ($86, $86, $91, $17), ($C1, $C1, $58, $99), ($1D, $1D, $27, $3A), ($9E, $9E, $B9, $27), ($E1, $E1, $38, $D9), ($F8, $F8, $13, $EB), ($98, $98, $B3, $2B), ($11, $11, $33, $22), ($69, $69, $BB, $D2), ($D9, $D9, $70, $A9), ($8E, $8E, $89, $07), ($94, $94, $A7, $33), ($9B, $9B, $B6, $2D), ($1E, $1E, $22, $3C), ($87, $87, $92, $15), ($E9, $E9, $20, $C9), ($CE, $CE, $49, $87), ($55, $55, $FF, $AA), ($28, $28, $78, $50), ($DF, $DF, $7A, $A5), ($8C, $8C, $8F, $03), ($A1, $A1, $F8, $59), ($89, $89, $80, $09), ($0D, $0D, $17, $1A), ($BF, $BF, $DA, $65), ($E6, $E6, $31, $D7), ($42, $42, $C6, $84), ($68, $68, $B8, $D0), ($41, $41, $C3, $82), ($99, $99, $B0, $29), ($2D, $2D, $77, $5A), ($0F, $0F, $11, $1E), ($B0, $B0, $CB, $7B), ($54, $54, $FC, $A8), ($BB, $BB, $D6, $6D), ($16, $16, $3A, $2C)); T5: array [0 .. 255, 0 .. 3] of Byte = ( ($51, $F4, $A7, $50), ($7E, $41, $65, $53), ($1A, $17, $A4, $C3), ($3A, $27, $5E, $96), ($3B, $AB, $6B, $CB), ($1F, $9D, $45, $F1), ($AC, $FA, $58, $AB), ($4B, $E3, $03, $93), ($20, $30, $FA, $55), ($AD, $76, $6D, $F6), ($88, $CC, $76, $91), ($F5, $02, $4C, $25), ($4F, $E5, $D7, $FC), ($C5, $2A, $CB, $D7), ($26, $35, $44, $80), ($B5, $62, $A3, $8F), ($DE, $B1, $5A, $49), ($25, $BA, $1B, $67), ($45, $EA, $0E, $98), ($5D, $FE, $C0, $E1), ($C3, $2F, $75, $02), ($81, $4C, $F0, $12), ($8D, $46, $97, $A3), ($6B, $D3, $F9, $C6), ($03, $8F, $5F, $E7), ($15, $92, $9C, $95), ($BF, $6D, $7A, $EB), ($95, $52, $59, $DA), ($D4, $BE, $83, $2D), ($58, $74, $21, $D3), ($49, $E0, $69, $29), ($8E, $C9, $C8, $44), ($75, $C2, $89, $6A), ($F4, $8E, $79, $78), ($99, $58, $3E, $6B), ($27, $B9, $71, $DD), ($BE, $E1, $4F, $B6), ($F0, $88, $AD, $17), ($C9, $20, $AC, $66), ($7D, $CE, $3A, $B4), ($63, $DF, $4A, $18), ($E5, $1A, $31, $82), ($97, $51, $33, $60), ($62, $53, $7F, $45), ($B1, $64, $77, $E0), ($BB, $6B, $AE, $84), ($FE, $81, $A0, $1C), ($F9, $08, $2B, $94), ($70, $48, $68, $58), ($8F, $45, $FD, $19), ($94, $DE, $6C, $87), ($52, $7B, $F8, $B7), ($AB, $73, $D3, $23), ($72, $4B, $02, $E2), ($E3, $1F, $8F, $57), ($66, $55, $AB, $2A), ($B2, $EB, $28, $07), ($2F, $B5, $C2, $03), ($86, $C5, $7B, $9A), ($D3, $37, $08, $A5), ($30, $28, $87, $F2), ($23, $BF, $A5, $B2), ($02, $03, $6A, $BA), ($ED, $16, $82, $5C), ($8A, $CF, $1C, $2B), ($A7, $79, $B4, $92), ($F3, $07, $F2, $F0), ($4E, $69, $E2, $A1), ($65, $DA, $F4, $CD), ($06, $05, $BE, $D5), ($D1, $34, $62, $1F), ($C4, $A6, $FE, $8A), ($34, $2E, $53, $9D), ($A2, $F3, $55, $A0), ($05, $8A, $E1, $32), ($A4, $F6, $EB, $75), ($0B, $83, $EC, $39), ($40, $60, $EF, $AA), ($5E, $71, $9F, $06), ($BD, $6E, $10, $51), ($3E, $21, $8A, $F9), ($96, $DD, $06, $3D), ($DD, $3E, $05, $AE), ($4D, $E6, $BD, $46), ($91, $54, $8D, $B5), ($71, $C4, $5D, $05), ($04, $06, $D4, $6F), ($60, $50, $15, $FF), ($19, $98, $FB, $24), ($D6, $BD, $E9, $97), ($89, $40, $43, $CC), ($67, $D9, $9E, $77), ($B0, $E8, $42, $BD), ($07, $89, $8B, $88), ($E7, $19, $5B, $38), ($79, $C8, $EE, $DB), ($A1, $7C, $0A, $47), ($7C, $42, $0F, $E9), ($F8, $84, $1E, $C9), ($00, $00, $00, $00), ($09, $80, $86, $83), ($32, $2B, $ED, $48), ($1E, $11, $70, $AC), ($6C, $5A, $72, $4E), ($FD, $0E, $FF, $FB), ($0F, $85, $38, $56), ($3D, $AE, $D5, $1E), ($36, $2D, $39, $27), ($0A, $0F, $D9, $64), ($68, $5C, $A6, $21), ($9B, $5B, $54, $D1), ($24, $36, $2E, $3A), ($0C, $0A, $67, $B1), ($93, $57, $E7, $0F), ($B4, $EE, $96, $D2), ($1B, $9B, $91, $9E), ($80, $C0, $C5, $4F), ($61, $DC, $20, $A2), ($5A, $77, $4B, $69), ($1C, $12, $1A, $16), ($E2, $93, $BA, $0A), ($C0, $A0, $2A, $E5), ($3C, $22, $E0, $43), ($12, $1B, $17, $1D), ($0E, $09, $0D, $0B), ($F2, $8B, $C7, $AD), ($2D, $B6, $A8, $B9), ($14, $1E, $A9, $C8), ($57, $F1, $19, $85), ($AF, $75, $07, $4C), ($EE, $99, $DD, $BB), ($A3, $7F, $60, $FD), ($F7, $01, $26, $9F), ($5C, $72, $F5, $BC), ($44, $66, $3B, $C5), ($5B, $FB, $7E, $34), ($8B, $43, $29, $76), ($CB, $23, $C6, $DC), ($B6, $ED, $FC, $68), ($B8, $E4, $F1, $63), ($D7, $31, $DC, $CA), ($42, $63, $85, $10), ($13, $97, $22, $40), ($84, $C6, $11, $20), ($85, $4A, $24, $7D), ($D2, $BB, $3D, $F8), ($AE, $F9, $32, $11), ($C7, $29, $A1, $6D), ($1D, $9E, $2F, $4B), ($DC, $B2, $30, $F3), ($0D, $86, $52, $EC), ($77, $C1, $E3, $D0), ($2B, $B3, $16, $6C), ($A9, $70, $B9, $99), ($11, $94, $48, $FA), ($47, $E9, $64, $22), ($A8, $FC, $8C, $C4), ($A0, $F0, $3F, $1A), ($56, $7D, $2C, $D8), ($22, $33, $90, $EF), ($87, $49, $4E, $C7), ($D9, $38, $D1, $C1), ($8C, $CA, $A2, $FE), ($98, $D4, $0B, $36), ($A6, $F5, $81, $CF), ($A5, $7A, $DE, $28), ($DA, $B7, $8E, $26), ($3F, $AD, $BF, $A4), ($2C, $3A, $9D, $E4), ($50, $78, $92, $0D), ($6A, $5F, $CC, $9B), ($54, $7E, $46, $62), ($F6, $8D, $13, $C2), ($90, $D8, $B8, $E8), ($2E, $39, $F7, $5E), ($82, $C3, $AF, $F5), ($9F, $5D, $80, $BE), ($69, $D0, $93, $7C), ($6F, $D5, $2D, $A9), ($CF, $25, $12, $B3), ($C8, $AC, $99, $3B), ($10, $18, $7D, $A7), ($E8, $9C, $63, $6E), ($DB, $3B, $BB, $7B), ($CD, $26, $78, $09), ($6E, $59, $18, $F4), ($EC, $9A, $B7, $01), ($83, $4F, $9A, $A8), ($E6, $95, $6E, $65), ($AA, $FF, $E6, $7E), ($21, $BC, $CF, $08), ($EF, $15, $E8, $E6), ($BA, $E7, $9B, $D9), ($4A, $6F, $36, $CE), ($EA, $9F, $09, $D4), ($29, $B0, $7C, $D6), ($31, $A4, $B2, $AF), ($2A, $3F, $23, $31), ($C6, $A5, $94, $30), ($35, $A2, $66, $C0), ($74, $4E, $BC, $37), ($FC, $82, $CA, $A6), ($E0, $90, $D0, $B0), ($33, $A7, $D8, $15), ($F1, $04, $98, $4A), ($41, $EC, $DA, $F7), ($7F, $CD, $50, $0E), ($17, $91, $F6, $2F), ($76, $4D, $D6, $8D), ($43, $EF, $B0, $4D), ($CC, $AA, $4D, $54), ($E4, $96, $04, $DF), ($9E, $D1, $B5, $E3), ($4C, $6A, $88, $1B), ($C1, $2C, $1F, $B8), ($46, $65, $51, $7F), ($9D, $5E, $EA, $04), ($01, $8C, $35, $5D), ($FA, $87, $74, $73), ($FB, $0B, $41, $2E), ($B3, $67, $1D, $5A), ($92, $DB, $D2, $52), ($E9, $10, $56, $33), ($6D, $D6, $47, $13), ($9A, $D7, $61, $8C), ($37, $A1, $0C, $7A), ($59, $F8, $14, $8E), ($EB, $13, $3C, $89), ($CE, $A9, $27, $EE), ($B7, $61, $C9, $35), ($E1, $1C, $E5, $ED), ($7A, $47, $B1, $3C), ($9C, $D2, $DF, $59), ($55, $F2, $73, $3F), ($18, $14, $CE, $79), ($73, $C7, $37, $BF), ($53, $F7, $CD, $EA), ($5F, $FD, $AA, $5B), ($DF, $3D, $6F, $14), ($78, $44, $DB, $86), ($CA, $AF, $F3, $81), ($B9, $68, $C4, $3E), ($38, $24, $34, $2C), ($C2, $A3, $40, $5F), ($16, $1D, $C3, $72), ($BC, $E2, $25, $0C), ($28, $3C, $49, $8B), ($FF, $0D, $95, $41), ($39, $A8, $01, $71), ($08, $0C, $B3, $DE), ($D8, $B4, $E4, $9C), ($64, $56, $C1, $90), ($7B, $CB, $84, $61), ($D5, $32, $B6, $70), ($48, $6C, $5C, $74), ($D0, $B8, $57, $42)); T6: array [0 .. 255, 0 .. 3] of Byte = ( ($50, $51, $F4, $A7), ($53, $7E, $41, $65), ($C3, $1A, $17, $A4), ($96, $3A, $27, $5E), ($CB, $3B, $AB, $6B), ($F1, $1F, $9D, $45), ($AB, $AC, $FA, $58), ($93, $4B, $E3, $03), ($55, $20, $30, $FA), ($F6, $AD, $76, $6D), ($91, $88, $CC, $76), ($25, $F5, $02, $4C), ($FC, $4F, $E5, $D7), ($D7, $C5, $2A, $CB), ($80, $26, $35, $44), ($8F, $B5, $62, $A3), ($49, $DE, $B1, $5A), ($67, $25, $BA, $1B), ($98, $45, $EA, $0E), ($E1, $5D, $FE, $C0), ($02, $C3, $2F, $75), ($12, $81, $4C, $F0), ($A3, $8D, $46, $97), ($C6, $6B, $D3, $F9), ($E7, $03, $8F, $5F), ($95, $15, $92, $9C), ($EB, $BF, $6D, $7A), ($DA, $95, $52, $59), ($2D, $D4, $BE, $83), ($D3, $58, $74, $21), ($29, $49, $E0, $69), ($44, $8E, $C9, $C8), ($6A, $75, $C2, $89), ($78, $F4, $8E, $79), ($6B, $99, $58, $3E), ($DD, $27, $B9, $71), ($B6, $BE, $E1, $4F), ($17, $F0, $88, $AD), ($66, $C9, $20, $AC), ($B4, $7D, $CE, $3A), ($18, $63, $DF, $4A), ($82, $E5, $1A, $31), ($60, $97, $51, $33), ($45, $62, $53, $7F), ($E0, $B1, $64, $77), ($84, $BB, $6B, $AE), ($1C, $FE, $81, $A0), ($94, $F9, $08, $2B), ($58, $70, $48, $68), ($19, $8F, $45, $FD), ($87, $94, $DE, $6C), ($B7, $52, $7B, $F8), ($23, $AB, $73, $D3), ($E2, $72, $4B, $02), ($57, $E3, $1F, $8F), ($2A, $66, $55, $AB), ($07, $B2, $EB, $28), ($03, $2F, $B5, $C2), ($9A, $86, $C5, $7B), ($A5, $D3, $37, $08), ($F2, $30, $28, $87), ($B2, $23, $BF, $A5), ($BA, $02, $03, $6A), ($5C, $ED, $16, $82), ($2B, $8A, $CF, $1C), ($92, $A7, $79, $B4), ($F0, $F3, $07, $F2), ($A1, $4E, $69, $E2), ($CD, $65, $DA, $F4), ($D5, $06, $05, $BE), ($1F, $D1, $34, $62), ($8A, $C4, $A6, $FE), ($9D, $34, $2E, $53), ($A0, $A2, $F3, $55), ($32, $05, $8A, $E1), ($75, $A4, $F6, $EB), ($39, $0B, $83, $EC), ($AA, $40, $60, $EF), ($06, $5E, $71, $9F), ($51, $BD, $6E, $10), ($F9, $3E, $21, $8A), ($3D, $96, $DD, $06), ($AE, $DD, $3E, $05), ($46, $4D, $E6, $BD), ($B5, $91, $54, $8D), ($05, $71, $C4, $5D), ($6F, $04, $06, $D4), ($FF, $60, $50, $15), ($24, $19, $98, $FB), ($97, $D6, $BD, $E9), ($CC, $89, $40, $43), ($77, $67, $D9, $9E), ($BD, $B0, $E8, $42), ($88, $07, $89, $8B), ($38, $E7, $19, $5B), ($DB, $79, $C8, $EE), ($47, $A1, $7C, $0A), ($E9, $7C, $42, $0F), ($C9, $F8, $84, $1E), ($00, $00, $00, $00), ($83, $09, $80, $86), ($48, $32, $2B, $ED), ($AC, $1E, $11, $70), ($4E, $6C, $5A, $72), ($FB, $FD, $0E, $FF), ($56, $0F, $85, $38), ($1E, $3D, $AE, $D5), ($27, $36, $2D, $39), ($64, $0A, $0F, $D9), ($21, $68, $5C, $A6), ($D1, $9B, $5B, $54), ($3A, $24, $36, $2E), ($B1, $0C, $0A, $67), ($0F, $93, $57, $E7), ($D2, $B4, $EE, $96), ($9E, $1B, $9B, $91), ($4F, $80, $C0, $C5), ($A2, $61, $DC, $20), ($69, $5A, $77, $4B), ($16, $1C, $12, $1A), ($0A, $E2, $93, $BA), ($E5, $C0, $A0, $2A), ($43, $3C, $22, $E0), ($1D, $12, $1B, $17), ($0B, $0E, $09, $0D), ($AD, $F2, $8B, $C7), ($B9, $2D, $B6, $A8), ($C8, $14, $1E, $A9), ($85, $57, $F1, $19), ($4C, $AF, $75, $07), ($BB, $EE, $99, $DD), ($FD, $A3, $7F, $60), ($9F, $F7, $01, $26), ($BC, $5C, $72, $F5), ($C5, $44, $66, $3B), ($34, $5B, $FB, $7E), ($76, $8B, $43, $29), ($DC, $CB, $23, $C6), ($68, $B6, $ED, $FC), ($63, $B8, $E4, $F1), ($CA, $D7, $31, $DC), ($10, $42, $63, $85), ($40, $13, $97, $22), ($20, $84, $C6, $11), ($7D, $85, $4A, $24), ($F8, $D2, $BB, $3D), ($11, $AE, $F9, $32), ($6D, $C7, $29, $A1), ($4B, $1D, $9E, $2F), ($F3, $DC, $B2, $30), ($EC, $0D, $86, $52), ($D0, $77, $C1, $E3), ($6C, $2B, $B3, $16), ($99, $A9, $70, $B9), ($FA, $11, $94, $48), ($22, $47, $E9, $64), ($C4, $A8, $FC, $8C), ($1A, $A0, $F0, $3F), ($D8, $56, $7D, $2C), ($EF, $22, $33, $90), ($C7, $87, $49, $4E), ($C1, $D9, $38, $D1), ($FE, $8C, $CA, $A2), ($36, $98, $D4, $0B), ($CF, $A6, $F5, $81), ($28, $A5, $7A, $DE), ($26, $DA, $B7, $8E), ($A4, $3F, $AD, $BF), ($E4, $2C, $3A, $9D), ($0D, $50, $78, $92), ($9B, $6A, $5F, $CC), ($62, $54, $7E, $46), ($C2, $F6, $8D, $13), ($E8, $90, $D8, $B8), ($5E, $2E, $39, $F7), ($F5, $82, $C3, $AF), ($BE, $9F, $5D, $80), ($7C, $69, $D0, $93), ($A9, $6F, $D5, $2D), ($B3, $CF, $25, $12), ($3B, $C8, $AC, $99), ($A7, $10, $18, $7D), ($6E, $E8, $9C, $63), ($7B, $DB, $3B, $BB), ($09, $CD, $26, $78), ($F4, $6E, $59, $18), ($01, $EC, $9A, $B7), ($A8, $83, $4F, $9A), ($65, $E6, $95, $6E), ($7E, $AA, $FF, $E6), ($08, $21, $BC, $CF), ($E6, $EF, $15, $E8), ($D9, $BA, $E7, $9B), ($CE, $4A, $6F, $36), ($D4, $EA, $9F, $09), ($D6, $29, $B0, $7C), ($AF, $31, $A4, $B2), ($31, $2A, $3F, $23), ($30, $C6, $A5, $94), ($C0, $35, $A2, $66), ($37, $74, $4E, $BC), ($A6, $FC, $82, $CA), ($B0, $E0, $90, $D0), ($15, $33, $A7, $D8), ($4A, $F1, $04, $98), ($F7, $41, $EC, $DA), ($0E, $7F, $CD, $50), ($2F, $17, $91, $F6), ($8D, $76, $4D, $D6), ($4D, $43, $EF, $B0), ($54, $CC, $AA, $4D), ($DF, $E4, $96, $04), ($E3, $9E, $D1, $B5), ($1B, $4C, $6A, $88), ($B8, $C1, $2C, $1F), ($7F, $46, $65, $51), ($04, $9D, $5E, $EA), ($5D, $01, $8C, $35), ($73, $FA, $87, $74), ($2E, $FB, $0B, $41), ($5A, $B3, $67, $1D), ($52, $92, $DB, $D2), ($33, $E9, $10, $56), ($13, $6D, $D6, $47), ($8C, $9A, $D7, $61), ($7A, $37, $A1, $0C), ($8E, $59, $F8, $14), ($89, $EB, $13, $3C), ($EE, $CE, $A9, $27), ($35, $B7, $61, $C9), ($ED, $E1, $1C, $E5), ($3C, $7A, $47, $B1), ($59, $9C, $D2, $DF), ($3F, $55, $F2, $73), ($79, $18, $14, $CE), ($BF, $73, $C7, $37), ($EA, $53, $F7, $CD), ($5B, $5F, $FD, $AA), ($14, $DF, $3D, $6F), ($86, $78, $44, $DB), ($81, $CA, $AF, $F3), ($3E, $B9, $68, $C4), ($2C, $38, $24, $34), ($5F, $C2, $A3, $40), ($72, $16, $1D, $C3), ($0C, $BC, $E2, $25), ($8B, $28, $3C, $49), ($41, $FF, $0D, $95), ($71, $39, $A8, $01), ($DE, $08, $0C, $B3), ($9C, $D8, $B4, $E4), ($90, $64, $56, $C1), ($61, $7B, $CB, $84), ($70, $D5, $32, $B6), ($74, $48, $6C, $5C), ($42, $D0, $B8, $57)); T7: array [0 .. 255, 0 .. 3] of Byte = ( ($A7, $50, $51, $F4), ($65, $53, $7E, $41), ($A4, $C3, $1A, $17), ($5E, $96, $3A, $27), ($6B, $CB, $3B, $AB), ($45, $F1, $1F, $9D), ($58, $AB, $AC, $FA), ($03, $93, $4B, $E3), ($FA, $55, $20, $30), ($6D, $F6, $AD, $76), ($76, $91, $88, $CC), ($4C, $25, $F5, $02), ($D7, $FC, $4F, $E5), ($CB, $D7, $C5, $2A), ($44, $80, $26, $35), ($A3, $8F, $B5, $62), ($5A, $49, $DE, $B1), ($1B, $67, $25, $BA), ($0E, $98, $45, $EA), ($C0, $E1, $5D, $FE), ($75, $02, $C3, $2F), ($F0, $12, $81, $4C), ($97, $A3, $8D, $46), ($F9, $C6, $6B, $D3), ($5F, $E7, $03, $8F), ($9C, $95, $15, $92), ($7A, $EB, $BF, $6D), ($59, $DA, $95, $52), ($83, $2D, $D4, $BE), ($21, $D3, $58, $74), ($69, $29, $49, $E0), ($C8, $44, $8E, $C9), ($89, $6A, $75, $C2), ($79, $78, $F4, $8E), ($3E, $6B, $99, $58), ($71, $DD, $27, $B9), ($4F, $B6, $BE, $E1), ($AD, $17, $F0, $88), ($AC, $66, $C9, $20), ($3A, $B4, $7D, $CE), ($4A, $18, $63, $DF), ($31, $82, $E5, $1A), ($33, $60, $97, $51), ($7F, $45, $62, $53), ($77, $E0, $B1, $64), ($AE, $84, $BB, $6B), ($A0, $1C, $FE, $81), ($2B, $94, $F9, $08), ($68, $58, $70, $48), ($FD, $19, $8F, $45), ($6C, $87, $94, $DE), ($F8, $B7, $52, $7B), ($D3, $23, $AB, $73), ($02, $E2, $72, $4B), ($8F, $57, $E3, $1F), ($AB, $2A, $66, $55), ($28, $07, $B2, $EB), ($C2, $03, $2F, $B5), ($7B, $9A, $86, $C5), ($08, $A5, $D3, $37), ($87, $F2, $30, $28), ($A5, $B2, $23, $BF), ($6A, $BA, $02, $03), ($82, $5C, $ED, $16), ($1C, $2B, $8A, $CF), ($B4, $92, $A7, $79), ($F2, $F0, $F3, $07), ($E2, $A1, $4E, $69), ($F4, $CD, $65, $DA), ($BE, $D5, $06, $05), ($62, $1F, $D1, $34), ($FE, $8A, $C4, $A6), ($53, $9D, $34, $2E), ($55, $A0, $A2, $F3), ($E1, $32, $05, $8A), ($EB, $75, $A4, $F6), ($EC, $39, $0B, $83), ($EF, $AA, $40, $60), ($9F, $06, $5E, $71), ($10, $51, $BD, $6E), ($8A, $F9, $3E, $21), ($06, $3D, $96, $DD), ($05, $AE, $DD, $3E), ($BD, $46, $4D, $E6), ($8D, $B5, $91, $54), ($5D, $05, $71, $C4), ($D4, $6F, $04, $06), ($15, $FF, $60, $50), ($FB, $24, $19, $98), ($E9, $97, $D6, $BD), ($43, $CC, $89, $40), ($9E, $77, $67, $D9), ($42, $BD, $B0, $E8), ($8B, $88, $07, $89), ($5B, $38, $E7, $19), ($EE, $DB, $79, $C8), ($0A, $47, $A1, $7C), ($0F, $E9, $7C, $42), ($1E, $C9, $F8, $84), ($00, $00, $00, $00), ($86, $83, $09, $80), ($ED, $48, $32, $2B), ($70, $AC, $1E, $11), ($72, $4E, $6C, $5A), ($FF, $FB, $FD, $0E), ($38, $56, $0F, $85), ($D5, $1E, $3D, $AE), ($39, $27, $36, $2D), ($D9, $64, $0A, $0F), ($A6, $21, $68, $5C), ($54, $D1, $9B, $5B), ($2E, $3A, $24, $36), ($67, $B1, $0C, $0A), ($E7, $0F, $93, $57), ($96, $D2, $B4, $EE), ($91, $9E, $1B, $9B), ($C5, $4F, $80, $C0), ($20, $A2, $61, $DC), ($4B, $69, $5A, $77), ($1A, $16, $1C, $12), ($BA, $0A, $E2, $93), ($2A, $E5, $C0, $A0), ($E0, $43, $3C, $22), ($17, $1D, $12, $1B), ($0D, $0B, $0E, $09), ($C7, $AD, $F2, $8B), ($A8, $B9, $2D, $B6), ($A9, $C8, $14, $1E), ($19, $85, $57, $F1), ($07, $4C, $AF, $75), ($DD, $BB, $EE, $99), ($60, $FD, $A3, $7F), ($26, $9F, $F7, $01), ($F5, $BC, $5C, $72), ($3B, $C5, $44, $66), ($7E, $34, $5B, $FB), ($29, $76, $8B, $43), ($C6, $DC, $CB, $23), ($FC, $68, $B6, $ED), ($F1, $63, $B8, $E4), ($DC, $CA, $D7, $31), ($85, $10, $42, $63), ($22, $40, $13, $97), ($11, $20, $84, $C6), ($24, $7D, $85, $4A), ($3D, $F8, $D2, $BB), ($32, $11, $AE, $F9), ($A1, $6D, $C7, $29), ($2F, $4B, $1D, $9E), ($30, $F3, $DC, $B2), ($52, $EC, $0D, $86), ($E3, $D0, $77, $C1), ($16, $6C, $2B, $B3), ($B9, $99, $A9, $70), ($48, $FA, $11, $94), ($64, $22, $47, $E9), ($8C, $C4, $A8, $FC), ($3F, $1A, $A0, $F0), ($2C, $D8, $56, $7D), ($90, $EF, $22, $33), ($4E, $C7, $87, $49), ($D1, $C1, $D9, $38), ($A2, $FE, $8C, $CA), ($0B, $36, $98, $D4), ($81, $CF, $A6, $F5), ($DE, $28, $A5, $7A), ($8E, $26, $DA, $B7), ($BF, $A4, $3F, $AD), ($9D, $E4, $2C, $3A), ($92, $0D, $50, $78), ($CC, $9B, $6A, $5F), ($46, $62, $54, $7E), ($13, $C2, $F6, $8D), ($B8, $E8, $90, $D8), ($F7, $5E, $2E, $39), ($AF, $F5, $82, $C3), ($80, $BE, $9F, $5D), ($93, $7C, $69, $D0), ($2D, $A9, $6F, $D5), ($12, $B3, $CF, $25), ($99, $3B, $C8, $AC), ($7D, $A7, $10, $18), ($63, $6E, $E8, $9C), ($BB, $7B, $DB, $3B), ($78, $09, $CD, $26), ($18, $F4, $6E, $59), ($B7, $01, $EC, $9A), ($9A, $A8, $83, $4F), ($6E, $65, $E6, $95), ($E6, $7E, $AA, $FF), ($CF, $08, $21, $BC), ($E8, $E6, $EF, $15), ($9B, $D9, $BA, $E7), ($36, $CE, $4A, $6F), ($09, $D4, $EA, $9F), ($7C, $D6, $29, $B0), ($B2, $AF, $31, $A4), ($23, $31, $2A, $3F), ($94, $30, $C6, $A5), ($66, $C0, $35, $A2), ($BC, $37, $74, $4E), ($CA, $A6, $FC, $82), ($D0, $B0, $E0, $90), ($D8, $15, $33, $A7), ($98, $4A, $F1, $04), ($DA, $F7, $41, $EC), ($50, $0E, $7F, $CD), ($F6, $2F, $17, $91), ($D6, $8D, $76, $4D), ($B0, $4D, $43, $EF), ($4D, $54, $CC, $AA), ($04, $DF, $E4, $96), ($B5, $E3, $9E, $D1), ($88, $1B, $4C, $6A), ($1F, $B8, $C1, $2C), ($51, $7F, $46, $65), ($EA, $04, $9D, $5E), ($35, $5D, $01, $8C), ($74, $73, $FA, $87), ($41, $2E, $FB, $0B), ($1D, $5A, $B3, $67), ($D2, $52, $92, $DB), ($56, $33, $E9, $10), ($47, $13, $6D, $D6), ($61, $8C, $9A, $D7), ($0C, $7A, $37, $A1), ($14, $8E, $59, $F8), ($3C, $89, $EB, $13), ($27, $EE, $CE, $A9), ($C9, $35, $B7, $61), ($E5, $ED, $E1, $1C), ($B1, $3C, $7A, $47), ($DF, $59, $9C, $D2), ($73, $3F, $55, $F2), ($CE, $79, $18, $14), ($37, $BF, $73, $C7), ($CD, $EA, $53, $F7), ($AA, $5B, $5F, $FD), ($6F, $14, $DF, $3D), ($DB, $86, $78, $44), ($F3, $81, $CA, $AF), ($C4, $3E, $B9, $68), ($34, $2C, $38, $24), ($40, $5F, $C2, $A3), ($C3, $72, $16, $1D), ($25, $0C, $BC, $E2), ($49, $8B, $28, $3C), ($95, $41, $FF, $0D), ($01, $71, $39, $A8), ($B3, $DE, $08, $0C), ($E4, $9C, $D8, $B4), ($C1, $90, $64, $56), ($84, $61, $7B, $CB), ($B6, $70, $D5, $32), ($5C, $74, $48, $6C), ($57, $42, $D0, $B8)); T8: array [0 .. 255, 0 .. 3] of Byte = ( ($F4, $A7, $50, $51), ($41, $65, $53, $7E), ($17, $A4, $C3, $1A), ($27, $5E, $96, $3A), ($AB, $6B, $CB, $3B), ($9D, $45, $F1, $1F), ($FA, $58, $AB, $AC), ($E3, $03, $93, $4B), ($30, $FA, $55, $20), ($76, $6D, $F6, $AD), ($CC, $76, $91, $88), ($02, $4C, $25, $F5), ($E5, $D7, $FC, $4F), ($2A, $CB, $D7, $C5), ($35, $44, $80, $26), ($62, $A3, $8F, $B5), ($B1, $5A, $49, $DE), ($BA, $1B, $67, $25), ($EA, $0E, $98, $45), ($FE, $C0, $E1, $5D), ($2F, $75, $02, $C3), ($4C, $F0, $12, $81), ($46, $97, $A3, $8D), ($D3, $F9, $C6, $6B), ($8F, $5F, $E7, $03), ($92, $9C, $95, $15), ($6D, $7A, $EB, $BF), ($52, $59, $DA, $95), ($BE, $83, $2D, $D4), ($74, $21, $D3, $58), ($E0, $69, $29, $49), ($C9, $C8, $44, $8E), ($C2, $89, $6A, $75), ($8E, $79, $78, $F4), ($58, $3E, $6B, $99), ($B9, $71, $DD, $27), ($E1, $4F, $B6, $BE), ($88, $AD, $17, $F0), ($20, $AC, $66, $C9), ($CE, $3A, $B4, $7D), ($DF, $4A, $18, $63), ($1A, $31, $82, $E5), ($51, $33, $60, $97), ($53, $7F, $45, $62), ($64, $77, $E0, $B1), ($6B, $AE, $84, $BB), ($81, $A0, $1C, $FE), ($08, $2B, $94, $F9), ($48, $68, $58, $70), ($45, $FD, $19, $8F), ($DE, $6C, $87, $94), ($7B, $F8, $B7, $52), ($73, $D3, $23, $AB), ($4B, $02, $E2, $72), ($1F, $8F, $57, $E3), ($55, $AB, $2A, $66), ($EB, $28, $07, $B2), ($B5, $C2, $03, $2F), ($C5, $7B, $9A, $86), ($37, $08, $A5, $D3), ($28, $87, $F2, $30), ($BF, $A5, $B2, $23), ($03, $6A, $BA, $02), ($16, $82, $5C, $ED), ($CF, $1C, $2B, $8A), ($79, $B4, $92, $A7), ($07, $F2, $F0, $F3), ($69, $E2, $A1, $4E), ($DA, $F4, $CD, $65), ($05, $BE, $D5, $06), ($34, $62, $1F, $D1), ($A6, $FE, $8A, $C4), ($2E, $53, $9D, $34), ($F3, $55, $A0, $A2), ($8A, $E1, $32, $05), ($F6, $EB, $75, $A4), ($83, $EC, $39, $0B), ($60, $EF, $AA, $40), ($71, $9F, $06, $5E), ($6E, $10, $51, $BD), ($21, $8A, $F9, $3E), ($DD, $06, $3D, $96), ($3E, $05, $AE, $DD), ($E6, $BD, $46, $4D), ($54, $8D, $B5, $91), ($C4, $5D, $05, $71), ($06, $D4, $6F, $04), ($50, $15, $FF, $60), ($98, $FB, $24, $19), ($BD, $E9, $97, $D6), ($40, $43, $CC, $89), ($D9, $9E, $77, $67), ($E8, $42, $BD, $B0), ($89, $8B, $88, $07), ($19, $5B, $38, $E7), ($C8, $EE, $DB, $79), ($7C, $0A, $47, $A1), ($42, $0F, $E9, $7C), ($84, $1E, $C9, $F8), ($00, $00, $00, $00), ($80, $86, $83, $09), ($2B, $ED, $48, $32), ($11, $70, $AC, $1E), ($5A, $72, $4E, $6C), ($0E, $FF, $FB, $FD), ($85, $38, $56, $0F), ($AE, $D5, $1E, $3D), ($2D, $39, $27, $36), ($0F, $D9, $64, $0A), ($5C, $A6, $21, $68), ($5B, $54, $D1, $9B), ($36, $2E, $3A, $24), ($0A, $67, $B1, $0C), ($57, $E7, $0F, $93), ($EE, $96, $D2, $B4), ($9B, $91, $9E, $1B), ($C0, $C5, $4F, $80), ($DC, $20, $A2, $61), ($77, $4B, $69, $5A), ($12, $1A, $16, $1C), ($93, $BA, $0A, $E2), ($A0, $2A, $E5, $C0), ($22, $E0, $43, $3C), ($1B, $17, $1D, $12), ($09, $0D, $0B, $0E), ($8B, $C7, $AD, $F2), ($B6, $A8, $B9, $2D), ($1E, $A9, $C8, $14), ($F1, $19, $85, $57), ($75, $07, $4C, $AF), ($99, $DD, $BB, $EE), ($7F, $60, $FD, $A3), ($01, $26, $9F, $F7), ($72, $F5, $BC, $5C), ($66, $3B, $C5, $44), ($FB, $7E, $34, $5B), ($43, $29, $76, $8B), ($23, $C6, $DC, $CB), ($ED, $FC, $68, $B6), ($E4, $F1, $63, $B8), ($31, $DC, $CA, $D7), ($63, $85, $10, $42), ($97, $22, $40, $13), ($C6, $11, $20, $84), ($4A, $24, $7D, $85), ($BB, $3D, $F8, $D2), ($F9, $32, $11, $AE), ($29, $A1, $6D, $C7), ($9E, $2F, $4B, $1D), ($B2, $30, $F3, $DC), ($86, $52, $EC, $0D), ($C1, $E3, $D0, $77), ($B3, $16, $6C, $2B), ($70, $B9, $99, $A9), ($94, $48, $FA, $11), ($E9, $64, $22, $47), ($FC, $8C, $C4, $A8), ($F0, $3F, $1A, $A0), ($7D, $2C, $D8, $56), ($33, $90, $EF, $22), ($49, $4E, $C7, $87), ($38, $D1, $C1, $D9), ($CA, $A2, $FE, $8C), ($D4, $0B, $36, $98), ($F5, $81, $CF, $A6), ($7A, $DE, $28, $A5), ($B7, $8E, $26, $DA), ($AD, $BF, $A4, $3F), ($3A, $9D, $E4, $2C), ($78, $92, $0D, $50), ($5F, $CC, $9B, $6A), ($7E, $46, $62, $54), ($8D, $13, $C2, $F6), ($D8, $B8, $E8, $90), ($39, $F7, $5E, $2E), ($C3, $AF, $F5, $82), ($5D, $80, $BE, $9F), ($D0, $93, $7C, $69), ($D5, $2D, $A9, $6F), ($25, $12, $B3, $CF), ($AC, $99, $3B, $C8), ($18, $7D, $A7, $10), ($9C, $63, $6E, $E8), ($3B, $BB, $7B, $DB), ($26, $78, $09, $CD), ($59, $18, $F4, $6E), ($9A, $B7, $01, $EC), ($4F, $9A, $A8, $83), ($95, $6E, $65, $E6), ($FF, $E6, $7E, $AA), ($BC, $CF, $08, $21), ($15, $E8, $E6, $EF), ($E7, $9B, $D9, $BA), ($6F, $36, $CE, $4A), ($9F, $09, $D4, $EA), ($B0, $7C, $D6, $29), ($A4, $B2, $AF, $31), ($3F, $23, $31, $2A), ($A5, $94, $30, $C6), ($A2, $66, $C0, $35), ($4E, $BC, $37, $74), ($82, $CA, $A6, $FC), ($90, $D0, $B0, $E0), ($A7, $D8, $15, $33), ($04, $98, $4A, $F1), ($EC, $DA, $F7, $41), ($CD, $50, $0E, $7F), ($91, $F6, $2F, $17), ($4D, $D6, $8D, $76), ($EF, $B0, $4D, $43), ($AA, $4D, $54, $CC), ($96, $04, $DF, $E4), ($D1, $B5, $E3, $9E), ($6A, $88, $1B, $4C), ($2C, $1F, $B8, $C1), ($65, $51, $7F, $46), ($5E, $EA, $04, $9D), ($8C, $35, $5D, $01), ($87, $74, $73, $FA), ($0B, $41, $2E, $FB), ($67, $1D, $5A, $B3), ($DB, $D2, $52, $92), ($10, $56, $33, $E9), ($D6, $47, $13, $6D), ($D7, $61, $8C, $9A), ($A1, $0C, $7A, $37), ($F8, $14, $8E, $59), ($13, $3C, $89, $EB), ($A9, $27, $EE, $CE), ($61, $C9, $35, $B7), ($1C, $E5, $ED, $E1), ($47, $B1, $3C, $7A), ($D2, $DF, $59, $9C), ($F2, $73, $3F, $55), ($14, $CE, $79, $18), ($C7, $37, $BF, $73), ($F7, $CD, $EA, $53), ($FD, $AA, $5B, $5F), ($3D, $6F, $14, $DF), ($44, $DB, $86, $78), ($AF, $F3, $81, $CA), ($68, $C4, $3E, $B9), ($24, $34, $2C, $38), ($A3, $40, $5F, $C2), ($1D, $C3, $72, $16), ($E2, $25, $0C, $BC), ($3C, $49, $8B, $28), ($0D, $95, $41, $FF), ($A8, $01, $71, $39), ($0C, $B3, $DE, $08), ($B4, $E4, $9C, $D8), ($56, $C1, $90, $64), ($CB, $84, $61, $7B), ($32, $B6, $70, $D5), ($6C, $5C, $74, $48), ($B8, $57, $42, $D0)); S5: array [0 .. 255] of Byte = ( $52, $09, $6A, $D5, $30, $36, $A5, $38, $BF, $40, $A3, $9E, $81, $F3, $D7, $FB, $7C, $E3, $39, $82, $9B, $2F, $FF, $87, $34, $8E, $43, $44, $C4, $DE, $E9, $CB, $54, $7B, $94, $32, $A6, $C2, $23, $3D, $EE, $4C, $95, $0B, $42, $FA, $C3, $4E, $08, $2E, $A1, $66, $28, $D9, $24, $B2, $76, $5B, $A2, $49, $6D, $8B, $D1, $25, $72, $F8, $F6, $64, $86, $68, $98, $16, $D4, $A4, $5C, $CC, $5D, $65, $B6, $92, $6C, $70, $48, $50, $FD, $ED, $B9, $DA, $5E, $15, $46, $57, $A7, $8D, $9D, $84, $90, $D8, $AB, $00, $8C, $BC, $D3, $0A, $F7, $E4, $58, $05, $B8, $B3, $45, $06, $D0, $2C, $1E, $8F, $CA, $3F, $0F, $02, $C1, $AF, $BD, $03, $01, $13, $8A, $6B, $3A, $91, $11, $41, $4F, $67, $DC, $EA, $97, $F2, $CF, $CE, $F0, $B4, $E6, $73, $96, $AC, $74, $22, $E7, $AD, $35, $85, $E2, $F9, $37, $E8, $1C, $75, $DF, $6E, $47, $F1, $1A, $71, $1D, $29, $C5, $89, $6F, $B7, $62, $0E, $AA, $18, $BE, $1B, $FC, $56, $3E, $4B, $C6, $D2, $79, $20, $9A, $DB, $C0, $FE, $78, $CD, $5A, $F4, $1F, $DD, $A8, $33, $88, $07, $C7, $31, $B1, $12, $10, $59, $27, $80, $EC, $5F, $60, $51, $7F, $A9, $19, $B5, $4A, $0D, $2D, $E5, $7A, $9F, $93, $C9, $9C, $EF, $A0, $E0, $3B, $4D, $AE, $2A, $F5, $B0, $C8, $EB, $BB, $3C, $83, $53, $99, $61, $17, $2B, $04, $7E, $BA, $77, $D6, $26, $E1, $69, $14, $63, $55, $21, $0C, $7D); U1: array [0 .. 255, 0 .. 3] of Byte = ( ($00, $00, $00, $00), ($0E, $09, $0D, $0B), ($1C, $12, $1A, $16), ($12, $1B, $17, $1D), ($38, $24, $34, $2C), ($36, $2D, $39, $27), ($24, $36, $2E, $3A), ($2A, $3F, $23, $31), ($70, $48, $68, $58), ($7E, $41, $65, $53), ($6C, $5A, $72, $4E), ($62, $53, $7F, $45), ($48, $6C, $5C, $74), ($46, $65, $51, $7F), ($54, $7E, $46, $62), ($5A, $77, $4B, $69), ($E0, $90, $D0, $B0), ($EE, $99, $DD, $BB), ($FC, $82, $CA, $A6), ($F2, $8B, $C7, $AD), ($D8, $B4, $E4, $9C), ($D6, $BD, $E9, $97), ($C4, $A6, $FE, $8A), ($CA, $AF, $F3, $81), ($90, $D8, $B8, $E8), ($9E, $D1, $B5, $E3), ($8C, $CA, $A2, $FE), ($82, $C3, $AF, $F5), ($A8, $FC, $8C, $C4), ($A6, $F5, $81, $CF), ($B4, $EE, $96, $D2), ($BA, $E7, $9B, $D9), ($DB, $3B, $BB, $7B), ($D5, $32, $B6, $70), ($C7, $29, $A1, $6D), ($C9, $20, $AC, $66), ($E3, $1F, $8F, $57), ($ED, $16, $82, $5C), ($FF, $0D, $95, $41), ($F1, $04, $98, $4A), ($AB, $73, $D3, $23), ($A5, $7A, $DE, $28), ($B7, $61, $C9, $35), ($B9, $68, $C4, $3E), ($93, $57, $E7, $0F), ($9D, $5E, $EA, $04), ($8F, $45, $FD, $19), ($81, $4C, $F0, $12), ($3B, $AB, $6B, $CB), ($35, $A2, $66, $C0), ($27, $B9, $71, $DD), ($29, $B0, $7C, $D6), ($03, $8F, $5F, $E7), ($0D, $86, $52, $EC), ($1F, $9D, $45, $F1), ($11, $94, $48, $FA), ($4B, $E3, $03, $93), ($45, $EA, $0E, $98), ($57, $F1, $19, $85), ($59, $F8, $14, $8E), ($73, $C7, $37, $BF), ($7D, $CE, $3A, $B4), ($6F, $D5, $2D, $A9), ($61, $DC, $20, $A2), ($AD, $76, $6D, $F6), ($A3, $7F, $60, $FD), ($B1, $64, $77, $E0), ($BF, $6D, $7A, $EB), ($95, $52, $59, $DA), ($9B, $5B, $54, $D1), ($89, $40, $43, $CC), ($87, $49, $4E, $C7), ($DD, $3E, $05, $AE), ($D3, $37, $08, $A5), ($C1, $2C, $1F, $B8), ($CF, $25, $12, $B3), ($E5, $1A, $31, $82), ($EB, $13, $3C, $89), ($F9, $08, $2B, $94), ($F7, $01, $26, $9F), ($4D, $E6, $BD, $46), ($43, $EF, $B0, $4D), ($51, $F4, $A7, $50), ($5F, $FD, $AA, $5B), ($75, $C2, $89, $6A), ($7B, $CB, $84, $61), ($69, $D0, $93, $7C), ($67, $D9, $9E, $77), ($3D, $AE, $D5, $1E), ($33, $A7, $D8, $15), ($21, $BC, $CF, $08), ($2F, $B5, $C2, $03), ($05, $8A, $E1, $32), ($0B, $83, $EC, $39), ($19, $98, $FB, $24), ($17, $91, $F6, $2F), ($76, $4D, $D6, $8D), ($78, $44, $DB, $86), ($6A, $5F, $CC, $9B), ($64, $56, $C1, $90), ($4E, $69, $E2, $A1), ($40, $60, $EF, $AA), ($52, $7B, $F8, $B7), ($5C, $72, $F5, $BC), ($06, $05, $BE, $D5), ($08, $0C, $B3, $DE), ($1A, $17, $A4, $C3), ($14, $1E, $A9, $C8), ($3E, $21, $8A, $F9), ($30, $28, $87, $F2), ($22, $33, $90, $EF), ($2C, $3A, $9D, $E4), ($96, $DD, $06, $3D), ($98, $D4, $0B, $36), ($8A, $CF, $1C, $2B), ($84, $C6, $11, $20), ($AE, $F9, $32, $11), ($A0, $F0, $3F, $1A), ($B2, $EB, $28, $07), ($BC, $E2, $25, $0C), ($E6, $95, $6E, $65), ($E8, $9C, $63, $6E), ($FA, $87, $74, $73), ($F4, $8E, $79, $78), ($DE, $B1, $5A, $49), ($D0, $B8, $57, $42), ($C2, $A3, $40, $5F), ($CC, $AA, $4D, $54), ($41, $EC, $DA, $F7), ($4F, $E5, $D7, $FC), ($5D, $FE, $C0, $E1), ($53, $F7, $CD, $EA), ($79, $C8, $EE, $DB), ($77, $C1, $E3, $D0), ($65, $DA, $F4, $CD), ($6B, $D3, $F9, $C6), ($31, $A4, $B2, $AF), ($3F, $AD, $BF, $A4), ($2D, $B6, $A8, $B9), ($23, $BF, $A5, $B2), ($09, $80, $86, $83), ($07, $89, $8B, $88), ($15, $92, $9C, $95), ($1B, $9B, $91, $9E), ($A1, $7C, $0A, $47), ($AF, $75, $07, $4C), ($BD, $6E, $10, $51), ($B3, $67, $1D, $5A), ($99, $58, $3E, $6B), ($97, $51, $33, $60), ($85, $4A, $24, $7D), ($8B, $43, $29, $76), ($D1, $34, $62, $1F), ($DF, $3D, $6F, $14), ($CD, $26, $78, $09), ($C3, $2F, $75, $02), ($E9, $10, $56, $33), ($E7, $19, $5B, $38), ($F5, $02, $4C, $25), ($FB, $0B, $41, $2E), ($9A, $D7, $61, $8C), ($94, $DE, $6C, $87), ($86, $C5, $7B, $9A), ($88, $CC, $76, $91), ($A2, $F3, $55, $A0), ($AC, $FA, $58, $AB), ($BE, $E1, $4F, $B6), ($B0, $E8, $42, $BD), ($EA, $9F, $09, $D4), ($E4, $96, $04, $DF), ($F6, $8D, $13, $C2), ($F8, $84, $1E, $C9), ($D2, $BB, $3D, $F8), ($DC, $B2, $30, $F3), ($CE, $A9, $27, $EE), ($C0, $A0, $2A, $E5), ($7A, $47, $B1, $3C), ($74, $4E, $BC, $37), ($66, $55, $AB, $2A), ($68, $5C, $A6, $21), ($42, $63, $85, $10), ($4C, $6A, $88, $1B), ($5E, $71, $9F, $06), ($50, $78, $92, $0D), ($0A, $0F, $D9, $64), ($04, $06, $D4, $6F), ($16, $1D, $C3, $72), ($18, $14, $CE, $79), ($32, $2B, $ED, $48), ($3C, $22, $E0, $43), ($2E, $39, $F7, $5E), ($20, $30, $FA, $55), ($EC, $9A, $B7, $01), ($E2, $93, $BA, $0A), ($F0, $88, $AD, $17), ($FE, $81, $A0, $1C), ($D4, $BE, $83, $2D), ($DA, $B7, $8E, $26), ($C8, $AC, $99, $3B), ($C6, $A5, $94, $30), ($9C, $D2, $DF, $59), ($92, $DB, $D2, $52), ($80, $C0, $C5, $4F), ($8E, $C9, $C8, $44), ($A4, $F6, $EB, $75), ($AA, $FF, $E6, $7E), ($B8, $E4, $F1, $63), ($B6, $ED, $FC, $68), ($0C, $0A, $67, $B1), ($02, $03, $6A, $BA), ($10, $18, $7D, $A7), ($1E, $11, $70, $AC), ($34, $2E, $53, $9D), ($3A, $27, $5E, $96), ($28, $3C, $49, $8B), ($26, $35, $44, $80), ($7C, $42, $0F, $E9), ($72, $4B, $02, $E2), ($60, $50, $15, $FF), ($6E, $59, $18, $F4), ($44, $66, $3B, $C5), ($4A, $6F, $36, $CE), ($58, $74, $21, $D3), ($56, $7D, $2C, $D8), ($37, $A1, $0C, $7A), ($39, $A8, $01, $71), ($2B, $B3, $16, $6C), ($25, $BA, $1B, $67), ($0F, $85, $38, $56), ($01, $8C, $35, $5D), ($13, $97, $22, $40), ($1D, $9E, $2F, $4B), ($47, $E9, $64, $22), ($49, $E0, $69, $29), ($5B, $FB, $7E, $34), ($55, $F2, $73, $3F), ($7F, $CD, $50, $0E), ($71, $C4, $5D, $05), ($63, $DF, $4A, $18), ($6D, $D6, $47, $13), ($D7, $31, $DC, $CA), ($D9, $38, $D1, $C1), ($CB, $23, $C6, $DC), ($C5, $2A, $CB, $D7), ($EF, $15, $E8, $E6), ($E1, $1C, $E5, $ED), ($F3, $07, $F2, $F0), ($FD, $0E, $FF, $FB), ($A7, $79, $B4, $92), ($A9, $70, $B9, $99), ($BB, $6B, $AE, $84), ($B5, $62, $A3, $8F), ($9F, $5D, $80, $BE), ($91, $54, $8D, $B5), ($83, $4F, $9A, $A8), ($8D, $46, $97, $A3)); U2: array [0 .. 255, 0 .. 3] of Byte = ( ($00, $00, $00, $00), ($0B, $0E, $09, $0D), ($16, $1C, $12, $1A), ($1D, $12, $1B, $17), ($2C, $38, $24, $34), ($27, $36, $2D, $39), ($3A, $24, $36, $2E), ($31, $2A, $3F, $23), ($58, $70, $48, $68), ($53, $7E, $41, $65), ($4E, $6C, $5A, $72), ($45, $62, $53, $7F), ($74, $48, $6C, $5C), ($7F, $46, $65, $51), ($62, $54, $7E, $46), ($69, $5A, $77, $4B), ($B0, $E0, $90, $D0), ($BB, $EE, $99, $DD), ($A6, $FC, $82, $CA), ($AD, $F2, $8B, $C7), ($9C, $D8, $B4, $E4), ($97, $D6, $BD, $E9), ($8A, $C4, $A6, $FE), ($81, $CA, $AF, $F3), ($E8, $90, $D8, $B8), ($E3, $9E, $D1, $B5), ($FE, $8C, $CA, $A2), ($F5, $82, $C3, $AF), ($C4, $A8, $FC, $8C), ($CF, $A6, $F5, $81), ($D2, $B4, $EE, $96), ($D9, $BA, $E7, $9B), ($7B, $DB, $3B, $BB), ($70, $D5, $32, $B6), ($6D, $C7, $29, $A1), ($66, $C9, $20, $AC), ($57, $E3, $1F, $8F), ($5C, $ED, $16, $82), ($41, $FF, $0D, $95), ($4A, $F1, $04, $98), ($23, $AB, $73, $D3), ($28, $A5, $7A, $DE), ($35, $B7, $61, $C9), ($3E, $B9, $68, $C4), ($0F, $93, $57, $E7), ($04, $9D, $5E, $EA), ($19, $8F, $45, $FD), ($12, $81, $4C, $F0), ($CB, $3B, $AB, $6B), ($C0, $35, $A2, $66), ($DD, $27, $B9, $71), ($D6, $29, $B0, $7C), ($E7, $03, $8F, $5F), ($EC, $0D, $86, $52), ($F1, $1F, $9D, $45), ($FA, $11, $94, $48), ($93, $4B, $E3, $03), ($98, $45, $EA, $0E), ($85, $57, $F1, $19), ($8E, $59, $F8, $14), ($BF, $73, $C7, $37), ($B4, $7D, $CE, $3A), ($A9, $6F, $D5, $2D), ($A2, $61, $DC, $20), ($F6, $AD, $76, $6D), ($FD, $A3, $7F, $60), ($E0, $B1, $64, $77), ($EB, $BF, $6D, $7A), ($DA, $95, $52, $59), ($D1, $9B, $5B, $54), ($CC, $89, $40, $43), ($C7, $87, $49, $4E), ($AE, $DD, $3E, $05), ($A5, $D3, $37, $08), ($B8, $C1, $2C, $1F), ($B3, $CF, $25, $12), ($82, $E5, $1A, $31), ($89, $EB, $13, $3C), ($94, $F9, $08, $2B), ($9F, $F7, $01, $26), ($46, $4D, $E6, $BD), ($4D, $43, $EF, $B0), ($50, $51, $F4, $A7), ($5B, $5F, $FD, $AA), ($6A, $75, $C2, $89), ($61, $7B, $CB, $84), ($7C, $69, $D0, $93), ($77, $67, $D9, $9E), ($1E, $3D, $AE, $D5), ($15, $33, $A7, $D8), ($08, $21, $BC, $CF), ($03, $2F, $B5, $C2), ($32, $05, $8A, $E1), ($39, $0B, $83, $EC), ($24, $19, $98, $FB), ($2F, $17, $91, $F6), ($8D, $76, $4D, $D6), ($86, $78, $44, $DB), ($9B, $6A, $5F, $CC), ($90, $64, $56, $C1), ($A1, $4E, $69, $E2), ($AA, $40, $60, $EF), ($B7, $52, $7B, $F8), ($BC, $5C, $72, $F5), ($D5, $06, $05, $BE), ($DE, $08, $0C, $B3), ($C3, $1A, $17, $A4), ($C8, $14, $1E, $A9), ($F9, $3E, $21, $8A), ($F2, $30, $28, $87), ($EF, $22, $33, $90), ($E4, $2C, $3A, $9D), ($3D, $96, $DD, $06), ($36, $98, $D4, $0B), ($2B, $8A, $CF, $1C), ($20, $84, $C6, $11), ($11, $AE, $F9, $32), ($1A, $A0, $F0, $3F), ($07, $B2, $EB, $28), ($0C, $BC, $E2, $25), ($65, $E6, $95, $6E), ($6E, $E8, $9C, $63), ($73, $FA, $87, $74), ($78, $F4, $8E, $79), ($49, $DE, $B1, $5A), ($42, $D0, $B8, $57), ($5F, $C2, $A3, $40), ($54, $CC, $AA, $4D), ($F7, $41, $EC, $DA), ($FC, $4F, $E5, $D7), ($E1, $5D, $FE, $C0), ($EA, $53, $F7, $CD), ($DB, $79, $C8, $EE), ($D0, $77, $C1, $E3), ($CD, $65, $DA, $F4), ($C6, $6B, $D3, $F9), ($AF, $31, $A4, $B2), ($A4, $3F, $AD, $BF), ($B9, $2D, $B6, $A8), ($B2, $23, $BF, $A5), ($83, $09, $80, $86), ($88, $07, $89, $8B), ($95, $15, $92, $9C), ($9E, $1B, $9B, $91), ($47, $A1, $7C, $0A), ($4C, $AF, $75, $07), ($51, $BD, $6E, $10), ($5A, $B3, $67, $1D), ($6B, $99, $58, $3E), ($60, $97, $51, $33), ($7D, $85, $4A, $24), ($76, $8B, $43, $29), ($1F, $D1, $34, $62), ($14, $DF, $3D, $6F), ($09, $CD, $26, $78), ($02, $C3, $2F, $75), ($33, $E9, $10, $56), ($38, $E7, $19, $5B), ($25, $F5, $02, $4C), ($2E, $FB, $0B, $41), ($8C, $9A, $D7, $61), ($87, $94, $DE, $6C), ($9A, $86, $C5, $7B), ($91, $88, $CC, $76), ($A0, $A2, $F3, $55), ($AB, $AC, $FA, $58), ($B6, $BE, $E1, $4F), ($BD, $B0, $E8, $42), ($D4, $EA, $9F, $09), ($DF, $E4, $96, $04), ($C2, $F6, $8D, $13), ($C9, $F8, $84, $1E), ($F8, $D2, $BB, $3D), ($F3, $DC, $B2, $30), ($EE, $CE, $A9, $27), ($E5, $C0, $A0, $2A), ($3C, $7A, $47, $B1), ($37, $74, $4E, $BC), ($2A, $66, $55, $AB), ($21, $68, $5C, $A6), ($10, $42, $63, $85), ($1B, $4C, $6A, $88), ($06, $5E, $71, $9F), ($0D, $50, $78, $92), ($64, $0A, $0F, $D9), ($6F, $04, $06, $D4), ($72, $16, $1D, $C3), ($79, $18, $14, $CE), ($48, $32, $2B, $ED), ($43, $3C, $22, $E0), ($5E, $2E, $39, $F7), ($55, $20, $30, $FA), ($01, $EC, $9A, $B7), ($0A, $E2, $93, $BA), ($17, $F0, $88, $AD), ($1C, $FE, $81, $A0), ($2D, $D4, $BE, $83), ($26, $DA, $B7, $8E), ($3B, $C8, $AC, $99), ($30, $C6, $A5, $94), ($59, $9C, $D2, $DF), ($52, $92, $DB, $D2), ($4F, $80, $C0, $C5), ($44, $8E, $C9, $C8), ($75, $A4, $F6, $EB), ($7E, $AA, $FF, $E6), ($63, $B8, $E4, $F1), ($68, $B6, $ED, $FC), ($B1, $0C, $0A, $67), ($BA, $02, $03, $6A), ($A7, $10, $18, $7D), ($AC, $1E, $11, $70), ($9D, $34, $2E, $53), ($96, $3A, $27, $5E), ($8B, $28, $3C, $49), ($80, $26, $35, $44), ($E9, $7C, $42, $0F), ($E2, $72, $4B, $02), ($FF, $60, $50, $15), ($F4, $6E, $59, $18), ($C5, $44, $66, $3B), ($CE, $4A, $6F, $36), ($D3, $58, $74, $21), ($D8, $56, $7D, $2C), ($7A, $37, $A1, $0C), ($71, $39, $A8, $01), ($6C, $2B, $B3, $16), ($67, $25, $BA, $1B), ($56, $0F, $85, $38), ($5D, $01, $8C, $35), ($40, $13, $97, $22), ($4B, $1D, $9E, $2F), ($22, $47, $E9, $64), ($29, $49, $E0, $69), ($34, $5B, $FB, $7E), ($3F, $55, $F2, $73), ($0E, $7F, $CD, $50), ($05, $71, $C4, $5D), ($18, $63, $DF, $4A), ($13, $6D, $D6, $47), ($CA, $D7, $31, $DC), ($C1, $D9, $38, $D1), ($DC, $CB, $23, $C6), ($D7, $C5, $2A, $CB), ($E6, $EF, $15, $E8), ($ED, $E1, $1C, $E5), ($F0, $F3, $07, $F2), ($FB, $FD, $0E, $FF), ($92, $A7, $79, $B4), ($99, $A9, $70, $B9), ($84, $BB, $6B, $AE), ($8F, $B5, $62, $A3), ($BE, $9F, $5D, $80), ($B5, $91, $54, $8D), ($A8, $83, $4F, $9A), ($A3, $8D, $46, $97)); U3: array [0 .. 255, 0 .. 3] of Byte = ( ($00, $00, $00, $00), ($0D, $0B, $0E, $09), ($1A, $16, $1C, $12), ($17, $1D, $12, $1B), ($34, $2C, $38, $24), ($39, $27, $36, $2D), ($2E, $3A, $24, $36), ($23, $31, $2A, $3F), ($68, $58, $70, $48), ($65, $53, $7E, $41), ($72, $4E, $6C, $5A), ($7F, $45, $62, $53), ($5C, $74, $48, $6C), ($51, $7F, $46, $65), ($46, $62, $54, $7E), ($4B, $69, $5A, $77), ($D0, $B0, $E0, $90), ($DD, $BB, $EE, $99), ($CA, $A6, $FC, $82), ($C7, $AD, $F2, $8B), ($E4, $9C, $D8, $B4), ($E9, $97, $D6, $BD), ($FE, $8A, $C4, $A6), ($F3, $81, $CA, $AF), ($B8, $E8, $90, $D8), ($B5, $E3, $9E, $D1), ($A2, $FE, $8C, $CA), ($AF, $F5, $82, $C3), ($8C, $C4, $A8, $FC), ($81, $CF, $A6, $F5), ($96, $D2, $B4, $EE), ($9B, $D9, $BA, $E7), ($BB, $7B, $DB, $3B), ($B6, $70, $D5, $32), ($A1, $6D, $C7, $29), ($AC, $66, $C9, $20), ($8F, $57, $E3, $1F), ($82, $5C, $ED, $16), ($95, $41, $FF, $0D), ($98, $4A, $F1, $04), ($D3, $23, $AB, $73), ($DE, $28, $A5, $7A), ($C9, $35, $B7, $61), ($C4, $3E, $B9, $68), ($E7, $0F, $93, $57), ($EA, $04, $9D, $5E), ($FD, $19, $8F, $45), ($F0, $12, $81, $4C), ($6B, $CB, $3B, $AB), ($66, $C0, $35, $A2), ($71, $DD, $27, $B9), ($7C, $D6, $29, $B0), ($5F, $E7, $03, $8F), ($52, $EC, $0D, $86), ($45, $F1, $1F, $9D), ($48, $FA, $11, $94), ($03, $93, $4B, $E3), ($0E, $98, $45, $EA), ($19, $85, $57, $F1), ($14, $8E, $59, $F8), ($37, $BF, $73, $C7), ($3A, $B4, $7D, $CE), ($2D, $A9, $6F, $D5), ($20, $A2, $61, $DC), ($6D, $F6, $AD, $76), ($60, $FD, $A3, $7F), ($77, $E0, $B1, $64), ($7A, $EB, $BF, $6D), ($59, $DA, $95, $52), ($54, $D1, $9B, $5B), ($43, $CC, $89, $40), ($4E, $C7, $87, $49), ($05, $AE, $DD, $3E), ($08, $A5, $D3, $37), ($1F, $B8, $C1, $2C), ($12, $B3, $CF, $25), ($31, $82, $E5, $1A), ($3C, $89, $EB, $13), ($2B, $94, $F9, $08), ($26, $9F, $F7, $01), ($BD, $46, $4D, $E6), ($B0, $4D, $43, $EF), ($A7, $50, $51, $F4), ($AA, $5B, $5F, $FD), ($89, $6A, $75, $C2), ($84, $61, $7B, $CB), ($93, $7C, $69, $D0), ($9E, $77, $67, $D9), ($D5, $1E, $3D, $AE), ($D8, $15, $33, $A7), ($CF, $08, $21, $BC), ($C2, $03, $2F, $B5), ($E1, $32, $05, $8A), ($EC, $39, $0B, $83), ($FB, $24, $19, $98), ($F6, $2F, $17, $91), ($D6, $8D, $76, $4D), ($DB, $86, $78, $44), ($CC, $9B, $6A, $5F), ($C1, $90, $64, $56), ($E2, $A1, $4E, $69), ($EF, $AA, $40, $60), ($F8, $B7, $52, $7B), ($F5, $BC, $5C, $72), ($BE, $D5, $06, $05), ($B3, $DE, $08, $0C), ($A4, $C3, $1A, $17), ($A9, $C8, $14, $1E), ($8A, $F9, $3E, $21), ($87, $F2, $30, $28), ($90, $EF, $22, $33), ($9D, $E4, $2C, $3A), ($06, $3D, $96, $DD), ($0B, $36, $98, $D4), ($1C, $2B, $8A, $CF), ($11, $20, $84, $C6), ($32, $11, $AE, $F9), ($3F, $1A, $A0, $F0), ($28, $07, $B2, $EB), ($25, $0C, $BC, $E2), ($6E, $65, $E6, $95), ($63, $6E, $E8, $9C), ($74, $73, $FA, $87), ($79, $78, $F4, $8E), ($5A, $49, $DE, $B1), ($57, $42, $D0, $B8), ($40, $5F, $C2, $A3), ($4D, $54, $CC, $AA), ($DA, $F7, $41, $EC), ($D7, $FC, $4F, $E5), ($C0, $E1, $5D, $FE), ($CD, $EA, $53, $F7), ($EE, $DB, $79, $C8), ($E3, $D0, $77, $C1), ($F4, $CD, $65, $DA), ($F9, $C6, $6B, $D3), ($B2, $AF, $31, $A4), ($BF, $A4, $3F, $AD), ($A8, $B9, $2D, $B6), ($A5, $B2, $23, $BF), ($86, $83, $09, $80), ($8B, $88, $07, $89), ($9C, $95, $15, $92), ($91, $9E, $1B, $9B), ($0A, $47, $A1, $7C), ($07, $4C, $AF, $75), ($10, $51, $BD, $6E), ($1D, $5A, $B3, $67), ($3E, $6B, $99, $58), ($33, $60, $97, $51), ($24, $7D, $85, $4A), ($29, $76, $8B, $43), ($62, $1F, $D1, $34), ($6F, $14, $DF, $3D), ($78, $09, $CD, $26), ($75, $02, $C3, $2F), ($56, $33, $E9, $10), ($5B, $38, $E7, $19), ($4C, $25, $F5, $02), ($41, $2E, $FB, $0B), ($61, $8C, $9A, $D7), ($6C, $87, $94, $DE), ($7B, $9A, $86, $C5), ($76, $91, $88, $CC), ($55, $A0, $A2, $F3), ($58, $AB, $AC, $FA), ($4F, $B6, $BE, $E1), ($42, $BD, $B0, $E8), ($09, $D4, $EA, $9F), ($04, $DF, $E4, $96), ($13, $C2, $F6, $8D), ($1E, $C9, $F8, $84), ($3D, $F8, $D2, $BB), ($30, $F3, $DC, $B2), ($27, $EE, $CE, $A9), ($2A, $E5, $C0, $A0), ($B1, $3C, $7A, $47), ($BC, $37, $74, $4E), ($AB, $2A, $66, $55), ($A6, $21, $68, $5C), ($85, $10, $42, $63), ($88, $1B, $4C, $6A), ($9F, $06, $5E, $71), ($92, $0D, $50, $78), ($D9, $64, $0A, $0F), ($D4, $6F, $04, $06), ($C3, $72, $16, $1D), ($CE, $79, $18, $14), ($ED, $48, $32, $2B), ($E0, $43, $3C, $22), ($F7, $5E, $2E, $39), ($FA, $55, $20, $30), ($B7, $01, $EC, $9A), ($BA, $0A, $E2, $93), ($AD, $17, $F0, $88), ($A0, $1C, $FE, $81), ($83, $2D, $D4, $BE), ($8E, $26, $DA, $B7), ($99, $3B, $C8, $AC), ($94, $30, $C6, $A5), ($DF, $59, $9C, $D2), ($D2, $52, $92, $DB), ($C5, $4F, $80, $C0), ($C8, $44, $8E, $C9), ($EB, $75, $A4, $F6), ($E6, $7E, $AA, $FF), ($F1, $63, $B8, $E4), ($FC, $68, $B6, $ED), ($67, $B1, $0C, $0A), ($6A, $BA, $02, $03), ($7D, $A7, $10, $18), ($70, $AC, $1E, $11), ($53, $9D, $34, $2E), ($5E, $96, $3A, $27), ($49, $8B, $28, $3C), ($44, $80, $26, $35), ($0F, $E9, $7C, $42), ($02, $E2, $72, $4B), ($15, $FF, $60, $50), ($18, $F4, $6E, $59), ($3B, $C5, $44, $66), ($36, $CE, $4A, $6F), ($21, $D3, $58, $74), ($2C, $D8, $56, $7D), ($0C, $7A, $37, $A1), ($01, $71, $39, $A8), ($16, $6C, $2B, $B3), ($1B, $67, $25, $BA), ($38, $56, $0F, $85), ($35, $5D, $01, $8C), ($22, $40, $13, $97), ($2F, $4B, $1D, $9E), ($64, $22, $47, $E9), ($69, $29, $49, $E0), ($7E, $34, $5B, $FB), ($73, $3F, $55, $F2), ($50, $0E, $7F, $CD), ($5D, $05, $71, $C4), ($4A, $18, $63, $DF), ($47, $13, $6D, $D6), ($DC, $CA, $D7, $31), ($D1, $C1, $D9, $38), ($C6, $DC, $CB, $23), ($CB, $D7, $C5, $2A), ($E8, $E6, $EF, $15), ($E5, $ED, $E1, $1C), ($F2, $F0, $F3, $07), ($FF, $FB, $FD, $0E), ($B4, $92, $A7, $79), ($B9, $99, $A9, $70), ($AE, $84, $BB, $6B), ($A3, $8F, $B5, $62), ($80, $BE, $9F, $5D), ($8D, $B5, $91, $54), ($9A, $A8, $83, $4F), ($97, $A3, $8D, $46)); U4: array [0 .. 255, 0 .. 3] of Byte = ( ($00, $00, $00, $00), ($09, $0D, $0B, $0E), ($12, $1A, $16, $1C), ($1B, $17, $1D, $12), ($24, $34, $2C, $38), ($2D, $39, $27, $36), ($36, $2E, $3A, $24), ($3F, $23, $31, $2A), ($48, $68, $58, $70), ($41, $65, $53, $7E), ($5A, $72, $4E, $6C), ($53, $7F, $45, $62), ($6C, $5C, $74, $48), ($65, $51, $7F, $46), ($7E, $46, $62, $54), ($77, $4B, $69, $5A), ($90, $D0, $B0, $E0), ($99, $DD, $BB, $EE), ($82, $CA, $A6, $FC), ($8B, $C7, $AD, $F2), ($B4, $E4, $9C, $D8), ($BD, $E9, $97, $D6), ($A6, $FE, $8A, $C4), ($AF, $F3, $81, $CA), ($D8, $B8, $E8, $90), ($D1, $B5, $E3, $9E), ($CA, $A2, $FE, $8C), ($C3, $AF, $F5, $82), ($FC, $8C, $C4, $A8), ($F5, $81, $CF, $A6), ($EE, $96, $D2, $B4), ($E7, $9B, $D9, $BA), ($3B, $BB, $7B, $DB), ($32, $B6, $70, $D5), ($29, $A1, $6D, $C7), ($20, $AC, $66, $C9), ($1F, $8F, $57, $E3), ($16, $82, $5C, $ED), ($0D, $95, $41, $FF), ($04, $98, $4A, $F1), ($73, $D3, $23, $AB), ($7A, $DE, $28, $A5), ($61, $C9, $35, $B7), ($68, $C4, $3E, $B9), ($57, $E7, $0F, $93), ($5E, $EA, $04, $9D), ($45, $FD, $19, $8F), ($4C, $F0, $12, $81), ($AB, $6B, $CB, $3B), ($A2, $66, $C0, $35), ($B9, $71, $DD, $27), ($B0, $7C, $D6, $29), ($8F, $5F, $E7, $03), ($86, $52, $EC, $0D), ($9D, $45, $F1, $1F), ($94, $48, $FA, $11), ($E3, $03, $93, $4B), ($EA, $0E, $98, $45), ($F1, $19, $85, $57), ($F8, $14, $8E, $59), ($C7, $37, $BF, $73), ($CE, $3A, $B4, $7D), ($D5, $2D, $A9, $6F), ($DC, $20, $A2, $61), ($76, $6D, $F6, $AD), ($7F, $60, $FD, $A3), ($64, $77, $E0, $B1), ($6D, $7A, $EB, $BF), ($52, $59, $DA, $95), ($5B, $54, $D1, $9B), ($40, $43, $CC, $89), ($49, $4E, $C7, $87), ($3E, $05, $AE, $DD), ($37, $08, $A5, $D3), ($2C, $1F, $B8, $C1), ($25, $12, $B3, $CF), ($1A, $31, $82, $E5), ($13, $3C, $89, $EB), ($08, $2B, $94, $F9), ($01, $26, $9F, $F7), ($E6, $BD, $46, $4D), ($EF, $B0, $4D, $43), ($F4, $A7, $50, $51), ($FD, $AA, $5B, $5F), ($C2, $89, $6A, $75), ($CB, $84, $61, $7B), ($D0, $93, $7C, $69), ($D9, $9E, $77, $67), ($AE, $D5, $1E, $3D), ($A7, $D8, $15, $33), ($BC, $CF, $08, $21), ($B5, $C2, $03, $2F), ($8A, $E1, $32, $05), ($83, $EC, $39, $0B), ($98, $FB, $24, $19), ($91, $F6, $2F, $17), ($4D, $D6, $8D, $76), ($44, $DB, $86, $78), ($5F, $CC, $9B, $6A), ($56, $C1, $90, $64), ($69, $E2, $A1, $4E), ($60, $EF, $AA, $40), ($7B, $F8, $B7, $52), ($72, $F5, $BC, $5C), ($05, $BE, $D5, $06), ($0C, $B3, $DE, $08), ($17, $A4, $C3, $1A), ($1E, $A9, $C8, $14), ($21, $8A, $F9, $3E), ($28, $87, $F2, $30), ($33, $90, $EF, $22), ($3A, $9D, $E4, $2C), ($DD, $06, $3D, $96), ($D4, $0B, $36, $98), ($CF, $1C, $2B, $8A), ($C6, $11, $20, $84), ($F9, $32, $11, $AE), ($F0, $3F, $1A, $A0), ($EB, $28, $07, $B2), ($E2, $25, $0C, $BC), ($95, $6E, $65, $E6), ($9C, $63, $6E, $E8), ($87, $74, $73, $FA), ($8E, $79, $78, $F4), ($B1, $5A, $49, $DE), ($B8, $57, $42, $D0), ($A3, $40, $5F, $C2), ($AA, $4D, $54, $CC), ($EC, $DA, $F7, $41), ($E5, $D7, $FC, $4F), ($FE, $C0, $E1, $5D), ($F7, $CD, $EA, $53), ($C8, $EE, $DB, $79), ($C1, $E3, $D0, $77), ($DA, $F4, $CD, $65), ($D3, $F9, $C6, $6B), ($A4, $B2, $AF, $31), ($AD, $BF, $A4, $3F), ($B6, $A8, $B9, $2D), ($BF, $A5, $B2, $23), ($80, $86, $83, $09), ($89, $8B, $88, $07), ($92, $9C, $95, $15), ($9B, $91, $9E, $1B), ($7C, $0A, $47, $A1), ($75, $07, $4C, $AF), ($6E, $10, $51, $BD), ($67, $1D, $5A, $B3), ($58, $3E, $6B, $99), ($51, $33, $60, $97), ($4A, $24, $7D, $85), ($43, $29, $76, $8B), ($34, $62, $1F, $D1), ($3D, $6F, $14, $DF), ($26, $78, $09, $CD), ($2F, $75, $02, $C3), ($10, $56, $33, $E9), ($19, $5B, $38, $E7), ($02, $4C, $25, $F5), ($0B, $41, $2E, $FB), ($D7, $61, $8C, $9A), ($DE, $6C, $87, $94), ($C5, $7B, $9A, $86), ($CC, $76, $91, $88), ($F3, $55, $A0, $A2), ($FA, $58, $AB, $AC), ($E1, $4F, $B6, $BE), ($E8, $42, $BD, $B0), ($9F, $09, $D4, $EA), ($96, $04, $DF, $E4), ($8D, $13, $C2, $F6), ($84, $1E, $C9, $F8), ($BB, $3D, $F8, $D2), ($B2, $30, $F3, $DC), ($A9, $27, $EE, $CE), ($A0, $2A, $E5, $C0), ($47, $B1, $3C, $7A), ($4E, $BC, $37, $74), ($55, $AB, $2A, $66), ($5C, $A6, $21, $68), ($63, $85, $10, $42), ($6A, $88, $1B, $4C), ($71, $9F, $06, $5E), ($78, $92, $0D, $50), ($0F, $D9, $64, $0A), ($06, $D4, $6F, $04), ($1D, $C3, $72, $16), ($14, $CE, $79, $18), ($2B, $ED, $48, $32), ($22, $E0, $43, $3C), ($39, $F7, $5E, $2E), ($30, $FA, $55, $20), ($9A, $B7, $01, $EC), ($93, $BA, $0A, $E2), ($88, $AD, $17, $F0), ($81, $A0, $1C, $FE), ($BE, $83, $2D, $D4), ($B7, $8E, $26, $DA), ($AC, $99, $3B, $C8), ($A5, $94, $30, $C6), ($D2, $DF, $59, $9C), ($DB, $D2, $52, $92), ($C0, $C5, $4F, $80), ($C9, $C8, $44, $8E), ($F6, $EB, $75, $A4), ($FF, $E6, $7E, $AA), ($E4, $F1, $63, $B8), ($ED, $FC, $68, $B6), ($0A, $67, $B1, $0C), ($03, $6A, $BA, $02), ($18, $7D, $A7, $10), ($11, $70, $AC, $1E), ($2E, $53, $9D, $34), ($27, $5E, $96, $3A), ($3C, $49, $8B, $28), ($35, $44, $80, $26), ($42, $0F, $E9, $7C), ($4B, $02, $E2, $72), ($50, $15, $FF, $60), ($59, $18, $F4, $6E), ($66, $3B, $C5, $44), ($6F, $36, $CE, $4A), ($74, $21, $D3, $58), ($7D, $2C, $D8, $56), ($A1, $0C, $7A, $37), ($A8, $01, $71, $39), ($B3, $16, $6C, $2B), ($BA, $1B, $67, $25), ($85, $38, $56, $0F), ($8C, $35, $5D, $01), ($97, $22, $40, $13), ($9E, $2F, $4B, $1D), ($E9, $64, $22, $47), ($E0, $69, $29, $49), ($FB, $7E, $34, $5B), ($F2, $73, $3F, $55), ($CD, $50, $0E, $7F), ($C4, $5D, $05, $71), ($DF, $4A, $18, $63), ($D6, $47, $13, $6D), ($31, $DC, $CA, $D7), ($38, $D1, $C1, $D9), ($23, $C6, $DC, $CB), ($2A, $CB, $D7, $C5), ($15, $E8, $E6, $EF), ($1C, $E5, $ED, $E1), ($07, $F2, $F0, $F3), ($0E, $FF, $FB, $FD), ($79, $B4, $92, $A7), ($70, $B9, $99, $A9), ($6B, $AE, $84, $BB), ($62, $A3, $8F, $B5), ($5D, $80, $BE, $9F), ($54, $8D, $B5, $91), ($4F, $9A, $A8, $83), ($46, $97, $A3, $8D)); rcon: array [0 .. 29] of Cardinal = ( $01, $02, $04, $08, $10, $20, $40, $80, $1B, $36, $6C, $D8, $AB, $4D, $9A, $2F, $5E, $BC, $63, $C6, $97, $35, $6A, $D4, $B3, $7D, $FA, $EF, $C5, $91); {$ENDREGION 'RijndaelDefine'} class procedure InvMixColumn(const a: PByteArray; const BC: Byte); public class procedure InitKey(buff: Pointer; Size: Integer; var KeyContext: TRijndaelkey); class procedure Encrypt(var KeyContext: TRijndaelkey; var Data: TRijndaelBlock); overload; class procedure Encrypt(var KeyContext: TRijndaelkey; var B1, B2, B3, B4: DWORD); overload; class procedure Decrypt(var KeyContext: TRijndaelkey; var Data: TRijndaelBlock); overload; class procedure Decrypt(var KeyContext: TRijndaelkey; var B1, B2, B3, B4: DWORD); overload; end; type { twofish } PTwofishKey = ^TTwofishKey; TTwofishKey = record ExpandedKey: array [0 .. 39] of DWORD; SBoxKey: array [0 .. 3] of DWORD; SBox0: array [0 .. 255] of Byte; SBox1: array [0 .. 255] of Byte; SBox2: array [0 .. 255] of Byte; SBox3: array [0 .. 255] of Byte; KeyLen: Integer; end; PTwofishBlock = ^TTwofishBlock; TTwofishBlock = array [0 .. 15] of Byte; TTwofish = class(TCoreClassObject) private const {$REGION 'TwofishDefine'} P8x8: array [0 .. 1, 0 .. 255] of Byte = (($A9, $67, $B3, $E8, $04, $FD, $A3, $76, $9A, $92, $80, $78, $E4, $DD, $D1, $38, $0D, $C6, $35, $98, $18, $F7, $EC, $6C, $43, $75, $37, $26, $FA, $13, $94, $48, $F2, $D0, $8B, $30, $84, $54, $DF, $23, $19, $5B, $3D, $59, $F3, $AE, $A2, $82, $63, $01, $83, $2E, $D9, $51, $9B, $7C, $A6, $EB, $A5, $BE, $16, $0C, $E3, $61, $C0, $8C, $3A, $F5, $73, $2C, $25, $0B, $BB, $4E, $89, $6B, $53, $6A, $B4, $F1, $E1, $E6, $BD, $45, $E2, $F4, $B6, $66, $CC, $95, $03, $56, $D4, $1C, $1E, $D7, $FB, $C3, $8E, $B5, $E9, $CF, $BF, $BA, $EA, $77, $39, $AF, $33, $C9, $62, $71, $81, $79, $09, $AD, $24, $CD, $F9, $D8, $E5, $C5, $B9, $4D, $44, $08, $86, $E7, $A1, $1D, $AA, $ED, $06, $70, $B2, $D2, $41, $7B, $A0, $11, $31, $C2, $27, $90, $20, $F6, $60, $FF, $96, $5C, $B1, $AB, $9E, $9C, $52, $1B, $5F, $93, $0A, $EF, $91, $85, $49, $EE, $2D, $4F, $8F, $3B, $47, $87, $6D, $46, $D6, $3E, $69, $64, $2A, $CE, $CB, $2F, $FC, $97, $05, $7A, $AC, $7F, $D5, $1A, $4B, $0E, $A7, $5A, $28, $14, $3F, $29, $88, $3C, $4C, $02, $B8, $DA, $B0, $17, $55, $1F, $8A, $7D, $57, $C7, $8D, $74, $B7, $C4, $9F, $72, $7E, $15, $22, $12, $58, $07, $99, $34, $6E, $50, $DE, $68, $65, $BC, $DB, $F8, $C8, $A8, $2B, $40, $DC, $FE, $32, $A4, $CA, $10, $21, $F0, $D3, $5D, $0F, $00, $6F, $9D, $36, $42, $4A, $5E, $C1, $E0), ($75, $F3, $C6, $F4, $DB, $7B, $FB, $C8, $4A, $D3, $E6, $6B, $45, $7D, $E8, $4B, $D6, $32, $D8, $FD, $37, $71, $F1, $E1, $30, $0F, $F8, $1B, $87, $FA, $06, $3F, $5E, $BA, $AE, $5B, $8A, $00, $BC, $9D, $6D, $C1, $B1, $0E, $80, $5D, $D2, $D5, $A0, $84, $07, $14, $B5, $90, $2C, $A3, $B2, $73, $4C, $54, $92, $74, $36, $51, $38, $B0, $BD, $5A, $FC, $60, $62, $96, $6C, $42, $F7, $10, $7C, $28, $27, $8C, $13, $95, $9C, $C7, $24, $46, $3B, $70, $CA, $E3, $85, $CB, $11, $D0, $93, $B8, $A6, $83, $20, $FF, $9F, $77, $C3, $CC, $03, $6F, $08, $BF, $40, $E7, $2B, $E2, $79, $0C, $AA, $82, $41, $3A, $EA, $B9, $E4, $9A, $A4, $97, $7E, $DA, $7A, $17, $66, $94, $A1, $1D, $3D, $F0, $DE, $B3, $0B, $72, $A7, $1C, $EF, $D1, $53, $3E, $8F, $33, $26, $5F, $EC, $76, $2A, $49, $81, $88, $EE, $21, $C4, $1A, $EB, $D9, $C5, $39, $99, $CD, $AD, $31, $8B, $01, $18, $23, $DD, $1F, $4E, $2D, $F9, $48, $4F, $F2, $65, $8E, $78, $5C, $58, $19, $8D, $E5, $98, $57, $67, $7F, $05, $64, $AF, $63, $B6, $FE, $F5, $B7, $3C, $A5, $CE, $E9, $68, $44, $E0, $4D, $43, $69, $29, $2E, $AC, $15, $59, $A8, $0A, $9E, $6E, $47, $DF, $34, $35, $6A, $CF, $DC, $22, $C9, $C0, $9B, $89, $D4, $ED, $AB, $12, $A2, $0D, $52, $BB, $02, $2F, $A9, $D7, $61, $1E, $B4, $50, $04, $F6, $C2, $16, $25, $86, $56, $55, $09, $BE, $91)); MDS: array [0 .. 3, 0 .. 7] of Byte = (($01, $A4, $55, $87, $5A, $58, $DB, $9E), ($A4, $56, $82, $F3, $1E, $C6, $68, $E5), ($02, $A1, $FC, $C1, $47, $AE, $3D, $19), ($A4, $55, $87, $5A, $58, $DB, $9E, $03)); Arr5B: array [0 .. 255] of DWORD = ( $00, $5B, $B6, $ED, $05, $5E, $B3, $E8, $0A, $51, $BC, $E7, $0F, $54, $B9, $E2, $14, $4F, $A2, $F9, $11, $4A, $A7, $FC, $1E, $45, $A8, $F3, $1B, $40, $AD, $F6, $28, $73, $9E, $C5, $2D, $76, $9B, $C0, $22, $79, $94, $CF, $27, $7C, $91, $CA, $3C, $67, $8A, $D1, $39, $62, $8F, $D4, $36, $6D, $80, $DB, $33, $68, $85, $DE, $50, $0B, $E6, $BD, $55, $0E, $E3, $B8, $5A, $01, $EC, $B7, $5F, $04, $E9, $B2, $44, $1F, $F2, $A9, $41, $1A, $F7, $AC, $4E, $15, $F8, $A3, $4B, $10, $FD, $A6, $78, $23, $CE, $95, $7D, $26, $CB, $90, $72, $29, $C4, $9F, $77, $2C, $C1, $9A, $6C, $37, $DA, $81, $69, $32, $DF, $84, $66, $3D, $D0, $8B, $63, $38, $D5, $8E, $A0, $FB, $16, $4D, $A5, $FE, $13, $48, $AA, $F1, $1C, $47, $AF, $F4, $19, $42, $B4, $EF, $02, $59, $B1, $EA, $07, $5C, $BE, $E5, $08, $53, $BB, $E0, $0D, $56, $88, $D3, $3E, $65, $8D, $D6, $3B, $60, $82, $D9, $34, $6F, $87, $DC, $31, $6A, $9C, $C7, $2A, $71, $99, $C2, $2F, $74, $96, $CD, $20, $7B, $93, $C8, $25, $7E, $F0, $AB, $46, $1D, $F5, $AE, $43, $18, $FA, $A1, $4C, $17, $FF, $A4, $49, $12, $E4, $BF, $52, $09, $E1, $BA, $57, $0C, $EE, $B5, $58, $03, $EB, $B0, $5D, $06, $D8, $83, $6E, $35, $DD, $86, $6B, $30, $D2, $89, $64, $3F, $D7, $8C, $61, $3A, $CC, $97, $7A, $21, $C9, $92, $7F, $24, $C6, $9D, $70, $2B, $C3, $98, $75, $2E); ArrEF: array [0 .. 255] of Byte = ( $00, $EF, $B7, $58, $07, $E8, $B0, $5F, $0E, $E1, $B9, $56, $09, $E6, $BE, $51, $1C, $F3, $AB, $44, $1B, $F4, $AC, $43, $12, $FD, $A5, $4A, $15, $FA, $A2, $4D, $38, $D7, $8F, $60, $3F, $D0, $88, $67, $36, $D9, $81, $6E, $31, $DE, $86, $69, $24, $CB, $93, $7C, $23, $CC, $94, $7B, $2A, $C5, $9D, $72, $2D, $C2, $9A, $75, $70, $9F, $C7, $28, $77, $98, $C0, $2F, $7E, $91, $C9, $26, $79, $96, $CE, $21, $6C, $83, $DB, $34, $6B, $84, $DC, $33, $62, $8D, $D5, $3A, $65, $8A, $D2, $3D, $48, $A7, $FF, $10, $4F, $A0, $F8, $17, $46, $A9, $F1, $1E, $41, $AE, $F6, $19, $54, $BB, $E3, $0C, $53, $BC, $E4, $0B, $5A, $B5, $ED, $02, $5D, $B2, $EA, $05, $E0, $0F, $57, $B8, $E7, $08, $50, $BF, $EE, $01, $59, $B6, $E9, $06, $5E, $B1, $FC, $13, $4B, $A4, $FB, $14, $4C, $A3, $F2, $1D, $45, $AA, $F5, $1A, $42, $AD, $D8, $37, $6F, $80, $DF, $30, $68, $87, $D6, $39, $61, $8E, $D1, $3E, $66, $89, $C4, $2B, $73, $9C, $C3, $2C, $74, $9B, $CA, $25, $7D, $92, $CD, $22, $7A, $95, $90, $7F, $27, $C8, $97, $78, $20, $CF, $9E, $71, $29, $C6, $99, $76, $2E, $C1, $8C, $63, $3B, $D4, $8B, $64, $3C, $D3, $82, $6D, $35, $DA, $85, $6A, $32, $DD, $A8, $47, $1F, $F0, $AF, $40, $18, $F7, $A6, $49, $11, $FE, $A1, $4E, $16, $F9, $B4, $5B, $03, $EC, $B3, $5C, $04, $EB, $BA, $55, $0D, $E2, $BD, $52, $0A, $E5); {$ENDREGION 'TwofishDefine'} class function TwofishCalculateSBoxes(x: DWORD; l: Pointer; KeySize: DWORD): DWORD; class function TwofishH(x: DWORD; l: Pointer; KeySize: DWORD): DWORD; overload; class function TwofishH(const x: DWORD; const key: TTwofishKey): DWORD; overload; class function RSMDSMul(const x, y: Byte): Byte; class function MultiplyMDS(const E, O: DWORD): DWORD; public class procedure InitKey(buff: PCCByteArray; Size: Integer; var KeyContext: TTwofishKey); class procedure Encrypt(var KeyContext: TTwofishKey; var Data: TTwofishBlock); class procedure Decrypt(var KeyContext: TTwofishKey; var Data: TTwofishBlock); end; {$ENDREGION 'cryptAndHash'} type TCipher_Base = class(TCoreClassObject) protected FCipherSecurity: TCipherSecurity; FLastGenerateKey: TCipherKeyBuffer; FLevel: Integer; FProcessTail: Boolean; FCBC: Boolean; public property CipherSecurity: TCipherSecurity read FCipherSecurity; property LastGenerateKey: TCipherKeyBuffer read FLastGenerateKey; property Level: Integer read FLevel write FLevel; property ProcessTail: Boolean read FProcessTail write FProcessTail; property CBC: Boolean read FCBC write FCBC; constructor Create(KeyBuffer_: TCipherKeyBuffer); virtual; destructor Destroy; override; procedure Encrypt(sour: Pointer; Size: NativeInt); virtual; procedure Decrypt(sour: Pointer; Size: NativeInt); virtual; procedure Process(sour: Pointer; Size: NativeInt; Level_: Integer; Encrypt_, ProcessTail_, CBC_: Boolean); procedure Test; virtual; end; TCipher_DES64 = class(TCipher_Base) private FDKey, FEkey: TDESContext; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; TCipher_DES128 = class(TCipher_Base) private FDKey, FEkey: TTripleDESContext; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; TCipher_DES192 = class(TCipher_Base) private FDKey, FEkey: TTripleDESContext3Key; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; TCipher_BlowFish = class(TCipher_Base) private Fkey: TBFContext; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; TCipher_LBC = class(TCipher_Base) private FDKey, FEkey: TLBCContext; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; TCipher_LQC = class(TCipher_Base) private Fkey: TKey128; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; TCipher_RNG32 = class(TCipher_Base) private Fkey: TRNG32Context; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; TCipher_RNG64 = class(TCipher_Base) private Fkey: TRNG64Context; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; TCipher_LSC = class(TCipher_Base) private Fkey: TLSCContext; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; TCipher_XXTea512 = class(TCipher_Base) private Fkey: TKey128; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; TCipher_RC6 = class(TCipher_Base) private Fkey: TRC6Key; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; TCipher_Serpent = class(TCipher_Base) private Fkey: TSerpentkey; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; TCipher_Mars = class(TCipher_Base) private Fkey: TMarskey; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; TCipher_Rijndael = class(TCipher_Base) private Fkey: TRijndaelkey; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; TCipher_TwoFish = class(TCipher_Base) private Fkey: TTwofishKey; public constructor Create(KeyBuffer_: TCipherKeyBuffer); override; procedure Encrypt(sour: Pointer; Size: NativeInt); override; procedure Decrypt(sour: Pointer; Size: NativeInt); override; end; function CreateCipherClass(cs: TCipherSecurity; KeyBuffer_: TCipherKeyBuffer): TCipher_Base; function CreateCipherClassFromPassword(cs: TCipherSecurity; password_: TPascalString): TCipher_Base; // compatible SequEncryptCBC function CreateCipherClassFromBuffer(cs: TCipherSecurity; key: TCipherKeyBuffer): TCipher_Base; overload; function CreateCipherClassFromBuffer(cs: TCipherSecurity; buffPtr: Pointer; Size: NativeInt): TCipher_Base; overload; procedure TestCoreCipher; implementation uses DoStatusIO; const { Blowfish lookup tables } bf_P: array [0 .. (BFRounds + 1)] of DWORD = ( $243F6A88, $85A308D3, $13198A2E, $03707344, $A4093822, $299F31D0, $082EFA98, $EC4E6C89, $452821E6, $38D01377, $BE5466CF, $34E90C6C, $C0AC29B7, $C97C50DD, $3F84D5B5, $B5470917, $9216D5D9, $8979FB1B); bf_S: array [0 .. 3, 0 .. 255] of DWORD = ( ($D1310BA6, $98DFB5AC, $2FFD72DB, $D01ADFB7, $B8E1AFED, $6A267E96, $BA7C9045, $F12C7F99, $24A19947, $B3916CF7, $0801F2E2, $858EFC16, $636920D8, $71574E69, $A458FEA3, $F4933D7E, $0D95748F, $728EB658, $718BCD58, $82154AEE, $7B54A41D, $C25A59B5, $9C30D539, $2AF26013, $C5D1B023, $286085F0, $CA417918, $B8DB38EF, $8E79DCB0, $603A180E, $6C9E0E8B, $B01E8A3E, $D71577C1, $BD314B27, $78AF2FDA, $55605C60, $E65525F3, $AA55AB94, $57489862, $63E81440, $55CA396A, $2AAB10B6, $B4CC5C34, $1141E8CE, $A15486AF, $7C72E993, $B3EE1411, $636FBC2A, $2BA9C55D, $741831F6, $CE5C3E16, $9B87931E, $AFD6BA33, $6C24CF5C, $7A325381, $28958677, $3B8F4898, $6B4BB9AF, $C4BFE81B, $66282193, $61D809CC, $FB21A991, $487CAC60, $5DEC8032, $EF845D5D, $E98575B1, $DC262302, $EB651B88, $23893E81, $D396ACC5, $0F6D6FF3, $83F44239, $2E0B4482, $A4842004, $69C8F04A, $9E1F9B5E, $21C66842, $F6E96C9A, $670C9C61, $ABD388F0, $6A51A0D2, $D8542F68, $960FA728, $AB5133A3, $6EEF0B6C, $137A3BE4, $BA3BF050, $7EFB2A98, $A1F1651D, $39AF0176, $66CA593E, $82430E88, $8CEE8619, $456F9FB4, $7D84A5C3, $3B8B5EBE, $E06F75D8, $85C12073, $401A449F, $56C16AA6, $4ED3AA62, $363F7706, $1BFEDF72, $429B023D, $37D0D724, $D00A1248, $DB0FEAD3, $49F1C09B, $075372C9, $80991B7B, $25D479D8, $F6E8DEF7, $E3FE501A, $B6794C3B, $976CE0BD, $04C006BA, $C1A94FB6, $409F60C4, $5E5C9EC2, $196A2463, $68FB6FAF, $3E6C53B5, $1339B2EB, $3B52EC6F, $6DFC511F, $9B30952C, $CC814544, $AF5EBD09, $BEE3D004, $DE334AFD, $660F2807, $192E4BB3, $C0CBA857, $45C8740F, $D20B5F39, $B9D3FBDB, $5579C0BD, $1A60320A, $D6A100C6, $402C7279, $679F25FE, $FB1FA3CC, $8EA5E9F8, $DB3222F8, $3C7516DF, $FD616B15, $2F501EC8, $AD0552AB, $323DB5FA, $FD238760, $53317B48, $3E00DF82, $9E5C57BB, $CA6F8CA0, $1A87562E, $DF1769DB, $D542A8F6, $287EFFC3, $AC6732C6, $8C4F5573, $695B27B0, $BBCA58C8, $E1FFA35D, $B8F011A0, $10FA3D98, $FD2183B8, $4AFCB56C, $2DD1D35B, $9A53E479, $B6F84565, $D28E49BC, $4BFB9790, $E1DDF2DA, $A4CB7E33, $62FB1341, $CEE4C6E8, $EF20CADA, $36774C01, $D07E9EFE, $2BF11FB4, $95DBDA4D, $AE909198, $EAAD8E71, $6B93D5A0, $D08ED1D0, $AFC725E0, $8E3C5B2F, $8E7594B7, $8FF6E2FB, $F2122B64, $8888B812, $900DF01C, $4FAD5EA0, $688FC31C, $D1CFF191, $B3A8C1AD, $2F2F2218, $BE0E1777, $EA752DFE, $8B021FA1, $E5A0CC0F, $B56F74E8, $18ACF3D6, $CE89E299, $B4A84FE0, $FD13E0B7, $7CC43B81, $D2ADA8D9, $165FA266, $80957705, $93CC7314, $211A1477, $E6AD2065, $77B5FA86, $C75442F5, $FB9D35CF, $EBCDAF0C, $7B3E89A0, $D6411BD3, $AE1E7E49, $00250E2D, $2071B35E, $226800BB, $57B8E0AF, $2464369B, $F009B91E, $5563911D, $59DFA6AA, $78C14389, $D95A537F, $207D5BA2, $02E5B9C5, $83260376, $6295CFA9, $11C81968, $4E734A41, $B3472DCA, $7B14A94A, $1B510052, $9A532915, $D60F573F, $BC9BC6E4, $2B60A476, $81E67400, $08BA6FB5, $571BE91F, $F296EC6B, $2A0DD915, $B6636521, $E7B9F9B6, $FF34052E, $C5855664, $53B02D5D, $A99F8FA1, $08BA4799, $6E85076A), { SECOND 256 } ($4B7A70E9, $B5B32944, $DB75092E, $C4192623, $AD6EA6B0, $49A7DF7D, $9CEE60B8, $8FEDB266, $ECAA8C71, $699A17FF, $5664526C, $C2B19EE1, $193602A5, $75094C29, $A0591340, $E4183A3E, $3F54989A, $5B429D65, $6B8FE4D6, $99F73FD6, $A1D29C07, $EFE830F5, $4D2D38E6, $F0255DC1, $4CDD2086, $8470EB26, $6382E9C6, $021ECC5E, $09686B3F, $3EBAEFC9, $3C971814, $6B6A70A1, $687F3584, $52A0E286, $B79C5305, $AA500737, $3E07841C, $7FDEAE5C, $8E7D44EC, $5716F2B8, $B03ADA37, $F0500C0D, $F01C1F04, $0200B3FF, $AE0CF51A, $3CB574B2, $25837A58, $DC0921BD, $D19113F9, $7CA92FF6, $94324773, $22F54701, $3AE5E581, $37C2DADC, $C8B57634, $9AF3DDA7, $A9446146, $0FD0030E, $ECC8C73E, $A4751E41, $E238CD99, $3BEA0E2F, $3280BBA1, $183EB331, $4E548B38, $4F6DB908, $6F420D03, $F60A04BF, $2CB81290, $24977C79, $5679B072, $BCAF89AF, $DE9A771F, $D9930810, $B38BAE12, $DCCF3F2E, $5512721F, $2E6B7124, $501ADDE6, $9F84CD87, $7A584718, $7408DA17, $BC9F9ABC, $E94B7D8C, $EC7AEC3A, $DB851DFA, $63094366, $C464C3D2, $EF1C1847, $3215D908, $DD433B37, $24C2BA16, $12A14D43, $2A65C451, $50940002, $133AE4DD, $71DFF89E, $10314E55, $81AC77D6, $5F11199B, $043556F1, $D7A3C76B, $3C11183B, $5924A509, $F28FE6ED, $97F1FBFA, $9EBABF2C, $1E153C6E, $86E34570, $EAE96FB1, $860E5E0A, $5A3E2AB3, $771FE71C, $4E3D06FA, $2965DCB9, $99E71D0F, $803E89D6, $5266C825, $2E4CC978, $9C10B36A, $C6150EBA, $94E2EA78, $A5FC3C53, $1E0A2DF4, $F2F74EA7, $361D2B3D, $1939260F, $19C27960, $5223A708, $F71312B6, $EBADFE6E, $EAC31F66, $E3BC4595, $A67BC883, $B17F37D1, $018CFF28, $C332DDEF, $BE6C5AA5, $65582185, $68AB9802, $EECEA50F, $DB2F953B, $2AEF7DAD, $5B6E2F84, $1521B628, $29076170, $ECDD4775, $619F1510, $13CCA830, $EB61BD96, $0334FE1E, $AA0363CF, $B5735C90, $4C70A239, $D59E9E0B, $CBAADE14, $EECC86BC, $60622CA7, $9CAB5CAB, $B2F3846E, $648B1EAF, $19BDF0CA, $A02369B9, $655ABB50, $40685A32, $3C2AB4B3, $319EE9D5, $C021B8F7, $9B540B19, $875FA099, $95F7997E, $623D7DA8, $F837889A, $97E32D77, $11ED935F, $16681281, $0E358829, $C7E61FD6, $96DEDFA1, $7858BA99, $57F584A5, $1B227263, $9B83C3FF, $1AC24696, $CDB30AEB, $532E3054, $8FD948E4, $6DBC3128, $58EBF2EF, $34C6FFEA, $FE28ED61, $EE7C3C73, $5D4A14D9, $E864B7E3, $42105D14, $203E13E0, $45EEE2B6, $A3AAABEA, $DB6C4F15, $FACB4FD0, $C742F442, $EF6ABBB5, $654F3B1D, $41CD2105, $D81E799E, $86854DC7, $E44B476A, $3D816250, $CF62A1F2, $5B8D2646, $FC8883A0, $C1C7B6A3, $7F1524C3, $69CB7492, $47848A0B, $5692B285, $095BBF00, $AD19489D, $1462B174, $23820E00, $58428D2A, $0C55F5EA, $1DADF43E, $233F7061, $3372F092, $8D937E41, $D65FECF1, $6C223BDB, $7CDE3759, $CBEE7460, $4085F2A7, $CE77326E, $A6078084, $19F8509E, $E8EFD855, $61D99735, $A969A7AA, $C50C06C2, $5A04ABFC, $800BCADC, $9E447A2E, $C3453484, $FDD56705, $0E1E9EC9, $DB73DBD3, $105588CD, $675FDA79, $E3674340, $C5C43465, $713E38D8, $3D28F89E, $F16DFF20, $153E21E7, $8FB03D4A, $E6E39F2B, $DB83ADF7), { THIRD 256 } ($E93D5A68, $948140F7, $F64C261C, $94692934, $411520F7, $7602D4F7, $BCF46B2E, $D4A20068, $D4082471, $3320F46A, $43B7D4B7, $500061AF, $1E39F62E, $97244546, $14214F74, $BF8B8840, $4D95FC1D, $96B591AF, $70F4DDD3, $66A02F45, $BFBC09EC, $03BD9785, $7FAC6DD0, $31CB8504, $96EB27B3, $55FD3941, $DA2547E6, $ABCA0A9A, $28507825, $530429F4, $0A2C86DA, $E9B66DFB, $68DC1462, $D7486900, $680EC0A4, $27A18DEE, $4F3FFEA2, $E887AD8C, $B58CE006, $7AF4D6B6, $AACE1E7C, $D3375FEC, $CE78A399, $406B2A42, $20FE9E35, $D9F385B9, $EE39D7AB, $3B124E8B, $1DC9FAF7, $4B6D1856, $26A36631, $EAE397B2, $3A6EFA74, $DD5B4332, $6841E7F7, $CA7820FB, $FB0AF54E, $D8FEB397, $454056AC, $BA489527, $55533A3A, $20838D87, $FE6BA9B7, $D096954B, $55A867BC, $A1159A58, $CCA92963, $99E1DB33, $A62A4A56, $3F3125F9, $5EF47E1C, $9029317C, $FDF8E802, $04272F70, $80BB155C, $05282CE3, $95C11548, $E4C66D22, $48C1133F, $C70F86DC, $07F9C9EE, $41041F0F, $404779A4, $5D886E17, $325F51EB, $D59BC0D1, $F2BCC18F, $41113564, $257B7834, $602A9C60, $DFF8E8A3, $1F636C1B, $0E12B4C2, $02E1329E, $AF664FD1, $CAD18115, $6B2395E0, $333E92E1, $3B240B62, $EEBEB922, $85B2A20E, $E6BA0D99, $DE720C8C, $2DA2F728, $D0127845, $95B794FD, $647D0862, $E7CCF5F0, $5449A36F, $877D48FA, $C39DFD27, $F33E8D1E, $0A476341, $992EFF74, $3A6F6EAB, $F4F8FD37, $A812DC60, $A1EBDDF8, $991BE14C, $DB6E6B0D, $C67B5510, $6D672C37, $2765D43B, $DCD0E804, $F1290DC7, $CC00FFA3, $B5390F92, $690FED0B, $667B9FFB, $CEDB7D9C, $A091CF0B, $D9155EA3, $BB132F88, $515BAD24, $7B9479BF, $763BD6EB, $37392EB3, $CC115979, $8026E297, $F42E312D, $6842ADA7, $C66A2B3B, $12754CCC, $782EF11C, $6A124237, $B79251E7, $06A1BBE6, $4BFB6350, $1A6B1018, $11CAEDFA, $3D25BDD8, $E2E1C3C9, $44421659, $0A121386, $D90CEC6E, $D5ABEA2A, $64AF674E, $DA86A85F, $BEBFE988, $64E4C3FE, $9DBC8057, $F0F7C086, $60787BF8, $6003604D, $D1FD8346, $F6381FB0, $7745AE04, $D736FCCC, $83426B33, $F01EAB71, $B0804187, $3C005E5F, $77A057BE, $BDE8AE24, $55464299, $BF582E61, $4E58F48F, $F2DDFDA2, $F474EF38, $8789BDC2, $5366F9C3, $C8B38E74, $B475F255, $46FCD9B9, $7AEB2661, $8B1DDF84, $846A0E79, $915F95E2, $466E598E, $20B45770, $8CD55591, $C902DE4C, $B90BACE1, $BB8205D0, $11A86248, $7574A99E, $B77F19B6, $E0A9DC09, $662D09A1, $C4324633, $E85A1F02, $09F0BE8C, $4A99A025, $1D6EFE10, $1AB93D1D, $0BA5A4DF, $A186F20F, $2868F169, $DCB7DA83, $573906FE, $A1E2CE9B, $4FCD7F52, $50115E01, $A70683FA, $A002B5C4, $0DE6D027, $9AF88C27, $773F8641, $C3604C06, $61A806B5, $F0177A28, $C0F586E0, $006058AA, $30DC7D62, $11E69ED7, $2338EA63, $53C2DD94, $C2C21634, $BBCBEE56, $90BCB6DE, $EBFC7DA1, $CE591D76, $6F05E409, $4B7C0188, $39720A3D, $7C927C24, $86E3725F, $724D9DB9, $1AC15BB4, $D39EB8FC, $ED545578, $08FCA5B5, $D83D7CD3, $4DAD0FC4, $1E50EF5E, $B161E6F8, $A28514D9, $6C51133C, $6FD5C7E7, $56E14EC4, $362ABFCE, $DDC6C837, $D79A3234, $92638212, $670EFA8E, $406000E0), { FOURTH 256 } ($3A39CE37, $D3FAF5CF, $ABC27737, $5AC52D1B, $5CB0679E, $4FA33742, $D3822740, $99BC9BBE, $D5118E9D, $BF0F7315, $D62D1C7E, $C700C47B, $B78C1B6B, $21A19045, $B26EB1BE, $6A366EB4, $5748AB2F, $BC946E79, $C6A376D2, $6549C2C8, $530FF8EE, $468DDE7D, $D5730A1D, $4CD04DC6, $2939BBDB, $A9BA4650, $AC9526E8, $BE5EE304, $A1FAD5F0, $6A2D519A, $63EF8CE2, $9A86EE22, $C089C2B8, $43242EF6, $A51E03AA, $9CF2D0A4, $83C061BA, $9BE96A4D, $8FE51550, $BA645BD6, $2826A2F9, $A73A3AE1, $4BA99586, $EF5562E9, $C72FEFD3, $F752F7DA, $3F046F69, $77FA0A59, $80E4A915, $87B08601, $9B09E6AD, $3B3EE593, $E990FD5A, $9E34D797, $2CF0B7D9, $022B8B51, $96D5AC3A, $017DA67D, $D1CF3ED6, $7C7D2D28, $1F9F25CF, $ADF2B89B, $5AD6B472, $5A88F54C, $E029AC71, $E019A5E6, $47B0ACFD, $ED93FA9B, $E8D3C48D, $283B57CC, $F8D56629, $79132E28, $785F0191, $ED756055, $F7960E44, $E3D35E8C, $15056DD4, $88F46DBA, $03A16125, $0564F0BD, $C3EB9E15, $3C9057A2, $97271AEC, $A93A072A, $1B3F6D9B, $1E6321F5, $F59C66FB, $26DCF319, $7533D928, $B155FDF5, $03563482, $8ABA3CBB, $28517711, $C20AD9F8, $ABCC5167, $CCAD925F, $4DE81751, $3830DC8E, $379D5862, $9320F991, $EA7A90C2, $FB3E7BCE, $5121CE64, $774FBE32, $A8B6E37E, $C3293D46, $48DE5369, $6413E680, $A2AE0810, $DD6DB224, $69852DFD, $09072166, $B39A460A, $6445C0DD, $586CDECF, $1C20C8AE, $5BBEF7DD, $1B588D40, $CCD2017F, $6BB4E3BB, $DDA26A7E, $3A59FF45, $3E350A44, $BCB4CDD5, $72EACEA8, $FA6484BB, $8D6612AE, $BF3C6F47, $D29BE463, $542F5D9E, $AEC2771B, $F64E6370, $740E0D8D, $E75B1357, $F8721671, $AF537D5D, $4040CB08, $4EB4E2CC, $34D2466A, $0115AF84, $E1B00428, $95983A1D, $06B89FB4, $CE6EA048, $6F3F3B82, $3520AB82, $011A1D4B, $277227F8, $611560B1, $E7933FDC, $BB3A792B, $344525BD, $A08839E1, $51CE794B, $2F32C9B7, $A01FBAC9, $E01CC87E, $BCC7D1F6, $CF0111C3, $A1E8AAC7, $1A908749, $D44FBD9A, $D0DADECB, $D50ADA38, $0339C32A, $C6913667, $8DF9317C, $E0B12B4F, $F79E59B7, $43F5BB3A, $F2D519FF, $27D9459C, $BF97222C, $15E6FC2A, $0F91FC71, $9B941525, $FAE59361, $CEB69CEB, $C2A86459, $12BAA8D1, $B6C1075E, $E3056A0C, $10D25065, $CB03A442, $E0EC6E0E, $1698DB3B, $4C98A0BE, $3278E964, $9F1F9532, $E0D392DF, $D3A0342B, $8971F21E, $1B0A7441, $4BA3348C, $C5BE7120, $C37632D8, $DF359F8D, $9B992F2E, $E60B6F47, $0FE3F11D, $E54CDA54, $1EDAD891, $CE6279CF, $CD3E7E6F, $1618B166, $FD2C1D05, $848FD2C5, $F6FB2299, $F523F357, $A6327623, $93A83531, $56CCCD02, $ACF08162, $5A75EBB5, $6E163697, $88D273CC, $DE966292, $81B949D0, $4C50901B, $71C65614, $E6C6C7BD, $327A140A, $45E1D006, $C3F27B9A, $C9AA53FD, $62A80F00, $BB25BFE2, $35BDD2F6, $71126905, $B2040222, $B6CBCF7C, $CD769C2B, $53113EC0, $1640E3D3, $38ABBD60, $2547ADF0, $BA38209C, $F746CE76, $77AFA1C5, $20756060, $85CBFE4E, $8AE88DD8, $7AAAF9B0, $4CF9AA7E, $1948C25C, $02FB8A8C, $01C36AE4, $D6EBE1F9, $90D4F869, $A65CDEA0, $3F09252D, $C208E69F, $B74E6132, $CE77E25B, $578FDFE3, $3AC372E6) ); { first 2048 bits of Pi in hexadecimal, low to high, without the leading "3" } Pi2048: array [0 .. 255] of Byte = ( $24, $3F, $6A, $88, $85, $A3, $08, $D3, $13, $19, $8A, $2E, $03, $70, $73, $44, $A4, $09, $38, $22, $29, $9F, $31, $D0, $08, $2E, $FA, $98, $EC, $4E, $6C, $89, $45, $28, $21, $E6, $38, $D0, $13, $77, $BE, $54, $66, $CF, $34, $E9, $0C, $6C, $C0, $AC, $29, $B7, $C9, $7C, $50, $DD, $3F, $84, $D5, $B5, $B5, $47, $09, $17, $92, $16, $D5, $D9, $89, $79, $FB, $1B, $D1, $31, $0B, $A6, $98, $DF, $B5, $AC, $2F, $FD, $72, $DB, $D0, $1A, $DF, $B7, $B8, $E1, $AF, $ED, $6A, $26, $7E, $96, $BA, $7C, $90, $45, $F1, $2C, $7F, $99, $24, $A1, $99, $47, $B3, $91, $6C, $F7, $08, $01, $F2, $E2, $85, $8E, $FC, $16, $63, $69, $20, $D8, $71, $57, $4E, $69, $A4, $58, $FE, $A3, $F4, $93, $3D, $7E, $0D, $95, $74, $8F, $72, $8E, $B6, $58, $71, $8B, $CD, $58, $82, $15, $4A, $EE, $7B, $54, $A4, $1D, $C2, $5A, $59, $B5, $9C, $30, $D5, $39, $2A, $F2, $60, $13, $C5, $D1, $B0, $23, $28, $60, $85, $F0, $CA, $41, $79, $18, $B8, $DB, $38, $EF, $8E, $79, $DC, $B0, $60, $3A, $18, $0E, $6C, $9E, $0E, $8B, $B0, $1E, $8A, $3E, $D7, $15, $77, $C1, $BD, $31, $4B, $27, $78, $AF, $2F, $DA, $55, $60, $5C, $60, $E6, $55, $25, $F3, $AA, $55, $AB, $94, $57, $48, $98, $62, $63, $E8, $14, $40, $55, $CA, $39, $6A, $2A, $AB, $10, $B6, $B4, $CC, $5C, $34, $11, $41, $E8, $CE, $A1, $54, $86, $AF, $7C, $72, $E9, $93); BCSalts: array [0 .. 3] of DWORD = ($55555555, $AAAAAAAA, $33333333, $CCCCCCCC); { SHA-1 constants } { 5 magic numbers } SHA1_A = DWORD($67452301); SHA1_B = DWORD($EFCDAB89); SHA1_C = DWORD($98BADCFE); SHA1_D = DWORD($10325476); SHA1_E = DWORD($C3D2E1F0); { four rounds consts } SHA1_K1 = DWORD($5A827999); SHA1_K2 = DWORD($6ED9EBA1); SHA1_K3 = DWORD($8F1BBCDC); SHA1_K4 = DWORD($CA62C1D6); { Maskes used in byte swap } LBMASK_HI = DWORD($FF0000); LBMASK_LO = DWORD($FF00); INPUTWHITEN = 0; RS_GF_FDBK = $14D; MDS_GF_FDBK = $169; SK_STEP = $02020202; SK_BUMP = $01010101; SK_ROTL = 9; Mars_SBox: array [0 .. 511] of DWORD = ( $09D0C479, $28C8FFE0, $84AA6C39, $9DAD7287, $7DFF9BE3, $D4268361, $C96DA1D4, $7974CC93, $85D0582E, $2A4B5705, $1CA16A62, $C3BD279D, $0F1F25E5, $5160372F, $C695C1FB, $4D7FF1E4, $AE5F6BF4, $0D72EE46, $FF23DE8A, $B1CF8E83, $F14902E2, $3E981E42, $8BF53EB6, $7F4BF8AC, $83631F83, $25970205, $76AFE784, $3A7931D4, $4F846450, $5C64C3F6, $210A5F18, $C6986A26, $28F4E826, $3A60A81C, $D340A664, $7EA820C4, $526687C5, $7EDDD12B, $32A11D1D, $9C9EF086, $80F6E831, $AB6F04AD, $56FB9B53, $8B2E095C, $B68556AE, $D2250B0D, $294A7721, $E21FB253, $AE136749, $E82AAE86, $93365104, $99404A66, $78A784DC, $B69BA84B, $04046793, $23DB5C1E, $46CAE1D6, $2FE28134, $5A223942, $1863CD5B, $C190C6E3, $07DFB846, $6EB88816, $2D0DCC4A, $A4CCAE59, $3798670D, $CBFA9493, $4F481D45, $EAFC8CA8, $DB1129D6, $B0449E20, $0F5407FB, $6167D9A8, $D1F45763, $4DAA96C3, $3BEC5958, $ABABA014, $B6CCD201, $38D6279F, $02682215, $8F376CD5, $092C237E, $BFC56593, $32889D2C, $854B3E95, $05BB9B43, $7DCD5DCD, $A02E926C, $FAE527E5, $36A1C330, $3412E1AE, $F257F462, $3C4F1D71, $30A2E809, $68E5F551, $9C61BA44, $5DED0AB8, $75CE09C8, $9654F93E, $698C0CCA, $243CB3E4, $2B062B97, $0F3B8D9E, $00E050DF, $FC5D6166, $E35F9288, $C079550D, $0591AEE8, $8E531E74, $75FE3578, $2F6D829A, $F60B21AE, $95E8EB8D, $6699486B, $901D7D9B, $FD6D6E31, $1090ACEF, $E0670DD8, $DAB2E692, $CD6D4365, $E5393514, $3AF345F0, $6241FC4D, $460DA3A3, $7BCF3729, $8BF1D1E0, $14AAC070, $1587ED55, $3AFD7D3E, $D2F29E01, $29A9D1F6, $EFB10C53, $CF3B870F, $B414935C, $664465ED, $024ACAC7, $59A744C1, $1D2936A7, $DC580AA6, $CF574CA8, $040A7A10, $6CD81807, $8A98BE4C, $ACCEA063, $C33E92B5, $D1E0E03D, $B322517E, $2092BD13, $386B2C4A, $52E8DD58, $58656DFB, $50820371, $41811896, $E337EF7E, $D39FB119, $C97F0DF6, $68FEA01B, $A150A6E5, $55258962, $EB6FF41B, $D7C9CD7A, $A619CD9E, $BCF09576, $2672C073, $F003FB3C, $4AB7A50B, $1484126A, $487BA9B1, $A64FC9C6, $F6957D49, $38B06A75, $DD805FCD, $63D094CF, $F51C999E, $1AA4D343, $B8495294, $CE9F8E99, $BFFCD770, $C7C275CC, $378453A7, $7B21BE33, $397F41BD, $4E94D131, $92CC1F98, $5915EA51, $99F861B7, $C9980A88, $1D74FD5F, $B0A495F8, $614DEED0, $B5778EEA, $5941792D, $FA90C1F8, $33F824B4, $C4965372, $3FF6D550, $4CA5FEC0, $8630E964, $5B3FBBD6, $7DA26A48, $B203231A, $04297514, $2D639306, $2EB13149, $16A45272, $532459A0, $8E5F4872, $F966C7D9, $07128DC0, $0D44DB62, $AFC8D52D, $06316131, $D838E7CE, $1BC41D00, $3A2E8C0F, $EA83837E, $B984737D, $13BA4891, $C4F8B949, $A6D6ACB3, $A215CDCE, $8359838B, $6BD1AA31, $F579DD52, $21B93F93, $F5176781, $187DFDDE, $E94AEB76, $2B38FD54, $431DE1DA, $AB394825, $9AD3048F, $DFEA32AA, $659473E3, $623F7863, $F3346C59, $AB3AB685, $3346A90B, $6B56443E, $C6DE01F8, $8D421FC0, $9B0ED10C, $88F1A1E9, $54C1F029, $7DEAD57B, $8D7BA426, $4CF5178A, $551A7CCA, $1A9A5F08, $FCD651B9, $25605182, $E11FC6C3, $B6FD9676, $337B3027, $B7C8EB14, $9E5FD030, $6B57E354, $AD913CF7, $7E16688D, $58872A69, $2C2FC7DF, $E389CCC6, $30738DF1, $0824A734, $E1797A8B, $A4A8D57B, $5B5D193B, $C8A8309B, $73F9A978, $73398D32, $0F59573E, $E9DF2B03, $E8A5B6C8, $848D0704, $98DF93C2, $720A1DC3, $684F259A, $943BA848, $A6370152, $863B5EA3, $D17B978B, $6D9B58EF, $0A700DD4, $A73D36BF, $8E6A0829, $8695BC14, $E35B3447, $933AC568, $8894B022, $2F511C27, $DDFBCC3C, $006662B6, $117C83FE, $4E12B414, $C2BCA766, $3A2FEC10, $F4562420, $55792E2A, $46F5D857, $CEDA25CE, $C3601D3B, $6C00AB46, $EFAC9C28, $B3C35047, $611DFEE3, $257C3207, $FDD58482, $3B14D84F, $23BECB64, $A075F3A3, $088F8EAD, $07ADF158, $7796943C, $FACABF3D, $C09730CD, $F7679969, $DA44E9ED, $2C854C12, $35935FA3, $2F057D9F, $690624F8, $1CB0BAFD, $7B0DBDC6, $810F23BB, $FA929A1A, $6D969A17, $6742979B, $74AC7D05, $010E65C4, $86A3D963, $F907B5A0, $D0042BD3, $158D7D03, $287A8255, $BBA8366F, $096EDC33, $21916A7B, $77B56B86, $951622F9, $A6C5E650, $8CEA17D1, $CD8C62BC, $A3D63433, $358A68FD, $0F9B9D3C, $D6AA295B, $FE33384A, $C000738E, $CD67EB2F, $E2EB6DC2, $97338B02, $06C9F246, $419CF1AD, $2B83C045, $3723F18A, $CB5B3089, $160BEAD7, $5D494656, $35F8A74B, $1E4E6C9E, $000399BD, $67466880, $B4174831, $ACF423B2, $CA815AB3, $5A6395E7, $302A67C5, $8BDB446B, $108F8FA4, $10223EDA, $92B8B48B, $7F38D0EE, $AB2701D4, $0262D415, $AF224A30, $B3D88ABA, $F8B2C3AF, $DAF7EF70, $CC97D3B7, $E9614B6C, $2BAEBFF4, $70F687CF, $386C9156, $CE092EE5, $01E87DA6, $6CE91E6A, $BB7BCC84, $C7922C20, $9D3B71FD, $060E41C6, $D7590F15, $4E03BB47, $183C198E, $63EEB240, $2DDBF49A, $6D5CBA54, $923750AF, $F9E14236, $7838162B, $59726C72, $81B66760, $BB2926C1, $48A0CE0D, $A6C0496D, $AD43507B, $718D496A, $9DF057AF, $44B1BDE6, $054356DC, $DE7CED35, $D51A138B, $62088CC9, $35830311, $C96EFCA2, $686F86EC, $8E77CB68, $63E1D6B8, $C80F9778, $79C491FD, $1B4C67F2, $72698D7D, $5E368C31, $F7D95E2E, $A1D3493F, $DCD9433E, $896F1552, $4BC4CA7A, $A6D1BAF4, $A5A96DCC, $0BEF8B46, $A169FDA7, $74DF40B7, $4E208804, $9A756607, $038E87C8, $20211E44, $8B7AD4BF, $C6403F35, $1848E36D, $80BDB038, $1E62891C, $643D2107, $BF04D6F8, $21092C8C, $F644F389, $0778404E, $7B78ADB8, $A2C52D53, $42157ABE, $A2253E2E, $7BF3F4AE, $80F594F9, $953194E7, $77EB92ED, $B3816930, $DA8D9336, $BF447469, $F26D9483, $EE6FAED5, $71371235, $DE425F73, $B4E59F43, $7DBE2D4E, $2D37B185, $49DC9A63, $98C39D98, $1301C9A2, $389B1BBF, $0C18588D, $A421C1BA, $7AA3865C, $71E08558, $3C5CFCAA, $7D239CA4, $0297D9DD, $D7DC2830, $4B37802B, $7428AB54, $AEEE0347, $4B3FBB85, $692F2F08, $134E578E, $36D9E0BF, $AE8B5FCF, $EDB93ECF, $2B27248E, $170EB1EF, $7DC57FD6, $1E760F16, $B1136601, $864E1B9B, $D7EA7319, $3AB871BD, $CFA4D76F, $E31BD782, $0DBEB469, $ABB96061, $5370F85D, $FFB07E37, $DA30D0FB, $EBC977B6, $0B98B40F, $3A4D0FE6, $DF4FC26B, $159CF22A, $C298D6E2, $2B78EF6A, $61A94AC0, $AB561187, $14EEA0F0, $DF0D4164, $19AF70EE); type TBlock2048 = array [0 .. 255] of Byte; TBCHalfBlock = array [0 .. 1] of Integer; TBFBlockEx = packed record Xl: array [0 .. 3] of Byte; Xr: array [0 .. 3] of Byte; end; class function TCipher.AllCipher: TCipherSecurityArray; var cs: TCipherSecurity; begin SetLength(Result, Integer(high(TCipherSecurity)) + 1); for cs := low(TCipherSecurity) to high(TCipherSecurity) do Result[Integer(cs)] := cs; end; class function TCipher.NameToHashSecurity(n: SystemString; var hash: THashSecurity): Boolean; var h: THashSecurity; begin Result := False; for h := low(THashSecurity) to high(THashSecurity) do if SameText(CHashName[h], n) then begin hash := h; Result := True; Exit; end; end; class function TCipher.BuffToString(buff: Pointer; Size: NativeInt): TPascalString; begin HashToString(buff, Size, Result); end; class function TCipher.StringToBuff(const Hex: TPascalString; var Buf; BufSize: Cardinal): Boolean; begin Result := HexToBuffer(Hex, Buf, BufSize); end; class procedure TCipher.HashToString(hash: Pointer; Size: NativeInt; var output: TPascalString); const HexArr: array [0 .. 15] of U_Char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'); var i: Integer; begin output.Len := Size * 2; for i := 0 to Size - 1 do begin output.buff[i * 2] := HexArr[(PByte(NativeUInt(hash) + i)^ shr 4) and $0F]; output.buff[i * 2 + 1] := HexArr[PByte(NativeUInt(hash) + i)^ and $0F]; end; end; class procedure TCipher.HashToString(hash: TSHA3_224_Digest; var output: TPascalString); begin HashToString(@hash[0], SizeOf(hash), output); end; class procedure TCipher.HashToString(hash: TSHA3_256_Digest; var output: TPascalString); begin HashToString(@hash[0], SizeOf(hash), output); end; class procedure TCipher.HashToString(hash: TSHA3_384_Digest; var output: TPascalString); begin HashToString(@hash[0], SizeOf(hash), output); end; class procedure TCipher.HashToString(hash: TSHA3_512_Digest; var output: TPascalString); begin HashToString(@hash[0], SizeOf(hash), output); end; class procedure TCipher.HashToString(hash: TSHA512Digest; var output: TPascalString); begin HashToString(@hash[0], SizeOf(hash), output); end; class procedure TCipher.HashToString(hash: TSHA256Digest; var output: TPascalString); begin HashToString(@hash[0], SizeOf(hash), output); end; class procedure TCipher.HashToString(hash: TSHA1Digest; var output: TPascalString); begin HashToString(@hash[0], SizeOf(hash), output); end; class procedure TCipher.HashToString(hash: TMD5Digest; var output: TPascalString); begin HashToString(@hash[0], SizeOf(hash), output); end; class procedure TCipher.HashToString(hash: TBytes; var output: TPascalString); begin HashToString(@hash[0], length(hash), output); end; class procedure TCipher.HashToString(hash: TBytes; var output: SystemString); var s: TPascalString; begin if length(hash) > 0 then begin HashToString(@hash[0], length(hash), s); output := s.Text; end else output := ''; end; class function TCipher.CompareHash(h1, h2: TSHA3_224_Digest): Boolean; begin Result := CompareMemory(@h1[0], @h2[0], SizeOf(h1)); end; class function TCipher.CompareHash(h1, h2: TSHA3_256_Digest): Boolean; begin Result := CompareMemory(@h1[0], @h2[0], SizeOf(h1)); end; class function TCipher.CompareHash(h1, h2: TSHA3_384_Digest): Boolean; begin Result := CompareMemory(@h1[0], @h2[0], SizeOf(h1)); end; class function TCipher.CompareHash(h1, h2: TSHA3_512_Digest): Boolean; begin Result := CompareMemory(@h1[0], @h2[0], SizeOf(h1)); end; class function TCipher.CompareHash(h1, h2: TSHA512Digest): Boolean; begin Result := CompareMemory(@h1[0], @h2[0], SizeOf(h1)); end; class function TCipher.CompareHash(h1, h2: TSHA256Digest): Boolean; begin Result := CompareMemory(@h1[0], @h2[0], SizeOf(h1)); end; class function TCipher.CompareHash(h1, h2: TSHA1Digest): Boolean; begin Result := CompareMemory(@h1[0], @h2[0], SizeOf(h1)); end; class function TCipher.CompareHash(h1, h2: TMD5Digest): Boolean; begin Result := CompareMemory(@h1[0], @h2[0], SizeOf(h1)); end; class function TCipher.CompareHash(h1, h2: Pointer; Size: NativeInt): Boolean; begin Result := CompareMemory(h1, h2, Size); end; class function TCipher.CompareHash(h1, h2: TBytes): Boolean; begin if length(h1) = 0 then Result := length(h2) = 0 else Result := (length(h1) = length(h2)) and (CompareMemory(@h1[0], @h2[0], length(h1))); end; class function TCipher.CompareKey(k1, k2: TCipherKeyBuffer): Boolean; begin if length(k1) = 0 then Result := length(k2) = 0 else Result := (length(k1) = length(k2)) and (CompareMemory(@k1[0], @k2[0], length(k1))); end; class function TCipher.GenerateSHA3_224Hash(sour: Pointer; Size: NativeInt): TSHA3_224_Digest; begin TSHA3.SHA224(Result, sour, Size); end; class function TCipher.GenerateSHA3_256Hash(sour: Pointer; Size: NativeInt): TSHA3_256_Digest; begin TSHA3.SHA256(Result, sour, Size); end; class function TCipher.GenerateSHA3_384Hash(sour: Pointer; Size: NativeInt): TSHA3_384_Digest; begin TSHA3.SHA384(Result, sour, Size); end; class function TCipher.GenerateSHA3_512Hash(sour: Pointer; Size: NativeInt): TSHA3_512_Digest; begin TSHA3.SHA512(Result, sour, Size); end; class function TCipher.GenerateSHA512Hash(sour: Pointer; Size: NativeInt): TSHA512Digest; begin TSHA512.SHA512(Result, sour^, Size); end; class function TCipher.GenerateSHA256Hash(sour: Pointer; Size: NativeInt): TSHA256Digest; begin TSHA256.SHA256(Result, sour^, Size); end; class function TCipher.GenerateSHA1Hash(sour: Pointer; Size: NativeInt): TSHA1Digest; begin TSHA1.SHA1(Result, sour^, Size); end; class function TCipher.GenerateMD5Hash(sour: Pointer; Size: NativeInt): TMD5Digest; begin {$IF Defined(FastMD5) and (Defined(WIN32) or Defined(WIN64))} Result := FastMD5(sour, Size); {$ELSE} THashMD5.HashMD5(Result, sour^, Size); {$IFEND} end; class procedure TCipher.GenerateMDHash(sour: Pointer; Size: NativeInt; OutHash: Pointer; HashSize: NativeInt); begin THashMD.HashLMD(OutHash^, HashSize, sour^, Size); end; class procedure TCipher.GenerateHashByte(hs: THashSecurity; sour: Pointer; Size: NativeInt; var output: TBytes); var swBuff: TBytes; begin if Size <= 0 then begin SetLength(output, 0); Exit; end; if Size < 6 then begin SetLength(output, 16); PMD5(@output[0])^ := umlMD5(PByte(sour), Size); Exit; end; case hs of hsNone: begin SetLength(output, 0); end; hsFastMD5: begin SetLength(output, 16); PMD5(@output[0])^ := umlMD5(PByte(sour), DWORD(Size)); end; hsMD5: begin SetLength(output, 16); THashMD5.HashMD5(PMD5Digest(@output[0])^, sour^, Size); end; hsSHA1: begin SetLength(output, 20); TSHA1.SHA1(PSHA1Digest(@output[0])^, sour^, Size); end; hsSHA256: begin SetLength(output, 32); TSHA256.SHA256(PSHA256Digest(@output[0])^, sour^, Size); end; hsSHA512: begin SetLength(output, 64); TSHA512.SHA512(PSHA512Digest(@output[0])^, sour^, Size); end; hsSHA3_224: begin SetLength(output, SizeOf(TSHA3_224_Digest)); TSHA3.SHA224(PSHA3_224_Digest(@output[0])^, sour, Size); end; hsSHA3_256: begin SetLength(output, SizeOf(TSHA3_256_Digest)); TSHA3.SHA256(PSHA3_256_Digest(@output[0])^, sour, Size); end; hsSHA3_384: begin SetLength(output, SizeOf(TSHA3_384_Digest)); TSHA3.SHA384(PSHA3_384_Digest(@output[0])^, sour, Size); end; hsSHA3_512: begin SetLength(output, SizeOf(TSHA3_512_Digest)); TSHA3.SHA512(PSHA3_512_Digest(@output[0])^, sour, Size); end; hs256: begin SetLength(output, 256); THashMD.HashLMD((@output[0])^, 256, sour^, Size); end; hs128: begin SetLength(output, 128); THashMD.HashLMD((@output[0])^, 128, sour^, Size); end; hs64: begin SetLength(output, 64); THashMD.HashLMD((@output[0])^, 64, sour^, Size); end; hs32: begin SetLength(output, 32); THashMD.HashLMD((@output[0])^, 32, sour^, Size); end; hs16: begin SetLength(output, 16); THashMD.HashLMD((@output[0])^, 16, sour^, Size); end; hsELF: begin SetLength(output, 4); TMISC.HashELF(PDWORD(@output[0])^, sour^, Size); end; hsELF64: begin SetLength(output, 8); TMISC.HashELF64(PInt64(@output[0])^, sour^, Size); end; hsMix128: begin SetLength(output, 4); if Size < 16 then begin SetLength(swBuff, 16); THashMD.HashLMD(swBuff[0], 16, sour^, Size); TMISC.HashMix128(PDWORD(@output[0])^, swBuff[0], 16); end else TMISC.HashMix128(PDWORD(@output[0])^, sour^, Size); end; hsCRC16: begin SetLength(output, 2); PWORD(@output[0])^ := umlCRC16(PByte(sour), Size); end; hsCRC32: begin SetLength(output, 4); PCardinal(@output[0])^ := umlCRC32(PByte(sour), Size); end; end; end; class function TCipher.GenerateHashString(hs: THashSecurity; sour: Pointer; Size: NativeInt): TPascalString; var h: TBytes; begin GenerateHashByte(hs, sour, Size, h); HashToString(h, Result); SetLength(h, 0); end; class function TCipher.BufferToHex(const Buf; BufSize: Cardinal): TPascalString; begin Result := BuffToString(@Buf, BufSize); end; class function TCipher.HexToBuffer(const Hex: TPascalString; var Buf; BufSize: Cardinal): Boolean; var i, c: Integer; filStr: TPascalString; Count: Integer; cChar: Char; begin Result := False; filStr.Text := ''; for cChar in Hex.buff do if CharIn(cChar, [c0to9, cLoAtoF, cHiAtoF]) then filStr.Append(cChar); FillPtrByte(@Buf, BufSize, 0); Count := Min(filStr.Len div 2, BufSize); for i := 0 to Count - 1 do begin val('$' + filStr[i * 2 + 1] + filStr[i * 2 + 2], TCCByteArray(Buf)[i], c); if c <> 0 then Exit; end; Result := True; end; class function TCipher.CopyKey(const k: TCipherKeyBuffer): TCipherKeyBuffer; begin SetLength(Result, length(k)); CopyPtr(@k[0], @Result[0], length(k)); end; class procedure TCipher.GenerateNoneKey(var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size); output[0] := Byte(TCipherKeyStyle.cksNone); end; class procedure TCipher.GenerateKey64(const s: TPascalString; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey64Size); output[0] := Byte(TCipherKeyStyle.cksKey64); THashMD.GenerateLMDKey((@output[1])^, cKey64Size, s.Bytes); end; class procedure TCipher.GenerateKey64(sour: Pointer; Size: NativeInt; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey64Size); output[0] := Byte(TCipherKeyStyle.cksKey64); THashMD.HashLMD((@output[1])^, cKey64Size, sour^, Size); end; class procedure TCipher.GenerateKey128(const s: TPascalString; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey128Size); output[0] := Byte(TCipherKeyStyle.cksKey128); THashMD.GenerateLMDKey((@output[1])^, cKey128Size, s.Bytes); end; class procedure TCipher.GenerateKey128(sour: Pointer; Size: NativeInt; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey128Size); output[0] := Byte(TCipherKeyStyle.cksKey128); THashMD.HashLMD((@output[1])^, cKey128Size, sour^, Size); end; class procedure TCipher.GenerateKey256(const s: TPascalString; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey256Size); output[0] := Byte(TCipherKeyStyle.cksKey256); THashMD.GenerateLMDKey((@output[1])^, cKey256Size, s.Bytes); end; class procedure TCipher.GenerateKey256(sour: Pointer; Size: NativeInt; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey256Size); output[0] := Byte(TCipherKeyStyle.cksKey256); THashMD.HashLMD((@output[1])^, cKey256Size, sour^, Size); end; class procedure TCipher.Generate3Key64(const s: TPascalString; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey192Size); output[0] := Byte(TCipherKeyStyle.cks3Key64); THashMD.GenerateLMDKey((@output[1])^, cKey192Size, s.Bytes); end; class procedure TCipher.Generate3Key64(sour: Pointer; Size: NativeInt; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey192Size); output[0] := Byte(TCipherKeyStyle.cks3Key64); THashMD.HashLMD((@output[1])^, cKey192Size, sour^, Size); end; class procedure TCipher.Generate2IntKey(const s: TPascalString; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey2DWORDSize); output[0] := Byte(TCipherKeyStyle.cks2IntKey); THashMD.GenerateLMDKey((@output[1])^, cKey2DWORDSize, s.Bytes); end; class procedure TCipher.Generate2IntKey(sour: Pointer; Size: NativeInt; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey2DWORDSize); output[0] := Byte(TCipherKeyStyle.cks2IntKey); THashMD.HashLMD((@output[1])^, cKey2DWORDSize, sour^, Size); end; class procedure TCipher.GenerateIntKey(const s: TPascalString; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKeyDWORDSize); output[0] := Byte(TCipherKeyStyle.cksIntKey); THashMD.GenerateLMDKey((@output[1])^, cKeyDWORDSize, s.Bytes); end; class procedure TCipher.GenerateIntKey(sour: Pointer; Size: NativeInt; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKeyDWORDSize); output[0] := Byte(TCipherKeyStyle.cksIntKey); THashMD.HashLMD((@output[1])^, cKeyDWORDSize, sour^, Size); end; class procedure TCipher.GenerateBytesKey(const s: TPascalString; KeySize: DWORD; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cIntSize + KeySize); output[0] := Byte(TCipherKeyStyle.ckyDynamicKey); PDWORD(@output[1])^ := KeySize; THashMD.GenerateLMDKey((@output[1 + cIntSize])^, KeySize, s.Bytes); end; class procedure TCipher.GenerateBytesKey(sour: Pointer; Size, KeySize: DWORD; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cIntSize + KeySize); output[0] := Byte(TCipherKeyStyle.ckyDynamicKey); PDWORD(@output[1])^ := KeySize; THashMD.HashLMD((@output[1 + cIntSize])^, KeySize, sour^, Size); end; class procedure TCipher.GenerateKey64(const k: TKey64; var output: TCipherKeyBuffer); begin GenerateKey(k, output); end; class procedure TCipher.GenerateKey128(const k1, k2: TKey64; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey128Size); output[0] := Byte(TCipherKeyStyle.cksKey128); PKey64(@output[1])^ := k1; PKey64(@output[1 + cKey64Size])^ := k2; end; class procedure TCipher.GenerateKey(const k: TKey64; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey64Size); output[0] := Byte(TCipherKeyStyle.cksKey64); PKey64(@output[1])^ := k; end; class procedure TCipher.GenerateKey(const k1, k2, k3: TKey64; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey192Size); output[0] := Byte(TCipherKeyStyle.cks3Key64); PKey64(@output[1])^ := k1; PKey64(@output[1 + cKey64Size])^ := k2; PKey64(@output[1 + cKey64Size + cKey64Size])^ := k3; end; class procedure TCipher.GenerateKey(const k: TKey128; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey128Size); output[0] := Byte(TCipherKeyStyle.cksKey128); PKey128(@output[1])^ := k; end; class procedure TCipher.GenerateKey(const k: TKey256; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey256Size); output[0] := Byte(TCipherKeyStyle.cksKey256); PKey256(@output[1])^ := k; end; class procedure TCipher.GenerateKey(const k1, k2: DWORD; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKey2DWORDSize); output[0] := Byte(TCipherKeyStyle.cks2IntKey); PInteger(@output[1])^ := k1; PInteger(@output[1 + cKeyDWORDSize])^ := k2; end; class procedure TCipher.GenerateKey(const k: DWORD; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cKeyDWORDSize); output[0] := Byte(TCipherKeyStyle.cksIntKey); PInteger(@output[1])^ := k; end; class procedure TCipher.GenerateKey(const key: PByte; Size: DWORD; var output: TCipherKeyBuffer); begin SetLength(output, C_Byte_Size + cIntSize + Size); output[0] := Byte(TCipherKeyStyle.ckyDynamicKey); PInteger(@output[1])^ := Size; CopyPtr(key, @output[1 + cIntSize], Size); end; class procedure TCipher.GenerateKey(cs: TCipherSecurity; buffPtr: Pointer; Size: NativeInt; var output: TCipherKeyBuffer); begin case cCipherKeyStyle[cs] of cksNone: GenerateNoneKey(output); cksKey64: GenerateKey64(buffPtr, Size, output); cks3Key64: Generate3Key64(buffPtr, Size, output); cksKey128: GenerateKey128(buffPtr, Size, output); cksKey256: GenerateKey256(buffPtr, Size, output); cks2IntKey: Generate2IntKey(buffPtr, Size, output); cksIntKey: GenerateIntKey(buffPtr, Size, output); ckyDynamicKey: GenerateBytesKey(buffPtr, Size, 32, output); end; end; class procedure TCipher.GenerateKey(cs: TCipherSecurity; s: TPascalString; var output: TCipherKeyBuffer); var buff: TBytes; key: TBytes; begin buff := s.Bytes; SetLength(key, 128); TCipher.GenerateMDHash(@buff[0], length(buff), @key[0], 128); GenerateKey(cs, @key[0], 128, output); end; class function TCipher.GetKeyStyle(const p: PCipherKeyBuffer): TCipherKeyStyle; begin Result := TCipherKeyStyle(p^[0]); end; class function TCipher.GetKey(const KeyBuffPtr: PCipherKeyBuffer; var k: TKey64): Boolean; begin Result := GetKeyStyle(KeyBuffPtr) = TCipherKeyStyle.cksKey64; if not Result then Exit; k := PKey64(@KeyBuffPtr^[1])^ end; class function TCipher.GetKey(const KeyBuffPtr: PCipherKeyBuffer; var k1, k2, k3: TKey64): Boolean; begin Result := GetKeyStyle(KeyBuffPtr) = TCipherKeyStyle.cks3Key64; if not Result then Exit; k1 := PKey64(@KeyBuffPtr^[1])^; k2 := PKey64(@KeyBuffPtr^[1 + cKey64Size])^; k3 := PKey64(@KeyBuffPtr^[1 + cKey64Size + cKey64Size])^; end; class function TCipher.GetKey(const KeyBuffPtr: PCipherKeyBuffer; var k: TKey128): Boolean; begin Result := GetKeyStyle(KeyBuffPtr) = TCipherKeyStyle.cksKey128; if not Result then Exit; k := PKey128(@KeyBuffPtr^[1])^ end; class function TCipher.GetKey(const KeyBuffPtr: PCipherKeyBuffer; var k: TKey256): Boolean; begin Result := GetKeyStyle(KeyBuffPtr) = TCipherKeyStyle.cksKey256; if not Result then Exit; k := PKey256(@KeyBuffPtr^[1])^ end; class function TCipher.GetKey(const KeyBuffPtr: PCipherKeyBuffer; var k1, k2: DWORD): Boolean; begin Result := GetKeyStyle(KeyBuffPtr) = TCipherKeyStyle.cks2IntKey; if not Result then Exit; k1 := PDWORD(@KeyBuffPtr^[1])^; k2 := PDWORD(@KeyBuffPtr^[1 + cKeyDWORDSize])^; end; class function TCipher.GetKey(const KeyBuffPtr: PCipherKeyBuffer; var k: DWORD): Boolean; begin Result := GetKeyStyle(KeyBuffPtr) = TCipherKeyStyle.cksIntKey; if not Result then Exit; k := PDWORD(@KeyBuffPtr^[1])^; end; class function TCipher.GetKey(const KeyBuffPtr: PCipherKeyBuffer; var key: TBytes): Boolean; var siz: Integer; begin Result := GetKeyStyle(KeyBuffPtr) = TCipherKeyStyle.ckyDynamicKey; if not Result then Exit; siz := PInteger(@KeyBuffPtr^[1])^; SetLength(key, siz); CopyPtr(@KeyBuffPtr^[1 + cIntSize], @key[0], siz); end; class procedure TCipher.EncryptTail(TailPtr: Pointer; TailSize: NativeInt); begin BlockCBC(TailPtr, TailSize, @SystemCBC[0], length(SystemCBC)); end; class function TCipher.DES64(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k: TKey64; d: TDESContext; p: NativeUInt; begin Result := False; if Size <= 0 then Exit; if Size >= 8 then begin if not GetKey(KeyBuff, k) then Exit; TDES.InitEncryptDES(k, d, Encrypt); p := 0; repeat TDES.EncryptDES(d, PDESBlock(NativeUInt(sour) + p)^); p := p + 8; until p + 8 > Size; end else p := 0; if (ProcessTail) and (Size - p > 0) then EncryptTail(Pointer(NativeUInt(sour) + p), Size - p); Result := True; end; class function TCipher.DES128(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k: TKey128; d: TTripleDESContext; p: NativeUInt; begin Result := False; if Size <= 0 then Exit; if Size >= 8 then begin if not GetKey(KeyBuff, k) then Exit; TDES.InitEncryptTripleDES(k, d, Encrypt); p := 0; repeat TDES.EncryptTripleDES(d, PDESBlock(NativeUInt(sour) + p)^); p := p + 8; until p + 8 > Size; end else p := 0; if (ProcessTail) and (Size - p > 0) then EncryptTail(Pointer(NativeUInt(sour) + p), Size - p); Result := True; end; class function TCipher.DES192(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k1, k2, k3: TKey64; d: TTripleDESContext3Key; p: NativeUInt; begin Result := False; if Size <= 0 then Exit; if Size >= 8 then begin if not GetKey(KeyBuff, k1, k2, k3) then Exit; TDES.InitEncryptTripleDES3Key(k1, k2, k3, d, Encrypt); p := 0; repeat TDES.EncryptTripleDES3Key(d, PDESBlock(NativeUInt(sour) + p)^); p := p + 8; until p + 8 > Size; end else p := 0; if (ProcessTail) and (Size - p > 0) then EncryptTail(Pointer(NativeUInt(sour) + p), Size - p); Result := True; end; class function TCipher.Blowfish(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k: TKey128; d: TBFContext; p: NativeUInt; begin Result := False; if Size <= 0 then Exit; if Size >= 8 then begin if not GetKey(KeyBuff, k) then Exit; TBlowfish.InitEncryptBF(k, d); p := 0; repeat TBlowfish.EncryptBF(d, PBFBlock(NativeUInt(sour) + p)^, Encrypt); p := p + 8; until p + 8 > Size; end else p := 0; if (ProcessTail) and (Size - p > 0) then EncryptTail(Pointer(NativeUInt(sour) + p), Size - p); Result := True; end; class function TCipher.LBC(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k: TKey128; d: TLBCContext; p: NativeUInt; begin Result := False; if Size <= 0 then Exit; if Size >= 16 then begin if not GetKey(KeyBuff, k) then Exit; TLBC.InitEncryptLBC(k, d, 16, Encrypt); p := 0; repeat TLBC.EncryptLBC(d, PLBCBlock(NativeUInt(sour) + p)^); p := p + 16; until p + 16 > Size; end else p := 0; if (ProcessTail) and (Size - p > 0) then EncryptTail(Pointer(NativeUInt(sour) + p), Size - p); Result := True; end; class function TCipher.LQC(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k: TKey128; p: NativeUInt; begin Result := False; if Size <= 0 then Exit; if Size >= 8 then begin if not GetKey(KeyBuff, k) then Exit; p := 0; repeat TLBC.EncryptLQC(k, PLQCBlock(NativeUInt(sour) + p)^, Encrypt); p := p + 8; until p + 8 > Size; end else p := 0; if (ProcessTail) and (Size - p > 0) then EncryptTail(Pointer(NativeUInt(sour) + p), Size - p); Result := True; end; class function TCipher.RNG32(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer): Boolean; var k: DWORD; d: TRNG32Context; begin Result := False; if Size <= 0 then Exit; if not GetKey(KeyBuff, k) then Exit; TRNG.InitEncryptRNG32(k, d); TRNG.EncryptRNG32(d, sour^, Size); Result := True; end; class function TCipher.RNG64(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer): Boolean; var k1, k2: DWORD; d: TRNG64Context; begin Result := False; if Size <= 0 then Exit; if not GetKey(KeyBuff, k1, k2) then Exit; TRNG.InitEncryptRNG64(k1, k2, d); TRNG.EncryptRNG64(d, sour^, Size); Result := True; end; class function TCipher.LSC(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer): Boolean; var k: TBytes; k255: TBytes; d: TLSCContext; begin Result := False; if Size <= 0 then Exit; if not GetKey(KeyBuff, k) then Exit; if length(k) > 255 then begin SetLength(k255, 255); THashMD.GenerateLMDKey((@k255[0])^, 255, k); end else k255 := k; TLSC.InitEncryptLSC((@k255[0])^, length(k255), d); TLSC.EncryptLSC(d, sour^, Size); Result := True; end; class function TCipher.XXTea512(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k: TKey128; p: NativeUInt; begin Result := False; if Size <= 0 then Exit; if Size >= 64 then begin if not GetKey(KeyBuff, k) then Exit; if Encrypt then begin p := 0; repeat XXTEAEncrypt(k, PXXTEABlock(NativeUInt(sour) + p)^); p := p + 64; until p + 64 > Size; end else begin p := 0; repeat XXTEADecrypt(k, PXXTEABlock(NativeUInt(sour) + p)^); p := p + 64; until p + 64 > Size; end; end else p := 0; if (ProcessTail) and (Size - p > 0) then EncryptTail(Pointer(NativeUInt(sour) + p), Size - p); Result := True; end; class function TCipher.RC6(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k, k256: TBytes; d: TRC6Key; p: NativeUInt; begin Result := False; if Size <= 0 then Exit; if Size >= 16 then begin if not GetKey(KeyBuff, k) then Exit; SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TRC6.InitKey(@k256[0], 32, d); if Encrypt then begin p := 0; repeat TRC6.Encrypt(d, PRC6Block(NativeUInt(sour) + p)^); p := p + 16; until p + 16 > Size; end else begin p := 0; repeat TRC6.Decrypt(d, PRC6Block(NativeUInt(sour) + p)^); p := p + 16; until p + 16 > Size; end; end else p := 0; if (ProcessTail) and (Size - p > 0) then EncryptTail(Pointer(NativeUInt(sour) + p), Size - p); Result := True; end; class function TCipher.Serpent(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k, k256: TBytes; d: TSerpentkey; p: NativeUInt; begin Result := False; if Size <= 0 then Exit; if Size >= 16 then begin if not GetKey(KeyBuff, k) then Exit; SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TSerpent.InitKey(@k256[0], 32, d); if Encrypt then begin p := 0; repeat TSerpent.Encrypt(d, PSerpentBlock(NativeUInt(sour) + p)^); p := p + 16; until p + 16 > Size; end else begin p := 0; repeat TSerpent.Decrypt(d, PSerpentBlock(NativeUInt(sour) + p)^); p := p + 16; until p + 16 > Size; end; end else p := 0; if (ProcessTail) and (Size - p > 0) then EncryptTail(Pointer(NativeUInt(sour) + p), Size - p); Result := True; end; class function TCipher.Mars(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k, k256: TBytes; d: TMarskey; p: NativeUInt; begin Result := False; if Size <= 0 then Exit; if Size >= 16 then begin if not GetKey(KeyBuff, k) then Exit; SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TMars.InitKey(@k256[0], 32, d); if Encrypt then begin p := 0; repeat TMars.Encrypt(d, PMarsBlock(NativeUInt(sour) + p)^); p := p + 16; until p + 16 > Size; end else begin p := 0; repeat TMars.Decrypt(d, PMarsBlock(NativeUInt(sour) + p)^); p := p + 16; until p + 16 > Size; end; end else p := 0; if (ProcessTail) and (Size - p > 0) then EncryptTail(Pointer(NativeUInt(sour) + p), Size - p); Result := True; end; class function TCipher.Rijndael(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k, k256: TBytes; d: TRijndaelkey; p: NativeUInt; begin Result := False; if Size <= 0 then Exit; if Size >= 16 then begin if not GetKey(KeyBuff, k) then Exit; SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TRijndael.InitKey(@k256[0], 32, d); if Encrypt then begin p := 0; repeat TRijndael.Encrypt(d, PRijndaelBlock(NativeUInt(sour) + p)^); p := p + 16; until p + 16 > Size; end else begin p := 0; repeat TRijndael.Decrypt(d, PRijndaelBlock(NativeUInt(sour) + p)^); p := p + 16; until p + 16 > Size; end; end else p := 0; if (ProcessTail) and (Size - p > 0) then EncryptTail(Pointer(NativeUInt(sour) + p), Size - p); Result := True; end; class function TCipher.TwoFish(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k, k256: TBytes; d: TTwofishKey; p: NativeUInt; begin Result := False; if Size <= 0 then Exit; if Size >= 16 then begin if not GetKey(KeyBuff, k) then Exit; SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TTwofish.InitKey(@k256[0], 32, d); if Encrypt then begin p := 0; repeat TTwofish.Encrypt(d, PTwofishBlock(NativeUInt(sour) + p)^); p := p + 16; until p + 16 > Size; end else begin p := 0; repeat TTwofish.Decrypt(d, PTwofishBlock(NativeUInt(sour) + p)^); p := p + 16; until p + 16 > Size; end; end else p := 0; if (ProcessTail) and (Size - p > 0) then EncryptTail(Pointer(NativeUInt(sour) + p), Size - p); Result := True; end; class procedure TCipher.BlockCBC(sour: Pointer; Size: NativeInt; boxBuff: Pointer; boxSiz: NativeInt); var p: NativeUInt; begin if Size = 0 then Exit; if boxSiz >= Size then begin TMISC.XorMem(sour^, boxBuff^, Size); end else begin p := 0; repeat TMISC.XorMem(Pointer(NativeUInt(sour) + p)^, boxBuff^, boxSiz); p := p + boxSiz; until p + boxSiz > Size; BlockCBC(Pointer(NativeUInt(sour) + p), Size - p, boxBuff, boxSiz); end; end; class function TCipher.EncryptBuffer(cs: TCipherSecurity; sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; begin Result := False; case cs of csNone: Result := True; csDES64: Result := DES64(sour, Size, KeyBuff, Encrypt, ProcessTail); csDES128: Result := DES128(sour, Size, KeyBuff, Encrypt, ProcessTail); csDES192: Result := DES192(sour, Size, KeyBuff, Encrypt, ProcessTail); csBlowfish: Result := Blowfish(sour, Size, KeyBuff, Encrypt, ProcessTail); csLBC: Result := LBC(sour, Size, KeyBuff, Encrypt, ProcessTail); csLQC: Result := LQC(sour, Size, KeyBuff, Encrypt, ProcessTail); csRNG32: Result := RNG32(sour, Size, KeyBuff); csRNG64: Result := RNG64(sour, Size, KeyBuff); csLSC: Result := LSC(sour, Size, KeyBuff); csTwoFish: Result := TwoFish(sour, Size, KeyBuff, Encrypt, ProcessTail); csXXTea512: Result := XXTea512(sour, Size, KeyBuff, Encrypt, ProcessTail); csRC6: Result := RC6(sour, Size, KeyBuff, Encrypt, ProcessTail); csSerpent: Result := Serpent(sour, Size, KeyBuff, Encrypt, ProcessTail); csMars: Result := Mars(sour, Size, KeyBuff, Encrypt, ProcessTail); csRijndael: Result := Rijndael(sour, Size, KeyBuff, Encrypt, ProcessTail); end; end; class function TCipher.EncryptBufferCBC(cs: TCipherSecurity; sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; begin if cs = TCipherSecurity.csNone then begin Result := True; Exit; end; if Encrypt then begin Result := EncryptBuffer(cs, sour, Size, KeyBuff, Encrypt, ProcessTail); if Result then BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end else begin BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); Result := EncryptBuffer(cs, sour, Size, KeyBuff, Encrypt, ProcessTail); end; end; {$IFDEF Parallel} procedure TParallelCipher.DES64_Parallel(Job, buff, key: Pointer; Size: NativeInt); var p: NativeUInt; begin p := 0; repeat TDES.EncryptDES(PDESContext(key)^, PDESBlock(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end; procedure TParallelCipher.DES128_Parallel(Job, buff, key: Pointer; Size: NativeInt); var p: NativeUInt; begin p := 0; repeat TDES.EncryptTripleDES(PTripleDESContext(key)^, PDESBlock(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end; procedure TParallelCipher.DES192_Parallel(Job, buff, key: Pointer; Size: NativeInt); var p: NativeUInt; begin p := 0; repeat TDES.EncryptTripleDES3Key(PTripleDESContext3Key(key)^, PDESBlock(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end; procedure TParallelCipher.Blowfish_Parallel(Job, buff, key: Pointer; Size: NativeInt); var p: NativeUInt; begin p := 0; repeat TBlowfish.EncryptBF(PBFContext(key)^, PBFBlock(NativeUInt(buff) + p)^, PParallelCipherJobData(Job)^.Encrypt); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end; procedure TParallelCipher.LBC_Parallel(Job, buff, key: Pointer; Size: NativeInt); var p: NativeUInt; begin p := 0; repeat TLBC.EncryptLBC(PLBCContext(key)^, PLBCBlock(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end; procedure TParallelCipher.LQC_Parallel(Job, buff, key: Pointer; Size: NativeInt); var p: NativeUInt; begin p := 0; repeat TLBC.EncryptLQC(PKey128(key)^, PLQCBlock(NativeUInt(buff) + p)^, PParallelCipherJobData(Job)^.Encrypt); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end; procedure TParallelCipher.TwoFish_Parallel(Job, buff, key: Pointer; Size: NativeInt); var p: NativeUInt; begin if PParallelCipherJobData(Job)^.Encrypt then begin p := 0; repeat TTwofish.Encrypt(PTwofishKey(key)^, PTwofishBlock(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end else begin p := 0; repeat TTwofish.Decrypt(PTwofishKey(key)^, PTwofishBlock(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end; end; procedure TParallelCipher.XXTea512_Parallel(Job, buff, key: Pointer; Size: NativeInt); var p: NativeUInt; begin if PParallelCipherJobData(Job)^.Encrypt then begin p := 0; repeat XXTEAEncrypt(PKey128(key)^, PXXTEABlock(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end else begin p := 0; repeat XXTEADecrypt(PKey128(key)^, PXXTEABlock(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end; end; procedure TParallelCipher.RC6_Parallel(Job, buff, key: Pointer; Size: NativeInt); var p: NativeUInt; begin if PParallelCipherJobData(Job)^.Encrypt then begin p := 0; repeat TRC6.Encrypt(PRC6Key(key)^, PRC6Block(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end else begin p := 0; repeat TRC6.Decrypt(PRC6Key(key)^, PRC6Block(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end; end; procedure TParallelCipher.Serpent_Parallel(Job, buff, key: Pointer; Size: NativeInt); var p: NativeUInt; begin if PParallelCipherJobData(Job)^.Encrypt then begin p := 0; repeat TSerpent.Encrypt(PSerpentkey(key)^, PSerpentBlock(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end else begin p := 0; repeat TSerpent.Decrypt(PSerpentkey(key)^, PSerpentBlock(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end; end; procedure TParallelCipher.Mars_Parallel(Job, buff, key: Pointer; Size: NativeInt); var p: NativeUInt; begin if PParallelCipherJobData(Job)^.Encrypt then begin p := 0; repeat TMars.Encrypt(PMarskey(key)^, PMarsBlock(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end else begin p := 0; repeat TMars.Decrypt(PMarskey(key)^, PMarsBlock(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end; end; procedure TParallelCipher.Rijndael_Parallel(Job, buff, key: Pointer; Size: NativeInt); var p: NativeUInt; begin if PParallelCipherJobData(Job)^.Encrypt then begin p := 0; repeat TRijndael.Encrypt(PRijndaelkey(key)^, PRijndaelBlock(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end else begin p := 0; repeat TRijndael.Decrypt(PRijndaelkey(key)^, PRijndaelBlock(NativeUInt(buff) + p)^); p := p + PParallelCipherJobData(Job)^.BlockLen; until p + PParallelCipherJobData(Job)^.BlockLen > Size; end; end; procedure TParallelCipher.BlockCBC_Parallel(Job, buff, key: Pointer; Size: NativeInt); begin TCipher.BlockCBC(buff, Size, key, PParallelCipherJobData(Job)^.BlockLen); end; procedure TParallelCipher.ParallelCipherCall(const JobData: PParallelCipherJobData; const FromIndex, ToIndex: Integer); var newBuffPtr: Pointer; newBuffSiz: NativeUInt; begin newBuffPtr := Pointer(NativeUInt(JobData^.OriginBuffer) + (FromIndex * JobData^.BlockLen)); newBuffSiz := (ToIndex - FromIndex) * JobData^.BlockLen; try JobData^.cipherFunc(JobData, newBuffPtr, JobData^.KeyBuffer, newBuffSiz); except end; inc(JobData^.CompletedBlock, (ToIndex - FromIndex)); end; procedure TParallelCipher.RunParallel(const JobData: PParallelCipherJobData; const Total, Depth: Integer); var StepTotal, stepW: Integer; {$IFDEF FPC} procedure Nested_ParallelFor(pass: Integer); var w: Integer; begin w := stepW * pass; if w + stepW <= Total then ParallelCipherCall(JobData, w, w + stepW) else ParallelCipherCall(JobData, w, Total); end; {$ENDIF FPC} begin if Total <= 0 then Exit; if (Depth <= 0) or (Total < Depth) then begin ParallelCipherCall(JobData, 0, Total); Exit; end; stepW := Total div Depth; StepTotal := Total div stepW; if Total mod stepW > 0 then inc(StepTotal); {$IFDEF FPC} FPCParallelFor(@Nested_ParallelFor, 0, StepTotal - 1); {$ELSE FPC} DelphiParallelFor(0, StepTotal - 1, procedure(pass: Integer) var w: Integer; begin w := stepW * pass; if w + stepW <= Total then ParallelCipherCall(JobData, w, w + stepW) else ParallelCipherCall(JobData, w, Total); end); {$ENDIF FPC} end; constructor TParallelCipher.Create; begin inherited Create; BlockDepth := DefaultParallelDepth; end; destructor TParallelCipher.Destroy; begin inherited Destroy; end; function TParallelCipher.DES64(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var JobData: TParallelCipherJobData; k: TKey64; Context: TDESContext; tailSiz: NativeInt; begin Result := False; if Size <= 0 then Exit; if Size >= 8 then begin if not TCipher.GetKey(KeyBuff, k) then Exit; TDES.InitEncryptDES(k, Context, Encrypt); JobData.cipherFunc := {$IFDEF FPC}@{$ENDIF FPC}DES64_Parallel; JobData.KeyBuffer := @Context; JobData.OriginBuffer := sour; JobData.BlockLen := 8; JobData.TotalBlock := Size div JobData.BlockLen; JobData.CompletedBlock := 0; JobData.Encrypt := Encrypt; RunParallel(@JobData, JobData.TotalBlock, BlockDepth); end; if ProcessTail then begin tailSiz := Size mod JobData.BlockLen; if tailSiz > 0 then TCipher.EncryptTail(Pointer(NativeUInt(sour) + Size - tailSiz), tailSiz); end; Result := True; end; function TParallelCipher.DES128(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var JobData: TParallelCipherJobData; k: TKey128; Context: TTripleDESContext; tailSiz: NativeInt; begin Result := False; if Size <= 0 then Exit; if Size >= 8 then begin if not TCipher.GetKey(KeyBuff, k) then Exit; TDES.InitEncryptTripleDES(k, Context, Encrypt); JobData.cipherFunc := {$IFDEF FPC}@{$ENDIF FPC}DES128_Parallel; JobData.KeyBuffer := @Context; JobData.OriginBuffer := sour; JobData.BlockLen := 8; JobData.TotalBlock := Size div JobData.BlockLen; JobData.CompletedBlock := 0; JobData.Encrypt := Encrypt; RunParallel(@JobData, JobData.TotalBlock, BlockDepth); end; if ProcessTail then begin tailSiz := Size mod JobData.BlockLen; if tailSiz > 0 then TCipher.EncryptTail(Pointer(NativeUInt(sour) + Size - tailSiz), tailSiz); end; Result := True; end; function TParallelCipher.DES192(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var JobData: TParallelCipherJobData; k1, k2, k3: TKey64; Context: TTripleDESContext3Key; tailSiz: NativeInt; begin Result := False; if Size <= 0 then Exit; if Size >= 8 then begin if not TCipher.GetKey(KeyBuff, k1, k2, k3) then Exit; TDES.InitEncryptTripleDES3Key(k1, k2, k3, Context, Encrypt); JobData.cipherFunc := {$IFDEF FPC}@{$ENDIF FPC}DES192_Parallel; JobData.KeyBuffer := @Context; JobData.OriginBuffer := sour; JobData.BlockLen := 8; JobData.TotalBlock := Size div JobData.BlockLen; JobData.CompletedBlock := 0; JobData.Encrypt := Encrypt; RunParallel(@JobData, JobData.TotalBlock, BlockDepth); end; if ProcessTail then begin tailSiz := Size mod JobData.BlockLen; if tailSiz > 0 then TCipher.EncryptTail(Pointer(NativeUInt(sour) + Size - tailSiz), tailSiz); end; Result := True; end; function TParallelCipher.Blowfish(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var JobData: TParallelCipherJobData; k: TKey128; Context: TBFContext; tailSiz: NativeInt; begin Result := False; if Size <= 0 then Exit; if Size >= 8 then begin if not TCipher.GetKey(KeyBuff, k) then Exit; TBlowfish.InitEncryptBF(k, Context); JobData.cipherFunc := {$IFDEF FPC}@{$ENDIF FPC}Blowfish_Parallel; JobData.KeyBuffer := @Context; JobData.OriginBuffer := sour; JobData.BlockLen := 8; JobData.TotalBlock := Size div JobData.BlockLen; JobData.CompletedBlock := 0; JobData.Encrypt := Encrypt; RunParallel(@JobData, JobData.TotalBlock, BlockDepth); end; if ProcessTail then begin tailSiz := Size mod JobData.BlockLen; if tailSiz > 0 then TCipher.EncryptTail(Pointer(NativeUInt(sour) + Size - tailSiz), tailSiz); end; Result := True; end; function TParallelCipher.LBC(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var JobData: TParallelCipherJobData; k: TKey128; Context: TLBCContext; tailSiz: NativeInt; begin Result := False; if Size <= 0 then Exit; if Size >= 16 then begin if not TCipher.GetKey(KeyBuff, k) then Exit; TLBC.InitEncryptLBC(k, Context, 16, Encrypt); JobData.cipherFunc := {$IFDEF FPC}@{$ENDIF FPC}LBC_Parallel; JobData.KeyBuffer := @Context; JobData.OriginBuffer := sour; JobData.BlockLen := 16; JobData.TotalBlock := Size div JobData.BlockLen; JobData.CompletedBlock := 0; JobData.Encrypt := Encrypt; RunParallel(@JobData, JobData.TotalBlock, BlockDepth); end; if ProcessTail then begin tailSiz := Size mod JobData.BlockLen; if tailSiz > 0 then TCipher.EncryptTail(Pointer(NativeUInt(sour) + Size - tailSiz), tailSiz); end; Result := True; end; function TParallelCipher.LQC(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var JobData: TParallelCipherJobData; k: TKey128; tailSiz: NativeInt; begin Result := False; if Size <= 0 then Exit; if Size >= 8 then begin if not TCipher.GetKey(KeyBuff, k) then Exit; JobData.cipherFunc := {$IFDEF FPC}@{$ENDIF FPC}LQC_Parallel; JobData.KeyBuffer := @k; JobData.OriginBuffer := sour; JobData.BlockLen := 8; JobData.TotalBlock := Size div JobData.BlockLen; JobData.CompletedBlock := 0; JobData.Encrypt := Encrypt; RunParallel(@JobData, JobData.TotalBlock, BlockDepth); end; if ProcessTail then begin tailSiz := Size mod JobData.BlockLen; if tailSiz > 0 then TCipher.EncryptTail(Pointer(NativeUInt(sour) + Size - tailSiz), tailSiz); end; Result := True; end; function TParallelCipher.XXTea512(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var JobData: TParallelCipherJobData; k: TKey128; tailSiz: NativeInt; begin Result := False; if Size <= 0 then Exit; if Size >= 64 then begin if not TCipher.GetKey(KeyBuff, k) then Exit; JobData.cipherFunc := {$IFDEF FPC}@{$ENDIF FPC}XXTea512_Parallel; JobData.KeyBuffer := @k; JobData.OriginBuffer := sour; JobData.BlockLen := 64; JobData.TotalBlock := Size div JobData.BlockLen; JobData.CompletedBlock := 0; JobData.Encrypt := Encrypt; RunParallel(@JobData, JobData.TotalBlock, BlockDepth); end; if ProcessTail then begin tailSiz := Size mod JobData.BlockLen; if tailSiz > 0 then TCipher.EncryptTail(Pointer(NativeUInt(sour) + Size - tailSiz), tailSiz); end; Result := True; end; function TParallelCipher.RC6(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var JobData: TParallelCipherJobData; k, k256: TBytes; Context: TRC6Key; tailSiz: NativeInt; begin Result := False; if Size <= 0 then Exit; if Size >= 16 then begin if not TCipher.GetKey(KeyBuff, k) then Exit; SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TRC6.InitKey(@k256[0], 32, Context); JobData.cipherFunc := {$IFDEF FPC}@{$ENDIF FPC}RC6_Parallel; JobData.KeyBuffer := @Context; JobData.OriginBuffer := sour; JobData.BlockLen := 16; JobData.TotalBlock := Size div JobData.BlockLen; JobData.CompletedBlock := 0; JobData.Encrypt := Encrypt; RunParallel(@JobData, JobData.TotalBlock, BlockDepth); end; if ProcessTail then begin tailSiz := Size mod JobData.BlockLen; if tailSiz > 0 then TCipher.EncryptTail(Pointer(NativeUInt(sour) + Size - tailSiz), tailSiz); end; Result := True; end; function TParallelCipher.Serpent(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var JobData: TParallelCipherJobData; k, k256: TBytes; Context: TSerpentkey; tailSiz: NativeInt; begin Result := False; if Size <= 0 then Exit; if Size >= 16 then begin if not TCipher.GetKey(KeyBuff, k) then Exit; SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TSerpent.InitKey(@k256[0], 32, Context); JobData.cipherFunc := {$IFDEF FPC}@{$ENDIF FPC}Serpent_Parallel; JobData.KeyBuffer := @Context; JobData.OriginBuffer := sour; JobData.BlockLen := 16; JobData.TotalBlock := Size div JobData.BlockLen; JobData.CompletedBlock := 0; JobData.Encrypt := Encrypt; RunParallel(@JobData, JobData.TotalBlock, BlockDepth); end; if ProcessTail then begin tailSiz := Size mod JobData.BlockLen; if tailSiz > 0 then TCipher.EncryptTail(Pointer(NativeUInt(sour) + Size - tailSiz), tailSiz); end; Result := True; end; function TParallelCipher.Mars(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var JobData: TParallelCipherJobData; k, k256: TBytes; Context: TMarskey; tailSiz: NativeInt; begin Result := False; if Size <= 0 then Exit; if Size >= 16 then begin if not TCipher.GetKey(KeyBuff, k) then Exit; SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TMars.InitKey(@k256[0], 32, Context); JobData.cipherFunc := {$IFDEF FPC}@{$ENDIF FPC}Mars_Parallel; JobData.KeyBuffer := @Context; JobData.OriginBuffer := sour; JobData.BlockLen := 16; JobData.TotalBlock := Size div JobData.BlockLen; JobData.CompletedBlock := 0; JobData.Encrypt := Encrypt; RunParallel(@JobData, JobData.TotalBlock, BlockDepth); end; if ProcessTail then begin tailSiz := Size mod JobData.BlockLen; if tailSiz > 0 then TCipher.EncryptTail(Pointer(NativeUInt(sour) + Size - tailSiz), tailSiz); end; Result := True; end; function TParallelCipher.Rijndael(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var JobData: TParallelCipherJobData; k, k256: TBytes; Context: TRijndaelkey; tailSiz: NativeInt; begin Result := False; if Size <= 0 then Exit; if Size >= 16 then begin if not TCipher.GetKey(KeyBuff, k) then Exit; SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TRijndael.InitKey(@k256[0], 32, Context); JobData.cipherFunc := {$IFDEF FPC}@{$ENDIF FPC}Rijndael_Parallel; JobData.KeyBuffer := @Context; JobData.OriginBuffer := sour; JobData.BlockLen := 16; JobData.TotalBlock := Size div JobData.BlockLen; JobData.CompletedBlock := 0; JobData.Encrypt := Encrypt; RunParallel(@JobData, JobData.TotalBlock, BlockDepth); end; if ProcessTail then begin tailSiz := Size mod JobData.BlockLen; if tailSiz > 0 then TCipher.EncryptTail(Pointer(NativeUInt(sour) + Size - tailSiz), tailSiz); end; Result := True; end; function TParallelCipher.TwoFish(sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var JobData: TParallelCipherJobData; k, k256: TBytes; Context: TTwofishKey; tailSiz: NativeInt; begin Result := False; if Size <= 0 then Exit; if Size >= 16 then begin if not TCipher.GetKey(KeyBuff, k) then Exit; SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TTwofish.InitKey(@k256[0], 32, Context); JobData.cipherFunc := {$IFDEF FPC}@{$ENDIF FPC}TwoFish_Parallel; JobData.KeyBuffer := @Context; JobData.OriginBuffer := sour; JobData.BlockLen := 16; JobData.TotalBlock := Size div JobData.BlockLen; JobData.CompletedBlock := 0; JobData.Encrypt := Encrypt; RunParallel(@JobData, JobData.TotalBlock, BlockDepth); end; if ProcessTail then begin tailSiz := Size mod JobData.BlockLen; if tailSiz > 0 then TCipher.EncryptTail(Pointer(NativeUInt(sour) + Size - tailSiz), tailSiz); end; Result := True; end; procedure TParallelCipher.BlockCBC(sour: Pointer; Size: NativeInt; boxBuff: Pointer; boxSiz: NativeInt); var JobData: TParallelCipherJobData; tailSiz: NativeInt; begin if Size <= 0 then Exit; if boxSiz <= 0 then Exit; if boxSiz >= Size then begin TCipher.BlockCBC(sour, Size, boxBuff, boxSiz); Exit; end; JobData.cipherFunc := {$IFDEF FPC}@{$ENDIF FPC}BlockCBC_Parallel; JobData.KeyBuffer := boxBuff; JobData.OriginBuffer := sour; JobData.BlockLen := boxSiz; JobData.TotalBlock := Size div JobData.BlockLen; JobData.CompletedBlock := 0; JobData.Encrypt := True; RunParallel(@JobData, JobData.TotalBlock, BlockDepth); tailSiz := Size mod JobData.BlockLen; if tailSiz > 0 then TCipher.BlockCBC(Pointer(NativeUInt(sour) + Size - tailSiz), tailSiz, boxBuff, boxSiz); end; function TParallelCipher.EncryptBuffer(cs: TCipherSecurity; sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; begin Result := False; case cs of csNone: Result := True; csDES64: Result := DES64(sour, Size, KeyBuff, Encrypt, ProcessTail); csDES128: Result := DES128(sour, Size, KeyBuff, Encrypt, ProcessTail); csDES192: Result := DES192(sour, Size, KeyBuff, Encrypt, ProcessTail); csBlowfish: Result := Blowfish(sour, Size, KeyBuff, Encrypt, ProcessTail); csLBC: Result := LBC(sour, Size, KeyBuff, Encrypt, ProcessTail); csLQC: Result := LQC(sour, Size, KeyBuff, Encrypt, ProcessTail); csRNG32: Result := TCipher.RNG32(sour, Size, KeyBuff); csRNG64: Result := TCipher.RNG64(sour, Size, KeyBuff); csLSC: Result := TCipher.LSC(sour, Size, KeyBuff); csTwoFish: Result := TwoFish(sour, Size, KeyBuff, Encrypt, ProcessTail); csXXTea512: Result := XXTea512(sour, Size, KeyBuff, Encrypt, ProcessTail); csRC6: Result := RC6(sour, Size, KeyBuff, Encrypt, ProcessTail); csSerpent: Result := Serpent(sour, Size, KeyBuff, Encrypt, ProcessTail); csMars: Result := Mars(sour, Size, KeyBuff, Encrypt, ProcessTail); csRijndael: Result := Rijndael(sour, Size, KeyBuff, Encrypt, ProcessTail); end; end; function TParallelCipher.EncryptBufferCBC(cs: TCipherSecurity; sour: Pointer; Size: NativeInt; KeyBuff: PCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; begin if cs = TCipherSecurity.csNone then begin Result := True; Exit; end; if Encrypt then begin Result := EncryptBuffer(cs, sour, Size, KeyBuff, Encrypt, ProcessTail); if Result then BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end else begin BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); Result := EncryptBuffer(cs, sour, Size, KeyBuff, Encrypt, ProcessTail); end; end; {$ENDIF} procedure InitSysCBCAndDefaultKey(rand: Int64); var i: Integer; Seed: TInt64; begin {$IFDEF Parallel} { system default Parallel depth } DefaultParallelDepth := CPUCount * 2; ParallelTriggerCondition := 1024; {$ENDIF} SetLength(SystemCBC, 64 * 1024); Seed.i := rand; for i := 0 to (length(SystemCBC) div 4) - 1 do PInteger(@SystemCBC[i * 4])^ := TMISC.Random64(Seed); end; function SequEncryptWithDirect(const cs: TCipherSecurity; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k: TCipherKeyBuffer; begin TCipher.GenerateKey(cs, @key[0], length(key), k); Result := TCipher.EncryptBuffer(cs, sour, Size, @k, Encrypt, ProcessTail); end; function SequEncryptWithDirect(const ca: TCipherSecurityArray; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var i: Integer; begin Result := True; if Encrypt then begin for i := low(ca) to high(ca) do Result := Result and SequEncryptWithDirect(ca[i], sour, Size, key, Encrypt, ProcessTail); end else begin for i := high(ca) downto low(ca) do Result := Result and SequEncryptWithDirect(ca[i], sour, Size, key, Encrypt, ProcessTail); end; end; {$IFDEF Parallel} function SequEncryptWithParallel(const cs: TCipherSecurity; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k: TCipherKeyBuffer; Parallel: TParallelCipher; begin TCipher.GenerateKey(cs, @key[0], length(key), k); Parallel := TParallelCipher.Create; Parallel.BlockDepth := DefaultParallelDepth; Result := Parallel.EncryptBuffer(cs, sour, Size, @k, Encrypt, ProcessTail); DisposeObject(Parallel); end; function SequEncryptWithParallel(const ca: TCipherSecurityArray; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var i: Integer; begin Result := True; if Encrypt then begin for i := low(ca) to high(ca) do Result := Result and SequEncryptWithParallel(ca[i], sour, Size, key, Encrypt, ProcessTail); end else begin for i := high(ca) downto low(ca) do Result := Result and SequEncryptWithParallel(ca[i], sour, Size, key, Encrypt, ProcessTail); end; end; {$ENDIF} function SequEncrypt(const ca: TCipherSecurityArray; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; begin {$IFDEF Parallel} if Size >= ParallelTriggerCondition then Result := SequEncryptWithParallel(ca, sour, Size, key, Encrypt, ProcessTail) else {$ENDIF} Result := SequEncryptWithDirect(ca, sour, Size, key, Encrypt, ProcessTail); end; function SequEncrypt(const cs: TCipherSecurity; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; begin {$IFDEF Parallel} if Size >= ParallelTriggerCondition then Result := SequEncryptWithParallel(cs, sour, Size, key, Encrypt, ProcessTail) else {$ENDIF} Result := SequEncryptWithDirect(cs, sour, Size, key, Encrypt, ProcessTail); end; function SequEncryptCBCWithDirect(const cs: TCipherSecurity; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k: TCipherKeyBuffer; begin TCipher.GenerateKey(cs, @key[0], length(key), k); Result := TCipher.EncryptBufferCBC(cs, sour, Size, @k, Encrypt, ProcessTail); end; function SequEncryptCBCWithDirect(const ca: TCipherSecurityArray; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var i: Integer; begin Result := True; if Encrypt then begin for i := low(ca) to high(ca) do Result := Result and SequEncryptCBCWithDirect(ca[i], sour, Size, key, Encrypt, ProcessTail); end else begin for i := high(ca) downto low(ca) do Result := Result and SequEncryptCBCWithDirect(ca[i], sour, Size, key, Encrypt, ProcessTail); end; end; {$IFDEF Parallel} function SequEncryptCBCWithParallel(const cs: TCipherSecurity; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var k: TCipherKeyBuffer; Parallel: TParallelCipher; begin TCipher.GenerateKey(cs, @key[0], length(key), k); Parallel := TParallelCipher.Create; Parallel.BlockDepth := DefaultParallelDepth; Result := Parallel.EncryptBufferCBC(cs, sour, Size, @k, Encrypt, ProcessTail); DisposeObject(Parallel); end; function SequEncryptCBCWithParallel(const ca: TCipherSecurityArray; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; var i: Integer; begin Result := True; if Encrypt then begin for i := low(ca) to high(ca) do Result := Result and SequEncryptCBCWithParallel(ca[i], sour, Size, key, Encrypt, ProcessTail); end else begin for i := high(ca) downto low(ca) do Result := Result and SequEncryptCBCWithParallel(ca[i], sour, Size, key, Encrypt, ProcessTail); end; end; {$ENDIF} function SequEncryptCBC(const ca: TCipherSecurityArray; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; begin {$IFDEF Parallel} if Size >= ParallelTriggerCondition then Result := SequEncryptCBCWithParallel(ca, sour, Size, key, Encrypt, ProcessTail) else {$ENDIF} Result := SequEncryptCBCWithDirect(ca, sour, Size, key, Encrypt, ProcessTail); end; function SequEncryptCBC(const cs: TCipherSecurity; sour: Pointer; Size: NativeInt; const key: TCipherKeyBuffer; Encrypt, ProcessTail: Boolean): Boolean; begin {$IFDEF Parallel} if Size >= ParallelTriggerCondition then Result := SequEncryptCBCWithParallel(cs, sour, Size, key, Encrypt, ProcessTail) else {$ENDIF} Result := SequEncryptCBCWithDirect(cs, sour, Size, key, Encrypt, ProcessTail); end; function GenerateSequHash(hssArry: THashSecuritys; sour: Pointer; Size: NativeInt): TPascalString; var h: THashSecurity; vl: THashStringList; hBuff: TBytes; n: SystemString; begin vl := THashStringList.Create; for h in hssArry do begin TCipher.GenerateHashByte(h, sour, Size, hBuff); n := ''; TCipher.HashToString(hBuff, n); vl[TCipher.CHashName[h]] := '(' + n + ')'; end; Result.Text := vl.AsText; DisposeObject([vl]); end; procedure GenerateSequHash(hssArry: THashSecuritys; sour: Pointer; Size: NativeInt; output: TListPascalString); var h: THashSecurity; vl: THashStringList; hBuff: TBytes; n: SystemString; begin vl := THashStringList.Create; for h in hssArry do begin TCipher.GenerateHashByte(h, sour, Size, hBuff); n := ''; TCipher.HashToString(hBuff, n); vl[TCipher.CHashName[h]] := '(' + n + ')'; end; vl.ExportAsStrings(output); DisposeObject([vl]); end; procedure GenerateSequHash(hssArry: THashSecuritys; sour: Pointer; Size: NativeInt; output: TCoreClassStream); var h: THashSecurity; vl: THashStringList; hBuff: TBytes; n: SystemString; begin vl := THashStringList.Create; for h in hssArry do begin TCipher.GenerateHashByte(h, sour, Size, hBuff); n := ''; TCipher.HashToString(hBuff, n); vl[TCipher.CHashName[h]] := '(' + n + ')'; end; vl.SaveToStream(output); DisposeObject([vl]); end; function CompareSequHash(HashVL: THashStringList; sour: Pointer; Size: NativeInt): Boolean; var ns: TListString; i: Integer; sourHash, destHash: TBytes; hName: SystemString; hValue: TPascalString; h: THashSecurity; begin Result := True; ns := TListString.Create; HashVL.GetNameList(ns); for i := 0 to ns.Count - 1 do begin hName := ns[i]; hValue := umlTrimSpace(HashVL.GetDefaultValue(hName, '')); if TCipher.NameToHashSecurity(hName, h) and ((hValue.Len >= 2) and (hValue.First = '(') and (hValue.Last = ')')) then begin hValue.DeleteFirst; hValue.DeleteLast; TCipher.GenerateHashByte(h, sour, Size, sourHash); SetLength(destHash, length(sourHash)); if length(destHash) > 0 then begin Result := Result and TCipher.HexToBuffer(hValue, destHash[0], length(destHash)); Result := Result and TCipher.CompareHash(sourHash, destHash); end; end; if not Result then Break; end; DisposeObject([ns]); end; function CompareSequHash(hashData: TPascalString; sour: Pointer; Size: NativeInt): Boolean; var vl: THashStringList; begin vl := THashStringList.Create; vl.AsText := hashData.Text; Result := CompareSequHash(vl, sour, Size); DisposeObject(vl); end; function CompareSequHash(hashData: TListPascalString; sour: Pointer; Size: NativeInt): Boolean; var vl: THashStringList; begin vl := THashStringList.Create; vl.ImportFromStrings(hashData); Result := CompareSequHash(vl, sour, Size); DisposeObject(vl); end; function CompareSequHash(hashData: TCoreClassStream; sour: Pointer; Size: NativeInt): Boolean; var vl: THashStringList; begin vl := THashStringList.Create; vl.LoadFromStream(hashData); Result := CompareSequHash(vl, sour, Size); DisposeObject(vl); end; function GenerateMemoryHash(hssArry: THashSecuritys; sour: Pointer; Size: NativeInt): TPascalString; var m64: TMemoryStream64; begin m64 := TMemoryStream64.Create; GenerateSequHash(hssArry, sour, Size, m64); umlEncodeStreamBASE64(m64, Result); DisposeObject(m64); Result := '(' + Result + ')'; end; function CompareMemoryHash(sour: Pointer; Size: NativeInt; const hashBuff: TPascalString): Boolean; var n: TPascalString; m64: TMemoryStream64; begin Result := False; n := hashBuff.TrimChar(#32); if (n.Len > 2) and (n.First = '(') and (n.Last = ')') then begin n.DeleteFirst; n.DeleteLast; m64 := TMemoryStream64.Create; umlDecodeStreamBASE64(n, m64); Result := CompareSequHash(m64, sour, Size); DisposeObject(m64); end; end; function GeneratePasswordHash(hssArry: THashSecuritys; const passwd: TPascalString): TPascalString; var buff: TBytes; m64: TMemoryStream64; begin buff := passwd.Bytes; m64 := TMemoryStream64.Create; GenerateSequHash(hssArry, @buff[0], length(buff), m64); umlEncodeStreamBASE64(m64, Result); DisposeObject(m64); Result := '(' + Result + ')'; SetLength(buff, 0); end; function ComparePasswordHash(const passwd, hashBuff: TPascalString): Boolean; var n: TPascalString; buff: TBytes; m64: TMemoryStream64; begin Result := False; n := hashBuff.TrimChar(#32); if (n.Len > 2) and (n.First = '(') and (n.Last = ')') then begin n.DeleteFirst; n.DeleteLast; buff := passwd.Bytes; m64 := TMemoryStream64.Create; umlDecodeStreamBASE64(n, m64); Result := CompareSequHash(m64, @buff[0], length(buff)); DisposeObject(m64); SetLength(buff, 0); end; end; function GeneratePassword(const ca: TCipherSecurityArray; const passwd: TPascalString): TPascalString; var KeyBuff: TBytes; buff: TBytes; begin KeyBuff := passwd.Bytes; buff := passwd.Bytes; SequEncryptCBC(ca, @buff[0], length(buff), KeyBuff, True, False); umlBase64EncodeBytes(buff, Result); Result := '(' + Result + ')'; SetLength(buff, 0); SetLength(KeyBuff, 0); end; function ComparePassword(const ca: TCipherSecurityArray; const passwd, passwdDataSource: TPascalString): Boolean; var sour: TPascalString; refBuff: TBytes; KeyBuff: TBytes; begin Result := False; sour := umlTrimSpace(passwdDataSource); if (sour.Len > 2) and (sour.First = '(') and (sour.Last = ')') then begin sour.DeleteFirst; sour.DeleteLast; umlBase64DecodeBytes(sour, refBuff); KeyBuff := passwd.Bytes; SequEncryptCBC(ca, @refBuff[0], length(refBuff), KeyBuff, False, False); Result := TCipher.CompareKey(refBuff, KeyBuff); SetLength(refBuff, 0); SetLength(KeyBuff, 0); end; end; function GeneratePassword(const cs: TCipherSecurity; const passwd: TPascalString): TPascalString; overload; var KeyBuff: TBytes; buff: TBytes; begin KeyBuff := passwd.Bytes; buff := passwd.Bytes; SequEncryptCBC(cs, @buff[0], length(buff), KeyBuff, True, False); umlBase64EncodeBytes(buff, Result); Result := '(' + Result + ')'; SetLength(buff, 0); SetLength(KeyBuff, 0); end; function ComparePassword(const cs: TCipherSecurity; const passwd, passwdDataSource: TPascalString): Boolean; overload; var sour: TPascalString; refBuff: TBytes; KeyBuff: TBytes; begin Result := False; sour := umlTrimSpace(passwdDataSource); if (sour.Len > 2) and (sour.First = '(') and (sour.Last = ')') then begin sour.DeleteFirst; sour.DeleteLast; umlBase64DecodeBytes(sour, refBuff); KeyBuff := passwd.Bytes; SequEncryptCBC(cs, @refBuff[0], length(refBuff), KeyBuff, False, False); Result := TCipher.CompareKey(refBuff, KeyBuff); SetLength(refBuff, 0); SetLength(KeyBuff, 0); end; end; function GenerateQuantumCryptographyPassword(const passwd: TPascalString): TPascalString; var buff, cryptBuff: TBytes; begin buff := passwd.Bytes; SetLength(cryptBuff, 512 div 8); TSHA3.SHAKE256(@cryptBuff[0], @buff[0], length(buff), 512); umlBase64EncodeBytes(cryptBuff, Result); Result := '(' + Result + ')'; SetLength(buff, 0); SetLength(cryptBuff, 0); end; function CompareQuantumCryptographyPassword(const passwd, passwdDataSource: TPascalString): Boolean; var sour: TPascalString; refBuff, buff, cryptBuff: TBytes; begin Result := False; sour := umlTrimSpace(passwdDataSource); if (sour.Len > 2) and (sour.First = '(') and (sour.Last = ')') then begin sour.DeleteFirst; sour.DeleteLast; umlBase64DecodeBytes(sour, refBuff); buff := passwd.Bytes; SetLength(cryptBuff, 512 div 8); TSHA3.SHAKE256(@cryptBuff[0], @buff[0], length(buff), 512); Result := TCipher.CompareKey(refBuff, cryptBuff); SetLength(refBuff, 0); SetLength(buff, 0); SetLength(cryptBuff, 0); end; end; type TQuantumEncryptHead = packed record CipherSecurity: Byte; Level: Word; Size: Int64; hash: TSHA3_512_Digest; end; procedure QuantumEncrypt(input, output: TCoreClassStream; SecurityLevel: Integer; key: TCipherKeyBuffer); var m64: TMemoryStream64; head: TQuantumEncryptHead; i: Integer; hh: TSHA3_512_Digest; begin m64 := TMemoryStream64.Create; input.Position := 0; m64.CopyFrom(input, input.Size); head.CipherSecurity := Byte(TCipherSecurity.csRijndael); head.Level := SecurityLevel; head.Size := m64.Size; // 2x-sha3-512 Secure Hash TSHA3.SHA512(hh, m64.Memory, head.Size); TSHA3.SHA512(head.hash, @hh[0], 64); // infinition encrypt for i := 0 to head.Level - 1 do SequEncryptCBC(TCipherSecurity(head.CipherSecurity), m64.Memory, m64.Size, key, True, True); output.write(head, SizeOf(head)); output.write(m64.Memory^, m64.Size); DisposeObject(m64); end; function QuantumDecrypt(input, output: TCoreClassStream; key: TCipherKeyBuffer): Boolean; var head: TQuantumEncryptHead; m64: TMemoryStream64; i: Integer; hh, h: TSHA3_512_Digest; begin Result := False; input.read(head, SizeOf(head)); m64 := TMemoryStream64.Create; if m64.CopyFrom(input, head.Size) <> head.Size then begin DisposeObject(m64); Exit; end; // infinition encrypt for i := 0 to head.Level - 1 do SequEncryptCBC(TCipherSecurity(head.CipherSecurity), m64.Memory, m64.Size, key, False, True); // 2x-sha3-512 Secure Hash TSHA3.SHA512(hh, m64.Memory, m64.Size); TSHA3.SHA512(h, @hh[0], 64); // compare if not TCipher.CompareHash(h, head.hash) then begin DisposeObject(m64); Exit; end; m64.Position := 0; output.CopyFrom(m64, m64.Size); DisposeObject(m64); Result := True; end; { TBlowfish } class procedure TBlowfish.EncryptBF(const Context: TBFContext; var Block: TBFBlock; Encrypt: Boolean); var i: Integer; TmpBlock: TBFBlockEx; { !!.01 } begin CopyPtr(@Block, @TmpBlock, SizeOf(TmpBlock)); { !!.01 } if Encrypt then begin Block[0] := Block[0] xor Context.PBox[0]; { 16 Rounds to go (8 double rounds to avoid swaps) } i := 1; repeat { first half round } Block[1] := Block[1] xor Context.PBox[i] xor ((( Context.SBox[0, TmpBlock.Xl[3]] + Context.SBox[1, TmpBlock.Xl[2]]) xor Context.SBox[2, TmpBlock.Xl[1]]) + Context.SBox[3, TmpBlock.Xl[0]]); { second half round } Block[0] := Block[0] xor Context.PBox[i + 1] xor ((( Context.SBox[0, TmpBlock.Xr[3]] + Context.SBox[1, TmpBlock.Xr[2]]) xor Context.SBox[2, TmpBlock.Xr[1]]) + Context.SBox[3, TmpBlock.Xr[0]]); inc(i, 2); until i > BFRounds; Block[1] := Block[1] xor Context.PBox[(BFRounds + 1)]; end else begin Block[1] := Block[1] xor Context.PBox[(BFRounds + 1)]; { 16 Rounds to go (8 double rounds to avoid swaps) } i := BFRounds; repeat { first half round } Block[0] := Block[0] xor Context.PBox[i] xor ((( Context.SBox[0, TmpBlock.Xr[3]] + Context.SBox[1, TmpBlock.Xr[2]]) xor Context.SBox[2, TmpBlock.Xr[1]]) + Context.SBox[3, TmpBlock.Xr[0]]); { second half round } Block[1] := Block[1] xor Context.PBox[i - 1] xor ((( Context.SBox[0, TmpBlock.Xl[3]] + Context.SBox[1, TmpBlock.Xl[2]]) xor Context.SBox[2, TmpBlock.Xl[1]]) + Context.SBox[3, TmpBlock.Xl[0]]); dec(i, 2); until i < 1; Block[0] := Block[0] xor Context.PBox[0]; end; end; class procedure TBlowfish.InitEncryptBF(key: TKey128; var Context: TBFContext); var i: Integer; j: Integer; k: Integer; Data: DWORD; Block: TBFBlock; begin { initialize PArray } CopyPtr(@bf_P, @Context.PBox, SizeOf(Context.PBox)); { initialize SBox } CopyPtr(@bf_S, @Context.SBox, SizeOf(Context.SBox)); { update PArray with the key bits } j := 0; for i := 0 to (BFRounds + 1) do begin Data := 0; for k := 0 to 3 do begin Data := (Data shl 8) or key[j]; inc(j); if j >= SizeOf(key) then j := 0; end; Context.PBox[i] := Context.PBox[i] xor Data; end; { encrypt an all-zero SystemString using the Blowfish algorithm and } { replace the elements of the P-array with the output of this process } Block[0] := 0; Block[1] := 0; i := 0; repeat EncryptBF(Context, Block, True); Context.PBox[i] := Block[0]; Context.PBox[i + 1] := Block[1]; inc(i, 2); until i > BFRounds + 1; { continue the process, replacing the elements of the four S-boxes in } { order, with the output of the continuously changing Blowfish algorithm } for j := 0 to 3 do begin i := 0; repeat EncryptBF(Context, Block, True); Context.SBox[j, i] := Block[0]; Context.SBox[j, i + 1] := Block[1]; inc(i, 2); until i > 255; end; { in total, 521 iterations are required to generate all required subkeys. } end; { TDES } class procedure TDES.EncryptDES(const Context: TDESContext; var Block: TDESBlock); const SPBox: array [0 .. 7, 0 .. 63] of DWORD = (($01010400, $00000000, $00010000, $01010404, $01010004, $00010404, $00000004, $00010000, $00000400, $01010400, $01010404, $00000400, $01000404, $01010004, $01000000, $00000004, $00000404, $01000400, $01000400, $00010400, $00010400, $01010000, $01010000, $01000404, $00010004, $01000004, $01000004, $00010004, $00000000, $00000404, $00010404, $01000000, $00010000, $01010404, $00000004, $01010000, $01010400, $01000000, $01000000, $00000400, $01010004, $00010000, $00010400, $01000004, $00000400, $00000004, $01000404, $00010404, $01010404, $00010004, $01010000, $01000404, $01000004, $00000404, $00010404, $01010400, $00000404, $01000400, $01000400, $00000000, $00010004, $00010400, $00000000, $01010004), ($80108020, $80008000, $00008000, $00108020, $00100000, $00000020, $80100020, $80008020, $80000020, $80108020, $80108000, $80000000, $80008000, $00100000, $00000020, $80100020, $00108000, $00100020, $80008020, $00000000, $80000000, $00008000, $00108020, $80100000, $00100020, $80000020, $00000000, $00108000, $00008020, $80108000, $80100000, $00008020, $00000000, $00108020, $80100020, $00100000, $80008020, $80100000, $80108000, $00008000, $80100000, $80008000, $00000020, $80108020, $00108020, $00000020, $00008000, $80000000, $00008020, $80108000, $00100000, $80000020, $00100020, $80008020, $80000020, $00100020, $00108000, $00000000, $80008000, $00008020, $80000000, $80100020, $80108020, $00108000), ($00000208, $08020200, $00000000, $08020008, $08000200, $00000000, $00020208, $08000200, $00020008, $08000008, $08000008, $00020000, $08020208, $00020008, $08020000, $00000208, $08000000, $00000008, $08020200, $00000200, $00020200, $08020000, $08020008, $00020208, $08000208, $00020200, $00020000, $08000208, $00000008, $08020208, $00000200, $08000000, $08020200, $08000000, $00020008, $00000208, $00020000, $08020200, $08000200, $00000000, $00000200, $00020008, $08020208, $08000200, $08000008, $00000200, $00000000, $08020008, $08000208, $00020000, $08000000, $08020208, $00000008, $00020208, $00020200, $08000008, $08020000, $08000208, $00000208, $08020000, $00020208, $00000008, $08020008, $00020200), ($00802001, $00002081, $00002081, $00000080, $00802080, $00800081, $00800001, $00002001, $00000000, $00802000, $00802000, $00802081, $00000081, $00000000, $00800080, $00800001, $00000001, $00002000, $00800000, $00802001, $00000080, $00800000, $00002001, $00002080, $00800081, $00000001, $00002080, $00800080, $00002000, $00802080, $00802081, $00000081, $00800080, $00800001, $00802000, $00802081, $00000081, $00000000, $00000000, $00802000, $00002080, $00800080, $00800081, $00000001, $00802001, $00002081, $00002081, $00000080, $00802081, $00000081, $00000001, $00002000, $00800001, $00002001, $00802080, $00800081, $00002001, $00002080, $00800000, $00802001, $00000080, $00800000, $00002000, $00802080), ($00000100, $02080100, $02080000, $42000100, $00080000, $00000100, $40000000, $02080000, $40080100, $00080000, $02000100, $40080100, $42000100, $42080000, $00080100, $40000000, $02000000, $40080000, $40080000, $00000000, $40000100, $42080100, $42080100, $02000100, $42080000, $40000100, $00000000, $42000000, $02080100, $02000000, $42000000, $00080100, $00080000, $42000100, $00000100, $02000000, $40000000, $02080000, $42000100, $40080100, $02000100, $40000000, $42080000, $02080100, $40080100, $00000100, $02000000, $42080000, $42080100, $00080100, $42000000, $42080100, $02080000, $00000000, $40080000, $42000000, $00080100, $02000100, $40000100, $00080000, $00000000, $40080000, $02080100, $40000100), ($20000010, $20400000, $00004000, $20404010, $20400000, $00000010, $20404010, $00400000, $20004000, $00404010, $00400000, $20000010, $00400010, $20004000, $20000000, $00004010, $00000000, $00400010, $20004010, $00004000, $00404000, $20004010, $00000010, $20400010, $20400010, $00000000, $00404010, $20404000, $00004010, $00404000, $20404000, $20000000, $20004000, $00000010, $20400010, $00404000, $20404010, $00400000, $00004010, $20000010, $00400000, $20004000, $20000000, $00004010, $20000010, $20404010, $00404000, $20400000, $00404010, $20404000, $00000000, $20400010, $00000010, $00004000, $20400000, $00404010, $00004000, $00400010, $20004010, $00000000, $20404000, $20000000, $00400010, $20004010), ($00200000, $04200002, $04000802, $00000000, $00000800, $04000802, $00200802, $04200800, $04200802, $00200000, $00000000, $04000002, $00000002, $04000000, $04200002, $00000802, $04000800, $00200802, $00200002, $04000800, $04000002, $04200000, $04200800, $00200002, $04200000, $00000800, $00000802, $04200802, $00200800, $00000002, $04000000, $00200800, $04000000, $00200800, $00200000, $04000802, $04000802, $04200002, $04200002, $00000002, $00200002, $04000000, $04000800, $00200000, $04200800, $00000802, $00200802, $04200800, $00000802, $04000002, $04200802, $04200000, $00200800, $00000000, $00000002, $04200802, $00000000, $00200802, $04200000, $00000800, $04000002, $04000800, $00000800, $00200002), ($10001040, $00001000, $00040000, $10041040, $10000000, $10001040, $00000040, $10000000, $00040040, $10040000, $10041040, $00041000, $10041000, $00041040, $00001000, $00000040, $10040000, $10000040, $10001000, $00001040, $00041000, $00040040, $10040040, $10041000, $00001040, $00000000, $00000000, $10040040, $10000040, $10001000, $00041040, $00040000, $00041040, $00040000, $10041000, $00001000, $00000040, $10040040, $00001000, $00041040, $10001000, $00000040, $10000040, $10040000, $10040040, $10000000, $00040000, $10001040, $00000000, $10041040, $00040040, $10000040, $10040000, $10001000, $10001040, $00000000, $10041040, $00041000, $00041000, $00001040, $00001040, $00040040, $10000000, $10041000)); var i, l, r, Work: DWORD; CPtr: PDWORD; procedure IPerm(var l, r: DWORD); var Work: DWORD; begin Work := ((l shr 4) xor r) and $0F0F0F0F; r := r xor Work; l := l xor Work shl 4; Work := ((l shr 16) xor r) and $0000FFFF; r := r xor Work; l := l xor Work shl 16; Work := ((r shr 2) xor l) and $33333333; l := l xor Work; r := r xor Work shl 2; Work := ((r shr 8) xor l) and $00FF00FF; l := l xor Work; r := r xor Work shl 8; r := (r shl 1) or (r shr 31); Work := (l xor r) and $AAAAAAAA; l := l xor Work; r := r xor Work; l := (l shl 1) or (l shr 31); end; procedure FPerm(var l, r: DWORD); var Work: DWORD; begin l := l; r := (r shl 31) or (r shr 1); Work := (l xor r) and $AAAAAAAA; l := l xor Work; r := r xor Work; l := (l shr 1) or (l shl 31); Work := ((l shr 8) xor r) and $00FF00FF; r := r xor Work; l := l xor Work shl 8; Work := ((l shr 2) xor r) and $33333333; r := r xor Work; l := l xor Work shl 2; Work := ((r shr 16) xor l) and $0000FFFF; l := l xor Work; r := r xor Work shl 16; Work := ((r shr 4) xor l) and $0F0F0F0F; l := l xor Work; r := r xor Work shl 4; end; begin SplitBlock(Block, l, r); IPerm(l, r); CPtr := @Context; for i := 0 to 7 do begin Work := (((r shr 4) or (r shl 28)) xor CPtr^); inc(CPtr); l := l xor SPBox[6, Work and $3F]; l := l xor SPBox[4, Work shr 8 and $3F]; l := l xor SPBox[2, Work shr 16 and $3F]; l := l xor SPBox[0, Work shr 24 and $3F]; Work := (r xor CPtr^); inc(CPtr); l := l xor SPBox[7, Work and $3F]; l := l xor SPBox[5, Work shr 8 and $3F]; l := l xor SPBox[3, Work shr 16 and $3F]; l := l xor SPBox[1, Work shr 24 and $3F]; Work := (((l shr 4) or (l shl 28)) xor CPtr^); inc(CPtr); r := r xor SPBox[6, Work and $3F]; r := r xor SPBox[4, Work shr 8 and $3F]; r := r xor SPBox[2, Work shr 16 and $3F]; r := r xor SPBox[0, Work shr 24 and $3F]; Work := (l xor CPtr^); inc(CPtr); r := r xor SPBox[7, Work and $3F]; r := r xor SPBox[5, Work shr 8 and $3F]; r := r xor SPBox[3, Work shr 16 and $3F]; r := r xor SPBox[1, Work shr 24 and $3F]; end; FPerm(l, r); JoinBlock(l, r, Block); end; class procedure TDES.EncryptTripleDES(const Context: TTripleDESContext; var Block: TDESBlock); begin EncryptDES(Context[0], Block); EncryptDES(Context[1], Block); EncryptDES(Context[0], Block); end; { !!.01 } class procedure TDES.EncryptTripleDES3Key(const Context: TTripleDESContext3Key; var Block: TDESBlock); begin EncryptDES(Context[2], Block); EncryptDES(Context[1], Block); EncryptDES(Context[0], Block); end; class procedure TDES.InitEncryptDES(const key: TKey64; var Context: TDESContext; Encrypt: Boolean); const PC1: array [0 .. 55] of Byte = (56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3); PC2: array [0 .. 47] of Byte = (13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9, 22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1, 40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47, 43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31); CTotRot: array [0 .. 15] of Byte = (1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28); CBitMask: array [0 .. 7] of Byte = (128, 64, 32, 16, 8, 4, 2, 1); var PC1M: array [0 .. 55] of Byte; PC1R: array [0 .. 55] of Byte; KS: array [0 .. 7] of Byte; i, j, l, m: Integer; begin { convert PC1 to bits of key } for j := 0 to 55 do begin l := PC1[j]; m := l mod 8; PC1M[j] := Ord((key[l div 8] and CBitMask[m]) <> 0); end; { key chunk for each iteration } for i := 0 to 15 do begin { rotate PC1 the right amount } for j := 0 to 27 do begin l := j + CTotRot[i]; if (l < 28) then begin PC1R[j] := PC1M[l]; PC1R[j + 28] := PC1M[l + 28]; end else begin PC1R[j] := PC1M[l - 28]; PC1R[j + 28] := PC1M[l]; end; end; { select bits individually } FillPtrByte(@KS, SizeOf(KS), 0); for j := 0 to 47 do if Boolean(PC1R[PC2[j]]) then begin l := j div 6; KS[l] := KS[l] or CBitMask[j mod 6] shr 2; end; { now convert to odd/even interleaved form for use in F } if Encrypt then begin Context.TransformedKey[i * 2] := (Integer(KS[0]) shl 24) or (Integer(KS[2]) shl 16) or (Integer(KS[4]) shl 8) or (Integer(KS[6])); Context.TransformedKey[i * 2 + 1] := (Integer(KS[1]) shl 24) or (Integer(KS[3]) shl 16) or (Integer(KS[5]) shl 8) or (Integer(KS[7])); end else begin Context.TransformedKey[31 - (i * 2 + 1)] := (Integer(KS[0]) shl 24) or (Integer(KS[2]) shl 16) or (Integer(KS[4]) shl 8) or (Integer(KS[6])); Context.TransformedKey[31 - (i * 2)] := (Integer(KS[1]) shl 24) or (Integer(KS[3]) shl 16) or (Integer(KS[5]) shl 8) or (Integer(KS[7])); end; end; Context.Encrypt := Encrypt; end; class procedure TDES.InitEncryptTripleDES(const key: TKey128; var Context: TTripleDESContext; Encrypt: Boolean); var KeyArray: array [0 .. 1] of TKey64; begin CopyPtr(@key, @KeyArray, SizeOf(KeyArray)); { !!.01 } if Encrypt then begin InitEncryptDES(KeyArray[0], Context[0], True); InitEncryptDES(KeyArray[1], Context[1], False); end else begin InitEncryptDES(KeyArray[0], Context[0], False); InitEncryptDES(KeyArray[1], Context[1], True); end; end; { !!.01 } class procedure TDES.InitEncryptTripleDES3Key(const Key1, Key2, Key3: TKey64; var Context: TTripleDESContext3Key; Encrypt: Boolean); begin if Encrypt then begin InitEncryptDES(Key1, Context[0], True); InitEncryptDES(Key2, Context[1], False); InitEncryptDES(Key3, Context[2], True); end else begin InitEncryptDES(Key1, Context[2], False); InitEncryptDES(Key2, Context[1], True); InitEncryptDES(Key3, Context[0], False); end; end; class procedure TDES.JoinBlock(const l, r: DWORD; var Block: TDESBlock); var Temp: TDesConverter; i: Integer; begin Temp.DWords[0] := DWORD(l); Temp.DWords[1] := DWORD(r); for i := low(Block) to high(Block) do Block[i] := Temp.Bytes[7 - i]; end; class procedure TDES.ShrinkDESKey(var key: TKey64); const SK1: TKey64 = ($C4, $08, $B0, $54, $0B, $A1, $E0, $AE); SK2: TKey64 = ($EF, $2C, $04, $1C, $E6, $38, $2F, $E6); var i: Integer; Work1: TKey64; Work2: TKey64; Context: TDESContext; begin { step #1 zero the parity bits - 8, 16, 24, ..., 64 } for i := 0 to 7 do Work1[i] := key[i] and $FE; { step #2 encrypt output of #1 with SK1 and xor with output of #1 } InitEncryptDES(SK1, Context, True); Work2 := Work1; { make copy } EncryptDES(Context, TDESBlock(Work2)); for i := 0 to 7 do Work1[i] := Work1[i] xor Work2[i]; { step #3 zero bits 1,2,3,4,8,16,17,18,19,20,24,32,33,34,35,36,40,48,49,50,51,52,56,64 } TInt64(Work1).Lo := TInt64(Work1).Lo and $F101F101; TInt64(Work1).Hi := TInt64(Work1).Hi and $F101F101; { step #4 encrypt output of #3 with SK2 } InitEncryptDES(SK2, Context, True); EncryptDES(Context, TDESBlock(Work1)); key := Work1; end; class procedure TDES.SplitBlock(const Block: TDESBlock; var l, r: DWORD); var Temp: TDesConverter; i: Integer; begin for i := low(Block) to high(Block) do Temp.Bytes[7 - i] := Block[i]; l := Temp.DWords[1]; r := Temp.DWords[0]; end; class procedure TSHA1.SHA1Clear(var Context: TSHA1Context); begin FillPtrByte(@Context, SizeOf(Context), $00); end; class procedure TSHA1.SHA1Hash(var Context: TSHA1Context); var a: DWORD; b: DWORD; c: DWORD; d: DWORD; E: DWORD; x: DWORD; w: array [0 .. 79] of DWORD; i: Integer; begin with Context do begin sdIndex := 0; CopyPtr(@sdBuf, @w, SizeOf(w)); // W := Mt, for t = 0 to 15 : Mt is M sub t for i := 0 to 15 do w[i] := SHA1SwapByteOrder(w[i]); // Transform Message block from 16 32 bit words to 80 32 bit words // Wt, = ( Wt-3 xor Wt-8 xor Wt-13 xor Wt-16 ) rolL 1 : Wt is W sub t for i := 16 to 79 do w[i] := TMISC.RolX(w[i - 3] xor w[i - 8] xor w[i - 14] xor w[i - 16], 1); a := sdHash[0]; b := sdHash[1]; c := sdHash[2]; d := sdHash[3]; E := sdHash[4]; // the four rounds for i := 0 to 19 do begin x := TMISC.RolX(a, 5) + (d xor (b and (c xor d))) + E + w[i] + SHA1_K1; E := d; d := c; c := TMISC.RolX(b, 30); b := a; a := x; end; for i := 20 to 39 do begin x := TMISC.RolX(a, 5) + (b xor c xor d) + E + w[i] + SHA1_K2; E := d; d := c; c := TMISC.RolX(b, 30); b := a; a := x; end; for i := 40 to 59 do begin x := TMISC.RolX(a, 5) + ((b and c) or (d and (b or c))) + E + w[i] + SHA1_K3; E := d; d := c; c := TMISC.RolX(b, 30); b := a; a := x; end; for i := 60 to 79 do begin x := TMISC.RolX(a, 5) + (b xor c xor d) + E + w[i] + SHA1_K4; E := d; d := c; c := TMISC.RolX(b, 30); b := a; a := x; end; sdHash[0] := sdHash[0] + a; sdHash[1] := sdHash[1] + b; sdHash[2] := sdHash[2] + c; sdHash[3] := sdHash[3] + d; sdHash[4] := sdHash[4] + E; FillPtrByte(@w, SizeOf(w), $00); FillPtrByte(@sdBuf, SizeOf(sdBuf), $00); end; end; class function TSHA1.SHA1SwapByteOrder(n: DWORD): DWORD; begin n := (n shr 24) or ((n shr 8) and LBMASK_LO) or ((n shl 8) and LBMASK_HI) or (n shl 24); Result := n; end; class procedure TSHA1.SHA1UpdateLen(var Context: TSHA1Context; Len: DWORD); begin inc(Context.sdLo, (Len shl 3)); if Context.sdLo < (Len shl 3) then inc(Context.sdHi); inc(Context.sdHi, Len shr 29); end; class procedure TSHA1.SHA1(var Digest: TSHA1Digest; const Buf; BufSize: NativeUInt); var Context: TSHA1Context; begin InitSHA1(Context); UpdateSHA1(Context, Buf, BufSize); FinalizeSHA1(Context, Digest); end; class procedure TSHA1.ByteBuffSHA1(var Digest: TSHA1Digest; const Bytes_: TBytes); begin SHA1(Digest, Bytes_[0], length(Bytes_)); end; class procedure TSHA1.InitSHA1(var Context: TSHA1Context); begin SHA1Clear(Context); Context.sdHash[0] := SHA1_A; Context.sdHash[1] := SHA1_B; Context.sdHash[2] := SHA1_C; Context.sdHash[3] := SHA1_D; Context.sdHash[4] := SHA1_E; end; class procedure TSHA1.UpdateSHA1(var Context: TSHA1Context; const Buf; BufSize: NativeUInt); var PBuf: PByte; begin with Context do begin SHA1UpdateLen(Context, BufSize); PBuf := @Buf; while BufSize > 0 do begin if (SizeOf(sdBuf) - sdIndex) <= DWORD(BufSize) then begin CopyPtr(PBuf, @sdBuf[sdIndex], SizeOf(sdBuf) - sdIndex); dec(BufSize, SizeOf(sdBuf) - sdIndex); inc(PBuf, SizeOf(sdBuf) - sdIndex); SHA1Hash(Context); end else begin CopyPtr(PBuf, @sdBuf[sdIndex], BufSize); inc(sdIndex, BufSize); BufSize := 0; end; end; end; end; { TSHA1 } class procedure TSHA1.FinalizeSHA1(var Context: TSHA1Context; var Digest: TSHA1Digest); begin with Context do begin sdBuf[sdIndex] := $80; if sdIndex >= 56 then SHA1Hash(Context); PDWORD(@sdBuf[56])^ := SHA1SwapByteOrder(sdHi); PDWORD(@sdBuf[60])^ := SHA1SwapByteOrder(sdLo); SHA1Hash(Context); sdHash[0] := SHA1SwapByteOrder(sdHash[0]); sdHash[1] := SHA1SwapByteOrder(sdHash[1]); sdHash[2] := SHA1SwapByteOrder(sdHash[2]); sdHash[3] := SHA1SwapByteOrder(sdHash[3]); sdHash[4] := SHA1SwapByteOrder(sdHash[4]); CopyPtr(@sdHash, @Digest, SizeOf(Digest)); SHA1Clear(Context); end; end; class procedure TSHA256.SwapDWORD(var a: DWORD); begin a := Endian(a); end; class procedure TSHA256.Compute(var Digest: TSHA256Digest; const buff: Pointer); var a, b, c, d, E, f, g, h, tmp1, tmp2: DWORD; w: array [0 .. 63] of DWORD; i: ShortInt; begin a := PDWORD(@Digest[0])^; b := PDWORD(@Digest[4])^; c := PDWORD(@Digest[8])^; d := PDWORD(@Digest[12])^; E := PDWORD(@Digest[16])^; f := PDWORD(@Digest[20])^; g := PDWORD(@Digest[24])^; h := PDWORD(@Digest[28])^; CopyPtr(buff, @w[0], 64); for i := 0 to 15 do SwapDWORD(w[i]); for i := 16 to 63 do w[i] := (((w[i - 2] shr 17) or (w[i - 2] shl 15)) xor ((w[i - 2] shr 19) or (w[i - 2] shl 13)) xor (w[i - 2] shr 10)) + w[i - 7] + (((w[i - 15] shr 7) or (w[i - 15] shl 25)) xor ((w[i - 15] shr 18) or (w[i - 15] shl 14)) xor (w[i - 15] shr 3)) + w[i - 16]; tmp1 := h + (((E shr 6) or (E shl 26)) xor ((E shr 11) or (E shl 21)) xor ((E shr 25) or (E shl 7))) + ((E and f) xor (not E and g)) + $428A2F98 + w[0]; tmp2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := tmp1 + tmp2; d := d + tmp1; tmp1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and E) xor (not d and f)) + $71374491 + w[1]; tmp2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := tmp1 + tmp2; c := c + tmp1; tmp1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and E)) + $B5C0FBCF + w[2]; tmp2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := tmp1 + tmp2; b := b + tmp1; tmp1 := E + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $E9B5DBA5 + w[3]; tmp2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); E := tmp1 + tmp2; a := a + tmp1; tmp1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $3956C25B + w[4]; tmp2 := (((E shr 2) or (E shl 30)) xor ((E shr 13) or (E shl 19)) xor ((E shr 22) xor (E shl 10))) + ((E and f) xor (E and g) xor (f and g)); d := tmp1 + tmp2; h := h + tmp1; tmp1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $59F111F1 + w[5]; tmp2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and E) xor (d and f) xor (E and f)); c := tmp1 + tmp2; g := g + tmp1; tmp1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $923F82A4 + w[6]; tmp2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and E) xor (d and E)); b := tmp1 + tmp2; f := f + tmp1; tmp1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $AB1C5ED5 + w[7]; tmp2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := tmp1 + tmp2; E := E + tmp1; tmp1 := h + (((E shr 6) or (E shl 26)) xor ((E shr 11) or (E shl 21)) xor ((E shr 25) or (E shl 7))) + ((E and f) xor (not E and g)) + $D807AA98 + w[8]; tmp2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := tmp1 + tmp2; d := d + tmp1; tmp1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and E) xor (not d and f)) + $12835B01 + w[9]; tmp2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := tmp1 + tmp2; c := c + tmp1; tmp1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and E)) + $243185BE + w[10]; tmp2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := tmp1 + tmp2; b := b + tmp1; tmp1 := E + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $550C7DC3 + w[11]; tmp2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); E := tmp1 + tmp2; a := a + tmp1; tmp1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $72BE5D74 + w[12]; tmp2 := (((E shr 2) or (E shl 30)) xor ((E shr 13) or (E shl 19)) xor ((E shr 22) xor (E shl 10))) + ((E and f) xor (E and g) xor (f and g)); d := tmp1 + tmp2; h := h + tmp1; tmp1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $80DEB1FE + w[13]; tmp2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and E) xor (d and f) xor (E and f)); c := tmp1 + tmp2; g := g + tmp1; tmp1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $9BDC06A7 + w[14]; tmp2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and E) xor (d and E)); b := tmp1 + tmp2; f := f + tmp1; tmp1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $C19BF174 + w[15]; tmp2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := tmp1 + tmp2; E := E + tmp1; tmp1 := h + (((E shr 6) or (E shl 26)) xor ((E shr 11) or (E shl 21)) xor ((E shr 25) or (E shl 7))) + ((E and f) xor (not E and g)) + $E49B69C1 + w[16]; tmp2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := tmp1 + tmp2; d := d + tmp1; tmp1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and E) xor (not d and f)) + $EFBE4786 + w[17]; tmp2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := tmp1 + tmp2; c := c + tmp1; tmp1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and E)) + $0FC19DC6 + w[18]; tmp2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := tmp1 + tmp2; b := b + tmp1; tmp1 := E + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $240CA1CC + w[19]; tmp2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); E := tmp1 + tmp2; a := a + tmp1; tmp1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $2DE92C6F + w[20]; tmp2 := (((E shr 2) or (E shl 30)) xor ((E shr 13) or (E shl 19)) xor ((E shr 22) xor (E shl 10))) + ((E and f) xor (E and g) xor (f and g)); d := tmp1 + tmp2; h := h + tmp1; tmp1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $4A7484AA + w[21]; tmp2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and E) xor (d and f) xor (E and f)); c := tmp1 + tmp2; g := g + tmp1; tmp1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $5CB0A9DC + w[22]; tmp2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and E) xor (d and E)); b := tmp1 + tmp2; f := f + tmp1; tmp1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $76F988DA + w[23]; tmp2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := tmp1 + tmp2; E := E + tmp1; tmp1 := h + (((E shr 6) or (E shl 26)) xor ((E shr 11) or (E shl 21)) xor ((E shr 25) or (E shl 7))) + ((E and f) xor (not E and g)) + $983E5152 + w[24]; tmp2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := tmp1 + tmp2; d := d + tmp1; tmp1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and E) xor (not d and f)) + $A831C66D + w[25]; tmp2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := tmp1 + tmp2; c := c + tmp1; tmp1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and E)) + $B00327C8 + w[26]; tmp2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := tmp1 + tmp2; b := b + tmp1; tmp1 := E + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $BF597FC7 + w[27]; tmp2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); E := tmp1 + tmp2; a := a + tmp1; tmp1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $C6E00BF3 + w[28]; tmp2 := (((E shr 2) or (E shl 30)) xor ((E shr 13) or (E shl 19)) xor ((E shr 22) xor (E shl 10))) + ((E and f) xor (E and g) xor (f and g)); d := tmp1 + tmp2; h := h + tmp1; tmp1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $D5A79147 + w[29]; tmp2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and E) xor (d and f) xor (E and f)); c := tmp1 + tmp2; g := g + tmp1; tmp1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $06CA6351 + w[30]; tmp2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and E) xor (d and E)); b := tmp1 + tmp2; f := f + tmp1; tmp1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $14292967 + w[31]; tmp2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := tmp1 + tmp2; E := E + tmp1; tmp1 := h + (((E shr 6) or (E shl 26)) xor ((E shr 11) or (E shl 21)) xor ((E shr 25) or (E shl 7))) + ((E and f) xor (not E and g)) + $27B70A85 + w[32]; tmp2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := tmp1 + tmp2; d := d + tmp1; tmp1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and E) xor (not d and f)) + $2E1B2138 + w[33]; tmp2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := tmp1 + tmp2; c := c + tmp1; tmp1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and E)) + $4D2C6DFC + w[34]; tmp2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := tmp1 + tmp2; b := b + tmp1; tmp1 := E + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $53380D13 + w[35]; tmp2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); E := tmp1 + tmp2; a := a + tmp1; tmp1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $650A7354 + w[36]; tmp2 := (((E shr 2) or (E shl 30)) xor ((E shr 13) or (E shl 19)) xor ((E shr 22) xor (E shl 10))) + ((E and f) xor (E and g) xor (f and g)); d := tmp1 + tmp2; h := h + tmp1; tmp1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $766A0ABB + w[37]; tmp2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and E) xor (d and f) xor (E and f)); c := tmp1 + tmp2; g := g + tmp1; tmp1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $81C2C92E + w[38]; tmp2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and E) xor (d and E)); b := tmp1 + tmp2; f := f + tmp1; tmp1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $92722C85 + w[39]; tmp2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := tmp1 + tmp2; E := E + tmp1; tmp1 := h + (((E shr 6) or (E shl 26)) xor ((E shr 11) or (E shl 21)) xor ((E shr 25) or (E shl 7))) + ((E and f) xor (not E and g)) + $A2BFE8A1 + w[40]; tmp2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := tmp1 + tmp2; d := d + tmp1; tmp1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and E) xor (not d and f)) + $A81A664B + w[41]; tmp2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := tmp1 + tmp2; c := c + tmp1; tmp1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and E)) + $C24B8B70 + w[42]; tmp2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := tmp1 + tmp2; b := b + tmp1; tmp1 := E + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $C76C51A3 + w[43]; tmp2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); E := tmp1 + tmp2; a := a + tmp1; tmp1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $D192E819 + w[44]; tmp2 := (((E shr 2) or (E shl 30)) xor ((E shr 13) or (E shl 19)) xor ((E shr 22) xor (E shl 10))) + ((E and f) xor (E and g) xor (f and g)); d := tmp1 + tmp2; h := h + tmp1; tmp1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $D6990624 + w[45]; tmp2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and E) xor (d and f) xor (E and f)); c := tmp1 + tmp2; g := g + tmp1; tmp1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $F40E3585 + w[46]; tmp2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and E) xor (d and E)); b := tmp1 + tmp2; f := f + tmp1; tmp1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $106AA070 + w[47]; tmp2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := tmp1 + tmp2; E := E + tmp1; tmp1 := h + (((E shr 6) or (E shl 26)) xor ((E shr 11) or (E shl 21)) xor ((E shr 25) or (E shl 7))) + ((E and f) xor (not E and g)) + $19A4C116 + w[48]; tmp2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := tmp1 + tmp2; d := d + tmp1; tmp1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and E) xor (not d and f)) + $1E376C08 + w[49]; tmp2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := tmp1 + tmp2; c := c + tmp1; tmp1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and E)) + $2748774C + w[50]; tmp2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := tmp1 + tmp2; b := b + tmp1; tmp1 := E + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $34B0BCB5 + w[51]; tmp2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); E := tmp1 + tmp2; a := a + tmp1; tmp1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $391C0CB3 + w[52]; tmp2 := (((E shr 2) or (E shl 30)) xor ((E shr 13) or (E shl 19)) xor ((E shr 22) xor (E shl 10))) + ((E and f) xor (E and g) xor (f and g)); d := tmp1 + tmp2; h := h + tmp1; tmp1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $4ED8AA4A + w[53]; tmp2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and E) xor (d and f) xor (E and f)); c := tmp1 + tmp2; g := g + tmp1; tmp1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $5B9CCA4F + w[54]; tmp2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and E) xor (d and E)); b := tmp1 + tmp2; f := f + tmp1; tmp1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $682E6FF3 + w[55]; tmp2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := tmp1 + tmp2; E := E + tmp1; tmp1 := h + (((E shr 6) or (E shl 26)) xor ((E shr 11) or (E shl 21)) xor ((E shr 25) or (E shl 7))) + ((E and f) xor (not E and g)) + $748F82EE + w[56]; tmp2 := (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h := tmp1 + tmp2; d := d + tmp1; tmp1 := g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and E) xor (not d and f)) + $78A5636F + w[57]; tmp2 := (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g := tmp1 + tmp2; c := c + tmp1; tmp1 := f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and E)) + $84C87814 + w[58]; tmp2 := (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f := tmp1 + tmp2; b := b + tmp1; tmp1 := E + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $8CC70208 + w[59]; tmp2 := (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); E := tmp1 + tmp2; a := a + tmp1; tmp1 := d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $90BEFFFA + w[60]; tmp2 := (((E shr 2) or (E shl 30)) xor ((E shr 13) or (E shl 19)) xor ((E shr 22) xor (E shl 10))) + ((E and f) xor (E and g) xor (f and g)); d := tmp1 + tmp2; h := h + tmp1; tmp1 := c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $A4506CEB + w[61]; tmp2 := (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and E) xor (d and f) xor (E and f)); c := tmp1 + tmp2; g := g + tmp1; tmp1 := b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $BEF9A3F7 + w[62]; tmp2 := (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and E) xor (d and E)); b := tmp1 + tmp2; f := f + tmp1; tmp1 := a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $C67178F2 + w[63]; tmp2 := (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a := tmp1 + tmp2; E := E + tmp1; inc(PDWORD(@Digest[0])^, a); inc(PDWORD(@Digest[4])^, b); inc(PDWORD(@Digest[8])^, c); inc(PDWORD(@Digest[12])^, d); inc(PDWORD(@Digest[16])^, E); inc(PDWORD(@Digest[20])^, f); inc(PDWORD(@Digest[24])^, g); inc(PDWORD(@Digest[28])^, h); end; class procedure TSHA256.SHA256(var Digest: TSHA256Digest; const Buf; BufSize: NativeUInt); var Lo, Hi: DWORD; p: PByte; ChunkIndex: Byte; ChunkBuf: array [0 .. 63] of Byte; begin PDWORD(@Digest[0])^ := $6A09E667; PDWORD(@Digest[4])^ := $BB67AE85; PDWORD(@Digest[8])^ := $3C6EF372; PDWORD(@Digest[12])^ := $A54FF53A; PDWORD(@Digest[16])^ := $510E527F; PDWORD(@Digest[20])^ := $9B05688C; PDWORD(@Digest[24])^ := $1F83D9AB; PDWORD(@Digest[28])^ := $5BE0CD19; Lo := 0; inc(Lo, BufSize shl 3); Hi := 0; inc(Hi, BufSize shr 29); SwapDWORD(Lo); SwapDWORD(Hi); p := @Buf; while BufSize >= 64 do begin Compute(Digest, p); inc(p, 64); dec(BufSize, 64); end; if BufSize > 0 then CopyPtr(p, @ChunkBuf[0], BufSize); ChunkBuf[BufSize] := $80; ChunkIndex := BufSize + 1; if ChunkIndex > 56 then begin if ChunkIndex < 64 then FillPtrByte(@ChunkBuf[ChunkIndex], 64 - ChunkIndex, 0); Compute(Digest, @ChunkBuf); ChunkIndex := 0 end; FillPtrByte(@ChunkBuf[ChunkIndex], 56 - ChunkIndex, 0); PDWORD(@ChunkBuf[56])^ := Hi; PDWORD(@ChunkBuf[60])^ := Lo; Compute(Digest, @ChunkBuf); SwapDWORD(PDWORD(@Digest[0])^); SwapDWORD(PDWORD(@Digest[4])^); SwapDWORD(PDWORD(@Digest[8])^); SwapDWORD(PDWORD(@Digest[12])^); SwapDWORD(PDWORD(@Digest[16])^); SwapDWORD(PDWORD(@Digest[20])^); SwapDWORD(PDWORD(@Digest[24])^); SwapDWORD(PDWORD(@Digest[28])^); end; class procedure TSHA512.SwapQWORD(var a: UInt64); begin a := Endian(a); end; class procedure TSHA512.Compute(var Digest: TSHA512Digest; const buff: Pointer); var a, b, c, d, E, f, g, h, T1, T2: UInt64; w: array [0 .. 79] of UInt64; i: ShortInt; begin {$IFDEF RangeCheck}{$R-}{$ENDIF} a := PUInt64(@Digest[0])^; b := PUInt64(@Digest[8])^; c := PUInt64(@Digest[16])^; d := PUInt64(@Digest[24])^; E := PUInt64(@Digest[32])^; f := PUInt64(@Digest[40])^; g := PUInt64(@Digest[48])^; h := PUInt64(@Digest[56])^; CopyPtr(buff, @w[0], 128); for i := 0 to 15 do SwapQWORD(w[i]); for i := 16 to 79 do w[i] := (((w[i - 2] shr 19) or (w[i - 2] shl 45)) xor ((w[i - 2] shr 61) or (w[i - 2] shl 3)) xor (w[i - 2] shr 6)) + w[i - 7] + (((w[i - 15] shr 1) or (w[i - 15] shl 63)) xor ((w[i - 15] shr 8) or (w[i - 15] shl 56)) xor (w[i - 15] shr 7)) + w[i - 16]; T1 := h + (((E shr 14) or (E shl 50)) xor ((E shr 18) or (E shl 46)) xor ((E shr 41) or (E shl 23))) + ((E and f) xor (not E and g)) + $428A2F98D728AE22 + w[0]; T2 := (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor ((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c)); d := d + T1; h := T1 + T2; T1 := g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor ((d shr 41) or (d shl 23))) + ((d and E) xor (not d and f)) + $7137449123EF65CD + w[1]; T2 := (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor ((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b)); c := c + T1; g := T1 + T2; T1 := f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor ((c shr 41) or (c shl 23))) + ((c and d) xor (not c and E)) + $B5C0FBCFEC4D3B2F + w[2]; T2 := (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor ((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a)); b := b + T1; f := T1 + T2; T1 := E + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor ((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) + $E9B5DBA58189DBBC + w[3]; T2 := (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor ((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h)); a := a + T1; E := T1 + T2; T1 := d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor ((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) + $3956C25BF348B538 + w[4]; T2 := (((E shr 28) or (E shl 36)) xor ((E shr 34) or (E shl 30)) xor ((E shr 39) or (E shl 25))) + ((E and f) xor (E and g) xor (f and g)); h := h + T1; d := T1 + T2; T1 := c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor ((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) + $59F111F1B605D019 + w[5]; T2 := (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor ((d shr 39) or (d shl 25))) + ((d and E) xor (d and f) xor (E and f)); g := g + T1; c := T1 + T2; T1 := b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor ((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) + $923F82A4AF194F9B + w[6]; T2 := (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor ((c shr 39) or (c shl 25))) + ((c and d) xor (c and E) xor (d and E)); f := f + T1; b := T1 + T2; T1 := a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor ((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) + $AB1C5ED5DA6D8118 + w[7]; T2 := (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor ((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d)); E := E + T1; a := T1 + T2; T1 := h + (((E shr 14) or (E shl 50)) xor ((E shr 18) or (E shl 46)) xor ((E shr 41) or (E shl 23))) + ((E and f) xor (not E and g)) + $D807AA98A3030242 + w[8]; T2 := (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor ((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c)); d := d + T1; h := T1 + T2; T1 := g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor ((d shr 41) or (d shl 23))) + ((d and E) xor (not d and f)) + $12835B0145706FBE + w[9]; T2 := (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor ((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b)); c := c + T1; g := T1 + T2; T1 := f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor ((c shr 41) or (c shl 23))) + ((c and d) xor (not c and E)) + $243185BE4EE4B28C + w[10]; T2 := (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor ((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a)); b := b + T1; f := T1 + T2; T1 := E + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor ((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) + $550C7DC3D5FFB4E2 + w[11]; T2 := (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor ((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h)); a := a + T1; E := T1 + T2; T1 := d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor ((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) + $72BE5D74F27B896F + w[12]; T2 := (((E shr 28) or (E shl 36)) xor ((E shr 34) or (E shl 30)) xor ((E shr 39) or (E shl 25))) + ((E and f) xor (E and g) xor (f and g)); h := h + T1; d := T1 + T2; T1 := c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor ((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) + $80DEB1FE3B1696B1 + w[13]; T2 := (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor ((d shr 39) or (d shl 25))) + ((d and E) xor (d and f) xor (E and f)); g := g + T1; c := T1 + T2; T1 := b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor ((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) + $9BDC06A725C71235 + w[14]; T2 := (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor ((c shr 39) or (c shl 25))) + ((c and d) xor (c and E) xor (d and E)); f := f + T1; b := T1 + T2; T1 := a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor ((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) + $C19BF174CF692694 + w[15]; T2 := (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor ((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d)); E := E + T1; a := T1 + T2; T1 := h + (((E shr 14) or (E shl 50)) xor ((E shr 18) or (E shl 46)) xor ((E shr 41) or (E shl 23))) + ((E and f) xor (not E and g)) + $E49B69C19EF14AD2 + w[16]; T2 := (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor ((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c)); d := d + T1; h := T1 + T2; T1 := g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor ((d shr 41) or (d shl 23))) + ((d and E) xor (not d and f)) + $EFBE4786384F25E3 + w[17]; T2 := (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor ((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b)); c := c + T1; g := T1 + T2; T1 := f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor ((c shr 41) or (c shl 23))) + ((c and d) xor (not c and E)) + $0FC19DC68B8CD5B5 + w[18]; T2 := (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor ((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a)); b := b + T1; f := T1 + T2; T1 := E + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor ((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) + $240CA1CC77AC9C65 + w[19]; T2 := (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor ((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h)); a := a + T1; E := T1 + T2; T1 := d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor ((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) + $2DE92C6F592B0275 + w[20]; T2 := (((E shr 28) or (E shl 36)) xor ((E shr 34) or (E shl 30)) xor ((E shr 39) or (E shl 25))) + ((E and f) xor (E and g) xor (f and g)); h := h + T1; d := T1 + T2; T1 := c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor ((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) + $4A7484AA6EA6E483 + w[21]; T2 := (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor ((d shr 39) or (d shl 25))) + ((d and E) xor (d and f) xor (E and f)); g := g + T1; c := T1 + T2; T1 := b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor ((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) + $5CB0A9DCBD41FBD4 + w[22]; T2 := (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor ((c shr 39) or (c shl 25))) + ((c and d) xor (c and E) xor (d and E)); f := f + T1; b := T1 + T2; T1 := a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor ((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) + $76F988DA831153B5 + w[23]; T2 := (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor ((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d)); E := E + T1; a := T1 + T2; T1 := h + (((E shr 14) or (E shl 50)) xor ((E shr 18) or (E shl 46)) xor ((E shr 41) or (E shl 23))) + ((E and f) xor (not E and g)) + $983E5152EE66DFAB + w[24]; T2 := (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor ((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c)); d := d + T1; h := T1 + T2; T1 := g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor ((d shr 41) or (d shl 23))) + ((d and E) xor (not d and f)) + $A831C66D2DB43210 + w[25]; T2 := (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor ((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b)); c := c + T1; g := T1 + T2; T1 := f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor ((c shr 41) or (c shl 23))) + ((c and d) xor (not c and E)) + $B00327C898FB213F + w[26]; T2 := (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor ((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a)); b := b + T1; f := T1 + T2; T1 := E + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor ((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) + $BF597FC7BEEF0EE4 + w[27]; T2 := (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor ((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h)); a := a + T1; E := T1 + T2; T1 := d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor ((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) + $C6E00BF33DA88FC2 + w[28]; T2 := (((E shr 28) or (E shl 36)) xor ((E shr 34) or (E shl 30)) xor ((E shr 39) or (E shl 25))) + ((E and f) xor (E and g) xor (f and g)); h := h + T1; d := T1 + T2; T1 := c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor ((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) + $D5A79147930AA725 + w[29]; T2 := (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor ((d shr 39) or (d shl 25))) + ((d and E) xor (d and f) xor (E and f)); g := g + T1; c := T1 + T2; T1 := b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor ((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) + $06CA6351E003826F + w[30]; T2 := (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor ((c shr 39) or (c shl 25))) + ((c and d) xor (c and E) xor (d and E)); f := f + T1; b := T1 + T2; T1 := a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor ((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) + $142929670A0E6E70 + w[31]; T2 := (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor ((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d)); E := E + T1; a := T1 + T2; T1 := h + (((E shr 14) or (E shl 50)) xor ((E shr 18) or (E shl 46)) xor ((E shr 41) or (E shl 23))) + ((E and f) xor (not E and g)) + $27B70A8546D22FFC + w[32]; T2 := (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor ((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c)); d := d + T1; h := T1 + T2; T1 := g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor ((d shr 41) or (d shl 23))) + ((d and E) xor (not d and f)) + $2E1B21385C26C926 + w[33]; T2 := (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor ((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b)); c := c + T1; g := T1 + T2; T1 := f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor ((c shr 41) or (c shl 23))) + ((c and d) xor (not c and E)) + $4D2C6DFC5AC42AED + w[34]; T2 := (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor ((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a)); b := b + T1; f := T1 + T2; T1 := E + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor ((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) + $53380D139D95B3DF + w[35]; T2 := (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor ((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h)); a := a + T1; E := T1 + T2; T1 := d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor ((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) + $650A73548BAF63DE + w[36]; T2 := (((E shr 28) or (E shl 36)) xor ((E shr 34) or (E shl 30)) xor ((E shr 39) or (E shl 25))) + ((E and f) xor (E and g) xor (f and g)); h := h + T1; d := T1 + T2; T1 := c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor ((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) + $766A0ABB3C77B2A8 + w[37]; T2 := (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor ((d shr 39) or (d shl 25))) + ((d and E) xor (d and f) xor (E and f)); g := g + T1; c := T1 + T2; T1 := b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor ((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) + $81C2C92E47EDAEE6 + w[38]; T2 := (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor ((c shr 39) or (c shl 25))) + ((c and d) xor (c and E) xor (d and E)); f := f + T1; b := T1 + T2; T1 := a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor ((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) + $92722C851482353B + w[39]; T2 := (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor ((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d)); E := E + T1; a := T1 + T2; T1 := h + (((E shr 14) or (E shl 50)) xor ((E shr 18) or (E shl 46)) xor ((E shr 41) or (E shl 23))) + ((E and f) xor (not E and g)) + $A2BFE8A14CF10364 + w[40]; T2 := (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor ((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c)); d := d + T1; h := T1 + T2; T1 := g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor ((d shr 41) or (d shl 23))) + ((d and E) xor (not d and f)) + $A81A664BBC423001 + w[41]; T2 := (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor ((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b)); c := c + T1; g := T1 + T2; T1 := f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor ((c shr 41) or (c shl 23))) + ((c and d) xor (not c and E)) + $C24B8B70D0F89791 + w[42]; T2 := (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor ((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a)); b := b + T1; f := T1 + T2; T1 := E + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor ((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) + $C76C51A30654BE30 + w[43]; T2 := (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor ((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h)); a := a + T1; E := T1 + T2; T1 := d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor ((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) + $D192E819D6EF5218 + w[44]; T2 := (((E shr 28) or (E shl 36)) xor ((E shr 34) or (E shl 30)) xor ((E shr 39) or (E shl 25))) + ((E and f) xor (E and g) xor (f and g)); h := h + T1; d := T1 + T2; T1 := c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor ((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) + $D69906245565A910 + w[45]; T2 := (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor ((d shr 39) or (d shl 25))) + ((d and E) xor (d and f) xor (E and f)); g := g + T1; c := T1 + T2; T1 := b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor ((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) + $F40E35855771202A + w[46]; T2 := (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor ((c shr 39) or (c shl 25))) + ((c and d) xor (c and E) xor (d and E)); f := f + T1; b := T1 + T2; T1 := a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor ((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) + $106AA07032BBD1B8 + w[47]; T2 := (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor ((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d)); E := E + T1; a := T1 + T2; T1 := h + (((E shr 14) or (E shl 50)) xor ((E shr 18) or (E shl 46)) xor ((E shr 41) or (E shl 23))) + ((E and f) xor (not E and g)) + $19A4C116B8D2D0C8 + w[48]; T2 := (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor ((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c)); d := d + T1; h := T1 + T2; T1 := g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor ((d shr 41) or (d shl 23))) + ((d and E) xor (not d and f)) + $1E376C085141AB53 + w[49]; T2 := (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor ((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b)); c := c + T1; g := T1 + T2; T1 := f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor ((c shr 41) or (c shl 23))) + ((c and d) xor (not c and E)) + $2748774CDF8EEB99 + w[50]; T2 := (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor ((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a)); b := b + T1; f := T1 + T2; T1 := E + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor ((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) + $34B0BCB5E19B48A8 + w[51]; T2 := (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor ((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h)); a := a + T1; E := T1 + T2; T1 := d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor ((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) + $391C0CB3C5C95A63 + w[52]; T2 := (((E shr 28) or (E shl 36)) xor ((E shr 34) or (E shl 30)) xor ((E shr 39) or (E shl 25))) + ((E and f) xor (E and g) xor (f and g)); h := h + T1; d := T1 + T2; T1 := c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor ((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) + $4ED8AA4AE3418ACB + w[53]; T2 := (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor ((d shr 39) or (d shl 25))) + ((d and E) xor (d and f) xor (E and f)); g := g + T1; c := T1 + T2; T1 := b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor ((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) + $5B9CCA4F7763E373 + w[54]; T2 := (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor ((c shr 39) or (c shl 25))) + ((c and d) xor (c and E) xor (d and E)); f := f + T1; b := T1 + T2; T1 := a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor ((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) + $682E6FF3D6B2B8A3 + w[55]; T2 := (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor ((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d)); E := E + T1; a := T1 + T2; T1 := h + (((E shr 14) or (E shl 50)) xor ((E shr 18) or (E shl 46)) xor ((E shr 41) or (E shl 23))) + ((E and f) xor (not E and g)) + $748F82EE5DEFB2FC + w[56]; T2 := (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor ((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c)); d := d + T1; h := T1 + T2; T1 := g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor ((d shr 41) or (d shl 23))) + ((d and E) xor (not d and f)) + $78A5636F43172F60 + w[57]; T2 := (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor ((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b)); c := c + T1; g := T1 + T2; T1 := f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor ((c shr 41) or (c shl 23))) + ((c and d) xor (not c and E)) + $84C87814A1F0AB72 + w[58]; T2 := (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor ((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a)); b := b + T1; f := T1 + T2; T1 := E + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor ((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) + $8CC702081A6439EC + w[59]; T2 := (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor ((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h)); a := a + T1; E := T1 + T2; T1 := d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor ((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) + $90BEFFFA23631E28 + w[60]; T2 := (((E shr 28) or (E shl 36)) xor ((E shr 34) or (E shl 30)) xor ((E shr 39) or (E shl 25))) + ((E and f) xor (E and g) xor (f and g)); h := h + T1; d := T1 + T2; T1 := c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor ((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) + $A4506CEBDE82BDE9 + w[61]; T2 := (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor ((d shr 39) or (d shl 25))) + ((d and E) xor (d and f) xor (E and f)); g := g + T1; c := T1 + T2; T1 := b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor ((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) + $BEF9A3F7B2C67915 + w[62]; T2 := (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor ((c shr 39) or (c shl 25))) + ((c and d) xor (c and E) xor (d and E)); f := f + T1; b := T1 + T2; T1 := a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor ((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) + $C67178F2E372532B + w[63]; T2 := (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor ((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d)); E := E + T1; a := T1 + T2; T1 := h + (((E shr 14) or (E shl 50)) xor ((E shr 18) or (E shl 46)) xor ((E shr 41) or (E shl 23))) + ((E and f) xor (not E and g)) + $CA273ECEEA26619C + w[64]; T2 := (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor ((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c)); d := d + T1; h := T1 + T2; T1 := g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor ((d shr 41) or (d shl 23))) + ((d and E) xor (not d and f)) + $D186B8C721C0C207 + w[65]; T2 := (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor ((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b)); c := c + T1; g := T1 + T2; T1 := f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor ((c shr 41) or (c shl 23))) + ((c and d) xor (not c and E)) + $EADA7DD6CDE0EB1E + w[66]; T2 := (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor ((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a)); b := b + T1; f := T1 + T2; T1 := E + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor ((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) + $F57D4F7FEE6ED178 + w[67]; T2 := (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor ((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h)); a := a + T1; E := T1 + T2; T1 := d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor ((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) + $06F067AA72176FBA + w[68]; T2 := (((E shr 28) or (E shl 36)) xor ((E shr 34) or (E shl 30)) xor ((E shr 39) or (E shl 25))) + ((E and f) xor (E and g) xor (f and g)); h := h + T1; d := T1 + T2; T1 := c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor ((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) + $0A637DC5A2C898A6 + w[69]; T2 := (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor ((d shr 39) or (d shl 25))) + ((d and E) xor (d and f) xor (E and f)); g := g + T1; c := T1 + T2; T1 := b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor ((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) + $113F9804BEF90DAE + w[70]; T2 := (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor ((c shr 39) or (c shl 25))) + ((c and d) xor (c and E) xor (d and E)); f := f + T1; b := T1 + T2; T1 := a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor ((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) + $1B710B35131C471B + w[71]; T2 := (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor ((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d)); E := E + T1; a := T1 + T2; T1 := h + (((E shr 14) or (E shl 50)) xor ((E shr 18) or (E shl 46)) xor ((E shr 41) or (E shl 23))) + ((E and f) xor (not E and g)) + $28DB77F523047D84 + w[72]; T2 := (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor ((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c)); d := d + T1; h := T1 + T2; T1 := g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor ((d shr 41) or (d shl 23))) + ((d and E) xor (not d and f)) + $32CAAB7B40C72493 + w[73]; T2 := (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor ((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b)); c := c + T1; g := T1 + T2; T1 := f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor ((c shr 41) or (c shl 23))) + ((c and d) xor (not c and E)) + $3C9EBE0A15C9BEBC + w[74]; T2 := (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor ((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a)); b := b + T1; f := T1 + T2; T1 := E + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor ((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) + $431D67C49C100D4C + w[75]; T2 := (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor ((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h)); a := a + T1; E := T1 + T2; T1 := d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor ((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) + $4CC5D4BECB3E42B6 + w[76]; T2 := (((E shr 28) or (E shl 36)) xor ((E shr 34) or (E shl 30)) xor ((E shr 39) or (E shl 25))) + ((E and f) xor (E and g) xor (f and g)); h := h + T1; d := T1 + T2; T1 := c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor ((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) + $597F299CFC657E2A + w[77]; T2 := (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor ((d shr 39) or (d shl 25))) + ((d and E) xor (d and f) xor (E and f)); g := g + T1; c := T1 + T2; T1 := b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor ((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) + $5FCB6FAB3AD6FAEC + w[78]; T2 := (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor ((c shr 39) or (c shl 25))) + ((c and d) xor (c and E) xor (d and E)); f := f + T1; b := T1 + T2; T1 := a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor ((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) + $6C44198C4A475817 + w[79]; T2 := (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor ((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d)); E := E + T1; a := T1 + T2; inc(PUInt64(@Digest[0])^, a); inc(PUInt64(@Digest[8])^, b); inc(PUInt64(@Digest[16])^, c); inc(PUInt64(@Digest[24])^, d); inc(PUInt64(@Digest[32])^, E); inc(PUInt64(@Digest[40])^, f); inc(PUInt64(@Digest[48])^, g); inc(PUInt64(@Digest[56])^, h); {$IFDEF RangeCheck}{$R+}{$ENDIF} end; class procedure TSHA512.SHA512(var Digest: TSHA512Digest; const Buf; BufSize: UInt64); var Lo, Hi: UInt64; p: PByte; ChunkIndex: Byte; ChunkBuf: array [0 .. 127] of Byte; begin {$IFDEF RangeCheck}{$R-}{$ENDIF} {$IFDEF OverflowCheck}{$Q-}{$ENDIF} PUInt64(@Digest[0])^ := $6A09E667F3BCC908; PUInt64(@Digest[8])^ := $BB67AE8584CAA73B; PUInt64(@Digest[16])^ := $3C6EF372FE94F82B; PUInt64(@Digest[24])^ := $A54FF53A5F1D36F1; PUInt64(@Digest[32])^ := $510E527FADE682D1; PUInt64(@Digest[40])^ := $9B05688C2B3E6C1F; PUInt64(@Digest[48])^ := $1F83D9ABFB41BD6B; PUInt64(@Digest[56])^ := $5BE0CD19137E2179; Lo := 0; Hi := 0; inc(Lo, BufSize shl 3); inc(Hi, BufSize shr 61); SwapQWORD(Lo); SwapQWORD(Hi); p := @Buf; while BufSize >= 128 do begin Compute(Digest, p); inc(p, 128); dec(BufSize, 128); end; if BufSize > 0 then CopyPtr(p, @ChunkBuf[0], BufSize); ChunkBuf[BufSize] := $80; ChunkIndex := BufSize + 1; if ChunkIndex > 112 then begin if ChunkIndex < 128 then FillPtrByte(@ChunkBuf[ChunkIndex], 128 - ChunkIndex, 0); Compute(Digest, @ChunkBuf); ChunkIndex := 0 end; FillPtrByte(@ChunkBuf[ChunkIndex], 112 - ChunkIndex, 0); PUInt64(@ChunkBuf[112])^ := Hi; PUInt64(@ChunkBuf[120])^ := Lo; Compute(Digest, @ChunkBuf); SwapQWORD(PUInt64(@Digest[0])^); SwapQWORD(PUInt64(@Digest[8])^); SwapQWORD(PUInt64(@Digest[16])^); SwapQWORD(PUInt64(@Digest[24])^); SwapQWORD(PUInt64(@Digest[32])^); SwapQWORD(PUInt64(@Digest[40])^); SwapQWORD(PUInt64(@Digest[48])^); SwapQWORD(PUInt64(@Digest[56])^); {$IFDEF RangeCheck}{$R+}{$ENDIF} {$IFDEF OverflowCheck}{$Q+}{$ENDIF} end; {$IFDEF RangeCheck}{$R-}{$ENDIF} {$IFDEF OverflowCheck}{$Q-}{$ENDIF} class function TSHA3.ComputeX(const x: Integer): Integer; begin if x < 0 then Result := ComputeX(x + 5) else Result := x mod 5; end; class function TSHA3.ComputeXY(const x, y: Integer): Integer; begin Result := ComputeX(x) + 5 * ComputeX(y); end; class procedure TSHA3.BlockSHA3(var Context: TSHA3Context); var i, x, y: Integer; begin i := 0; while i < Context.BlockLen do begin Context.a[i shr 3] := Context.a[i shr 3] Xor PUInt64(@Context.Buffer[i])^; inc(i, 8); end; // keccakf for i := 0 to 23 do begin for x := 0 to 4 do Context.c[x] := Context.a[ComputeXY(x, 0)] Xor Context.a[ComputeXY(x, 1)] Xor Context.a[ComputeXY(x, 2)] Xor Context.a[ComputeXY(x, 3)] Xor Context.a[ComputeXY(x, 4)]; for x := 0 to 4 do begin Context.d[x] := Context.c[ComputeX(x - 1)] Xor ROL64(Context.c[ComputeX(x + 1)], 1); for y := 0 to 4 do Context.a[ComputeXY(x, y)] := Context.a[ComputeXY(x, y)] Xor Context.d[x]; end; for x := 0 to 4 do for y := 0 to 4 do Context.b[ComputeXY(y, x * 2 + 3 * y)] := ROL64(Context.a[ComputeXY(x, y)], RO[ComputeXY(x, y)]); for x := 0 to 4 do for y := 0 to 4 do Context.a[ComputeXY(x, y)] := Context.b[ComputeXY(x, y)] Xor ((not Context.b[ComputeXY(x + 1, y)]) And Context.b[ComputeXY(x + 2, y)]); Context.a[0] := Context.a[0] Xor RC[i]; end; Context.BufSize := 0; end; {$IFDEF RangeCheck}{$R+}{$ENDIF} {$IFDEF OverflowCheck}{$Q+}{$ENDIF} class procedure TSHA3.InitializeSHA3(var Context: TSHA3Context; HashLength: Integer); var i: Integer; begin Context.HashLength := HashLength; Context.BlockLen := 200 - 2 * HashLength; SetLength(Context.Buffer, Context.BlockLen); Context.BufSize := 0; for i := 0 to 24 do begin Context.a[i] := 0; Context.b[i] := 0; end; for i := 0 to 4 do begin Context.c[i] := 0; Context.d[i] := 0; end; end; class procedure TSHA3.SHA3(var Context: TSHA3Context; Chunk: PByte; Size: NativeInt); var Needed: NativeInt; begin while Size > 0 do begin Needed := Min(NativeInt(Context.BlockLen - Context.BufSize), Size); CopyPtr(Chunk, @Context.Buffer[Context.BufSize], Needed); inc(Context.BufSize, Needed); dec(Size, Needed); if Context.BufSize = Context.BlockLen then begin BlockSHA3(Context); Context.BufSize := 0; inc(Chunk, Needed); end; end; end; class procedure TSHA3.FinalizeSHA3(var Context: TSHA3Context; const output: PCCByteArray); var i: Integer; begin if (Context.BufSize = Context.BlockLen - 1) then Context.Buffer[Context.BufSize] := Byte($81) else begin Context.Buffer[Context.BufSize] := Byte($06); FillPtrByte(@Context.Buffer[Context.BufSize + 1], (Context.BlockLen - 2) - (Context.BufSize + 1), 0); Context.Buffer[Context.BlockLen - 1] := Byte($80); end; BlockSHA3(Context); i := 0; while i < Context.HashLength do begin PUInt64(@output^[i])^ := Context.a[i shr 3]; inc(i, 8); end; for i := 0 to 24 do Context.a[i] := 0; Context.BufSize := 0; SetLength(Context.Buffer, 0); end; class procedure TSHA3.FinalizeSHAKE(var Context: TSHA3Context; Limit: Integer; const output: PCCByteArray); var tmp: array of Byte; i, k, Size: Integer; begin if Context.BufSize = Context.BlockLen - 1 then Context.Buffer[Context.BufSize] := Byte($9F) else begin Context.Buffer[Context.BufSize] := Byte($1F); FillPtrByte(@Context.Buffer[Context.BufSize + 1], (Context.BlockLen - 2) - (Context.BufSize + 1), 0); Context.Buffer[Context.BlockLen - 1] := Byte($80); end; BlockSHA3(Context); FillPtrByte(@Context.Buffer[0], length(Context.Buffer), 0); SetLength(tmp, Context.BlockLen); k := 0; while True do begin i := 0; while i < Context.BlockLen do begin PUInt64(@tmp[i])^ := Context.a[i shr 3]; inc(i, 8); end; Size := Min(Limit, Context.BlockLen); CopyPtr(@tmp[0], @output^[k], Min(Size, Limit - k)); dec(Limit, Size); inc(k, Size); if Limit <= 0 then Break; BlockSHA3(Context); end; for i := 0 to 24 do Context.a[i] := 0; Context.BufSize := 0; SetLength(Context.Buffer, 0); end; class procedure TSHA3.SHA224(var Digest: TSHA3_224_Digest; Buf: PByte; BufSize: NativeInt); var Ctx: TSHA3Context; begin InitializeSHA3(Ctx, 224 div 8); SHA3(Ctx, Buf, BufSize); FinalizeSHA3(Ctx, @Digest[0]); end; class procedure TSHA3.SHA256(var Digest: TSHA3_256_Digest; Buf: PByte; BufSize: NativeInt); var Ctx: TSHA3Context; begin InitializeSHA3(Ctx, 256 div 8); SHA3(Ctx, Buf, BufSize); FinalizeSHA3(Ctx, @Digest[0]); end; class procedure TSHA3.SHA384(var Digest: TSHA3_384_Digest; Buf: PByte; BufSize: NativeInt); var Ctx: TSHA3Context; begin InitializeSHA3(Ctx, 384 div 8); SHA3(Ctx, Buf, BufSize); FinalizeSHA3(Ctx, @Digest[0]); end; class procedure TSHA3.SHA512(var Digest: TSHA3_512_Digest; Buf: PByte; BufSize: NativeInt); var Ctx: TSHA3Context; begin InitializeSHA3(Ctx, 512 div 8); SHA3(Ctx, Buf, BufSize); FinalizeSHA3(Ctx, @Digest[0]); end; class procedure TSHA3.SHAKE128(const Digest: PCCByteArray; Buf: PByte; BufSize: NativeInt; Limit: Integer); var Ctx: TSHA3Context; begin InitializeSHA3(Ctx, 128 div 8); SHA3(Ctx, Buf, BufSize); FinalizeSHAKE(Ctx, Limit div 8, Digest); end; class procedure TSHA3.SHAKE256(const Digest: PCCByteArray; Buf: PByte; BufSize: NativeInt; Limit: Integer); var Ctx: TSHA3Context; begin InitializeSHA3(Ctx, 256 div 8); SHA3(Ctx, Buf, BufSize); FinalizeSHAKE(Ctx, Limit div 8, Digest); end; { TLBC } class procedure TLBC.EncryptLBC(const Context: TLBCContext; var Block: TLBCBlock); var Blocks: array [0 .. 1] of TBCHalfBlock; { !!.01 } Work: TBCHalfBlock; Right: TBCHalfBlock; Left: TBCHalfBlock; AA, BB: Integer; CC, DD: Integer; r, t: Integer; begin CopyPtr(@Block, @Blocks, SizeOf(Blocks)); { !!.01 } Right := Blocks[0]; Left := Blocks[1]; for r := 0 to Context.Rounds - 1 do begin { transform the right side } AA := Right[0]; BB := TBCHalfBlock(Context.SubKeys64[r])[0]; CC := Right[1]; DD := TBCHalfBlock(Context.SubKeys64[r])[1]; { mix it once... } AA := AA + DD; DD := DD + AA; AA := AA xor (AA shr 7); BB := BB + AA; AA := AA + BB; BB := BB xor (BB shl 13); CC := CC + BB; BB := BB + CC; CC := CC xor (CC shr 17); DD := DD + CC; CC := CC + DD; DD := DD xor (DD shl 9); AA := AA + DD; DD := DD + AA; AA := AA xor (AA shr 3); BB := BB + AA; AA := AA + BB; BB := BB xor (BB shl 7); CC := CC + BB; BB := BB + CC; CC := CC xor (DD shr 15); DD := DD + CC; CC := CC + DD; DD := DD xor (DD shl 11); { swap sets... } t := AA; AA := CC; CC := t; t := BB; BB := DD; DD := t; { mix it twice } AA := AA + DD; DD := DD + AA; AA := AA xor (AA shr 7); BB := BB + AA; AA := AA + BB; BB := BB xor (BB shl 13); CC := CC + BB; BB := BB + CC; CC := CC xor (CC shr 17); DD := DD + CC; CC := CC + DD; DD := DD xor (DD shl 9); AA := AA + DD; DD := DD + AA; AA := AA xor (AA shr 3); BB := BB + AA; AA := AA + BB; BB := BB xor (BB shl 7); CC := CC + BB; BB := BB + CC; CC := CC xor (DD shr 15); DD := DD + CC; CC := CC + DD; DD := DD xor (DD shl 11); Work[0] := Left[0] xor AA xor BB; Work[1] := Left[1] xor CC xor DD; Left := Right; Right := Work; end; Blocks[0] := Left; Blocks[1] := Right; CopyPtr(@Blocks, @Block, SizeOf(Block)); { !!.01 } end; class procedure TLBC.EncryptLQC(const key: TKey128; var Block: TLQCBlock; Encrypt: Boolean); const CKeyBox: array [False .. True, 0 .. 3, 0 .. 2] of Integer = (((0, 3, 1), (2, 1, 3), (1, 0, 2), (3, 2, 0)), ((3, 2, 0), (1, 0, 2), (2, 1, 3), (0, 3, 1))); var KeyInts: array [0 .. 3] of Integer; { !!.01 } Blocks: array [0 .. 1] of Integer; { !!.01 } Work: Integer; Right: Integer; Left: Integer; r: Integer; AA, BB: Integer; CC, DD: Integer; begin CopyPtr(@key, @KeyInts, SizeOf(KeyInts)); { !!.01 } CopyPtr(@Block, @Blocks, SizeOf(Blocks)); { !!.01 } Right := Blocks[0]; Left := Blocks[1]; for r := 0 to 3 do begin { transform the right side } AA := Right; BB := KeyInts[CKeyBox[Encrypt, r, 0]]; CC := KeyInts[CKeyBox[Encrypt, r, 1]]; DD := KeyInts[CKeyBox[Encrypt, r, 2]]; { commented code does not affect results - removed for speed } AA := AA + DD; DD := DD + AA; AA := AA xor (AA shr 7); BB := BB + AA; AA := AA + BB; BB := BB xor (BB shl 13); CC := CC + BB; BB := BB + CC; CC := CC xor (CC shr 17); DD := DD + CC; CC := CC + DD; DD := DD xor (DD shl 9); AA := AA + DD; DD := DD + AA; AA := AA xor (AA shr 3); BB := BB + AA; { AA := AA + BB; } BB := BB xor (BB shl 7); CC := CC + BB; { BB := BB + CC; } CC := CC xor (DD shr 15); DD := DD + CC; { CC := CC + DD; } DD := DD xor (DD shl 11); Work := Left xor DD; Left := Right; Right := Work; end; Blocks[0] := Left; Blocks[1] := Right; CopyPtr(@Blocks, @Block, SizeOf(Block)); { !!.01 } end; class procedure TLBC.InitEncryptLBC(const key: TKey128; var Context: TLBCContext; Rounds: Integer; Encrypt: Boolean); type TDCPTFSubKeys = packed record case Byte of 0: (SubKeys64: array [0 .. 15] of TKey64); 1: (SubKeysInts: array [0 .. 3, 0 .. 7] of DWORD); end; var KeyArray: PDWordArray; AA, BB: DWORD; CC, DD: DWORD; EE, FF: DWORD; GG, hh: DWORD; i, r: Integer; Temp: TDCPTFSubKeys; begin KeyArray := @key; Context.Encrypt := Encrypt; Context.Rounds := Max(4, Min(16, Rounds)); { fill subkeys by propagating seed } for i := 0 to 3 do begin { interleave the key with the salt } AA := KeyArray^[0]; BB := BCSalts[i]; CC := KeyArray^[1]; DD := BCSalts[i]; EE := KeyArray^[2]; FF := BCSalts[i]; GG := KeyArray^[3]; hh := BCSalts[i]; { mix all the bits around for 8 rounds } { achieves avalanche and eliminates funnels } for r := 0 to 7 do begin AA := AA xor (BB shl 11); DD := DD + AA; BB := BB + CC; BB := BB xor (CC shr 2); EE := EE + BB; CC := CC + DD; CC := CC xor (DD shl 8); FF := FF + CC; DD := DD + EE; DD := DD xor (EE shr 16); GG := GG + DD; EE := EE + FF; EE := EE xor (FF shl 10); hh := hh + EE; FF := FF + GG; FF := FF xor (GG shr 4); AA := AA + FF; GG := GG + hh; GG := GG xor (hh shl 8); BB := BB + GG; hh := hh + AA; hh := hh xor (AA shr 9); CC := CC + hh; AA := AA + BB; end; { assign value to subkey } Context.SubKeysInts[i, 0] := AA; Context.SubKeysInts[i, 1] := BB; Context.SubKeysInts[i, 2] := CC; Context.SubKeysInts[i, 3] := DD; Context.SubKeysInts[i, 4] := EE; Context.SubKeysInts[i, 5] := FF; Context.SubKeysInts[i, 6] := GG; Context.SubKeysInts[i, 7] := hh; end; { reverse subkeys if decrypting - easier for EncryptLBC routine } if not Encrypt then begin for i := 0 to Context.Rounds - 1 do Temp.SubKeys64[(Context.Rounds - 1) - i] := Context.SubKeys64[i]; for i := 0 to Context.Rounds - 1 do Context.SubKeys64[i] := Temp.SubKeys64[i]; end; end; class procedure THashMD5.GenerateMD5Key(var key: TKey128; const Bytes_: TBytes); var d: TMD5Digest; begin HashMD5(d, Bytes_[0], length(Bytes_)); end; class procedure THashMD5.HashMD5(var Digest: TMD5Digest; const Buf; BufSize: NativeInt); var Context: TMD5Context; begin FillPtrByte(@Context, SizeOf(Context), $00); InitMD5(Context); UpdateMD5(Context, Buf, BufSize); FinalizeMD5(Context, Digest); end; class procedure THashMD5.ByteBuffHashMD5(var Digest: TMD5Digest; const Bytes_: TBytes); begin HashMD5(Digest, Bytes_[0], length(Bytes_)); end; class procedure THashMD5.InitMD5(var Context: TMD5Context); begin Context.Count[0] := 0; Context.Count[1] := 0; { load magic initialization constants } Context.State[0] := $67452301; Context.State[1] := $EFCDAB89; Context.State[2] := $98BADCFE; Context.State[3] := $10325476; end; class procedure THashMD5.UpdateMD5(var Context: TMD5Context; const Buf; BufSize: NativeInt); var InBuf: TTransformInput; BufOfs: DWORD; MDI: DWORD; i: DWORD; begin // { compute number of bytes mod 64 } MDI := (Context.Count[0] shr 3) and $3F; // { update number of bits } if BufSize shl 3 < 0 then inc(Context.Count[1]); inc(Context.Count[0], BufSize shl 3); inc(Context.Count[1], BufSize shr 29); { add new byte acters to buffer } BufOfs := 0; while (BufSize > 0) do begin dec(BufSize); Context.Buf[MDI] := TCCByteArray(Buf)[BufOfs]; { !!.01 } inc(MDI); inc(BufOfs); if (MDI = $40) then begin for i := 0 to 15 do InBuf[i] := PDWORD(@Context.Buf[i * 4])^; TMISC.Transform(Context.State, InBuf); MDI := 0; end; end; end; { THashMD5 } class procedure THashMD5.FinalizeMD5(var Context: TMD5Context; var Digest: TMD5Digest); const Padding: array [0 .. 63] of Byte = ( $80, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00); var InBuf: TTransformInput; MDI: Integer; i: Word; II: Word; PadLen: Word; begin { save number of bits } InBuf[14] := Context.Count[0]; InBuf[15] := Context.Count[1]; { compute number of bytes mod 64 } MDI := (Context.Count[0] shr 3) and $3F; { pad out to 56 mod 64 } if (MDI < 56) then PadLen := 56 - MDI else PadLen := 120 - MDI; UpdateMD5(Context, Padding, PadLen); CopyPtr(@Context, @Context, SizeOf(Context)); { !!.01 } { append length in bits and transform } II := 0; for i := 0 to 13 do begin InBuf[i] := (DWORD(Context.Buf[II + 3]) shl 24) or (DWORD(Context.Buf[II + 2]) shl 16) or (DWORD(Context.Buf[II + 1]) shl 8) or DWORD(Context.Buf[II]); inc(II, 4); end; TMISC.Transform(Context.State, InBuf); { store buffer in digest } II := 0; for i := 0 to 3 do begin Digest[II] := Byte(Context.State[i] and $FF); Digest[II + 1] := Byte((Context.State[i] shr 8) and $FF); Digest[II + 2] := Byte((Context.State[i] shr 16) and $FF); Digest[II + 3] := Byte((Context.State[i] shr 24) and $FF); inc(II, 4); end; end; { TRNG } class procedure TRNG.EncryptRNG32(var Context: TRNG32Context; var Buf; BufSize: Integer); var i: Integer; begin for i := 0 to BufSize - 1 do TCCByteArray(Buf)[i] := TCCByteArray(Buf)[i] xor { !!.01 } TMISC.Random32Byte(Integer(Context)); end; class procedure TRNG.EncryptRNG64(var Context: TRNG64Context; var Buf; BufSize: Integer); var i: Integer; begin for i := 0 to BufSize - 1 do TCCByteArray(Buf)[i] := TCCByteArray(Buf)[i] xor { !!.01 } TMISC.Random64Byte(TInt64(Context)); end; class procedure TRNG.InitEncryptRNG32(key: DWORD; var Context: TRNG32Context); begin DWORD(Context) := key; end; class procedure TRNG.InitEncryptRNG64(KeyHi, KeyLo: DWORD; var Context: TRNG64Context); begin TInt64(Context).Lo := Integer(KeyLo); TInt64(Context).Hi := Integer(KeyHi); end; class procedure THashMD.GenerateLMDKey(var key; KeySize: Integer; const Bytes_: TBytes); begin HashLMD(key, KeySize, Bytes_[0], length(Bytes_)); end; class procedure THashMD.HashLMD(var Digest; DigestSize: Integer; const Buf; BufSize: NativeInt); var Context: TLMDContext; begin InitLMD(Context); UpdateLMD(Context, Buf, BufSize); FinalizeLMD(Context, Digest, DigestSize); end; class procedure THashMD.ByteBuffHashLMD(var Digest; DigestSize: Integer; const Bytes_: TBytes); begin HashLMD(Digest, DigestSize, Bytes_[0], length(Bytes_)); end; class procedure THashMD.InitLMD(var Context: TLMDContext); begin Context.DigestIndex := 0; TBlock2048(Context.Digest) := TBlock2048(Pi2048); Context.KeyIndex := 0; Context.KeyInts[0] := $55555555; Context.KeyInts[1] := $55555555; Context.KeyInts[2] := $55555555; Context.KeyInts[3] := $55555555; end; class procedure THashMD.UpdateLMD(var Context: TLMDContext; const Buf; BufSize: NativeInt); var AA, BB, CC, DD: DWORD; i, r: NativeInt; begin for i := 0 to BufSize - 1 do with Context do begin { update Digest } Digest[DigestIndex] := Digest[DigestIndex] xor TCCByteArray(Buf)[i]; { !!.01 } DigestIndex := DigestIndex + 1; if (DigestIndex = SizeOf(Digest)) then DigestIndex := 0; { update BlockKey } key[KeyIndex] := key[KeyIndex] xor TCCByteArray(Buf)[i]; { !!.01 } KeyIndex := KeyIndex + 1; if (KeyIndex = SizeOf(key) div 2) then begin AA := KeyInts[3]; BB := KeyInts[2]; CC := KeyInts[1]; DD := KeyInts[0]; { mix all the bits around for 4 rounds } { achieves avalanche and eliminates funnels } for r := 0 to 3 do begin inc(AA, DD); inc(DD, AA); AA := AA xor (AA shr 7); inc(BB, AA); inc(AA, BB); BB := BB xor (BB shl 13); inc(CC, BB); inc(BB, CC); CC := CC xor (CC shr 17); inc(DD, CC); inc(CC, DD); DD := DD xor (DD shl 9); inc(AA, DD); inc(DD, AA); AA := AA xor (AA shr 3); inc(BB, AA); inc(AA, BB); BB := BB xor (BB shl 7); inc(CC, BB); inc(BB, CC); CC := CC xor (DD shr 15); inc(DD, CC); inc(CC, DD); DD := DD xor (DD shl 11); end; KeyInts[0] := AA; KeyInts[1] := BB; KeyInts[2] := CC; KeyInts[3] := DD; KeyIndex := 0; end; end; end; { THashMD } class procedure THashMD.FinalizeLMD(var Context: TLMDContext; var Digest; DigestSize: Integer); const Padding: array [0 .. 7] of Byte = (1, 0, 0, 0, 0, 0, 0, 0); var BCContext: TLBCContext; i: Integer; begin { pad with "1", followed by as many "0"s as needed to fill the block } UpdateLMD(Context, Padding, SizeOf(Padding) - Context.KeyIndex); { mix context using block cipher } TLBC.InitEncryptLBC(Context.key, BCContext, 8, True); for i := 0 to (SizeOf(Context.Digest) div SizeOf(TLBCBlock)) - 1 do TLBC.EncryptLBC(BCContext, PLBCBlock(@Context.Digest[i * SizeOf(TLBCBlock)])^); { return Digest of requested DigestSize } { max digest is 2048-bit, although it could be greater if Pi2048 was larger } if DigestSize > SizeOf(Context.Digest) then FillPtrByte(@Digest, DigestSize, 0); CopyPtr(@Context.Digest, @Digest, Min(SizeOf(Context.Digest), DigestSize)); end; { TLSC } class procedure TLSC.EncryptLSC(var Context: TLSCContext; var Buf; BufSize: Integer); var l, y, x: Integer; i, a: Integer; begin i := Context.index; a := Context.Accumulator; for l := 0 to BufSize - 1 do begin i := i + 1; x := Context.SBox[Byte(i)]; y := Context.SBox[Byte(x)] + x; Context.SBox[Byte(i)] := Context.SBox[Byte(y)]; Context.SBox[Byte(y)] := x; a := a + Context.SBox[Byte(Byte(y shr 8) + Byte(y))]; TCCByteArray(Buf)[l] := TCCByteArray(Buf)[l] xor Byte(a); { !!.01 } end; Context.index := i; Context.Accumulator := a; end; class procedure TLSC.InitEncryptLSC(const key; KeySize: Integer; var Context: TLSCContext); var r, i, a: Integer; x: Byte; begin { initialize SBox } for i := 0 to 255 do Context.SBox[i] := i; a := 0; for r := 0 to 2 do { 3 rounds - "A" accumulates } for i := 0 to 255 do begin a := a + Context.SBox[i] + TCCByteArray(key)[i mod KeySize]; { !!.01 } x := Context.SBox[i]; Context.SBox[i] := Context.SBox[Byte(a)]; Context.SBox[Byte(a)] := x; end; Context.index := 0; Context.Accumulator := a; end; { TMISC } class procedure TMISC.GenerateRandomKey(var key; KeySize: Integer); var i: Integer; begin MT19937Randomize; for i := 0 to KeySize - 1 do TCCByteArray(key)[i] := MT19937Rand32(256); { !!.01 } end; class procedure TMISC.HashELF(var Digest: DWORD; const Buf; BufSize: NativeUInt); var i: NativeUInt; x: DWORD; begin Digest := 0; for i := 0 to BufSize - 1 do begin Digest := (Digest shl 4) + TCCByteArray(Buf)[i]; { !!.01 } x := Digest and $F0000000; if (x <> 0) then Digest := Digest xor (x shr 24); Digest := Digest and (not x); end; end; class procedure TMISC.HashELF64(var Digest: Int64; const Buf; BufSize: NativeUInt); var i: NativeUInt; x: Int64; begin Digest := 0; for i := 0 to BufSize - 1 do begin Digest := (Digest shl 4) + TCCByteArray(Buf)[i]; { !!.01 } x := Digest and Int64($F000000000000000); if (x <> 0) then Digest := Digest xor (x shr 56); Digest := Digest and (not x); end; end; class procedure TMISC.HashMix128(var Digest: DWORD; const Buf; BufSize: NativeInt); type T128BitArray = array [0 .. MaxStructSize div SizeOf(T128Bit) - 1] of T128Bit; var Temp: T128Bit; PTemp: PCCByteArray; i, l: NativeInt; begin {$IFDEF RangeCheck}{$R-}{$ENDIF} Temp[0] := $243F6A88; { first 16 bytes of Pi in binary } Temp[1] := $93F40317; Temp[2] := $0C110496; Temp[3] := $C709C289; l := BufSize div SizeOf(T128Bit); for i := 0 to l - 1 do begin Temp[0] := Temp[0] + T128BitArray(Buf)[i][0]; { !!.01 } Temp[1] := Temp[1] + T128BitArray(Buf)[i][1]; { !!.01 } Temp[2] := Temp[2] + T128BitArray(Buf)[i][2]; { !!.01 } Temp[3] := Temp[3] + T128BitArray(Buf)[i][3]; { !!.01 } Mix128(Temp); end; PTemp := @Temp; if (BufSize > l * SizeOf(T128Bit)) then begin for i := 0 to (BufSize - l * SizeOf(T128Bit)) - 1 do inc(PTemp^[i], PCCByteArray(@Buf)^[(l * SizeOf(T128Bit)) + i]); { !!.01 } Mix128(Temp); end; Digest := Temp[3]; {$IFDEF RangeCheck}{$R+}{$ENDIF} end; class procedure TMISC.Mix128(var x: T128Bit); var AA, BB, CC, DD: DWORD; begin AA := x[0]; BB := x[1]; CC := x[2]; DD := x[3]; AA := AA + DD; DD := DD + AA; AA := AA xor (AA shr 7); BB := BB + AA; AA := AA + BB; BB := BB xor (BB shl 13); CC := CC + BB; BB := BB + CC; CC := CC xor (CC shr 17); DD := DD + CC; CC := CC + DD; DD := DD xor (DD shl 9); AA := AA + DD; DD := DD + AA; AA := AA xor (AA shr 3); BB := BB + AA; AA := AA + BB; BB := BB xor (BB shl 7); CC := CC + BB; BB := BB + CC; CC := CC xor (DD shr 15); DD := DD + CC; CC := CC + DD; DD := DD xor (DD shl 11); x[0] := AA; x[1] := BB; x[2] := CC; x[3] := DD; end; class function TMISC.Ran01(var Seed: Integer): Integer; begin Result := Ran0Prim(Seed, 16807, 127773, 2836); end; class function TMISC.Ran02(var Seed: Integer): Integer; begin Result := Ran0Prim(Seed, 48271, 44488, 3399); end; class function TMISC.Ran03(var Seed: Integer): Integer; begin Result := Ran0Prim(Seed, 69621, 30845, 23902); end; class function TMISC.Ran0Prim(var Seed: Integer; IA, IQ, IR: Integer): Integer; const IM = 2147483647; MA = 123459876; var i, k: Integer; begin { XORing with mask avoids seeds of zero } i := Seed xor MA; k := i div IQ; i := (IA * (i - (k * IQ))) - (IR * k); if i < 0 then i := i + IM; Result := i xor MA; Seed := Result; end; class function TMISC.Random32Byte(var Seed: Integer): Byte; var l: Integer; r: TInt32; begin l := Ran01(Seed); r := TInt32(l); Result := r.LoLo xor r.LoHi xor r.HiLo xor r.HiHi; end; class function TMISC.Random64(var Seed: TInt64): Integer; begin Ran01(Seed.Lo); Ran01(Seed.Hi); Result := Seed.Lo xor Seed.Hi; end; class function TMISC.Random64Byte(var Seed: TInt64): Byte; var l: Integer; r: TInt32; begin l := Random64(Seed); r := TInt32(l); Result := r.LoLo xor r.LoHi xor r.HiLo xor r.HiHi; end; class function TMISC.RolX(i, c: DWORD): DWORD; begin Result := (i shl (c and 31)) or (i shr (32 - (c and 31))); end; class procedure TMISC.ByteBuffHashELF(var Digest: DWORD; const Bytes_: TBytes); begin HashELF(Digest, Bytes_[0], length(Bytes_)); end; class procedure TMISC.ByteBuffHashMix128(var Digest: DWORD; const Bytes_: TBytes); begin HashMix128(Digest, Bytes_[0], length(Bytes_)); end; class procedure TMISC.Transform(var OutputBuffer: TTransformOutput; var InBuf: TTransformInput); const S11 = 7; S12 = 12; S13 = 17; S14 = 22; S21 = 5; S22 = 9; S23 = 14; S24 = 20; S31 = 4; S32 = 11; S33 = 16; S34 = 23; S41 = 6; S42 = 10; S43 = 15; S44 = 21; var a: DWORD; b: DWORD; c: DWORD; d: DWORD; procedure FF(var a: DWORD; const b, c, d, x, s, AC: DWORD); begin a := RolX(a + ((b and c) or (not b and d)) + x + AC, s) + b; end; procedure GG(var a: DWORD; const b, c, d, x, s, AC: DWORD); begin a := RolX(a + ((b and d) or (c and not d)) + x + AC, s) + b; end; procedure hh(var a: DWORD; const b, c, d, x, s, AC: DWORD); begin a := RolX(a + (b xor c xor d) + x + AC, s) + b; end; procedure II(var a: DWORD; const b, c, d, x, s, AC: DWORD); begin a := RolX(a + (c xor (b or not d)) + x + AC, s) + b; end; begin a := OutputBuffer[0]; b := OutputBuffer[1]; c := OutputBuffer[2]; d := OutputBuffer[3]; { round 1 } FF(a, b, c, d, InBuf[0], S11, $D76AA478); { 1 } FF(d, a, b, c, InBuf[1], S12, $E8C7B756); { 2 } FF(c, d, a, b, InBuf[2], S13, $242070DB); { 3 } FF(b, c, d, a, InBuf[3], S14, $C1BDCEEE); { 4 } FF(a, b, c, d, InBuf[4], S11, $F57C0FAF); { 5 } FF(d, a, b, c, InBuf[5], S12, $4787C62A); { 6 } FF(c, d, a, b, InBuf[6], S13, $A8304613); { 7 } FF(b, c, d, a, InBuf[7], S14, $FD469501); { 8 } FF(a, b, c, d, InBuf[8], S11, $698098D8); { 9 } FF(d, a, b, c, InBuf[9], S12, $8B44F7AF); { 10 } FF(c, d, a, b, InBuf[10], S13, $FFFF5BB1); { 11 } FF(b, c, d, a, InBuf[11], S14, $895CD7BE); { 12 } FF(a, b, c, d, InBuf[12], S11, $6B901122); { 13 } FF(d, a, b, c, InBuf[13], S12, $FD987193); { 14 } FF(c, d, a, b, InBuf[14], S13, $A679438E); { 15 } FF(b, c, d, a, InBuf[15], S14, $49B40821); { 16 } { round 2 } GG(a, b, c, d, InBuf[1], S21, $F61E2562); { 17 } GG(d, a, b, c, InBuf[6], S22, $C040B340); { 18 } GG(c, d, a, b, InBuf[11], S23, $265E5A51); { 19 } GG(b, c, d, a, InBuf[0], S24, $E9B6C7AA); { 20 } GG(a, b, c, d, InBuf[5], S21, $D62F105D); { 21 } GG(d, a, b, c, InBuf[10], S22, $02441453); { 22 } GG(c, d, a, b, InBuf[15], S23, $D8A1E681); { 23 } GG(b, c, d, a, InBuf[4], S24, $E7D3FBC8); { 24 } GG(a, b, c, d, InBuf[9], S21, $21E1CDE6); { 25 } GG(d, a, b, c, InBuf[14], S22, $C33707D6); { 26 } GG(c, d, a, b, InBuf[3], S23, $F4D50D87); { 27 } GG(b, c, d, a, InBuf[8], S24, $455A14ED); { 28 } GG(a, b, c, d, InBuf[13], S21, $A9E3E905); { 29 } GG(d, a, b, c, InBuf[2], S22, $FCEFA3F8); { 30 } GG(c, d, a, b, InBuf[7], S23, $676F02D9); { 31 } GG(b, c, d, a, InBuf[12], S24, $8D2A4C8A); { 32 } { round 3 } hh(a, b, c, d, InBuf[5], S31, $FFFA3942); { 33 } hh(d, a, b, c, InBuf[8], S32, $8771F681); { 34 } hh(c, d, a, b, InBuf[11], S33, $6D9D6122); { 35 } hh(b, c, d, a, InBuf[14], S34, $FDE5380C); { 36 } hh(a, b, c, d, InBuf[1], S31, $A4BEEA44); { 37 } hh(d, a, b, c, InBuf[4], S32, $4BDECFA9); { 38 } hh(c, d, a, b, InBuf[7], S33, $F6BB4B60); { 39 } hh(b, c, d, a, InBuf[10], S34, $BEBFBC70); { 40 } hh(a, b, c, d, InBuf[13], S31, $289B7EC6); { 41 } hh(d, a, b, c, InBuf[0], S32, $EAA127FA); { 42 } hh(c, d, a, b, InBuf[3], S33, $D4EF3085); { 43 } hh(b, c, d, a, InBuf[6], S34, $4881D05); { 44 } hh(a, b, c, d, InBuf[9], S31, $D9D4D039); { 45 } hh(d, a, b, c, InBuf[12], S32, $E6DB99E5); { 46 } hh(c, d, a, b, InBuf[15], S33, $1FA27CF8); { 47 } hh(b, c, d, a, InBuf[2], S34, $C4AC5665); { 48 } { round 4 } II(a, b, c, d, InBuf[0], S41, $F4292244); { 49 } II(d, a, b, c, InBuf[7], S42, $432AFF97); { 50 } II(c, d, a, b, InBuf[14], S43, $AB9423A7); { 51 } II(b, c, d, a, InBuf[5], S44, $FC93A039); { 52 } II(a, b, c, d, InBuf[12], S41, $655B59C3); { 53 } II(d, a, b, c, InBuf[3], S42, $8F0CCC92); { 54 } II(c, d, a, b, InBuf[10], S43, $FFEFF47D); { 55 } II(b, c, d, a, InBuf[1], S44, $85845DD1); { 56 } II(a, b, c, d, InBuf[8], S41, $6FA87E4F); { 57 } II(d, a, b, c, InBuf[15], S42, $FE2CE6E0); { 58 } II(c, d, a, b, InBuf[6], S43, $A3014314); { 59 } II(b, c, d, a, InBuf[13], S44, $4E0811A1); { 60 } II(a, b, c, d, InBuf[4], S41, $F7537E82); { 61 } II(d, a, b, c, InBuf[11], S42, $BD3AF235); { 62 } II(c, d, a, b, InBuf[2], S43, $2AD7D2BB); { 63 } II(b, c, d, a, InBuf[9], S44, $EB86D391); { 64 } inc(OutputBuffer[0], a); inc(OutputBuffer[1], b); inc(OutputBuffer[2], c); inc(OutputBuffer[3], d); end; class procedure TMISC.XorMem(var Mem1; const Mem2; Count: NativeInt); var siz: Byte; i: Integer; p1, p2: NativeUInt; begin p1 := NativeUInt(@Mem1); p2 := NativeUInt(@Mem2); siz := SizeOf(NativeUInt); for i := 1 to Count div siz do begin PNativeUInt(p1)^ := PNativeUInt(p1)^ xor PNativeUInt(p2)^; p1 := p1 + siz; p2 := p2 + siz; end; for i := 1 to Count mod siz do begin PByte(p1)^ := PByte(p1)^ xor PByte(p2)^; p1 := p1 + 1; p2 := p2 + 1; end; end; function XXTeaMX(Sum, y, z, p, E: DWORD; const k: PDWordArray): DWORD; begin {$IFDEF OverflowCheck}{$Q-}{$ENDIF} {$IFDEF RangeCheck}{$R-}{$ENDIF} Result := (((z shr 5) xor (y shl 2)) + ((y shr 3) xor (z shl 4))) xor ((Sum xor y) + (k^[p and 3 xor E] xor z)); {$IFDEF RangeCheck}{$R+}{$ENDIF} {$IFDEF OverflowCheck}{$Q+}{$ENDIF} end; procedure XXTEAEncrypt(var key: TKey128; var Block: TXXTEABlock); const XXTeaDelta = $9E3779B9; var k, v: PDWordArray; n, z, y, Sum, E, p, q: DWORD; begin {$IFDEF RangeCheck}{$R-}{$ENDIF} n := 64 div 4 - 1; k := PDWordArray(@key[0]); v := PDWordArray(@Block[0]); z := v^[n]; Sum := 0; q := 6 + 52 div (n + 1); repeat inc(Sum, XXTeaDelta); E := (Sum shr 2) and 3; for p := 0 to n - 1 do begin y := v^[p + 1]; inc(v^[p], XXTeaMX(Sum, y, z, p, E, k)); z := v^[p]; end; p := n; y := v^[0]; inc(v^[p], XXTeaMX(Sum, y, z, p, E, k)); z := v^[p]; dec(q); until q = 0; {$IFDEF RangeCheck}{$R+}{$ENDIF} end; procedure XXTEADecrypt(var key: TKey128; var Block: TXXTEABlock); const XXTeaDelta = $9E3779B9; var k, v: PDWordArray; n, z, y, Sum, E, p, q: DWORD; begin {$IFDEF RangeCheck}{$R-}{$ENDIF} n := 64 div 4 - 1; k := PDWordArray(@key[0]); v := PDWordArray(@Block[0]); y := v^[0]; q := 6 + 52 div (n + 1); Sum := q * XXTeaDelta; while (Sum <> 0) do begin E := (Sum shr 2) and 3; for p := n downto 1 do begin z := v^[p - 1]; dec(v^[p], XXTeaMX(Sum, y, z, p, E, k)); y := v^[p]; end; p := 0; z := v^[n]; dec(v^[0], XXTeaMX(Sum, y, z, p, E, k)); y := v^[0]; dec(Sum, XXTeaDelta); end; {$IFDEF RangeCheck}{$R+}{$ENDIF} end; class function TRC6.LRot32(x, c: DWORD): DWORD; begin LRot32 := ROL32(x, Byte(c)); end; class function TRC6.RRot32(x, c: DWORD): DWORD; begin RRot32 := ROR32(x, Byte(c)) end; class procedure TRC6.InitKey(buff: Pointer; Size: Integer; var KeyContext: TRC6Key); const cRC6_sBox: array [0 .. 51] of DWORD = ( $B7E15163, $5618CB1C, $F45044D5, $9287BE8E, $30BF3847, $CEF6B200, $6D2E2BB9, $0B65A572, $A99D1F2B, $47D498E4, $E60C129D, $84438C56, $227B060F, $C0B27FC8, $5EE9F981, $FD21733A, $9B58ECF3, $399066AC, $D7C7E065, $75FF5A1E, $1436D3D7, $B26E4D90, $50A5C749, $EEDD4102, $8D14BABB, $2B4C3474, $C983AE2D, $67BB27E6, $05F2A19F, $A42A1B58, $42619511, $E0990ECA, $7ED08883, $1D08023C, $BB3F7BF5, $5976F5AE, $F7AE6F67, $95E5E920, $341D62D9, $D254DC92, $708C564B, $0EC3D004, $ACFB49BD, $4B32C376, $E96A3D2F, $87A1B6E8, $25D930A1, $C410AA5A, $62482413, $007F9DCC, $9EB71785, $3CEE913E); var xKeyD: array [0 .. 63] of DWORD; i, j, k, xKeyLen, a, b: DWORD; begin Size := Size div 8; CopyPtr(buff, @xKeyD, Size); xKeyLen := Size div 4; if (Size mod 4) <> 0 then inc(xKeyLen); CopyPtr(@cRC6_sBox, @KeyContext, ((cRC6_NumRounds * 2) + 4) * 4); i := 0; j := 0; a := 0; b := 0; if xKeyLen > ((cRC6_NumRounds * 2) + 4) then k := xKeyLen * 3 else k := ((cRC6_NumRounds * 2) + 4) * 3; for k := 1 to k do begin a := LRot32(KeyContext[i] + a + b, 3); KeyContext[i] := a; b := LRot32(xKeyD[j] + a + b, a + b); xKeyD[j] := b; i := (i + 1) mod ((cRC6_NumRounds * 2) + 4); j := (j + 1) mod xKeyLen; end; end; class procedure TRC6.Encrypt(var KeyContext: TRC6Key; var Data: TRC6Block); var x0, x1, x2, x3: PDWORD; u, t, i: DWORD; begin {$IFDEF RangeCheck}{$R-}{$ENDIF} x0 := PDWORD(@Data[0]); x1 := PDWORD(@Data[4]); x2 := PDWORD(@Data[8]); x3 := PDWORD(@Data[12]); x1^ := x1^ + KeyContext[0]; x3^ := x3^ + KeyContext[1]; for i := 1 to cRC6_NumRounds do begin t := LRot32(x1^ * (2 * x1^ + 1), 5); u := LRot32(x3^ * (2 * x3^ + 1), 5); x0^ := LRot32(x0^ xor t, u) + KeyContext[2 * i]; x2^ := LRot32(x2^ xor u, t) + KeyContext[2 * i + 1]; t := x0^; x0^ := x1^; x1^ := x2^; x2^ := x3^; x3^ := t; end; x0^ := x0^ + KeyContext[(2 * cRC6_NumRounds) + 2]; x2^ := x2^ + KeyContext[(2 * cRC6_NumRounds) + 3]; {$IFDEF RangeCheck}{$R+}{$ENDIF} end; class procedure TRC6.Decrypt(var KeyContext: TRC6Key; var Data: TRC6Block); var x0, x1, x2, x3: PDWORD; u, t, i: DWORD; begin {$IFDEF RangeCheck}{$R-}{$ENDIF} x0 := PDWORD(@Data[0]); x1 := PDWORD(@Data[4]); x2 := PDWORD(@Data[8]); x3 := PDWORD(@Data[12]); x2^ := x2^ - KeyContext[(2 * cRC6_NumRounds) + 3]; x0^ := x0^ - KeyContext[(2 * cRC6_NumRounds) + 2]; for i := cRC6_NumRounds downto 1 do begin t := x0^; x0^ := x3^; x3^ := x2^; x2^ := x1^; x1^ := t; u := LRot32(x3^ * (2 * x3^ + 1), 5); t := LRot32(x1^ * (2 * x1^ + 1), 5); x2^ := RRot32(x2^ - KeyContext[2 * i + 1], t) xor u; x0^ := RRot32(x0^ - KeyContext[2 * i], u) xor t; end; x3^ := x3^ - KeyContext[1]; x1^ := x1^ - KeyContext[0]; {$IFDEF RangeCheck}{$R+}{$ENDIF} end; class procedure TSerpent.InitKey(buff: Pointer; Size: Integer; var KeyContext: TSerpentkey); var kp: array [0 .. 139] of DWORD; i, n: DWORD; t0, T1, T2, T3, T4, T5, T6, T7, T8, t9, t10, t11, t12, t13, t14, t15, t16, t17: DWORD; a, b, c, d: DWORD; begin FillPtrByte(@kp[0], SizeOf(kp), 0); CopyPtr(buff, @kp[0], Size); for i := 8 to 139 do begin t0 := kp[i - 8] xor kp[i - 5] xor kp[i - 3] xor kp[i - 1] xor $9E3779B9 xor DWORD(i - 8); kp[i] := (t0 shl 11) or (t0 shr 21); end; for i := 0 to 3 do begin n := i * 32; a := kp[n + 4 * 0 + 8]; b := kp[n + 4 * 0 + 9]; c := kp[n + 4 * 0 + 10]; d := kp[n + 4 * 0 + 11]; T1 := a xor c; T2 := a or d; T3 := a and b; T4 := a and d; T5 := b or T4; T6 := T1 and T2; kp[9 + n] := T5 xor T6; T8 := b xor d; t9 := c or T3; t10 := T6 xor T8; kp[11 + n] := t9 xor t10; t12 := c xor T3; t13 := T2 and kp[11 + n]; kp[10 + n] := t12 xor t13; t15 := not kp[10 + n]; t16 := T2 xor T3; t17 := kp[9 + n] and t15; kp[8 + n] := t16 xor t17; a := kp[n + 4 * 1 + 8]; b := kp[n + 4 * 1 + 9]; c := kp[n + 4 * 1 + 10]; d := kp[n + 4 * 1 + 11]; T1 := not a; T2 := b xor d; T3 := c and T1; kp[12 + n] := T2 xor T3; T5 := c xor T1; T6 := c xor kp[12 + n]; T7 := b and T6; kp[15 + n] := T5 xor T7; t9 := d or T7; t10 := kp[12 + n] or T5; t11 := t9 and t10; kp[14 + n] := a xor t11; t13 := d or T1; t14 := T2 xor kp[15 + n]; t15 := kp[14 + n] xor t13; kp[13 + n] := t14 xor t15; a := kp[n + 4 * 2 + 8]; b := kp[n + 4 * 2 + 9]; c := kp[n + 4 * 2 + 10]; d := kp[n + 4 * 2 + 11]; T1 := a xor d; T2 := b xor d; T3 := a and b; T4 := not c; T5 := T2 xor T3; kp[18 + n] := T4 xor T5; T7 := a xor T2; T8 := b or T4; t9 := d or kp[18 + n]; t10 := T7 and t9; kp[17 + n] := T8 xor t10; t12 := c xor d; t13 := T1 or T2; t14 := kp[17 + n] xor t12; kp[19 + n] := t13 xor t14; t16 := T1 or kp[18 + n]; t17 := T8 xor t14; kp[16 + n] := t16 xor t17; a := kp[n + 4 * 3 + 8]; b := kp[n + 4 * 3 + 9]; c := kp[n + 4 * 3 + 10]; d := kp[n + 4 * 3 + 11]; T1 := b xor d; T2 := not T1; T3 := a or d; T4 := b xor c; kp[23 + n] := T3 xor T4; T6 := a xor b; T7 := a or T4; T8 := c and T6; t9 := T2 or T8; kp[20 + n] := T7 xor t9; t11 := a xor kp[23 + n]; t12 := T1 and T6; t13 := kp[20 + n] xor t11; kp[21 + n] := t12 xor t13; t15 := kp[20 + n] or kp[21 + n]; t16 := T3 and t15; kp[22 + n] := b xor t16; a := kp[n + 4 * 4 + 8]; b := kp[n + 4 * 4 + 9]; c := kp[n + 4 * 4 + 10]; d := kp[n + 4 * 4 + 11]; T1 := not c; T2 := b xor c; T3 := b or T1; T4 := d xor T3; T5 := a and T4; kp[27 + n] := T2 xor T5; T7 := a xor d; T8 := b xor T5; t9 := T2 or T8; kp[25 + n] := T7 xor t9; t11 := d and T3; t12 := T5 xor kp[25 + n]; t13 := kp[27 + n] and t12; kp[26 + n] := t11 xor t13; t15 := T1 or T4; t16 := t12 xor kp[26 + n]; kp[24 + n] := t15 xor t16; a := kp[n + 4 * 5 + 8]; b := kp[n + 4 * 5 + 9]; c := kp[n + 4 * 5 + 10]; d := kp[n + 4 * 5 + 11]; T1 := a xor c; T2 := b or d; T3 := b xor c; T4 := not T3; T5 := a and d; kp[29 + n] := T4 xor T5; T7 := b or c; T8 := d xor T1; t9 := T7 and T8; kp[31 + n] := T2 xor t9; t11 := T1 and T7; t12 := T4 xor T8; t13 := kp[31 + n] and t11; kp[28 + n] := t12 xor t13; t15 := T3 xor t11; t16 := kp[31 + n] or t15; kp[30 + n] := t12 xor t16; a := kp[n + 4 * 6 + 8]; b := kp[n + 4 * 6 + 9]; c := kp[n + 4 * 6 + 10]; d := kp[n + 4 * 6 + 11]; T1 := not a; T2 := a xor b; T3 := a xor d; T4 := c xor T1; T5 := T2 or T3; kp[32 + n] := T4 xor T5; T7 := not d; T8 := kp[32 + n] and T7; kp[33 + n] := T2 xor T8; t10 := b or kp[33 + n]; t11 := c or kp[32 + n]; t12 := T7 xor t10; kp[35 + n] := t11 xor t12; t14 := d or kp[33 + n]; t15 := T1 xor t14; t16 := kp[32 + n] or kp[35 + n]; kp[34 + n] := t15 xor t16; a := kp[n + 4 * 7 + 8]; b := kp[n + 4 * 7 + 9]; c := kp[n + 4 * 7 + 10]; d := kp[n + 4 * 7 + 11]; T1 := not a; T2 := a xor d; T3 := a xor b; T4 := c xor T1; T5 := T2 or T3; kp[36 + n] := T4 xor T5; T7 := not kp[36 + n]; T8 := b or T7; kp[39 + n] := T2 xor T8; t10 := a and kp[36 + n]; t11 := b xor kp[39 + n]; t12 := T8 and t11; kp[38 + n] := t10 xor t12; t14 := a or T7; t15 := T3 xor t14; t16 := kp[39 + n] and kp[38 + n]; kp[37 + n] := t15 xor t16; end; a := kp[136]; b := kp[137]; c := kp[138]; d := kp[139]; T1 := a xor c; T2 := a or d; T3 := a and b; T4 := a and d; T5 := b or T4; T6 := T1 and T2; kp[137] := T5 xor T6; T8 := b xor d; t9 := c or T3; t10 := T6 xor T8; kp[139] := t9 xor t10; t12 := c xor T3; t13 := T2 and kp[139]; kp[138] := t12 xor t13; t15 := not kp[138]; t16 := T2 xor T3; t17 := kp[137] and t15; kp[136] := t16 xor t17; CopyPtr(@kp, @KeyContext, SizeOf(KeyContext)); end; class procedure TSerpent.Encrypt(var KeyContext: TSerpentkey; var Data: TSerpentBlock); var i: DWORD; a, b, c, d, E, f, g, h: DWORD; T1, T2, T3, T4, T5, T6, T7, T8, t9, t10, t11, t12, t13, t14, t15, t16, t17: DWORD; begin a := PDWORD(@Data[0])^; b := PDWORD(@Data[4])^; c := PDWORD(@Data[8])^; d := PDWORD(@Data[12])^; i := 0; while i < 32 do begin a := a xor KeyContext[4 * (i)]; b := b xor KeyContext[4 * (i) + 1]; c := c xor KeyContext[4 * (i) + 2]; d := d xor KeyContext[4 * (i) + 3]; T1 := b xor d; T2 := not T1; T3 := a or d; T4 := b xor c; h := T3 xor T4; T6 := a xor b; T7 := a or T4; T8 := c and T6; t9 := T2 or T8; E := T7 xor t9; t11 := a xor h; t12 := T1 and T6; t13 := E xor t11; f := t12 xor t13; t15 := E or f; t16 := T3 and t15; g := b xor t16; E := (E shl 13) or (E shr 19); g := (g shl 3) or (g shr 29); f := f xor E xor g; h := h xor g xor (E shl 3); f := (f shl 1) or (f shr 31); h := (h shl 7) or (h shr 25); E := E xor f xor h; g := g xor h xor (f shl 7); E := (E shl 5) or (E shr 27); g := (g shl 22) or (g shr 10); E := E xor KeyContext[4 * (i + 1)]; f := f xor KeyContext[4 * (i + 1) + 1]; g := g xor KeyContext[4 * (i + 1) + 2]; h := h xor KeyContext[4 * (i + 1) + 3]; T1 := E xor h; T2 := f xor h; T3 := E and f; T4 := not g; T5 := T2 xor T3; c := T4 xor T5; T7 := E xor T2; T8 := f or T4; t9 := h or c; t10 := T7 and t9; b := T8 xor t10; t12 := g xor h; t13 := T1 or T2; t14 := b xor t12; d := t13 xor t14; t16 := T1 or c; t17 := T8 xor t14; a := t16 xor t17; a := (a shl 13) or (a shr 19); c := (c shl 3) or (c shr 29); b := b xor a xor c; d := d xor c xor (a shl 3); b := (b shl 1) or (b shr 31); d := (d shl 7) or (d shr 25); a := a xor b xor d; c := c xor d xor (b shl 7); a := (a shl 5) or (a shr 27); c := (c shl 22) or (c shr 10); a := a xor KeyContext[4 * (i + 2)]; b := b xor KeyContext[4 * (i + 2) + 1]; c := c xor KeyContext[4 * (i + 2) + 2]; d := d xor KeyContext[4 * (i + 2) + 3]; T1 := not a; T2 := b xor d; T3 := c and T1; E := T2 xor T3; T5 := c xor T1; T6 := c xor E; T7 := b and T6; h := T5 xor T7; t9 := d or T7; t10 := E or T5; t11 := t9 and t10; g := a xor t11; t13 := d or T1; t14 := T2 xor h; t15 := g xor t13; f := t14 xor t15; E := (E shl 13) or (E shr 19); g := (g shl 3) or (g shr 29); f := f xor E xor g; h := h xor g xor (E shl 3); f := (f shl 1) or (f shr 31); h := (h shl 7) or (h shr 25); E := E xor f xor h; g := g xor h xor (f shl 7); E := (E shl 5) or (E shr 27); g := (g shl 22) or (g shr 10); E := E xor KeyContext[4 * (i + 3)]; f := f xor KeyContext[4 * (i + 3) + 1]; g := g xor KeyContext[4 * (i + 3) + 2]; h := h xor KeyContext[4 * (i + 3) + 3]; T1 := E xor g; T2 := E or h; T3 := E and f; T4 := E and h; T5 := f or T4; T6 := T1 and T2; b := T5 xor T6; T8 := f xor h; t9 := g or T3; t10 := T6 xor T8; d := t9 xor t10; t12 := g xor T3; t13 := T2 and d; c := t12 xor t13; t15 := not c; t16 := T2 xor T3; t17 := b and t15; a := t16 xor t17; a := (a shl 13) or (a shr 19); c := (c shl 3) or (c shr 29); b := b xor a xor c; d := d xor c xor (a shl 3); b := (b shl 1) or (b shr 31); d := (d shl 7) or (d shr 25); a := a xor b xor d; c := c xor d xor (b shl 7); a := (a shl 5) or (a shr 27); c := (c shl 22) or (c shr 10); a := a xor KeyContext[4 * (i + 4)]; b := b xor KeyContext[4 * (i + 4) + 1]; c := c xor KeyContext[4 * (i + 4) + 2]; d := d xor KeyContext[4 * (i + 4) + 3]; T1 := not a; T2 := a xor d; T3 := a xor b; T4 := c xor T1; T5 := T2 or T3; E := T4 xor T5; T7 := not E; T8 := b or T7; h := T2 xor T8; t10 := a and E; t11 := b xor h; t12 := T8 and t11; g := t10 xor t12; t14 := a or T7; t15 := T3 xor t14; t16 := h and g; f := t15 xor t16; E := (E shl 13) or (E shr 19); g := (g shl 3) or (g shr 29); f := f xor E xor g; h := h xor g xor (E shl 3); f := (f shl 1) or (f shr 31); h := (h shl 7) or (h shr 25); E := E xor f xor h; g := g xor h xor (f shl 7); E := (E shl 5) or (E shr 27); g := (g shl 22) or (g shr 10); E := E xor KeyContext[4 * (i + 5)]; f := f xor KeyContext[4 * (i + 5) + 1]; g := g xor KeyContext[4 * (i + 5) + 2]; h := h xor KeyContext[4 * (i + 5) + 3]; T1 := not E; T2 := E xor f; T3 := E xor h; T4 := g xor T1; T5 := T2 or T3; a := T4 xor T5; T7 := not h; T8 := a and T7; b := T2 xor T8; t10 := f or b; t11 := g or a; t12 := T7 xor t10; d := t11 xor t12; t14 := h or b; t15 := T1 xor t14; t16 := a or d; c := t15 xor t16; a := (a shl 13) or (a shr 19); c := (c shl 3) or (c shr 29); b := b xor a xor c; d := d xor c xor (a shl 3); b := (b shl 1) or (b shr 31); d := (d shl 7) or (d shr 25); a := a xor b xor d; c := c xor d xor (b shl 7); a := (a shl 5) or (a shr 27); c := (c shl 22) or (c shr 10); a := a xor KeyContext[4 * (i + 6)]; b := b xor KeyContext[4 * (i + 6) + 1]; c := c xor KeyContext[4 * (i + 6) + 2]; d := d xor KeyContext[4 * (i + 6) + 3]; T1 := a xor c; T2 := b or d; T3 := b xor c; T4 := not T3; T5 := a and d; f := T4 xor T5; T7 := b or c; T8 := d xor T1; t9 := T7 and T8; h := T2 xor t9; t11 := T1 and T7; t12 := T4 xor T8; t13 := h and t11; E := t12 xor t13; t15 := T3 xor t11; t16 := h or t15; g := t12 xor t16; E := (E shl 13) or (E shr 19); g := (g shl 3) or (g shr 29); f := f xor E xor g; h := h xor g xor (E shl 3); f := (f shl 1) or (f shr 31); h := (h shl 7) or (h shr 25); E := E xor f xor h; g := g xor h xor (f shl 7); E := (E shl 5) or (E shr 27); g := (g shl 22) or (g shr 10); E := E xor KeyContext[4 * (i + 7)]; f := f xor KeyContext[4 * (i + 7) + 1]; g := g xor KeyContext[4 * (i + 7) + 2]; h := h xor KeyContext[4 * (i + 7) + 3]; T1 := not g; T2 := f xor g; T3 := f or T1; T4 := h xor T3; T5 := E and T4; d := T2 xor T5; T7 := E xor h; T8 := f xor T5; t9 := T2 or T8; b := T7 xor t9; t11 := h and T3; t12 := T5 xor b; t13 := d and t12; c := t11 xor t13; t15 := T1 or T4; t16 := t12 xor c; a := t15 xor t16; inc(i, 8); if i < 32 then begin a := (a shl 13) or (a shr 19); c := (c shl 3) or (c shr 29); b := b xor a xor c; d := d xor c xor (a shl 3); b := (b shl 1) or (b shr 31); d := (d shl 7) or (d shr 25); a := a xor b xor d; c := c xor d xor (b shl 7); a := (a shl 5) or (a shr 27); c := (c shl 22) or (c shr 10); end; end; a := a xor KeyContext[128]; b := b xor KeyContext[128 + 1]; c := c xor KeyContext[128 + 2]; d := d xor KeyContext[128 + 3]; PDWORD(@Data[0])^ := a; PDWORD(@Data[4])^ := b; PDWORD(@Data[8])^ := c; PDWORD(@Data[12])^ := d; end; class procedure TSerpent.Decrypt(var KeyContext: TSerpentkey; var Data: TSerpentBlock); var i: DWORD; a, b, c, d, E, f, g, h: DWORD; T1, T2, T3, T4, T5, T6, T7, T8, t9, t10, t11, t12, t13, t14, t15, t16: DWORD; begin a := PDWORD(@Data[0])^; b := PDWORD(@Data[4])^; c := PDWORD(@Data[8])^; d := PDWORD(@Data[12])^; i := 32; a := a xor KeyContext[4 * 32]; b := b xor KeyContext[4 * 32 + 1]; c := c xor KeyContext[4 * 32 + 2]; d := d xor KeyContext[4 * 32 + 3]; while i > 0 do begin if i < 32 then begin c := (c shr 22) or (c shl 10); a := (a shr 5) or (a shl 27); c := c xor d xor (b shl 7); a := a xor b xor d; d := (d shr 7) or (d shl 25); b := (b shr 1) or (b shl 31); d := d xor c xor (a shl 3); b := b xor a xor c; c := (c shr 3) or (c shl 29); a := (a shr 13) or (a shl 19); end; T1 := a and b; T2 := a or b; T3 := c or T1; T4 := d and T2; h := T3 xor T4; T6 := not d; T7 := b xor T4; T8 := h xor T6; t9 := T7 or T8; f := a xor t9; t11 := c xor T7; t12 := d or f; E := t11 xor t12; t14 := a and h; t15 := T3 xor f; t16 := E xor t14; g := t15 xor t16; E := E xor KeyContext[4 * (i - 1)]; f := f xor KeyContext[4 * (i - 1) + 1]; g := g xor KeyContext[4 * (i - 1) + 2]; h := h xor KeyContext[4 * (i - 1) + 3]; g := (g shr 22) or (g shl 10); E := (E shr 5) or (E shl 27); g := g xor h xor (f shl 7); E := E xor f xor h; h := (h shr 7) or (h shl 25); f := (f shr 1) or (f shl 31); h := h xor g xor (E shl 3); f := f xor E xor g; g := (g shr 3) or (g shl 29); E := (E shr 13) or (E shl 19); T1 := not g; T2 := E xor g; T3 := f xor h; T4 := E or T1; b := T3 xor T4; T6 := E or f; T7 := f and T2; T8 := b xor T6; t9 := T7 or T8; a := g xor t9; t11 := not b; t12 := h or T2; t13 := t9 xor t11; d := t12 xor t13; t15 := f xor t11; t16 := a and d; c := t15 xor t16; a := a xor KeyContext[4 * (i - 2)]; b := b xor KeyContext[4 * (i - 2) + 1]; c := c xor KeyContext[4 * (i - 2) + 2]; d := d xor KeyContext[4 * (i - 2) + 3]; c := (c shr 22) or (c shl 10); a := (a shr 5) or (a shl 27); c := c xor d xor (b shl 7); a := a xor b xor d; d := (d shr 7) or (d shl 25); b := (b shr 1) or (b shl 31); d := d xor c xor (a shl 3); b := b xor a xor c; c := (c shr 3) or (c shl 29); a := (a shr 13) or (a shl 19); T1 := not c; T2 := b and T1; T3 := d xor T2; T4 := a and T3; T5 := b xor T1; h := T4 xor T5; T7 := b or h; T8 := a and T7; f := T3 xor T8; t10 := a or d; t11 := T1 xor T7; E := t10 xor t11; t13 := a xor c; t14 := b and t10; t15 := T4 or t13; g := t14 xor t15; E := E xor KeyContext[4 * (i - 3)]; f := f xor KeyContext[4 * (i - 3) + 1]; g := g xor KeyContext[4 * (i - 3) + 2]; h := h xor KeyContext[4 * (i - 3) + 3]; g := (g shr 22) or (g shl 10); E := (E shr 5) or (E shl 27); g := g xor h xor (f shl 7); E := E xor f xor h; h := (h shr 7) or (h shl 25); f := (f shr 1) or (f shl 31); h := h xor g xor (E shl 3); f := f xor E xor g; g := (g shr 3) or (g shl 29); E := (E shr 13) or (E shl 19); T1 := g xor h; T2 := g or h; T3 := f xor T2; T4 := E and T3; b := T1 xor T4; T6 := E xor h; T7 := f or h; T8 := T6 and T7; d := T3 xor T8; t10 := not E; t11 := g xor d; t12 := t10 or t11; a := T3 xor t12; t14 := g or T4; t15 := T7 xor t14; t16 := d or t10; c := t15 xor t16; a := a xor KeyContext[4 * (i - 4)]; b := b xor KeyContext[4 * (i - 4) + 1]; c := c xor KeyContext[4 * (i - 4) + 2]; d := d xor KeyContext[4 * (i - 4) + 3]; c := (c shr 22) or (c shl 10); a := (a shr 5) or (a shl 27); c := c xor d xor (b shl 7); a := a xor b xor d; d := (d shr 7) or (d shl 25); b := (b shr 1) or (b shl 31); d := d xor c xor (a shl 3); b := b xor a xor c; c := (c shr 3) or (c shl 29); a := (a shr 13) or (a shl 19); T1 := b xor c; T2 := b or c; T3 := a xor c; T4 := T2 xor T3; T5 := d or T4; E := T1 xor T5; T7 := a xor d; T8 := T1 or T5; t9 := T2 xor T7; g := T8 xor t9; t11 := a and T4; t12 := E or t9; f := t11 xor t12; t14 := a and g; t15 := T2 xor t14; t16 := E and t15; h := T4 xor t16; E := E xor KeyContext[4 * (i - 5)]; f := f xor KeyContext[4 * (i - 5) + 1]; g := g xor KeyContext[4 * (i - 5) + 2]; h := h xor KeyContext[4 * (i - 5) + 3]; g := (g shr 22) or (g shl 10); E := (E shr 5) or (E shl 27); g := g xor h xor (f shl 7); E := E xor f xor h; h := (h shr 7) or (h shl 25); f := (f shr 1) or (f shl 31); h := h xor g xor (E shl 3); f := f xor E xor g; g := (g shr 3) or (g shl 29); E := (E shr 13) or (E shl 19); T1 := f xor h; T2 := not T1; T3 := E xor g; T4 := g xor T1; T5 := f and T4; a := T3 xor T5; T7 := E or T2; T8 := h xor T7; t9 := T3 or T8; d := T1 xor t9; t11 := not T4; t12 := a or d; b := t11 xor t12; t14 := h and t11; t15 := T3 xor t12; c := t14 xor t15; a := a xor KeyContext[4 * (i - 6)]; b := b xor KeyContext[4 * (i - 6) + 1]; c := c xor KeyContext[4 * (i - 6) + 2]; d := d xor KeyContext[4 * (i - 6) + 3]; c := (c shr 22) or (c shl 10); a := (a shr 5) or (a shl 27); c := c xor d xor (b shl 7); a := a xor b xor d; d := (d shr 7) or (d shl 25); b := (b shr 1) or (b shl 31); d := d xor c xor (a shl 3); b := b xor a xor c; c := (c shr 3) or (c shl 29); a := (a shr 13) or (a shl 19); T1 := a xor d; T2 := a and b; T3 := b xor c; T4 := a xor T3; T5 := b or d; h := T4 xor T5; T7 := c or T1; T8 := b xor T7; t9 := T4 and T8; f := T1 xor t9; t11 := not T2; t12 := h and f; t13 := t9 xor t11; g := t12 xor t13; t15 := a and d; t16 := c xor t13; E := t15 xor t16; E := E xor KeyContext[4 * (i - 7)]; f := f xor KeyContext[4 * (i - 7) + 1]; g := g xor KeyContext[4 * (i - 7) + 2]; h := h xor KeyContext[4 * (i - 7) + 3]; g := (g shr 22) or (g shl 10); E := (E shr 5) or (E shl 27); g := g xor h xor (f shl 7); E := E xor f xor h; h := (h shr 7) or (h shl 25); f := (f shr 1) or (f shl 31); h := h xor g xor (E shl 3); f := f xor E xor g; g := (g shr 3) or (g shl 29); E := (E shr 13) or (E shl 19); T1 := E xor h; T2 := g xor h; T3 := not T2; T4 := E or f; c := T3 xor T4; T6 := f xor T1; T7 := g or T6; T8 := E xor T7; t9 := T2 and T8; b := T6 xor t9; t11 := not T8; t12 := f and h; t13 := b or t12; d := t11 xor t13; t15 := T2 xor t12; t16 := b or d; a := t15 xor t16; a := a xor KeyContext[4 * (i - 8)]; b := b xor KeyContext[4 * (i - 8) + 1]; c := c xor KeyContext[4 * (i - 8) + 2]; d := d xor KeyContext[4 * (i - 8) + 3]; dec(i, 8); end; PDWORD(@Data[0])^ := a; PDWORD(@Data[4])^ := b; PDWORD(@Data[8])^ := c; PDWORD(@Data[12])^ := d; end; class procedure TMars.gen_mask(var x, m: DWORD); var u: DWORD; begin u := x and (x shr 1); u := u and (u shr 2); u := u and (u shr 4); u := u and (u shr 1) and (u shr 2); m := u; u := (x xor $FFFFFFFF) and ((x xor $FFFFFFFF) shr 1); u := u and (u shr 2); u := u and (u shr 4); u := u and (u shr 1) and (u shr 2); u := u or m; m := (u shl 1) or (u shl 2) or (u shl 3) or (u shl 4) or (u shl 5) or (u shl 6) or (u shl 7) or (u shl 8); m := (m or u or (u shl 9)) and ((x xor $FFFFFFFF) xor (x shl 1)) and ((x xor $FFFFFFFF) xor (x shr 1)); m := m and $FFFFFFFC; end; class procedure TMars.InitKey(buff: Pointer; Size: Integer; var KeyContext: TMarskey); const vk: array [0 .. 6] of DWORD = ($09D0C479, $28C8FFE0, $84AA6C39, $9DAD7287, $7DFF9BE3, $D4268361, $C96DA1D4); var i, j: Integer; m, u, w, siz4: DWORD; t: array [-7 .. 39] of DWORD; KeyB: array [0 .. 39] of DWORD; begin m := 0; FillPtrByte(@KeyB, SizeOf(KeyB), 0); FillPtrByte(@t, SizeOf(t), 0); CopyPtr(buff, @KeyB, Size); siz4 := Size div 4; CopyPtr(@vk, @t, SizeOf(vk)); for i := 0 to 38 do begin u := t[i - 7] xor t[i - 2]; t[i] := TRC6.LRot32(u, 3) xor KeyB[i mod siz4] xor i; end; t[39] := siz4; for j := 0 to 6 do begin for i := 1 to 39 do begin u := t[i] + Mars_SBox[t[i - 1] and $1FF]; t[i] := TRC6.LRot32(u, 9); end; u := t[0] + Mars_SBox[t[39] and $1FF]; t[0] := TRC6.LRot32(u, 9); end; for i := 0 to 39 do KeyContext[(7 * i) mod 40] := t[i]; i := 5; repeat u := Mars_SBox[265 + (KeyContext[i] and $3)]; j := KeyContext[i + 3] and $1F; w := KeyContext[i] or $3; gen_mask(w, m); KeyContext[i] := w xor (TRC6.LRot32(u, j) and m); inc(i, 2); until i >= 37; end; class procedure TMars.Encrypt(var KeyContext: TMarskey; var Data: TMarsBlock); var l, m, r, t, a, b, c, d: DWORD; begin {$IFDEF RangeCheck}{$R-}{$ENDIF} a := PDWORD(@Data[0])^; b := PDWORD(@Data[4])^; c := PDWORD(@Data[8])^; d := PDWORD(@Data[12])^; a := a + KeyContext[0]; b := b + KeyContext[1]; c := c + KeyContext[2]; d := d + KeyContext[3]; b := b xor Mars_SBox[a and $FF]; b := b + Mars_SBox[((a shr 8) and $FF) + 256]; c := c + Mars_SBox[(a shr 16) and $FF]; d := d xor Mars_SBox[((a shr 24) and $FF) + 256]; a := TRC6.RRot32(a, 24); a := a + d; c := c xor Mars_SBox[b and $FF]; c := c + Mars_SBox[((b shr 8) and $FF) + 256]; d := d + Mars_SBox[(b shr 16) and $FF]; a := a xor Mars_SBox[((b shr 24) and $FF) + 256]; b := TRC6.RRot32(b, 24); b := b + c; d := d xor Mars_SBox[c and $FF]; d := d + Mars_SBox[((c shr 8) and $FF) + 256]; a := a + Mars_SBox[(c shr 16) and $FF]; b := b xor Mars_SBox[((c shr 24) and $FF) + 256]; c := TRC6.RRot32(c, 24); a := a xor Mars_SBox[d and $FF]; a := a + Mars_SBox[((d shr 8) and $FF) + 256]; b := b + Mars_SBox[(d shr 16) and $FF]; c := c xor Mars_SBox[((d shr 24) and $FF) + 256]; d := TRC6.RRot32(d, 24); b := b xor Mars_SBox[a and $FF]; b := b + Mars_SBox[((a shr 8) and $FF) + 256]; c := c + Mars_SBox[(a shr 16) and $FF]; d := d xor Mars_SBox[((a shr 24) and $FF) + 256]; a := TRC6.RRot32(a, 24); a := a + d; c := c xor Mars_SBox[b and $FF]; c := c + Mars_SBox[((b shr 8) and $FF) + 256]; d := d + Mars_SBox[(b shr 16) and $FF]; a := a xor Mars_SBox[((b shr 24) and $FF) + 256]; b := TRC6.RRot32(b, 24); b := b + c; d := d xor Mars_SBox[c and $FF]; d := d + Mars_SBox[((c shr 8) and $FF) + 256]; a := a + Mars_SBox[(c shr 16) and $FF]; b := b xor Mars_SBox[((c shr 24) and $FF) + 256]; c := TRC6.RRot32(c, 24); a := a xor Mars_SBox[d and $FF]; a := a + Mars_SBox[((d shr 8) and $FF) + 256]; b := b + Mars_SBox[(d shr 16) and $FF]; c := c xor Mars_SBox[((d shr 24) and $FF) + 256]; d := TRC6.RRot32(d, 24); m := a + KeyContext[4]; r := TRC6.LRot32(a, 13) * KeyContext[5]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); a := TRC6.LRot32(a, 13); b := b + l; c := c + m; d := d xor r; m := b + KeyContext[6]; r := TRC6.LRot32(b, 13) * KeyContext[7]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); b := TRC6.LRot32(b, 13); c := c + l; d := d + m; a := a xor r; m := c + KeyContext[8]; r := TRC6.LRot32(c, 13) * KeyContext[9]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); c := TRC6.LRot32(c, 13); d := d + l; a := a + m; b := b xor r; m := d + KeyContext[10]; r := TRC6.LRot32(d, 13) * KeyContext[11]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); d := TRC6.LRot32(d, 13); a := a + l; b := b + m; c := c xor r; m := a + KeyContext[12]; r := TRC6.LRot32(a, 13) * KeyContext[13]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); a := TRC6.LRot32(a, 13); b := b + l; c := c + m; d := d xor r; m := b + KeyContext[14]; r := TRC6.LRot32(b, 13) * KeyContext[15]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); b := TRC6.LRot32(b, 13); c := c + l; d := d + m; a := a xor r; m := c + KeyContext[16]; r := TRC6.LRot32(c, 13) * KeyContext[17]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); c := TRC6.LRot32(c, 13); d := d + l; a := a + m; b := b xor r; m := d + KeyContext[18]; r := TRC6.LRot32(d, 13) * KeyContext[19]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); d := TRC6.LRot32(d, 13); a := a + l; b := b + m; c := c xor r; m := a + KeyContext[20]; r := TRC6.LRot32(a, 13) * KeyContext[21]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); a := TRC6.LRot32(a, 13); d := d + l; c := c + m; b := b xor r; m := b + KeyContext[22]; r := TRC6.LRot32(b, 13) * KeyContext[23]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); b := TRC6.LRot32(b, 13); a := a + l; d := d + m; c := c xor r; m := c + KeyContext[24]; r := TRC6.LRot32(c, 13) * KeyContext[25]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); c := TRC6.LRot32(c, 13); b := b + l; a := a + m; d := d xor r; m := d + KeyContext[26]; r := TRC6.LRot32(d, 13) * KeyContext[27]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); d := TRC6.LRot32(d, 13); c := c + l; b := b + m; a := a xor r; m := a + KeyContext[28]; r := TRC6.LRot32(a, 13) * KeyContext[29]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); a := TRC6.LRot32(a, 13); d := d + l; c := c + m; b := b xor r; m := b + KeyContext[30]; r := TRC6.LRot32(b, 13) * KeyContext[31]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); b := TRC6.LRot32(b, 13); a := a + l; d := d + m; c := c xor r; m := c + KeyContext[32]; r := TRC6.LRot32(c, 13) * KeyContext[33]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); c := TRC6.LRot32(c, 13); b := b + l; a := a + m; d := d xor r; m := d + KeyContext[34]; r := TRC6.LRot32(d, 13) * KeyContext[35]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); d := TRC6.LRot32(d, 13); c := c + l; b := b + m; a := a xor r; b := b xor Mars_SBox[(a and $FF) + 256]; c := c - Mars_SBox[(a shr 24) and $FF]; d := d - Mars_SBox[((a shr 16) and $FF) + 256]; d := d xor Mars_SBox[(a shr 8) and $FF]; a := TRC6.LRot32(a, 24); c := c xor Mars_SBox[(b and $FF) + 256]; d := d - Mars_SBox[(b shr 24) and $FF]; a := a - Mars_SBox[((b shr 16) and $FF) + 256]; a := a xor Mars_SBox[(b shr 8) and $FF]; b := TRC6.LRot32(b, 24); c := c - b; d := d xor Mars_SBox[(c and $FF) + 256]; a := a - Mars_SBox[(c shr 24) and $FF]; b := b - Mars_SBox[((c shr 16) and $FF) + 256]; b := b xor Mars_SBox[(c shr 8) and $FF]; c := TRC6.LRot32(c, 24); d := d - a; a := a xor Mars_SBox[(d and $FF) + 256]; b := b - Mars_SBox[(d shr 24) and $FF]; c := c - Mars_SBox[((d shr 16) and $FF) + 256]; c := c xor Mars_SBox[(d shr 8) and $FF]; d := TRC6.LRot32(d, 24); b := b xor Mars_SBox[(a and $FF) + 256]; c := c - Mars_SBox[(a shr 24) and $FF]; d := d - Mars_SBox[((a shr 16) and $FF) + 256]; d := d xor Mars_SBox[(a shr 8) and $FF]; a := TRC6.LRot32(a, 24); c := c xor Mars_SBox[(b and $FF) + 256]; d := d - Mars_SBox[(b shr 24) and $FF]; a := a - Mars_SBox[((b shr 16) and $FF) + 256]; a := a xor Mars_SBox[(b shr 8) and $FF]; b := TRC6.LRot32(b, 24); c := c - b; d := d xor Mars_SBox[(c and $FF) + 256]; a := a - Mars_SBox[(c shr 24) and $FF]; b := b - Mars_SBox[((c shr 16) and $FF) + 256]; b := b xor Mars_SBox[(c shr 8) and $FF]; c := TRC6.LRot32(c, 24); d := d - a; a := a xor Mars_SBox[(d and $FF) + 256]; b := b - Mars_SBox[(d shr 24) and $FF]; c := c - Mars_SBox[((d shr 16) and $FF) + 256]; c := c xor Mars_SBox[(d shr 8) and $FF]; d := TRC6.LRot32(d, 24); a := a - KeyContext[36]; b := b - KeyContext[37]; c := c - KeyContext[38]; d := d - KeyContext[39]; PDWORD(@Data[0])^ := a; PDWORD(@Data[4])^ := b; PDWORD(@Data[8])^ := c; PDWORD(@Data[12])^ := d; {$IFDEF RangeCheck}{$R+}{$ENDIF} end; class procedure TMars.Decrypt(var KeyContext: TMarskey; var Data: TMarsBlock); var l, m, r, t, a, b, c, d: DWORD; begin {$IFDEF RangeCheck}{$R-}{$ENDIF} a := PDWORD(@Data[0])^; b := PDWORD(@Data[4])^; c := PDWORD(@Data[8])^; d := PDWORD(@Data[12])^; a := a + KeyContext[36]; b := b + KeyContext[37]; c := c + KeyContext[38]; d := d + KeyContext[39]; d := TRC6.RRot32(d, 24); c := c xor Mars_SBox[(d shr 8) and $FF]; c := c + Mars_SBox[((d shr 16) and $FF) + 256]; b := b + Mars_SBox[(d shr 24) and $FF]; a := a xor Mars_SBox[(d and $FF) + 256]; d := d + a; c := TRC6.RRot32(c, 24); b := b xor Mars_SBox[(c shr 8) and $FF]; b := b + Mars_SBox[((c shr 16) and $FF) + 256]; a := a + Mars_SBox[(c shr 24) and $FF]; d := d xor Mars_SBox[(c and $FF) + 256]; c := c + b; b := TRC6.RRot32(b, 24); a := a xor Mars_SBox[(b shr 8) and $FF]; a := a + Mars_SBox[((b shr 16) and $FF) + 256]; d := d + Mars_SBox[(b shr 24) and $FF]; c := c xor Mars_SBox[(b and $FF) + 256]; a := TRC6.RRot32(a, 24); d := d xor Mars_SBox[(a shr 8) and $FF]; d := d + Mars_SBox[((a shr 16) and $FF) + 256]; c := c + Mars_SBox[(a shr 24) and $FF]; b := b xor Mars_SBox[(a and $FF) + 256]; d := TRC6.RRot32(d, 24); c := c xor Mars_SBox[(d shr 8) and $FF]; c := c + Mars_SBox[((d shr 16) and $FF) + 256]; b := b + Mars_SBox[(d shr 24) and $FF]; a := a xor Mars_SBox[(d and $FF) + 256]; d := d + a; c := TRC6.RRot32(c, 24); b := b xor Mars_SBox[(c shr 8) and $FF]; b := b + Mars_SBox[((c shr 16) and $FF) + 256]; a := a + Mars_SBox[(c shr 24) and $FF]; d := d xor Mars_SBox[(c and $FF) + 256]; c := c + b; b := TRC6.RRot32(b, 24); a := a xor Mars_SBox[(b shr 8) and $FF]; a := a + Mars_SBox[((b shr 16) and $FF) + 256]; d := d + Mars_SBox[(b shr 24) and $FF]; c := c xor Mars_SBox[(b and $FF) + 256]; a := TRC6.RRot32(a, 24); d := d xor Mars_SBox[(a shr 8) and $FF]; d := d + Mars_SBox[((a shr 16) and $FF) + 256]; c := c + Mars_SBox[(a shr 24) and $FF]; b := b xor Mars_SBox[(a and $FF) + 256]; d := TRC6.RRot32(d, 13); m := d + KeyContext[34]; r := TRC6.LRot32(d, 13) * KeyContext[35]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); c := c - l; b := b - m; a := a xor r; c := TRC6.RRot32(c, 13); m := c + KeyContext[32]; r := TRC6.LRot32(c, 13) * KeyContext[33]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); b := b - l; a := a - m; d := d xor r; b := TRC6.RRot32(b, 13); m := b + KeyContext[30]; r := TRC6.LRot32(b, 13) * KeyContext[31]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); a := a - l; d := d - m; c := c xor r; a := TRC6.RRot32(a, 13); m := a + KeyContext[28]; r := TRC6.LRot32(a, 13) * KeyContext[29]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); d := d - l; c := c - m; b := b xor r; d := TRC6.RRot32(d, 13); m := d + KeyContext[26]; r := TRC6.LRot32(d, 13) * KeyContext[27]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); c := c - l; b := b - m; a := a xor r; c := TRC6.RRot32(c, 13); m := c + KeyContext[24]; r := TRC6.LRot32(c, 13) * KeyContext[25]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); b := b - l; a := a - m; d := d xor r; b := TRC6.RRot32(b, 13); m := b + KeyContext[22]; r := TRC6.LRot32(b, 13) * KeyContext[23]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); a := a - l; d := d - m; c := c xor r; a := TRC6.RRot32(a, 13); m := a + KeyContext[20]; r := TRC6.LRot32(a, 13) * KeyContext[21]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); d := d - l; c := c - m; b := b xor r; d := TRC6.RRot32(d, 13); m := d + KeyContext[18]; r := TRC6.LRot32(d, 13) * KeyContext[19]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); a := a - l; b := b - m; c := c xor r; c := TRC6.RRot32(c, 13); m := c + KeyContext[16]; r := TRC6.LRot32(c, 13) * KeyContext[17]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); d := d - l; a := a - m; b := b xor r; b := TRC6.RRot32(b, 13); m := b + KeyContext[14]; r := TRC6.LRot32(b, 13) * KeyContext[15]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); c := c - l; d := d - m; a := a xor r; a := TRC6.RRot32(a, 13); m := a + KeyContext[12]; r := TRC6.LRot32(a, 13) * KeyContext[13]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); b := b - l; c := c - m; d := d xor r; d := TRC6.RRot32(d, 13); m := d + KeyContext[10]; r := TRC6.LRot32(d, 13) * KeyContext[11]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); a := a - l; b := b - m; c := c xor r; c := TRC6.RRot32(c, 13); m := c + KeyContext[8]; r := TRC6.LRot32(c, 13) * KeyContext[9]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); d := d - l; a := a - m; b := b xor r; b := TRC6.RRot32(b, 13); m := b + KeyContext[6]; r := TRC6.LRot32(b, 13) * KeyContext[7]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); c := c - l; d := d - m; a := a xor r; a := TRC6.RRot32(a, 13); m := a + KeyContext[4]; r := TRC6.LRot32(a, 13) * KeyContext[5]; l := Mars_SBox[m and $1FF]; r := TRC6.LRot32(r, 5); t := r and $1F; m := TRC6.LRot32(m, t); l := l xor r; r := TRC6.LRot32(r, 5); l := l xor r; t := r and $1F; l := TRC6.LRot32(l, t); b := b - l; c := c - m; d := d xor r; d := TRC6.LRot32(d, 24); c := c xor Mars_SBox[((d shr 24) and $FF) + 256]; b := b - Mars_SBox[(d shr 16) and $FF]; a := a - Mars_SBox[((d shr 8) and $FF) + 256]; a := a xor Mars_SBox[d and $FF]; c := TRC6.LRot32(c, 24); b := b xor Mars_SBox[((c shr 24) and $FF) + 256]; a := a - Mars_SBox[(c shr 16) and $FF]; d := d - Mars_SBox[((c shr 8) and $FF) + 256]; d := d xor Mars_SBox[c and $FF]; b := b - c; b := TRC6.LRot32(b, 24); a := a xor Mars_SBox[((b shr 24) and $FF) + 256]; d := d - Mars_SBox[(b shr 16) and $FF]; c := c - Mars_SBox[((b shr 8) and $FF) + 256]; c := c xor Mars_SBox[b and $FF]; a := a - d; a := TRC6.LRot32(a, 24); d := d xor Mars_SBox[((a shr 24) and $FF) + 256]; c := c - Mars_SBox[(a shr 16) and $FF]; b := b - Mars_SBox[((a shr 8) and $FF) + 256]; b := b xor Mars_SBox[a and $FF]; d := TRC6.LRot32(d, 24); c := c xor Mars_SBox[((d shr 24) and $FF) + 256]; b := b - Mars_SBox[(d shr 16) and $FF]; a := a - Mars_SBox[((d shr 8) and $FF) + 256]; a := a xor Mars_SBox[d and $FF]; c := TRC6.LRot32(c, 24); b := b xor Mars_SBox[((c shr 24) and $FF) + 256]; a := a - Mars_SBox[(c shr 16) and $FF]; d := d - Mars_SBox[((c shr 8) and $FF) + 256]; d := d xor Mars_SBox[c and $FF]; b := b - c; b := TRC6.LRot32(b, 24); a := a xor Mars_SBox[((b shr 24) and $FF) + 256]; d := d - Mars_SBox[(b shr 16) and $FF]; c := c - Mars_SBox[((b shr 8) and $FF) + 256]; c := c xor Mars_SBox[b and $FF]; a := a - d; a := TRC6.LRot32(a, 24); d := d xor Mars_SBox[((a shr 24) and $FF) + 256]; c := c - Mars_SBox[(a shr 16) and $FF]; b := b - Mars_SBox[((a shr 8) and $FF) + 256]; b := b xor Mars_SBox[a and $FF]; a := a - KeyContext[0]; b := b - KeyContext[1]; c := c - KeyContext[2]; d := d - KeyContext[3]; PDWORD(@Data[0])^ := a; PDWORD(@Data[4])^ := b; PDWORD(@Data[8])^ := c; PDWORD(@Data[12])^ := d; {$IFDEF RangeCheck}{$R+}{$ENDIF} end; class procedure TRijndael.InvMixColumn(const a: PByteArray; const BC: Byte); var j: Integer; begin for j := 0 to (BC - 1) do PDWORD(@(a^[j * 4]))^ := PDWORD(@U1[a^[j * 4 + 0]])^ xor PDWORD(@U2[a^[j * 4 + 1]])^ xor PDWORD(@U3[a^[j * 4 + 2]])^ xor PDWORD(@U4[a^[j * 4 + 3]])^; end; class procedure TRijndael.InitKey(buff: Pointer; Size: Integer; var KeyContext: TRijndaelkey); const s_box: array [0 .. 255] of Byte = ( 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22); var KC, Rounds: DWORD; j, r, t, rconpointer: Integer; tk: array [0 .. 8 - 1, 0 .. 3] of Byte; begin FillPtrByte(@tk, SizeOf(tk), 0); CopyPtr(buff, @tk, Size); if Size <= 16 then begin KC := 4; Rounds := 10; end else if Size <= 24 then begin KC := 6; Rounds := 12; end else begin KC := 8; Rounds := 14; end; KeyContext.NumRounds := Rounds; r := 0; t := 0; j := 0; while (j < KC) and (r < (Rounds + 1)) do begin while (j < KC) and (t < 4) do begin KeyContext.rk[r, t] := PDWORD(@tk[j])^; inc(j); inc(t); end; if t = 4 then begin t := 0; inc(r); end; end; rconpointer := 0; while (r < (Rounds + 1)) do begin tk[0, 0] := tk[0, 0] xor s_box[tk[KC - 1, 1]]; tk[0, 1] := tk[0, 1] xor s_box[tk[KC - 1, 2]]; tk[0, 2] := tk[0, 2] xor s_box[tk[KC - 1, 3]]; tk[0, 3] := tk[0, 3] xor s_box[tk[KC - 1, 0]]; tk[0, 0] := tk[0, 0] xor rcon[rconpointer]; inc(rconpointer); if KC <> 8 then begin for j := 1 to (KC - 1) do PDWORD(@tk[j])^ := PDWORD(@tk[j])^ xor PDWORD(@tk[j - 1])^; end else begin for j := 1 to ((KC div 2) - 1) do PDWORD(@tk[j])^ := PDWORD(@tk[j])^ xor PDWORD(@tk[j - 1])^; tk[KC div 2, 0] := tk[KC div 2, 0] xor s_box[tk[KC div 2 - 1, 0]]; tk[KC div 2, 1] := tk[KC div 2, 1] xor s_box[tk[KC div 2 - 1, 1]]; tk[KC div 2, 2] := tk[KC div 2, 2] xor s_box[tk[KC div 2 - 1, 2]]; tk[KC div 2, 3] := tk[KC div 2, 3] xor s_box[tk[KC div 2 - 1, 3]]; for j := ((KC div 2) + 1) to (KC - 1) do PDWORD(@tk[j])^ := PDWORD(@tk[j])^ xor PDWORD(@tk[j - 1])^; end; j := 0; while (j < KC) and (r < (Rounds + 1)) do begin while (j < KC) and (t < 4) do begin KeyContext.rk[r, t] := PDWORD(@tk[j])^; inc(j); inc(t); end; if t = 4 then begin inc(r); t := 0; end; end; end; CopyPtr(@KeyContext.rk, @KeyContext.drk, SizeOf(KeyContext.rk)); for r := 1 to (Rounds - 1) do InvMixColumn(@KeyContext.drk[r], 4); end; class procedure TRijndael.Encrypt(var KeyContext: TRijndaelkey; var Data: TRijndaelBlock); begin Encrypt(KeyContext, PDWORD(@Data[0])^, PDWORD(@Data[4])^, PDWORD(@Data[8])^, PDWORD(@Data[12])^); end; class procedure TRijndael.Encrypt(var KeyContext: TRijndaelkey; var B1, B2, B3, B4: DWORD); var r: DWORD; tempb: array [0 .. 3, 0 .. 3] of Byte; a: array [0 .. 3, 0 .. 3] of Byte; begin PDWORD(@a[0, 0])^ := B1; PDWORD(@a[1, 0])^ := B2; PDWORD(@a[2, 0])^ := B3; PDWORD(@a[3, 0])^ := B4; for r := 0 to (KeyContext.NumRounds - 2) do begin PDWORD(@tempb[0])^ := PDWORD(@a[0])^ xor KeyContext.rk[r, 0]; PDWORD(@tempb[1])^ := PDWORD(@a[1])^ xor KeyContext.rk[r, 1]; PDWORD(@tempb[2])^ := PDWORD(@a[2])^ xor KeyContext.rk[r, 2]; PDWORD(@tempb[3])^ := PDWORD(@a[3])^ xor KeyContext.rk[r, 3]; PDWORD(@a[0])^ := PDWORD(@T1[tempb[0, 0]])^ xor PDWORD(@T2[tempb[1, 1]])^ xor PDWORD(@T3[tempb[2, 2]])^ xor PDWORD(@T4[tempb[3, 3]])^; PDWORD(@a[1])^ := PDWORD(@T1[tempb[1, 0]])^ xor PDWORD(@T2[tempb[2, 1]])^ xor PDWORD(@T3[tempb[3, 2]])^ xor PDWORD(@T4[tempb[0, 3]])^; PDWORD(@a[2])^ := PDWORD(@T1[tempb[2, 0]])^ xor PDWORD(@T2[tempb[3, 1]])^ xor PDWORD(@T3[tempb[0, 2]])^ xor PDWORD(@T4[tempb[1, 3]])^; PDWORD(@a[3])^ := PDWORD(@T1[tempb[3, 0]])^ xor PDWORD(@T2[tempb[0, 1]])^ xor PDWORD(@T3[tempb[1, 2]])^ xor PDWORD(@T4[tempb[2, 3]])^; end; PDWORD(@tempb[0])^ := PDWORD(@a[0])^ xor KeyContext.rk[KeyContext.NumRounds - 1, 0]; PDWORD(@tempb[1])^ := PDWORD(@a[1])^ xor KeyContext.rk[KeyContext.NumRounds - 1, 1]; PDWORD(@tempb[2])^ := PDWORD(@a[2])^ xor KeyContext.rk[KeyContext.NumRounds - 1, 2]; PDWORD(@tempb[3])^ := PDWORD(@a[3])^ xor KeyContext.rk[KeyContext.NumRounds - 1, 3]; a[0, 0] := T1[tempb[0, 0], 1]; a[0, 1] := T1[tempb[1, 1], 1]; a[0, 2] := T1[tempb[2, 2], 1]; a[0, 3] := T1[tempb[3, 3], 1]; a[1, 0] := T1[tempb[1, 0], 1]; a[1, 1] := T1[tempb[2, 1], 1]; a[1, 2] := T1[tempb[3, 2], 1]; a[1, 3] := T1[tempb[0, 3], 1]; a[2, 0] := T1[tempb[2, 0], 1]; a[2, 1] := T1[tempb[3, 1], 1]; a[2, 2] := T1[tempb[0, 2], 1]; a[2, 3] := T1[tempb[1, 3], 1]; a[3, 0] := T1[tempb[3, 0], 1]; a[3, 1] := T1[tempb[0, 1], 1]; a[3, 2] := T1[tempb[1, 2], 1]; a[3, 3] := T1[tempb[2, 3], 1]; B1 := PDWORD(@a[0])^ xor KeyContext.rk[KeyContext.NumRounds, 0]; B2 := PDWORD(@a[1])^ xor KeyContext.rk[KeyContext.NumRounds, 1]; B3 := PDWORD(@a[2])^ xor KeyContext.rk[KeyContext.NumRounds, 2]; B4 := PDWORD(@a[3])^ xor KeyContext.rk[KeyContext.NumRounds, 3]; end; class procedure TRijndael.Decrypt(var KeyContext: TRijndaelkey; var Data: TRijndaelBlock); begin Decrypt(KeyContext, PDWORD(@Data[0])^, PDWORD(@Data[4])^, PDWORD(@Data[8])^, PDWORD(@Data[12])^); end; class procedure TRijndael.Decrypt(var KeyContext: TRijndaelkey; var B1, B2, B3, B4: DWORD); var r: Integer; tempb: array [0 .. 3, 0 .. 3] of Byte; a: array [0 .. 3, 0 .. 3] of Byte; begin PDWORD(@a[0, 0])^ := B1; PDWORD(@a[1, 0])^ := B2; PDWORD(@a[2, 0])^ := B3; PDWORD(@a[3, 0])^ := B4; for r := KeyContext.NumRounds downto 2 do begin PDWORD(@tempb[0])^ := PDWORD(@a[0])^ xor KeyContext.drk[r, 0]; PDWORD(@tempb[1])^ := PDWORD(@a[1])^ xor KeyContext.drk[r, 1]; PDWORD(@tempb[2])^ := PDWORD(@a[2])^ xor KeyContext.drk[r, 2]; PDWORD(@tempb[3])^ := PDWORD(@a[3])^ xor KeyContext.drk[r, 3]; PDWORD(@a[0])^ := PDWORD(@T5[tempb[0, 0]])^ xor PDWORD(@T6[tempb[3, 1]])^ xor PDWORD(@T7[tempb[2, 2]])^ xor PDWORD(@T8[tempb[1, 3]])^; PDWORD(@a[1])^ := PDWORD(@T5[tempb[1, 0]])^ xor PDWORD(@T6[tempb[0, 1]])^ xor PDWORD(@T7[tempb[3, 2]])^ xor PDWORD(@T8[tempb[2, 3]])^; PDWORD(@a[2])^ := PDWORD(@T5[tempb[2, 0]])^ xor PDWORD(@T6[tempb[1, 1]])^ xor PDWORD(@T7[tempb[0, 2]])^ xor PDWORD(@T8[tempb[3, 3]])^; PDWORD(@a[3])^ := PDWORD(@T5[tempb[3, 0]])^ xor PDWORD(@T6[tempb[2, 1]])^ xor PDWORD(@T7[tempb[1, 2]])^ xor PDWORD(@T8[tempb[0, 3]])^; end; PDWORD(@tempb[0])^ := PDWORD(@a[0])^ xor KeyContext.drk[1, 0]; PDWORD(@tempb[1])^ := PDWORD(@a[1])^ xor KeyContext.drk[1, 1]; PDWORD(@tempb[2])^ := PDWORD(@a[2])^ xor KeyContext.drk[1, 2]; PDWORD(@tempb[3])^ := PDWORD(@a[3])^ xor KeyContext.drk[1, 3]; a[0, 0] := S5[tempb[0, 0]]; a[0, 1] := S5[tempb[3, 1]]; a[0, 2] := S5[tempb[2, 2]]; a[0, 3] := S5[tempb[1, 3]]; a[1, 0] := S5[tempb[1, 0]]; a[1, 1] := S5[tempb[0, 1]]; a[1, 2] := S5[tempb[3, 2]]; a[1, 3] := S5[tempb[2, 3]]; a[2, 0] := S5[tempb[2, 0]]; a[2, 1] := S5[tempb[1, 1]]; a[2, 2] := S5[tempb[0, 2]]; a[2, 3] := S5[tempb[3, 3]]; a[3, 0] := S5[tempb[3, 0]]; a[3, 1] := S5[tempb[2, 1]]; a[3, 2] := S5[tempb[1, 2]]; a[3, 3] := S5[tempb[0, 3]]; B1 := PDWORD(@a[0])^ xor KeyContext.drk[0, 0]; B2 := PDWORD(@a[1])^ xor KeyContext.drk[0, 1]; B3 := PDWORD(@a[2])^ xor KeyContext.drk[0, 2]; B4 := PDWORD(@a[3])^ xor KeyContext.drk[0, 3]; end; class function TTwofish.TwofishCalculateSBoxes(x: DWORD; l: Pointer; KeySize: DWORD): DWORD; var b0, B1, B2, B3: Byte; begin { precalculating permutations for H function } b0 := x and $FF; B1 := (x shr 8) and $FF; B2 := (x shr 16) and $FF; B3 := x shr 24; if KeySize > 192 then begin b0 := P8x8[1, b0] xor PByte(NativeUInt(l) + 12)^; B1 := P8x8[0, B1] xor PByte(NativeUInt(l) + 13)^; B2 := P8x8[0, B2] xor PByte(NativeUInt(l) + 14)^; B3 := P8x8[1, B3] xor PByte(NativeUInt(l) + 15)^; end; if KeySize > 128 then begin b0 := P8x8[1, b0] xor PByte(NativeUInt(l) + 8)^; B1 := P8x8[1, B1] xor PByte(NativeUInt(l) + 9)^; B2 := P8x8[0, B2] xor PByte(NativeUInt(l) + 10)^; B3 := P8x8[0, B3] xor PByte(NativeUInt(l) + 11)^; end; b0 := P8x8[0, b0] xor PByte(NativeUInt(l) + 4)^; B1 := P8x8[1, B1] xor PByte(NativeUInt(l) + 5)^; B2 := P8x8[0, B2] xor PByte(NativeUInt(l) + 6)^; B3 := P8x8[1, B3] xor PByte(NativeUInt(l) + 7)^; b0 := P8x8[1, P8x8[0, b0] xor PByte(l)^]; B1 := P8x8[0, P8x8[0, B1] xor PByte(NativeUInt(l) + 1)^]; B2 := P8x8[1, P8x8[1, B2] xor PByte(NativeUInt(l) + 2)^]; B3 := P8x8[0, P8x8[1, B3] xor PByte(NativeUInt(l) + 3)^]; Result := DWORD(b0) or (DWORD(B1) shl 8) or (DWORD(B2) shl 16) or (DWORD(B3) shl 24); end; class function TTwofish.TwofishH(x: DWORD; l: Pointer; KeySize: DWORD): DWORD; var b0, B1, B2, B3, z0, z1, z2, z3: Byte; begin b0 := x and $FF; B1 := (x shr 8) and $FF; B2 := (x shr 16) and $FF; B3 := x shr 24; if KeySize > 192 then begin b0 := P8x8[1, b0] xor PByte(NativeUInt(l) + 12)^; B1 := P8x8[0, B1] xor PByte(NativeUInt(l) + 13)^; B2 := P8x8[0, B2] xor PByte(NativeUInt(l) + 14)^; B3 := P8x8[1, B3] xor PByte(NativeUInt(l) + 15)^; end; if KeySize > 128 then begin b0 := P8x8[1, b0] xor PByte(NativeUInt(l) + 8)^; B1 := P8x8[1, B1] xor PByte(NativeUInt(l) + 9)^; B2 := P8x8[0, B2] xor PByte(NativeUInt(l) + 10)^; B3 := P8x8[0, B3] xor PByte(NativeUInt(l) + 11)^; end; b0 := P8x8[0, b0] xor PByte(NativeUInt(l) + 4)^; B1 := P8x8[1, B1] xor PByte(NativeUInt(l) + 5)^; B2 := P8x8[0, B2] xor PByte(NativeUInt(l) + 6)^; B3 := P8x8[1, B3] xor PByte(NativeUInt(l) + 7)^; b0 := P8x8[1, P8x8[0, b0] xor PByte(l)^]; B1 := P8x8[0, P8x8[0, B1] xor PByte(NativeUInt(l) + 1)^]; B2 := P8x8[1, P8x8[1, B2] xor PByte(NativeUInt(l) + 2)^]; B3 := P8x8[0, P8x8[1, B3] xor PByte(NativeUInt(l) + 3)^]; z0 := b0 xor ArrEF[B1] xor Arr5B[B2] xor Arr5B[B3]; z1 := Arr5B[b0] xor ArrEF[B1] xor ArrEF[B2] xor B3; z2 := ArrEF[b0] xor Arr5B[B1] xor B2 xor ArrEF[B3]; z3 := ArrEF[b0] xor B1 xor ArrEF[B2] xor Arr5B[B3]; Result := DWORD(z0) or (DWORD(z1) shl 8) or (DWORD(z2) shl 16) or (DWORD(z3) shl 24); end; class function TTwofish.TwofishH(const x: DWORD; const key: TTwofishKey): DWORD; var b0, B1, B2, B3, z0, z1, z2, z3: Byte; begin b0 := key.SBox0[x and $FF]; B1 := key.SBox1[(x shr 8) and $FF]; B2 := key.SBox2[(x shr 16) and $FF]; B3 := key.SBox3[x shr 24]; { P8x8 permutations are precalculated and stored in Key.SBoxes } z0 := b0 xor ArrEF[B1] xor Arr5B[B2] xor Arr5B[B3]; z1 := Arr5B[b0] xor ArrEF[B1] xor ArrEF[B2] xor B3; z2 := ArrEF[b0] xor Arr5B[B1] xor B2 xor ArrEF[B3]; z3 := ArrEF[b0] xor B1 xor ArrEF[B2] xor Arr5B[B3]; Result := DWORD(z0) or (DWORD(z1) shl 8) or (DWORD(z2) shl 16) or (DWORD(z3) shl 24); end; class function TTwofish.RSMDSMul(const x, y: Byte): Byte; var Res: DWORD; index: Byte; begin Res := 0; for Index := 7 downto 0 do begin if (y and (1 shl Index)) <> 0 then Res := Res xor (DWORD(x) shl Index); if (Res and (1 shl (8 + Index))) <> 0 then Res := Res xor ($14D shl Index); end; Result := Byte(Res); end; class function TTwofish.MultiplyMDS(const E, O: DWORD): DWORD; var E0, E1, E2, E3, O0, O1, O2, O3, R0, R1, R2, R3: Byte; begin E0 := E and $FF; E1 := (E shr 8) and $FF; E2 := (E shr 16) and $FF; E3 := (E shr 24) and $FF; O0 := O and $FF; O1 := (O shr 8) and $FF; O2 := (O shr 16) and $FF; O3 := (O shr 24) and $FF; R0 := RSMDSMul(E0, MDS[0, 0]) xor RSMDSMul(E1, MDS[0, 1]) xor RSMDSMul(E2, MDS[0, 2]) xor RSMDSMul(E3, MDS[0, 3]) xor RSMDSMul(O0, MDS[0, 4]) xor RSMDSMul(O1, MDS[0, 5]) xor RSMDSMul(O2, MDS[0, 6]) xor RSMDSMul(O3, MDS[0, 7]); R1 := RSMDSMul(E0, MDS[1, 0]) xor RSMDSMul(E1, MDS[1, 1]) xor RSMDSMul(E2, MDS[1, 2]) xor RSMDSMul(E3, MDS[1, 3]) xor RSMDSMul(O0, MDS[1, 4]) xor RSMDSMul(O1, MDS[1, 5]) xor RSMDSMul(O2, MDS[1, 6]) xor RSMDSMul(O3, MDS[1, 7]); R2 := RSMDSMul(E0, MDS[2, 0]) xor RSMDSMul(E1, MDS[2, 1]) xor RSMDSMul(E2, MDS[2, 2]) xor RSMDSMul(E3, MDS[2, 3]) xor RSMDSMul(O0, MDS[2, 4]) xor RSMDSMul(O1, MDS[2, 5]) xor RSMDSMul(O2, MDS[2, 6]) xor RSMDSMul(O3, MDS[2, 7]); R3 := RSMDSMul(E0, MDS[3, 0]) xor RSMDSMul(E1, MDS[3, 1]) xor RSMDSMul(E2, MDS[3, 2]) xor RSMDSMul(E3, MDS[3, 3]) xor RSMDSMul(O0, MDS[3, 4]) xor RSMDSMul(O1, MDS[3, 5]) xor RSMDSMul(O2, MDS[3, 6]) xor RSMDSMul(O3, MDS[3, 7]); Result := R0 or (R1 shl 8) or (R2 shl 16) or (R3 shl 24); end; class procedure TTwofish.InitKey(buff: PCCByteArray; Size: Integer; var KeyContext: TTwofishKey); var i: DWORD; Cnt: DWORD; KE: array [0 .. 3] of DWORD; KO: array [0 .. 3] of DWORD; a, b: DWORD; begin Cnt := (Size shl 3 + 63) shr 6; KeyContext.KeyLen := Size shl 3; for i := 0 to Cnt - 1 do begin KE[i] := buff^[i shl 3] + buff^[i shl 3 + 1] shl 8 + buff^[i shl 3 + 2] shl 16 + buff^[i shl 3 + 3] shl 24; KO[i] := buff^[i shl 3 + 4] + buff^[i shl 3 + 5] shl 8 + buff^[i shl 3 + 6] shl 16 + buff^[i shl 3 + 7] shl 24; KeyContext.SBoxKey[Cnt - i - 1] := MultiplyMDS(KE[i], KO[i]); end; for i := 0 to 19 do begin a := TwofishH(i * $02020202, @KE, KeyContext.KeyLen); b := TwofishH(i * $02020202 + $01010101, @KO, KeyContext.KeyLen); b := (b shl 8) or (b shr 24); KeyContext.ExpandedKey[i shl 1] := a + b; b := a + b shl 1; KeyContext.ExpandedKey[i shl 1 + 1] := (b shl 9) or (b shr 23); end; for i := 0 to 255 do begin a := (i and $FF) or ((i and $FF) shl 8) or ((i and $FF) shl 16) or ((i and $FF) shl 24); a := TwofishCalculateSBoxes(a, @KeyContext.SBoxKey, KeyContext.KeyLen); KeyContext.SBox0[i] := a and $FF; KeyContext.SBox1[i] := (a shr 8) and $FF; KeyContext.SBox2[i] := (a shr 16) and $FF; KeyContext.SBox3[i] := (a shr 24) and $FF; end; end; class procedure TTwofish.Encrypt(var KeyContext: TTwofishKey; var Data: TTwofishBlock); var R0, R1, R2, R3, t0, T1, F0, F1: DWORD; begin { prewhitening } R0 := PDWORD(@Data[0])^ xor KeyContext.ExpandedKey[0]; R1 := PDWORD(@Data[4])^ xor KeyContext.ExpandedKey[1]; R2 := PDWORD(@Data[8])^ xor KeyContext.ExpandedKey[2]; R3 := PDWORD(@Data[12])^ xor KeyContext.ExpandedKey[3]; { 0 round } t0 := TwofishH(R0, KeyContext); T1 := (R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext); F0 := (t0 + T1 + KeyContext.ExpandedKey[8]); F1 := (t0 + T1 shl 1 + KeyContext.ExpandedKey[9]); R2 := R2 xor F0; R2 := (R2 shr 1) or (R2 shl 31); R3 := (R3 shl 1) or (R3 shr 31) xor F1; { 1 round } t0 := TwofishH(R2, KeyContext); T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[10]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[11]); R0 := R0 xor F0; R0 := (R0 shr 1) or DWORD(R0 shl 31); R1 := DWORD(R1 shl 1) or (R1 shr 31) xor F1; { 2 round } t0 := TwofishH(R0, KeyContext); T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[12]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[13]); R2 := R2 xor F0; R2 := (R2 shr 1) or DWORD(R2 shl 31); R3 := DWORD(R3 shl 1) or (R3 shr 31) xor F1; { 3 round } t0 := TwofishH(R2, KeyContext); T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[14]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[15]); R0 := R0 xor F0; R0 := (R0 shr 1) or DWORD(R0 shl 31); R1 := DWORD(R1 shl 1) or (R1 shr 31) xor F1; { 4 round } t0 := TwofishH(R0, KeyContext); T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[16]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[17]); R2 := R2 xor F0; R2 := (R2 shr 1) or DWORD(R2 shl 31); R3 := DWORD(R3 shl 1) or (R3 shr 31) xor F1; { 5 round } t0 := TwofishH(R2, KeyContext); T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[18]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[19]); R0 := R0 xor F0; R0 := (R0 shr 1) or DWORD(R0 shl 31); R1 := DWORD(R1 shl 1) or (R1 shr 31) xor F1; { 6 round } t0 := TwofishH(R0, KeyContext); T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[20]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[21]); R2 := R2 xor F0; R2 := (R2 shr 1) or DWORD(R2 shl 31); R3 := DWORD(R3 shl 1) or (R3 shr 31) xor F1; { 7 round } t0 := TwofishH(R2, KeyContext); T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[22]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[23]); R0 := R0 xor F0; R0 := (R0 shr 1) or DWORD(R0 shl 31); R1 := DWORD(R1 shl 1) or (R1 shr 31) xor F1; { 8 round } t0 := TwofishH(R0, KeyContext); T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[24]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[25]); R2 := R2 xor F0; R2 := (R2 shr 1) or DWORD(R2 shl 31); R3 := DWORD(R3 shl 1) or (R3 shr 31) xor F1; { 9 round } t0 := TwofishH(R2, KeyContext); T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[26]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[27]); R0 := R0 xor F0; R0 := (R0 shr 1) or DWORD(R0 shl 31); R1 := DWORD(R1 shl 1) or (R1 shr 31) xor F1; { 10 round } t0 := TwofishH(R0, KeyContext); T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[28]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[29]); R2 := R2 xor F0; R2 := (R2 shr 1) or DWORD(R2 shl 31); R3 := DWORD(R3 shl 1) or (R3 shr 31) xor F1; { 11 round } t0 := TwofishH(R2, KeyContext); T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[30]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[31]); R0 := R0 xor F0; R0 := (R0 shr 1) or DWORD(R0 shl 31); R1 := DWORD(R1 shl 1) or (R1 shr 31) xor F1; { 12 round } t0 := TwofishH(R0, KeyContext); T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[32]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[33]); R2 := R2 xor F0; R2 := (R2 shr 1) or DWORD(R2 shl 31); R3 := DWORD(R3 shl 1) or (R3 shr 31) xor F1; { 13 round } t0 := TwofishH(R2, KeyContext); T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[34]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[35]); R0 := R0 xor F0; R0 := (R0 shr 1) or DWORD(R0 shl 31); R1 := DWORD(R1 shl 1) or (R1 shr 31) xor F1; { 14 round } t0 := TwofishH(R0, KeyContext); T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[36]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[37]); R2 := R2 xor F0; R2 := (R2 shr 1) or DWORD(R2 shl 31); R3 := DWORD(R3 shl 1) or (R3 shr 31) xor F1; { 15 round } t0 := TwofishH(R2, KeyContext); T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[38]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[39]); R0 := R0 xor F0; R0 := (R0 shr 1) or DWORD(R0 shl 31); R1 := DWORD(R1 shl 1) or (R1 shr 31) xor F1; PDWORD(@Data[0])^ := R2 xor KeyContext.ExpandedKey[4]; PDWORD(@Data[4])^ := R3 xor KeyContext.ExpandedKey[5]; PDWORD(@Data[8])^ := R0 xor KeyContext.ExpandedKey[6]; PDWORD(@Data[12])^ := R1 xor KeyContext.ExpandedKey[7]; end; class procedure TTwofish.Decrypt(var KeyContext: TTwofishKey; var Data: TTwofishBlock); var R0, R1, R2, R3, t0, T1, F0, F1: DWORD; begin { prewhitening } R0 := PDWORD(@Data[0])^ xor KeyContext.ExpandedKey[4]; R1 := PDWORD(@Data[4])^ xor KeyContext.ExpandedKey[5]; R2 := PDWORD(@Data[8])^ xor KeyContext.ExpandedKey[6]; R3 := PDWORD(@Data[12])^ xor KeyContext.ExpandedKey[7]; { R0,R1 and R2,R3 are replaced from round to round - small optimization } { 15 round } t0 := TwofishH(R0, KeyContext);; T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[38]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[39]); R2 := (R2 shl 1) or DWORD(R2 shr 31) xor F0; R3 := R3 xor F1; R3 := DWORD(R3 shr 1) or (R3 shl 31); { 14 round } t0 := TwofishH(R2, KeyContext);; T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[36]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[37]); R0 := (R0 shl 1) or DWORD(R0 shr 31) xor F0; R1 := R1 xor F1; R1 := DWORD(R1 shr 1) or (R1 shl 31); { 13 round } t0 := TwofishH(R0, KeyContext);; T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[34]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[35]); R2 := (R2 shl 1) or DWORD(R2 shr 31) xor F0; R3 := R3 xor F1; R3 := DWORD(R3 shr 1) or (R3 shl 31); { 12 round } t0 := TwofishH(R2, KeyContext);; T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[32]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[33]); R0 := (R0 shl 1) or DWORD(R0 shr 31) xor F0; R1 := R1 xor F1; R1 := DWORD(R1 shr 1) or (R1 shl 31); { 11 round } t0 := TwofishH(R0, KeyContext);; T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[30]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[31]); R2 := (R2 shl 1) or DWORD(R2 shr 31) xor F0; R3 := R3 xor F1; R3 := DWORD(R3 shr 1) or (R3 shl 31); { 10 round } t0 := TwofishH(R2, KeyContext);; T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[28]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[29]); R0 := (R0 shl 1) or DWORD(R0 shr 31) xor F0; R1 := R1 xor F1; R1 := DWORD(R1 shr 1) or (R1 shl 31); { 9 round } t0 := TwofishH(R0, KeyContext);; T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[26]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[27]); R2 := (R2 shl 1) or DWORD(R2 shr 31) xor F0; R3 := R3 xor F1; R3 := DWORD(R3 shr 1) or (R3 shl 31); { 8 round } t0 := TwofishH(R2, KeyContext);; T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[24]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[25]); R0 := (R0 shl 1) or DWORD(R0 shr 31) xor F0; R1 := R1 xor F1; R1 := DWORD(R1 shr 1) or (R1 shl 31); { 7 round } t0 := TwofishH(R0, KeyContext); T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext); F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[22]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[23]); R2 := (R2 shl 1) or DWORD(R2 shr 31) xor F0; R3 := R3 xor F1; R3 := DWORD(R3 shr 1) or (R3 shl 31); { 6 round } t0 := TwofishH(R2, KeyContext);; T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[20]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[21]); R0 := (R0 shl 1) or DWORD(R0 shr 31) xor F0; R1 := R1 xor F1; R1 := DWORD(R1 shr 1) or (R1 shl 31); { 5 round } t0 := TwofishH(R0, KeyContext);; T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[18]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[19]); R2 := (R2 shl 1) or DWORD(R2 shr 31) xor F0; R3 := R3 xor F1; R3 := DWORD(R3 shr 1) or (R3 shl 31); { 4 round } t0 := TwofishH(R2, KeyContext);; T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[16]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[17]); R0 := (R0 shl 1) or DWORD(R0 shr 31) xor F0; R1 := R1 xor F1; R1 := DWORD(R1 shr 1) or (R1 shl 31); { 3 round } t0 := TwofishH(R0, KeyContext);; T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[14]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[15]); R2 := (R2 shl 1) or DWORD(R2 shr 31) xor F0; R3 := R3 xor F1; R3 := DWORD(R3 shr 1) or (R3 shl 31); { 2 round } t0 := TwofishH(R2, KeyContext);; T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[12]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[13]); R0 := (R0 shl 1) or DWORD(R0 shr 31) xor F0; R1 := R1 xor F1; R1 := DWORD(R1 shr 1) or (R1 shl 31); { 1 round } t0 := TwofishH(R0, KeyContext);; T1 := DWORD(R1 shl 8) or (R1 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[10]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[11]); R2 := (R2 shl 1) or DWORD(R2 shr 31) xor F0; R3 := R3 xor F1; R3 := DWORD(R3 shr 1) or (R3 shl 31); { 0 round } t0 := TwofishH(R2, KeyContext);; T1 := DWORD(R3 shl 8) or (R3 shr 24); T1 := TwofishH(T1, KeyContext);; F0 := DWORD(t0 + T1 + KeyContext.ExpandedKey[8]); F1 := DWORD(t0 + T1 shl 1 + KeyContext.ExpandedKey[9]); R0 := (R0 shl 1) or DWORD(R0 shr 31) xor F0; R1 := R1 xor F1; R1 := DWORD(R1 shr 1) or (R1 shl 31); PDWORD(@Data[0])^ := R2 xor KeyContext.ExpandedKey[0]; PDWORD(@Data[4])^ := R3 xor KeyContext.ExpandedKey[1]; PDWORD(@Data[8])^ := R0 xor KeyContext.ExpandedKey[2]; PDWORD(@Data[12])^ := R1 xor KeyContext.ExpandedKey[3]; end; constructor TCipher_Base.Create(KeyBuffer_: TCipherKeyBuffer); begin inherited Create; FCipherSecurity := csNone; SetLength(FLastGenerateKey, 0); FLevel := 1; FProcessTail := True; FCBC := False; end; destructor TCipher_Base.Destroy; begin SetLength(FLastGenerateKey, 0); inherited Destroy; end; procedure TCipher_Base.Encrypt(sour: Pointer; Size: NativeInt); begin end; procedure TCipher_Base.Decrypt(sour: Pointer; Size: NativeInt); begin end; procedure TCipher_Base.Process(sour: Pointer; Size: NativeInt; Level_: Integer; Encrypt_, ProcessTail_, CBC_: Boolean); begin FLevel := Level_; FProcessTail := ProcessTail_; FCBC := CBC_; if Encrypt_ then Encrypt(sour, Size) else Decrypt(sour, Size); end; procedure TCipher_Base.Test; var m64: TMemoryStream64; md5_1, md5_2: TMD5; i: Integer; begin m64 := TMemoryStream64.Create; m64.Size := 999; MT19937Rand32(MaxInt, m64.Memory, m64.Size div 4); for i := 1 to 4 do begin FProcessTail := not FProcessTail; FLevel := i; md5_1 := umlStreamMD5(m64); Encrypt(m64.Memory, m64.Size); Decrypt(m64.Memory, m64.Size); md5_2 := umlStreamMD5(m64); if umlCompareMD5(md5_1, md5_2) then DoStatus('test %s level %d ok.', [ClassName, FLevel]) else DoStatus('test %s level %d error.', [ClassName, FLevel]); end; DisposeObject(m64); end; constructor TCipher_DES64.Create(KeyBuffer_: TCipherKeyBuffer); var k: TKey64; begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, k); TDES.InitEncryptDES(k, FEkey, True); TDES.InitEncryptDES(k, FDKey, False); end; procedure TCipher_DES64.Encrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; for i := 0 to FLevel - 1 do begin p := 0; while p + 8 <= Size do begin TDES.EncryptDES(FEkey, PDESBlock(GetOffset(sour, p))^); inc(p, 8); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_DES64.Decrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); for i := 0 to FLevel - 1 do begin p := 0; while p + 8 <= Size do begin TDES.EncryptDES(FDKey, PDESBlock(GetOffset(sour, p))^); inc(p, 8); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); end; constructor TCipher_DES128.Create(KeyBuffer_: TCipherKeyBuffer); var k: TKey128; begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, k); TDES.InitEncryptTripleDES(k, FEkey, True); TDES.InitEncryptTripleDES(k, FDKey, False); end; procedure TCipher_DES128.Encrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; for i := 0 to FLevel - 1 do begin p := 0; while p + 8 <= Size do begin TDES.EncryptTripleDES(FEkey, PDESBlock(GetOffset(sour, p))^); inc(p, 8); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_DES128.Decrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); for i := 0 to FLevel - 1 do begin p := 0; while p + 8 <= Size do begin TDES.EncryptTripleDES(FDKey, PDESBlock(GetOffset(sour, p))^); inc(p, 8); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); end; constructor TCipher_DES192.Create(KeyBuffer_: TCipherKeyBuffer); var k1, k2, k3: TKey64; begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, k1, k2, k3); TDES.InitEncryptTripleDES3Key(k1, k2, k3, FEkey, True); TDES.InitEncryptTripleDES3Key(k1, k2, k3, FDKey, False); end; procedure TCipher_DES192.Encrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; for i := 0 to FLevel - 1 do begin p := 0; while p + 8 <= Size do begin TDES.EncryptTripleDES3Key(FEkey, PDESBlock(GetOffset(sour, p))^); inc(p, 8); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_DES192.Decrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); for i := 0 to FLevel - 1 do begin p := 0; while p + 8 <= Size do begin TDES.EncryptTripleDES3Key(FDKey, PDESBlock(GetOffset(sour, p))^); inc(p, 8); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); end; constructor TCipher_BlowFish.Create(KeyBuffer_: TCipherKeyBuffer); var k: TKey128; begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, k); TBlowfish.InitEncryptBF(k, Fkey); end; procedure TCipher_BlowFish.Encrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; for i := 0 to FLevel - 1 do begin p := 0; while p + 8 <= Size do begin TBlowfish.EncryptBF(Fkey, PBFBlock(GetOffset(sour, p))^, True); inc(p, 8); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_BlowFish.Decrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); for i := 0 to FLevel - 1 do begin p := 0; while p + 8 <= Size do begin TBlowfish.EncryptBF(Fkey, PBFBlock(GetOffset(sour, p))^, False); inc(p, 8); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); end; constructor TCipher_LBC.Create(KeyBuffer_: TCipherKeyBuffer); var k: TKey128; begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, k); TLBC.InitEncryptLBC(k, FEkey, 16, True); TLBC.InitEncryptLBC(k, FDKey, 16, False); end; procedure TCipher_LBC.Encrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; for i := 0 to FLevel - 1 do begin p := 0; while p + 16 <= Size do begin TLBC.EncryptLBC(FEkey, PLBCBlock(GetOffset(sour, p))^); inc(p, 16); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_LBC.Decrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); for i := 0 to FLevel - 1 do begin p := 0; while p + 16 <= Size do begin TLBC.EncryptLBC(FDKey, PLBCBlock(GetOffset(sour, p))^); inc(p, 16); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); end; constructor TCipher_LQC.Create(KeyBuffer_: TCipherKeyBuffer); begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, Fkey); end; procedure TCipher_LQC.Encrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; for i := 0 to FLevel - 1 do begin p := 0; while p + 8 <= Size do begin TLBC.EncryptLQC(Fkey, PLQCBlock(GetOffset(sour, p))^, True); inc(p, 8); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_LQC.Decrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); for i := 0 to FLevel - 1 do begin p := 0; while p + 8 <= Size do begin TLBC.EncryptLQC(Fkey, PLQCBlock(GetOffset(sour, p))^, False); inc(p, 8); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); end; constructor TCipher_RNG32.Create(KeyBuffer_: TCipherKeyBuffer); var k: DWORD; begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, k); TRNG.InitEncryptRNG32(k, Fkey); end; procedure TCipher_RNG32.Encrypt(sour: Pointer; Size: NativeInt); var tmp: TRNG32Context; begin tmp := Fkey; TRNG.EncryptRNG32(tmp, sour^, Size); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_RNG32.Decrypt(sour: Pointer; Size: NativeInt); var tmp: TRNG32Context; begin if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); tmp := Fkey; TRNG.EncryptRNG32(tmp, sour^, Size); end; constructor TCipher_RNG64.Create(KeyBuffer_: TCipherKeyBuffer); var k1, k2: DWORD; begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, k1, k2); TRNG.InitEncryptRNG64(k1, k2, Fkey); end; procedure TCipher_RNG64.Encrypt(sour: Pointer; Size: NativeInt); var tmp: TRNG64Context; begin tmp := Fkey; TRNG.EncryptRNG64(tmp, sour^, Size); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_RNG64.Decrypt(sour: Pointer; Size: NativeInt); var tmp: TRNG64Context; begin if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); tmp := Fkey; TRNG.EncryptRNG64(tmp, sour^, Size); end; constructor TCipher_LSC.Create(KeyBuffer_: TCipherKeyBuffer); var k: TBytes; k255: TBytes; begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, k); if length(k) > 255 then begin SetLength(k255, 255); THashMD.GenerateLMDKey((@k255[0])^, 255, k); end else k255 := k; TLSC.InitEncryptLSC((@k255[0])^, length(k255), Fkey); end; procedure TCipher_LSC.Encrypt(sour: Pointer; Size: NativeInt); var tmp: TLSCContext; begin tmp := Fkey; TLSC.EncryptLSC(tmp, sour^, Size); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_LSC.Decrypt(sour: Pointer; Size: NativeInt); var tmp: TLSCContext; begin if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); tmp := Fkey; TLSC.EncryptLSC(tmp, sour^, Size); end; constructor TCipher_XXTea512.Create(KeyBuffer_: TCipherKeyBuffer); begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, Fkey); end; procedure TCipher_XXTea512.Encrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; for i := 0 to FLevel - 1 do begin p := 0; while p + 64 <= Size do begin XXTEAEncrypt(Fkey, PXXTEABlock(GetOffset(sour, p))^); inc(p, 64); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_XXTea512.Decrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); for i := 0 to FLevel - 1 do begin p := 0; while p + 64 <= Size do begin XXTEADecrypt(Fkey, PXXTEABlock(GetOffset(sour, p))^); inc(p, 64); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); end; constructor TCipher_RC6.Create(KeyBuffer_: TCipherKeyBuffer); var k, k256: TBytes; begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, k); SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TRC6.InitKey(@k256[0], 32, Fkey); end; procedure TCipher_RC6.Encrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; for i := 0 to FLevel - 1 do begin p := 0; while p + 16 <= Size do begin TRC6.Encrypt(Fkey, PRC6Block(GetOffset(sour, p))^); inc(p, 16); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_RC6.Decrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); for i := 0 to FLevel - 1 do begin p := 0; while p + 16 <= Size do begin TRC6.Decrypt(Fkey, PRC6Block(GetOffset(sour, p))^); inc(p, 16); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); end; constructor TCipher_Serpent.Create(KeyBuffer_: TCipherKeyBuffer); var k, k256: TBytes; begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, k); SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TSerpent.InitKey(@k256[0], 32, Fkey); end; procedure TCipher_Serpent.Encrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; for i := 0 to FLevel - 1 do begin p := 0; while p + 16 <= Size do begin TSerpent.Encrypt(Fkey, PSerpentBlock(GetOffset(sour, p))^); inc(p, 16); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_Serpent.Decrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); for i := 0 to FLevel - 1 do begin p := 0; while p + 16 <= Size do begin TSerpent.Decrypt(Fkey, PSerpentBlock(GetOffset(sour, p))^); inc(p, 16); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); end; constructor TCipher_Mars.Create(KeyBuffer_: TCipherKeyBuffer); var k, k256: TBytes; begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, k); SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TMars.InitKey(@k256[0], 32, Fkey); end; procedure TCipher_Mars.Encrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; for i := 0 to FLevel - 1 do begin p := 0; while p + 16 <= Size do begin TMars.Encrypt(Fkey, PMarsBlock(GetOffset(sour, p))^); inc(p, 16); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_Mars.Decrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); for i := 0 to FLevel - 1 do begin p := 0; while p + 16 <= Size do begin TMars.Decrypt(Fkey, PMarsBlock(GetOffset(sour, p))^); inc(p, 16); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); end; constructor TCipher_Rijndael.Create(KeyBuffer_: TCipherKeyBuffer); var k, k256: TBytes; begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, k); SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TRijndael.InitKey(@k256[0], 32, Fkey); end; procedure TCipher_Rijndael.Encrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; for i := 0 to FLevel - 1 do begin p := 0; while p + 16 <= Size do begin TRijndael.Encrypt(Fkey, PRijndaelBlock(GetOffset(sour, p))^); inc(p, 16); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_Rijndael.Decrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); for i := 0 to FLevel - 1 do begin p := 0; while p + 16 <= Size do begin TRijndael.Decrypt(Fkey, PRijndaelBlock(GetOffset(sour, p))^); inc(p, 16); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); end; constructor TCipher_TwoFish.Create(KeyBuffer_: TCipherKeyBuffer); var k, k256: TBytes; begin inherited Create(KeyBuffer_); TCipher.GetKey(@KeyBuffer_, k); SetLength(k256, 32); THashMD.GenerateLMDKey((@k256[0])^, 32, k); TTwofish.InitKey(@k256[0], 32, Fkey); end; procedure TCipher_TwoFish.Encrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; for i := 0 to FLevel - 1 do begin p := 0; while p + 16 <= Size do begin TTwofish.Encrypt(Fkey, PTwofishBlock(GetOffset(sour, p))^); inc(p, 16); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); end; procedure TCipher_TwoFish.Decrypt(sour: Pointer; Size: NativeInt); var i: Integer; p: NativeInt; begin if Size = 0 then Exit; if FCBC then TCipher.BlockCBC(sour, Size, @SystemCBC[0], length(SystemCBC)); for i := 0 to FLevel - 1 do begin p := 0; while p + 16 <= Size do begin TTwofish.Decrypt(Fkey, PTwofishBlock(GetOffset(sour, p))^); inc(p, 16); end; end; if FProcessTail and (p < Size) then TCipher.EncryptTail(GetOffset(sour, p), Size - p); end; function CreateCipherClass(cs: TCipherSecurity; KeyBuffer_: TCipherKeyBuffer): TCipher_Base; begin case cs of csNone: Result := TCipher_Base.Create(KeyBuffer_); csDES64: Result := TCipher_DES64.Create(KeyBuffer_); csDES128: Result := TCipher_DES128.Create(KeyBuffer_); csDES192: Result := TCipher_DES192.Create(KeyBuffer_); csBlowfish: Result := TCipher_BlowFish.Create(KeyBuffer_); csLBC: Result := TCipher_LBC.Create(KeyBuffer_); csLQC: Result := TCipher_LQC.Create(KeyBuffer_); csRNG32: Result := TCipher_RNG32.Create(KeyBuffer_); csRNG64: Result := TCipher_RNG64.Create(KeyBuffer_); csLSC: Result := TCipher_LSC.Create(KeyBuffer_); csTwoFish: Result := TCipher_TwoFish.Create(KeyBuffer_); csXXTea512: Result := TCipher_XXTea512.Create(KeyBuffer_); csRC6: Result := TCipher_RC6.Create(KeyBuffer_); csSerpent: Result := TCipher_Serpent.Create(KeyBuffer_); csMars: Result := TCipher_Mars.Create(KeyBuffer_); csRijndael: Result := TCipher_Rijndael.Create(KeyBuffer_); else Result := TCipher_Base.Create(KeyBuffer_); end; Result.FCipherSecurity := cs; end; function CreateCipherClassFromPassword(cs: TCipherSecurity; password_: TPascalString): TCipher_Base; var k: TCipherKeyBuffer; begin TCipher.GenerateKey(cs, password_, k); Result := CreateCipherClass(cs, k); end; function CreateCipherClassFromBuffer(cs: TCipherSecurity; key: TCipherKeyBuffer): TCipher_Base; var k: TCipherKeyBuffer; begin TCipher.GenerateKey(cs, @key[0], length(key), k); Result := CreateCipherClass(cs, k); SetLength(k, 0); // copy key SetLength(Result.FLastGenerateKey, length(key)); CopyPtr(@key[0], @Result.FLastGenerateKey[0], length(key)); end; function CreateCipherClassFromBuffer(cs: TCipherSecurity; buffPtr: Pointer; Size: NativeInt): TCipher_Base; var k: TCipherKeyBuffer; begin TCipher.GenerateKey(cs, buffPtr, Size, k); Result := CreateCipherClass(cs, k); SetLength(k, 0); // copy key SetLength(Result.FLastGenerateKey, Size); CopyPtr(buffPtr, @Result.FLastGenerateKey[0], Size); end; procedure TestCoreCipher; var Buffer: TBytes; sour, Dest: TMemoryStream64; k: TCipherKeyBuffer; cs: TCipherSecurity; sourHash: TSHA1Digest; d: TTimeTick; hs: THashSecurity; hByte: TBytes; {$IFDEF Parallel} Parallel: TParallelCipher; {$ENDIF} ps: TListPascalString; cBase: TCipher_Base; s: TPascalString; begin sour := TMemoryStream64.Create; sour.Size := Int64(10 * 1024 * 1024 + 9); FillPtrByte(sour.Memory, sour.Size, $7F); DoStatus('stream mode md5 :' + umlStreamMD5String(sour).Text); DoStatus('pointer mode md5:' + umlMD5String(sour.Memory, sour.Size).Text); DisposeObject(sour); DoStatus('Generate and verify QuantumCryptographyPassword test'); s := GenerateQuantumCryptographyPassword('123456'); if not CompareQuantumCryptographyPassword('123456', s) then DoStatus('QuantumCryptographyPassword failed!'); if CompareQuantumCryptographyPassword('1234560', s) then DoStatus('QuantumCryptographyPassword failed!'); DoStatus('Generate and verify password test'); DoStatus('verify short password'); s := GeneratePasswordHash(TCipher.CAllHash, '1'); if not ComparePasswordHash('1', s) then DoStatus('PasswordHash failed!'); if ComparePasswordHash('11', s) then DoStatus('PasswordHash failed!'); DoStatus('verify long password'); s := GeneratePasswordHash(TCipher.CAllHash, 'hello world 123456'); if not ComparePasswordHash('hello world 123456', s) then DoStatus('PasswordHash failed!'); if ComparePasswordHash('111 hello world 123456', s) then DoStatus('PasswordHash failed!'); DoStatus('verify full chiher style password'); s := GeneratePassword(TCipher.AllCipher, 'hello world'); if not ComparePassword(TCipher.AllCipher, 'hello world', s) then DoStatus('Password cipher test failed! cipher: %s', ['']); if ComparePassword(TCipher.AllCipher, 'hello_world', s) then DoStatus('Password cipher test failed! cipher: %s', ['']); for cs in TCipher.AllCipher do begin DoStatus('verify %s chiher style password', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); s := GeneratePassword(TCipher.AllCipher, 'hello world'); if not ComparePassword(TCipher.AllCipher, 'hello world', s) then DoStatus('Password cipher test failed! cipher: %s', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); if ComparePassword(TCipher.AllCipher, 'hello_world', s) then DoStatus('Password cipher test failed! cipher: %s', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); end; // hash and Sequence Encrypt SetLength(Buffer, 128 * 1024); FillPtrByte(@Buffer[0], length(Buffer), 99); ps := TListPascalString.Create; DoStatus('Generate Sequence Hash'); GenerateSequHash(TCipher.CAllHash, @Buffer[0], length(Buffer), ps); // DoStatus(ps.Text); if not CompareSequHash(ps, @Buffer[0], length(Buffer)) then DoStatus('hash compare failed!'); DoStatus('test Sequence Encrypt'); k := TPascalString('hello world').Bytes; if not SequEncryptWithDirect(TCipher.AllCipher, @Buffer[0], length(Buffer), k, True, True) then DoStatus('SequEncrypt failed!'); if not SequEncryptWithDirect(TCipher.AllCipher, @Buffer[0], length(Buffer), k, False, True) then DoStatus('SequEncrypt failed!'); DoStatus('verify Sequence Encrypt'); if not CompareSequHash(ps, @Buffer[0], length(Buffer)) then DoStatus('hash compare failed!'); // cipher Encrypt performance SetLength(Buffer, 1024 * 1024 * 1 + 99); FillPtrByte(@Buffer[0], length(Buffer), $7F); sour := TMemoryStream64.Create; Dest := TMemoryStream64.Create; sour.write(Buffer[0], high(Buffer)); Dest.Clear; sour.Position := 0; Dest.CopyFrom(sour, sour.Size); sour.Position := 0; Dest.Position := 0; sourHash := TCipher.GenerateSHA1Hash(sour.Memory, sour.Size); {$IFDEF Parallel} DoStatus(#13#10'Parallel cipher performance test'); for cs in TCipher.AllCipher do begin TCipher.GenerateKey(cs, 'hello world', k); Parallel := TParallelCipher.Create; Dest.Clear; sour.Position := 0; Dest.CopyFrom(sour, sour.Size); sour.Position := 0; Dest.Position := 0; d := GetTimeTick; if not Parallel.EncryptBufferCBC(cs, Dest.Memory, Dest.Size, @k, True, True) then DoStatus('%s: Parallel encode failed', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); if not Parallel.EncryptBufferCBC(cs, Dest.Memory, Dest.Size, @k, False, True) then DoStatus('%s: Parallel decode failed', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); DoStatus('%s - Parallel performance:%dms', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs)), GetTimeTick - d]); if not TCipher.CompareHash(TCipher.GenerateSHA1Hash(Dest.Memory, Dest.Size), sourHash) then DoStatus('%s Parallel hash error!', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); DisposeObject(Parallel); end; for cs in TCipher.AllCipher do begin TCipher.GenerateKey(cs, 'hello world', k); Parallel := TParallelCipher.Create; Dest.Clear; sour.Position := 0; Dest.CopyFrom(sour, sour.Size); sour.Position := 0; Dest.Position := 0; d := GetTimeTick; if not TCipher.EncryptBufferCBC(cs, Dest.Memory, Dest.Size, @k, True, True) then DoStatus('%s: normal 2 Parallel encode failed', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); if not Parallel.EncryptBufferCBC(cs, Dest.Memory, Dest.Size, @k, False, True) then DoStatus('%s: normal 2 Parallel decode failed', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); DoStatus('%s - normal 2 Parallel performance:%dms', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs)), GetTimeTick - d]); if not TCipher.CompareHash(TCipher.GenerateSHA1Hash(Dest.Memory, Dest.Size), sourHash) then DoStatus('%s normal 2 Parallel hash error!', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); DisposeObject(Parallel); end; for cs in TCipher.AllCipher do begin TCipher.GenerateKey(cs, 'hello world', k); Parallel := TParallelCipher.Create; Dest.Clear; sour.Position := 0; Dest.CopyFrom(sour, sour.Size); sour.Position := 0; Dest.Position := 0; d := GetTimeTick; if not Parallel.EncryptBufferCBC(cs, Dest.Memory, Dest.Size, @k, True, True) then DoStatus('%s: Parallel 2 normal encode failed', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); if not TCipher.EncryptBufferCBC(cs, Dest.Memory, Dest.Size, @k, False, True) then DoStatus('%s: Parallel 2 normal decode failed', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); DoStatus('%s - Parallel 2 normal performance:%dms', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs)), GetTimeTick - d]); if not TCipher.CompareHash(TCipher.GenerateSHA1Hash(Dest.Memory, Dest.Size), sourHash) then DoStatus('%s Parallel 2 normal hash error!', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); DisposeObject(Parallel); end; {$ENDIF} DoStatus(#13#10'normal cipher performance test'); for cs in TCipher.AllCipher do begin TCipher.GenerateKey(cs, 'hello world', k); Dest.Clear; sour.Position := 0; Dest.CopyFrom(sour, sour.Size); sour.Position := 0; Dest.Position := 0; d := GetTimeTick; if not TCipher.EncryptBufferCBC(cs, Dest.Memory, Dest.Size, @k, True, True) then DoStatus('%s: encode failed', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); if not TCipher.EncryptBufferCBC(cs, Dest.Memory, Dest.Size, @k, False, True) then DoStatus('%s: decode failed', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); DoStatus('%s - normal performance:%dms', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs)), GetTimeTick - d]); if not TCipher.CompareHash(TCipher.GenerateSHA1Hash(Dest.Memory, Dest.Size), sourHash) then DoStatus('%s hash error!', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); end; DoStatus(#13#10'cipher instance classes test'); // cipher class test for cs in TCipher.AllCipher do begin TCipher.GenerateKey(cs, 'hello world', k); Dest.Clear; sour.Position := 0; Dest.CopyFrom(sour, sour.Size); sour.Position := 0; Dest.Position := 0; d := GetTimeTick; if not TCipher.EncryptBufferCBC(cs, Dest.Memory, Dest.Size, @k, True, True) then DoStatus('%s: encode failed', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); cBase := CreateCipherClass(cs, k); cBase.FProcessTail := True; cBase.FCBC := True; cBase.Decrypt(Dest.Memory, Dest.Size); DoStatus('%s - instance encrypt performance:%dms', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs)), GetTimeTick - d]); if not TCipher.CompareHash(TCipher.GenerateSHA1Hash(Dest.Memory, Dest.Size), sourHash) then DoStatus('%s decrypt for %s hash error!', [cBase.ClassName, GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); DisposeObject(cBase); end; for cs in TCipher.AllCipher do begin TCipher.GenerateKey(cs, 'hello world', k); Dest.Clear; sour.Position := 0; Dest.CopyFrom(sour, sour.Size); sour.Position := 0; Dest.Position := 0; d := GetTimeTick; cBase := CreateCipherClass(cs, k); cBase.FProcessTail := True; cBase.FCBC := True; cBase.Encrypt(Dest.Memory, Dest.Size); if not TCipher.EncryptBufferCBC(cs, Dest.Memory, Dest.Size, @k, False, True) then DoStatus('%s: Decode failed', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); DoStatus('%s - instance encrypt performance:%dms', [GetEnumName(TypeInfo(TCipherSecurity), Integer(cs)), GetTimeTick - d]); if not TCipher.CompareHash(TCipher.GenerateSHA1Hash(Dest.Memory, Dest.Size), sourHash) then DoStatus('%s encrypt for %s hash error!', [cBase.ClassName, GetEnumName(TypeInfo(TCipherSecurity), Integer(cs))]); DisposeObject(cBase); end; // hash performance DoStatus(#13#10'hash performance test'); Dest.Clear; sour.Position := 0; Dest.CopyFrom(sour, sour.Size); sour.Position := 0; Dest.Position := 0; for hs := low(THashSecurity) to high(THashSecurity) do begin d := GetTimeTick; TCipher.GenerateHashByte(hs, Dest.Memory, Dest.Size, hByte); DoStatus('%s - performance:%dms', [GetEnumName(TypeInfo(THashSecurity), Integer(hs)), (GetTimeTick - d)]); end; DoStatus(#13#10'Cipher test done!'); DisposeObject([ps, sour, Dest]); end; initialization InitSysCBCAndDefaultKey(Int64($F0F0F0F0F0F00F0F)); finalization SetLength(SystemCBC, 0); end.
unit VirtualIconThread; // Version 1.3.0 // // 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/ // // Alternatively, you may redistribute this library, use and/or modify it under the terms of the // GNU Lesser General Public License as published by the Free Software Foundation; // either version 2.1 of the License, or (at your option) any later version. // You may obtain a copy of the LGPL at http://www.gnu.org/copyleft/. // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the // specific language governing rights and limitations under the License. // // The initial developer of this code is Jim Kueneman <jimdk@mindspring.com> // //---------------------------------------------------------------------------- interface {$include Compilers.inc} {$include VSToolsAddIns.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, ShlObj, ShellAPI, ActiveX, VirtualShellUtilities, VirtualNamespace, VirtualResources; const SAFETLYVALVEMAX = 20; // Number of times PostMessage it tried if it fails (very unlikely) type PVirtualThreadIconInfo = ^TVirtualThreadIconInfo; TVirtualThreadIconInfo = packed record PIDL: PItemIDList; // PIDL to the object that requested the image index IconIndex: integer; // Extracted Icon Index LargeIcon: Boolean; // Extract the large Icon or Small Icon Control: TWinControl; // The window that needs the icon UserData: Pointer; // In VET and VLVEx this is the node. The value in this field is used as the test in ClearPendingItem(TestItem: Pointer) so true is if UserData = TestItem UserData2: Pointer; // User definable Tag: integer; // In VLVEx this is the item index MessageID: LongWord; // The WM_xxx Message to send the control end; TWMVTSetIconIndex = packed record Msg: Cardinal; IconInfo: PVirtualThreadIconInfo; end; type { Thread to extract images without slowing down VET } TVirtualImageThread = class(TThread) private FQueryList: TThreadList; FImageThreadEvent: THandle; // FMalloc: IMalloc; FExtractedIconIndex: integer; protected procedure AddNewItem(Control: TWinControl; WindowsMessageID: LongWord; PIDL: PItemIDList; LargeIcon: Boolean; UserData: Pointer; Tag: integer); procedure ClearPendingItem(Control: TWinControl; TestItem: Pointer; MessageID: LongWord; const Malloc: IMalloc); procedure ClearPendingItems(Control: TWinControl; MessageID: LongWord; const Malloc: IMalloc); function CopyPIDL(APIDL: PItemIDList; const Malloc: IMalloc): PItemIDList; procedure Execute; override; function ExtractIconImage(APIDL: PItemIDLIst): Integer; procedure ExtractInfo(PIDL: PItemIDList; Info: PVirtualThreadIconInfo); virtual; procedure ExtractedInfoLoad(Info: PVirtualThreadIconInfo); virtual; // Load Info before being sent to Control(s) procedure InsertNewItem(Control: TWinControl; WindowsMessageID: LongWord; PIDL: PItemIDList; LargeIcon: Boolean; UserData: Pointer; Tag: integer); procedure InvalidateExtraction; virtual; // Called if after extraction the item can't be dispatched function NextID(APIDL: PItemIDList): PItemIDList; function PIDLSize(APIDL: PItemIDList): Integer; procedure ReleaseItem(Item: PVirtualThreadIconInfo; const Malloc: IMalloc); virtual; procedure SetEvent; function StripLastID(IDList: PItemIDList; var Last_CB: Word; var LastID: PItemIDList): PItemIDList; property ExtractedIconIndex: integer read FExtractedIconIndex write FExtractedIconIndex; property ImageThreadEvent: THandle read FImageThreadEvent write FImageThreadEvent; // property Malloc: IMalloc read FMalloc write FMalloc; property QueryList: TThreadList read FQueryList; public constructor Create(CreateSuspended: Boolean); destructor Destroy; override; end; IVirtualImageThreadManager = interface(IUnknown) ['{F6CDCFE6-4294-4169-A6ED-D1E24F3152AC}'] procedure AddNewItem(Control: TWinControl; WindowsMessageID: LongWord; PIDL: PItemIDList; LargeIcon: Boolean; UserData: Pointer; Tag: integer); procedure ClearPendingItems(Control: TWinControl; MessageID: LongWord; const Malloc: IMalloc); procedure ClearPendingItem(Control: TWinControl; TestItem: Pointer; MessageID: LongWord; const Malloc: IMalloc); procedure InsertNewItem(Control: TWinControl; WindowsMessageID: LongWord; PIDL: PItemIDList; LargeIcon: Boolean; UserData: Pointer; Tag: integer); function LockThread: TList; procedure RegisterControl(Control: TWinControl); procedure ReleaseItem(Item: PVirtualThreadIconInfo; const Malloc: IMalloc); procedure SetThreadPriority(Priority: TThreadPriority); procedure UnLockThread; procedure UnRegisterControl(Control: TWinControl); end; TVirtualImageThreadManager = class(TInterfacedObject, IVirtualImageThreadManager) private FControlList: TThreadList; FImageThread: TVirtualImageThread; FThreadPriority: TThreadPriority; protected procedure ReleaseImageThread; function RegisteredControl(Control: TWinControl): Boolean; property ControlList: TThreadList read FControlList write FControlList; property ImageThread: TVirtualImageThread read FImageThread write FImageThread; property ThreadPriority: TThreadPriority read FThreadPriority write FThreadPriority; public constructor Create; destructor Destroy; override; procedure AddNewItem(Control: TWinControl; WindowsMessageID: LongWord; PIDL: PItemIDList; LargeIcon: Boolean; UserData: Pointer; Tag: integer); procedure ClearPendingItems(Control: TWinControl; MessageID: LongWord; const Malloc: IMalloc); procedure ClearPendingItem(Control: TWinControl; TestItem: Pointer; MessageID: LongWord; const Malloc: IMalloc); procedure InsertNewItem(Control: TWinControl; WindowsMessageID: LongWord; PIDL: PItemIDList; LargeIcon: Boolean; UserData: Pointer; Tag: integer); function LockThread: TList; procedure RegisterControl(Control: TWinControl); procedure ReleaseItem(Item: PVirtualThreadIconInfo; const Malloc: IMalloc); procedure SetThreadPriority(Priority: TThreadPriority); procedure UnLockThread; procedure UnRegisterControl(Control: TWinControl); end; function ImageThreadManager: IVirtualImageThreadManager; implementation var ImageManager: IVirtualImageThreadManager = nil; function ImageThreadManager: IVirtualImageThreadManager; begin if not Assigned(ImageManager) then ImageManager := TVirtualImageThreadManager.Create as IVirtualImageThreadManager; Result := ImageManager end; { TVirtualImageThread } procedure TVirtualImageThread.AddNewItem(Control: TWinControl; WindowsMessageID: LongWord; PIDL: PItemIDList; LargeIcon: Boolean; UserData: Pointer; Tag: integer); var List: TList; Info: PVirtualThreadIconInfo; begin List := QueryList.LockList; try Info := AllocMem(SizeOf(TVirtualThreadIconInfo)); Info.Control := Control; Info.PIDL := PIDLMgr.CopyPIDL(PIDL); Info.LargeIcon := LargeIcon; Info.UserData := UserData; Info.Tag := Tag; Info.MessageID := WindowsMessageID; List.Add(Info); SetEvent finally QueryList.UnlockList; end end; procedure TVirtualImageThread.ClearPendingItem(Control: TWinControl; TestItem: Pointer; MessageID: Longword; const Malloc: IMalloc); // This method makes one big assumption. It assumes that the TestItem is equal to the // PVirtualThreadIconInfo.UserData field. var List: TList; i : integer; Msg: TMsg; begin // Lock the thread from dispatching any more messages List := QueryList.LockList; try // Since we have the list locked we can pick any messages that are in // message queue that are pending. They may reference the Item we are // now deleting! By handling this message while the list is locked we // can be sure all pending icon updates are done before we delete a Item. if Control.HandleAllocated then begin // First flush out any pending messages and let them be processed while PeekMessage(Msg, Control.Handle, MessageID, MessageID, PM_REMOVE) do begin TranslateMessage(Msg); DispatchMessage(Msg) end; end; for i := 0 to List.Count - 1 do begin if (PVirtualThreadIconInfo(List[i])^.Control = Control) then begin if (TestItem = PVirtualThreadIconInfo(List[i])^.UserData) then begin ReleaseItem(PVirtualThreadIconInfo(List[i]), Malloc); List[i] := nil end end end; List.Pack; finally QueryList.UnlockList; end end; procedure TVirtualImageThread.ClearPendingItems(Control: TWinControl; MessageID: LongWord; const Malloc: IMalloc); var List: TList; i : integer; Msg: TMsg; begin // Lock the thread from dispatching any more messages List := QueryList.LockList; try // Since we have the list locked we can pick any messages that are in // message queue that are pending. They may reference the Item we are // now deleting! By handling this message while the list is locked we // can be sure all pending icon updates are done before we delete a Item. if Control.HandleAllocated then begin // First flush out any pending messages and let them be processed while PeekMessage(Msg, Control.Handle, MessageID, MessageID, PM_REMOVE) do begin TranslateMessage(Msg); DispatchMessage(Msg) end; end; for i := 0 to List.Count - 1 do begin if (PVirtualThreadIconInfo(List[i])^.Control = Control) then begin ReleaseItem(PVirtualThreadIconInfo(List[i]), Malloc); List[i] := nil end end; List.Pack; finally QueryList.UnlockList; end end; function TVirtualImageThread.CopyPIDL(APIDL: PItemIDList; const Malloc: IMalloc): PItemIDList; // Copies the PIDL and returns a newly allocated PIDL. It is not associated // with any instance of TPIDLManager so it may be assigned to any instance. var Size: integer; begin if Assigned(APIDL) then begin Size := PIDLSize(APIDL); Result := Malloc.Alloc(Size); if Result <> nil then CopyMemory(Result, APIDL, Size); end else Result := nil end; constructor TVirtualImageThread.Create(CreateSuspended: Boolean); begin inherited Create(CreateSuspended); { NEED A UNIQUE EVENT FOR EACH THREAD IDIOT!!!} ImageThreadEvent := CreateEvent(nil, True, False, ''); FQueryList := TThreadList.Create; end; destructor TVirtualImageThread.Destroy; begin inherited; { Important to keep resources valid until after the inherited Destroy returns. } { The Execute method is terminated during a WaitFor called in this destructor. } { During that time Execute may still reference these resources. } FQueryList.Free; if ImageThreadEvent <> 0 then CloseHandle(ImageThreadEvent); end; procedure TVirtualImageThread.Execute; var Index: Integer; List: TList; SafetyValve: integer; Info: PVirtualThreadIconInfo; PIDL: PItemIDList; Malloc: IMalloc; begin CoInitialize(nil); try SHGetMalloc(Malloc); // Create in the context of the thread while not Terminated do begin WaitForSingleObject(ImageThreadEvent, INFINITE); if not Terminated then begin // Ok everyone .... breath Sleep(1); // Get the next waiting node List := QueryList.LockList; try Info := nil; // Grab the last item but don't remove it from the list yet. // If we remove it then if a control flushs pending queries before // we dispatch it we will send it to a control that is not ready. // If there are not items in the list then we are done so reset // local varaibles and reset the event so WaitForSingleObject waits again if List.Count > 0 then begin Index := List.Count - 1; Info := PVirtualThreadIconInfo(List.Items[Index]); // We can't use the actual Info object as it my be deleted on us PIDL := CopyPIDL(Info.PIDL, Malloc); end else begin Index := -1; PIDL := nil; ResetEvent(ImageThreadEvent); // Reset ourselves when there are no more images end; finally QueryList.UnlockList end; // Check again to see if we are terminated if Assigned(PIDL) then try // Call the long processing method if necessary. ExtractInfo(PIDL, Info); // Ok the slow extraction is done time to dispatch it List := QueryList.LockList; try // Free the temp PIDL if PIDL <> nil then Malloc.Free(PIDL); // Check to see if there are any items in the list or if items have // been deleted first. If they are the item will be left if the queue // and it will have to be done again if (List.Count > 0) and (Index < List.Count) then begin // See if the node was deleted and removed from the list or the // contexts were shifted if List[Index] = Info then begin ExtractedInfoLoad(Info); // No it is still there so we can remove it List.Delete(Index); // Note: It is possible by the time the VET gets this TMessage // the node can be destroyed so main thread locks the list // the PeekMessage's to remove all WM_VTSETICONINDEX before // freeing node. // Can't SendMessage because the main thread may be blocked // waiting for the list and SendMessage will deadlock. // Here again accessing a TWinControl is not thread safe but // we are only reading the properties if Info.Control.HandleAllocated then begin SafetyValve := 0; while not PostMessage(Info.Control.Handle, Info.MessageID, Integer(Info), 0) and (SafetyValve < SAFETLYVALVEMAX) do begin Inc(SafetyValve); Sleep(1); end; if SafetyValve >= SAFETLYVALVEMAX then ReleaseItem(Info, Malloc) end else ReleaseItem(Info, Malloc) end else InvalidateExtraction end else InvalidateExtraction finally QueryList.UnlockList; end except // Don't let exceptions escape the thread end end end finally // Make sure WaitFor is in the Wait Function before the thread really ends Sleep(100); Malloc := nil; CoUninitialize; end; end; procedure TVirtualImageThread.ExtractedInfoLoad(Info: PVirtualThreadIconInfo); // This is called from within a locked list so it is safe to maniulate begin Info.IconIndex := ExtractedIconIndex; end; function TVirtualImageThread.ExtractIconImage(APIDL: PItemIDLIst): integer; function GetIconByIShellIcon(PIDL: PItemIDList; var Index: integer): Boolean; var Flags: Longword; OldCB: Word; Old_ID: PItemIDList; {$IFNDEF VIRTUALNAMESPACES} Desktop, {$ENDIF} Folder: IShellFolder; ShellIcon: IShellIcon; begin Result := False; StripLastID(PIDL, OldCB, Old_ID); try {$IFDEF VIRTUALNAMESPACES} Old_ID.mkid.cb := OldCB; Folder := NamespaceExtensionFactory.BindToVirtualParentObject(PIDL); {$ELSE} SHGetDesktopFolder(Desktop); Desktop.BindToObject(PIDL, nil, IShellFolder, Pointer(Folder)); Old_ID.mkid.cb := OldCB; {$ENDIF} if Assigned(Folder) then if Folder.QueryInterface(IShellIcon, ShellIcon) = S_OK then begin Flags := 0; Result := ShellIcon.GetIconOf(Old_ID, Flags, Index) = NOERROR end finally {$IFNDEF VIRTUALNAMESPACES} Old_ID.mkid.cb := OldCB {$ENDIF} end end; procedure GetIconBySHGetFileInfo(APIDL: PItemIDList; var Index: Integer); var Flags: integer; Info: TSHFILEINFO; begin Flags := SHGFI_PIDL or SHGFI_SYSICONINDEX or SHGFI_SHELLICONSIZE; Flags := Flags or SHGFI_SMALLICON; if SHGetFileInfo(PChar(APIDL), 0, Info, SizeOf(Info), Flags) <> 0 then Index := Info.iIcon else Index := 0 end; begin if not GetIconByIShellIcon(APIDL, Result) then GetIconBySHGetFileInfo(APIDL, Result); end; procedure TVirtualImageThread.ExtractInfo(PIDL: PItemIDList; Info: PVirtualThreadIconInfo); // Use the passed PIDL to figure out what what to extract begin ExtractedIconIndex := ExtractIconImage(PIDL); end; procedure TVirtualImageThread.InsertNewItem(Control: TWinControl; WindowsMessageID: LongWord; PIDL: PItemIDList; LargeIcon: Boolean; UserData: Pointer; Tag: integer); var List: TList; Info: PVirtualThreadIconInfo; begin List := QueryList.LockList; try Info := AllocMem(SizeOf(TVirtualThreadIconInfo)); Info.Control := Control; Info.PIDL := PIDLMgr.CopyPIDL(PIDL); Info.LargeIcon := LargeIcon; Info.UserData := UserData; Info.Tag := Tag; Info.MessageID := WindowsMessageID; List.Insert(0, Info); SetEvent finally QueryList.UnlockList; end end; procedure TVirtualImageThread.InvalidateExtraction; begin end; function TVirtualImageThread.NextID(APIDL: PItemIDList): PItemIDList; begin Result := APIDL; if Assigned(APIDL) then Inc(PChar(Result), APIDL^.mkid.cb); end; function TVirtualImageThread.PIDLSize(APIDL: PItemIDList): integer; // Returns the total Memory in bytes the PIDL occupies. begin Result := 0; if Assigned(APIDL) then begin Result := SizeOf( Word); // add the null terminating last ItemID while APIDL.mkid.cb <> 0 do begin Result := Result + APIDL.mkid.cb; APIDL := NextID(APIDL); end; end; end; procedure TVirtualImageThread.ReleaseItem(Item: PVirtualThreadIconInfo; const Malloc: IMalloc); begin if Assigned(Item) then begin if Assigned(Item.PIDL) then Malloc.Free(Item.PIDL); FreeMem(Item) end end; procedure TVirtualImageThread.SetEvent; begin Windows.SetEvent(ImageThreadEvent); end; function TVirtualImageThread.StripLastID(IDList: PItemIDList; var Last_CB: Word; var LastID: PItemIDList): PItemIDList; var MarkerID: PItemIDList; begin Last_CB := 0; LastID := nil; Result := IDList; MarkerID := IDList; if Assigned(IDList) then begin while IDList.mkid.cb <> 0 do begin MarkerID := IDList; IDList := NextID(IDList); end; Last_CB := MarkerID.mkid.cb; LastID := MarkerID; MarkerID.mkid.cb := 0; end; end; { TVirtualImageThreadManager } procedure TVirtualImageThreadManager.AddNewItem(Control: TWinControl; WindowsMessageID: LongWord; PIDL: PItemIDList; LargeIcon: Boolean; UserData: Pointer; Tag: integer); begin if Assigned(ImageThread) then begin Assert(RegisteredControl(Control), 'Trying to add Image Thread Item to a unregistered control'); ImageThread.AddNewItem(Control, WindowsMessageID, PIDL, LargeIcon, UserData, Tag) end end; procedure TVirtualImageThreadManager.ClearPendingItem(Control: TWinControl; TestItem: Pointer; MessageID: LongWord; const Malloc: IMalloc); // Looks for the matching TestItem in the Item field of the record as a flag to delete // the record begin if Assigned(ImageThread) then begin if RegisteredControl(Control) then begin ImageThread.ClearPendingItem(Control, TestItem, MessageID, Malloc) end else Assert(True=False, 'Trying to clear pending Image Thead Items from an unregistered control'); end end; procedure TVirtualImageThreadManager.ClearPendingItems(Control: TWinControl; MessageID: LongWord; const Malloc: IMalloc); begin if Assigned(ImageThread) then begin if RegisteredControl(Control) then begin ImageThread.ClearPendingItems(Control, MessageID, Malloc) end else Assert(True=False, 'Trying to clear pending Image Thead Items from an unregistered control'); end end; constructor TVirtualImageThreadManager.Create; begin ControlList := TThreadList.Create; ThreadPriority := tpNormal; end; destructor TVirtualImageThreadManager.Destroy; begin ReleaseImageThread; ControlList.Free; inherited; end; function TVirtualImageThreadManager.LockThread: TList; begin if Assigned(ImageThread) then Result := ImageThread.QueryList.LockList else Result := nil end; procedure TVirtualImageThreadManager.InsertNewItem(Control: TWinControl; WindowsMessageID: LongWord; PIDL: PItemIDList; LargeIcon: Boolean; UserData: Pointer; Tag: integer); begin if Assigned(ImageThread) then begin Assert(RegisteredControl(Control), 'Trying to add Image Thread Item to a unregistered control'); ImageThread.InsertNewItem(Control, WindowsMessageID, PIDL, LargeIcon, UserData, Tag) end end; procedure TVirtualImageThreadManager.RegisterControl(Control: TWinControl); var List: TList; begin List := ControlList.LockList; try List.Add(Control); if not Assigned(ImageThread) then begin ImageThread := TVirtualImageThread.Create(False); ImageThread.Priority := ThreadPriority; end finally ControlList.UnlockList end end; function TVirtualImageThreadManager.RegisteredControl( Control: TWinControl): Boolean; var List: TList; begin if Assigned(Control) then begin List := ControlList.LockList; try Result := List.IndexOf(Control) > -1 finally ControlList.UnlockList end end else Result := False; end; procedure TVirtualImageThreadManager.ReleaseItem(Item: PVirtualThreadIconInfo; const Malloc: IMalloc); begin ImageThread.ReleaseItem(Item, Malloc) end; procedure TVirtualImageThreadManager.ReleaseImageThread; begin if Assigned(ImageThread) then begin ImageThread.Priority := tpNormal; // So D6 shuts down faster. ImageThread.Terminate; ImageThread.SetEvent; ImageThread.WaitFor; FreeAndNil(FImageThread) end end; procedure TVirtualImageThreadManager.SetThreadPriority( Priority: TThreadPriority); begin ThreadPriority := Priority; if Assigned(ImageThread) then ImageThread.Priority := ThreadPriority end; procedure TVirtualImageThreadManager.UnLockThread; begin if Assigned(ImageThread) then ImageThread.QueryList.UnLockList end; procedure TVirtualImageThreadManager.UnRegisterControl(Control: TWinControl); var List: TList; Index: integer; begin List := ControlList.LockList; try Index := List.IndexOf(Control); if Index > -1 then begin List.Delete(Index); if List.Count = 0 then ReleaseImageThread; end finally ControlList.UnlockList end end; initialization finalization ImageManager := nil; end.
unit nfsPropNotification; interface uses Classes, SysUtils, Contnrs, Controls, StdCtrls, ExtCtrls, Graphics, nfsPropPos, Winapi.Windows; { type TCircleMargin = class X: Integer; Y: Integer; end; } type TKreis = class A: TPoint; B: TPoint; end; type RMass=Record Height: Integer; Width : Integer; End; type TnfsPropNotification = class(TPersistent) private fOnChanged: TNotifyEvent; fWidth: Integer; fHeight: Integer; fPosX: Integer; fPosY: Integer; fCanvas: TCanvas; fCircleAlignment: TImageAlignment; fCirclePos: TnfsPropPos; fCaption: string; fCircleFrameColor: TColor; fCircleColor: TColor; fFont: TFont; fKreis: TKreis; fTextPos: TPoint; fTextMass: RMass; fKreisMass: RMass; fCircleColorTransparent: Boolean; fCircleMarginX: Integer; fCircleMarginY: Integer; procedure setHeight(const Value: Integer); procedure setWidth(const Value: Integer); procedure setPosX(const Value: Integer); procedure setPosY(const Value: Integer); procedure SetCircleAlignment(const Value: TImageAlignment); procedure PropPosChanged(Sender: TObject); procedure setCaption(const Value: string); procedure setCircleColor(const Value: TColor); procedure setCircleFrameColor(const Value: TColor); procedure setFont(const Value: TFont); procedure BerechneKreis; procedure BerechneZifferKoord; procedure setCircleColorTransparent(const Value: Boolean); procedure setCircleMarginX(const Value: Integer); procedure setCircleMarginY(const Value: Integer); protected public constructor Create; destructor Destroy; override; property Width: Integer read fWidth write setWidth; property Height: Integer read fHeight write setHeight; property PosX: Integer read fPosX write setPosX; property PosY: Integer read fPosY write setPosY; property Canvas: TCanvas read fCanvas write fCanvas; property TextPos: TPoint read fTextPos; property KreisPos: TKreis read fKreis; published property OnChanged: TNotifyEvent read fOnChanged write fOnChanged; property CircleAlignment: TImageAlignment read fCircleAlignment write SetCircleAlignment default iaLeft; property CirclePos: TnfsPropPos read fCirclePos write fCirclePos; property CircleMarginX: Integer read fCircleMarginX write setCircleMarginX; property CircleMarginY: Integer read fCircleMarginY write setCircleMarginY; property CircleColor: TColor read fCircleColor write setCircleColor default clRed; property CircleColorTransparent: Boolean read fCircleColorTransparent write setCircleColorTransparent default false; property CircleFrameColor: TColor read fCircleFrameColor write setCircleFrameColor default clWhite; property Caption: string read fCaption write setCaption; property Font: TFont read fFont write setFont; end; implementation { TnfsPropNotification } constructor TnfsPropNotification.Create; begin fCanvas := nil; fKreis := TKreis.Create; fFont := TFont.Create; fFont.Size := 7; fFont.Color := clWhite; fCircleMarginX := 3; fCircleMarginY := 3; fCircleColor := clRed; fCircleFrameColor := clWhite; fCirclePos := TnfsPropPos.Create; fCirclePos.OnChanged := PropPosChanged; fCircleColorTransparent := false; end; destructor TnfsPropNotification.Destroy; begin FreeAndNil(fCirclePos); FreeAndNil(fFont); FreeAndNil(fKreis); inherited; end; procedure TnfsPropNotification.PropPosChanged(Sender: TObject); begin BerechneKreis; end; procedure TnfsPropNotification.setCaption(const Value: string); begin fCaption := Value; BerechneKreis; end; procedure TnfsPropNotification.SetCircleAlignment(const Value: TImageAlignment); begin fCircleAlignment := Value; BerechneKreis; end; procedure TnfsPropNotification.setCircleColor(const Value: TColor); begin fCircleColor := Value; BerechneKreis; end; procedure TnfsPropNotification.setCircleColorTransparent(const Value: Boolean); begin fCircleColorTransparent := Value; BerechneKreis; end; procedure TnfsPropNotification.setCircleFrameColor(const Value: TColor); begin fCircleFrameColor := Value; BerechneKreis; end; procedure TnfsPropNotification.setCircleMarginX(const Value: Integer); begin fCircleMarginX := Value; BerechneKreis; end; procedure TnfsPropNotification.setCircleMarginY(const Value: Integer); begin fCircleMarginY := Value; BerechneKreis; end; procedure TnfsPropNotification.setFont(const Value: TFont); begin fFont.Assign(Value); BerechneKreis; end; procedure TnfsPropNotification.setHeight(const Value: Integer); begin fHeight := Value; BerechneKreis; end; procedure TnfsPropNotification.setPosX(const Value: Integer); begin fPosX := Value; end; procedure TnfsPropNotification.setPosY(const Value: Integer); begin fPosY := Value; end; procedure TnfsPropNotification.setWidth(const Value: Integer); begin fWidth := Value; BerechneKreis; end; procedure TnfsPropNotification.BerechneKreis; var TextPosMitte: TPoint; KreisPos1: TPoint; KreisPos2: TPoint; KreisHalbe: Integer; WidthHalbe: Integer; begin if fCanvas = nil then exit; fcanvas.Font.Assign(fFont); fTextMass.Height := fCanvas.TextHeight(fCaption); fTextMass.Width := fCanvas.TextWidth(fCaption); TextPosMitte.Y := trunc(fTextMass.Height/2) + 1; TextPosMitte.X := trunc(fTextMass.Width/2); if fCircleAlignment = iaLeft then begin fPosX := fCirclePos.Left; fPosY := 0; end; KreisPos2.X := fTextMass.Width + (fCircleMarginX * 2); KreisPos2.Y := fTextMass.Height + (fCircleMarginY * 2); if KreisPos2.Y > KreisPos2.X then KreisPos2.X := KreisPos2.Y; fKreisMass.Width := KreisPos2.X; fKreisMass.Height := KreisPos2.Y; if fCircleAlignment = iaRight then begin fPosX := fWidth - fKreisMass.Width; fPosX := fPosX - fCirclePos.Right; fPosY := fCirclePos.Top; end; if fCircleAlignment = iaCenter then begin KreisHalbe := trunc(fKreisMass.Width / 2); WidthHalbe := trunc(fWidth/2); fPosX := WidthHalbe - KreisHalbe; KreisHalbe := trunc(fKreisMass.Height / 2); WidthHalbe := trunc(fHeight/2); fPosY := WidthHalbe - KreisHalbe; if fCirclePos.Top > 0 then fPosY := fCirclePos.Top; if fCirclePos.Left > 0 then fPosX := fCirclePos.Left; end; KreisPos1.X := fPosX; KreisPos1.Y := fPosY; fKreis.A.X := KreisPos1.X; fKreis.A.Y := KreisPos1.Y; fKreis.B.X := fKreis.A.X + fKreisMass.Width; fKreis.B.Y := fKreis.A.Y + fKreisMass.Height; BerechneZifferKoord; if Assigned(fOnChanged) then fOnChanged(Self); end; procedure TnfsPropNotification.BerechneZifferKoord; var KreisHalbe: TPoint; TextHalbe: TPoint; begin KreisHalbe.X := (trunc(fKreisMass.Width / 2)); KreisHalbe.Y := (trunc(fKreisMass.Height / 2)); TextHalbe.X := trunc(fTextMass.Width / 2); TextHalbe.Y := trunc(fTextMass.Height / 2); fTextPos.X := KreisHalbe.X - TextHalbe.X + fPosX; fTextPos.Y := KreisHalbe.Y - TextHalbe.Y + fPosY; end; end.
{ En un taller de reparación de vehículos, se ha registrado en un archivo los siguientes datos de las unidades:  Tipo (1-particular, 2-carga, 3-transporte de pasajeros, 4-oficial, 5-servicios)  Costo de la reparación Se pide leer la información para calcular e informar para cada tipo, el monto recaudado y el porcentaje que representa del total. } Program eje17; Type St10 = String[10]; TV = array[0..100] of byte; TVC = array[0..100] of real; TVConst = array[1..5] of st10; Const TipoServicio:TVConst = ('Particular','Carga','Transporte','Oficial','Servicios'); Procedure LeerArchivo(Var Tipo:TV; Var Cost:TVC; Var N:byte); Var Arch:text; begin N:= 0; assign(arch,'eje17.txt');reset(arch); while not eof (arch) do begin N:= N + 1; readln(Arch,Tipo[N],Cost[N]); end; close(arch); end; Function SumaTotal(Tipo:TV; Cost:TVC; N:byte):real; Var i:byte; aux:real; begin aux:= 0; For i:= 1 to N do begin aux:= aux + Cost[i]; end; SumaTotal:= aux; end; Procedure Porcentaje(Tipo:TV; Cost:TVC; N:byte; Var SumaTipo:TVC); Var i,j,aux:byte; Porc,SumaTotal:real; begin SumaTotal:= 0; For i:= 1 to N do begin SumaTotal:= SumaTotal + Cost[i]; aux:= Tipo[i]; SumaTipo[aux]:= SumaTipo[aux] + Cost[i]; end; For j:= 1 to 5 do //Recorremos en referencia a particular,carga,transporte de pasajeros,oficial y servicios. begin Porc:= (SumaTipo[j] / SumaTotal) * 100; writeln('El servicio ',TipoServicio[j],' recaudo: $',SumaTipo[j]:2:0,' y su porcentaje es del ',Porc:2:0,' % sobre el total'); end; end; Var Tipo:TV; Cost,SumaTipo:TVC; N:byte; Begin LeerArchivo(Tipo,Cost,N); Porcentaje(Tipo,Cost,N,SumaTipo); end.
program SimpleRL; uses Crt; type TPoint = record X, Y : Integer; end; const Map : Array [1..10] of String[10] = ( '#### ####', '# #### #', '# #', '## ##', ' # # ', ' # # ', '## ##', '# #', '# #### #', '#### ####'); var P : TPoint = ( X: 2; Y: 2); Key : Char; procedure DrawTile(C: Char); begin GotoXY(P.X, P.Y); Write(c); end; procedure MovePlayer(X, Y: Integer); begin if Map[Y][X] = ' ' then begin P.X := X; P.Y := Y; end; end; procedure DrawMap; var I : Integer; begin for I := Low(Map) to High(Map) do WriteLn(Map[I]); end; begin ClrScr; DrawMap; DrawTile('@'); repeat Key := ReadKey; DrawTile(' '); case Key of '8' : MovePlayer(P.X, P.Y - 1); '2' : MovePlayer(P.X, P.Y + 1); '4' : MovePlayer(P.X - 1, P.Y); '6' : MovePlayer(P.X + 1, P.Y); end; DrawTile('@'); until Key = 'q'; end.
(* * FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * *) unit uFrmMessageBox; interface uses LCLIntf, LCLType, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Buttons ,uLanguage; type TfrmMessageBox = class(TForm) bbButton1: TBitBtn; bbButton2: TBitBtn; bbButton0: TBitBtn; reText: TMemo; Bevel1: TBevel; procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); private { Private declarations } public { Public declarations } btType : Integer; btDefault : Integer; end; var frmMessageBox: TfrmMessageBox; function feMessageBox( title, msg : string; msgtype, dbutton : Integer ) : Integer; implementation {$R *.lfm} function feMessageBox( title, msg : string; msgtype, dbutton : Integer ) : Integer; begin frmMessageBox.btType := msgtype; frmMessageBox.Caption := title; frmMessageBox.reText.Text := msg; frmMessageBox.btDefault := dbutton; frmMessageBox.ShowModal; result := frmMessageBox.ModalResult; end; procedure TfrmMessageBox.FormCreate(Sender: TObject); begin btType := 0; btDefault := 0; end; procedure TfrmMessageBox.FormActivate(Sender: TObject); begin bbButton0.Default := false; bbButton1.Default := false; bbButton2.Default := false; bbButton0.Hide; bbButton1.Hide; bbButton2.Hide; case btType of 0 : begin bbButton2.Show; bbButton2.Default := true; end; 2, 3 : begin bbButton0.Show; bbButton1.Show; bbButton2.Show; case btDefault of 1 : bbButton0.Default := true; 2 : bbButton1.Default := true; 3 : bbButton2.Default := true; end; end; 1, 4, 5 : begin bbButton1.Show; bbButton2.Show; case btDefault of 1 : bbButton1.Default := true; 2 : bbButton2.Default := true; end; end; end; case btType of 0 : begin bbButton2.ModalResult := mrOK; bbButton2.Caption:=LNG_ACCEPT; end; 1 : begin bbButton1.ModalResult := mrOK; bbButton2.ModalResult := mrCancel; bbButton1.Caption:= LNG_ACCEPT; bbButton2.Caption:=LNG_CANCEL; end; 2 : begin bbButton0.ModalResult := mrAbort; bbButton1.ModalResult := mrRetry; bbButton2.ModalResult := mrIgnore; bbButton0.Caption:=LNG_ABORT; bbButton1.Caption:=LNG_RETRY; bbButton2.Caption:=LNG_IGNORE; end; 3 : begin bbButton0.ModalResult := mrYes; bbButton1.ModalResult := mrNo; bbButton2.ModalResult := mrCancel; bbButton0.Caption:=LNG_YES; bbButton1.Caption:=LNG_NO; bbButton2.Caption:=LNG_CANCEL; end; 4 : begin bbButton1.ModalResult := mrYes; bbButton2.ModalResult := mrNo; bbButton1.Caption:=LNG_YES; bbButton2.Caption:=LNG_NO; end; 5 : begin bbButton1.ModalResult := mrRetry; bbButton2.ModalResult := mrCancel; bbButton1.Caption:=LNG_RETRY; bbButton2.Caption:=LNG_CANCEL; end; end; end; end.
unit Unit_SD_TP06_EX02; interface Type PCellule = ^Cellule; Cellule = record cadeau : String; prenom : String; prix : Real; precedent : PCellule; suivant : PCellule; end; Liste = record pDeb : PCellule; pCour : PCellule; pFin : PCellule; end; Procedure ajoutDebutListe(var l : Liste; cadeau : String; prenom : String; prix : Real); Procedure ajoutFinListe(var l : Liste; cadeau : String; prenom : String; prix : Real); Procedure afficheOrdre(l : Liste); Procedure afficheOrdreInverse(l : Liste); Function estContenu(l : liste; prenom : String) : PCellule; Procedure supprimeCadeau(var l : liste; prenom : String); implementation Procedure ajoutDebutListe(var l : Liste; cadeau : String; prenom : String; prix : Real); Var p, r : PCellule; begin new(p); p^.cadeau := cadeau; p^.prenom := prenom; p^.prix := prix; p^.precedent := NIL; p^.suivant := l.pDeb; l.pDeb := p; l.pCour := p; if (l.pFin=NIL) then //Si la liste est vide. begin l.pFin := p end else //Sinon begin (p^.suivant)^.precedent := p; end; end; Procedure ajoutFinListe(var l : Liste; cadeau : String; prenom : String; prix : Real); Var p, r : PCellule; begin new(p); p^.cadeau := cadeau; p^.prenom := prenom; p^.prix := prix; p^.precedent := l.pFin; p^.suivant := NIL; l.pCour := p; l.pFin := p; if (l.pFin=NIL) then //Si la liste est vide. begin l.pDeb := p end else //Sinon begin (p^.precedent)^.suivant := p; end; end; Procedure afficheOrdre(l : Liste); begin l.pCour := l.pDeb; while (l.pCour <> NIL) do begin writeln((l.pCour)^.cadeau); writeln((l.pCour)^.prenom); writeln((l.pCour)^.prix); l.pCour := (l.pCour)^.suivant; end; end; Procedure afficheOrdreInverse(l : Liste); begin l.pCour := l.pFin; while (l.pCour <> NIL) do begin writeln((l.pCour)^.cadeau); writeln((l.pCour)^.prenom); writeln((l.pCour)^.prix); l.pCour := (l.pCour)^.precedent; end; end; Function estContenu(l : liste; prenom : String) : PCellule; Var fini : Boolean; adresse : PCellule; begin fini := False; l.pCour := l.pDeb; while (fini = False) do begin if l.pCour = NIL then begin fini := True; adresse := NIL; end else begin if (l.pCour)^.prenom = prenom then begin fini := True; adresse := l.pCour; end else begin l.pCour := (l.pCour)^.suivant; end; end; end; Result := adresse; end; Procedure supprimeCadeau(var l : liste; prenom : String); Var fini : Boolean; p, r : PCellule; begin fini := False; l.pCour := l.pDeb; while (fini = False) do begin if l.pCour = NIL then begin fini := True; writeln('Le prenom n''est pas dans la liste'); end else begin if (l.pCour)^.prenom = prenom then begin fini := True; if l.pCour = l.pDeb then begin (l.pCour)^.precedent := NIL; end else if l.pCour = l.pFin then begin (l.pCour)^.suivant := NIL; l.pCour := l.pDeb; end else begin {p := (l.pCour)^.precedent; r := (l.pCour)^.suivant; r.precedent := p; r.suivant := r; dispose(l.pDeb); l.pCour := l.pDeb; } end; dispose(l.pCour); end else begin l.pCour := (l.pCour)^.suivant; end; end; end; end; end.
unit Main; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms3D, FMX.Dialogs, FMX.Types3D, FMX.Objects3D, FMX.Layers3D, FMX.Edit, FMX.Layouts, FMX.Memo, FMX.Objects, FMX.Colors, FMX.ListBox, FMX.Ani, FMX.TabControl, FMX.Effects, FMX.ExtCtrls, FMX.Menus, FMX.Materials, FMX.MaterialSources, FMX.Controls3D, FMX.StdCtrls; type TFrmMain = class(TForm3D) Text3D: TText3D; Light1: TLight; Rectangle: TRectangle3D; MemoText: TMemo; LayoutLeft: TLayout; FrameTextSet: TRectangle; HorizMargin: TTrackBar; Label4: TLabel; GroupFrameCorners: TRectangle; CheckTopLeft: TCheckBox; CheckTopRight: TCheckBox; CheckBottomRight: TCheckBox; CheckBottomLeft: TCheckBox; RectDepth: TTrackBar; Label6: TLabel; RectRadius: TTrackBar; Label7: TLabel; Text3DDepth: TTrackBar; VertMargin: TTrackBar; Label5: TLabel; ColorPanelFrame: TColorPanel; ColorAnimation1: TColorAnimation; ListFrame: TListBox; ListBoxItem1: TListBoxItem; ListBoxItem2: TListBoxItem; ListBoxItem3: TListBoxItem; VertScrollBox1: TVertScrollBox; ExpanderFrame: TExpander; ExpanderText: TExpander; ColorPanelText: TColorPanel; ListText: TListBox; ListBoxItem4: TListBoxItem; ListBoxItem5: TListBoxItem; ExpanderExport: TExpander; LayoutRight: TLayout; Circle1: TCircle; CornerList: TListBox; ListBoxItem6: TListBoxItem; ListBoxItem7: TListBoxItem; ListBoxItem8: TListBoxItem; ListBoxItem9: TListBoxItem; Rectangle2: TRectangle; Layout3: TLayout; Layout4: TLayout; Rectangle3: TRectangle; Layout5: TLayout; Rectangle4: TRectangle; Layout6: TLayout; Rectangle5: TRectangle; ExpanderBack: TExpander; ColorPanelBackgroud: TColorPanel; GlowEffect1: TGlowEffect; ArrowUp: TPath; ArrowDown: TPath; ArrowLeft: TPath; ArrowRight: TPath; LayoutNavigator: TLayout; SBUp: TSpeedButton; SBDown: TSpeedButton; SBLeft: TSpeedButton; SBRight: TSpeedButton; TrackBarObjectDepth: TTrackBar; GlowEffect2: TGlowEffect; GlowEffect3: TGlowEffect; EdFileName: TEdit; Label1: TLabel; BtExport: TCornerButton; Layer3DLeft: TLayer3D; Layer3DRight: TLayer3D; StyleBook1: TStyleBook; Layer3DCenter: TLayer3D; FrameTexture: TImage; OpenDialogImages: TOpenDialog; Panel1: TPanel; Label2: TLabel; Panel2: TPanel; TextTexture: TImage; Label3: TLabel; CleanFrameTexture: TSpeedButton; Path1: TPath; CleanTextTexture: TSpeedButton; Path2: TPath; MainDummy: TDummy; DummyY: TDummy; DummyX: TDummy; Camera1: TCamera; SBFont: TSpeedButton; Path3: TPath; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; FloatAnimationCameraY: TFloatAnimation; FloatAnimationCameraX1: TFloatAnimation; FloatAnimationCameraX2: TFloatAnimation; FloatAnimationCameraX3: TFloatAnimation; RectangleMaterialShaftSource: TLightMaterialSource; RectangleMaterialBackSource: TLightMaterialSource; RectangleMaterialSource: TLightMaterialSource; Text3DMaterialSource: TLightMaterialSource; Text3DMaterialShaftSource: TLightMaterialSource; Text3DMaterialBackSource: TLightMaterialSource; procedure Viewport3D1MouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); procedure Viewport3D1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure Viewport3D1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); procedure MemoTextChange(Sender: TObject); procedure HorizMarginChange(Sender: TObject); procedure VertMarginChange(Sender: TObject); procedure RectDepthChange(Sender: TObject); procedure RectRadiusChange(Sender: TObject); procedure CheckTopRightChange(Sender: TObject); procedure CheckTopLeftChange(Sender: TObject); procedure CheckBottomLeftChange(Sender: TObject); procedure CheckBottomRightChange(Sender: TObject); procedure Text3DDepthChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ColorPanelFrameChange(Sender: TObject); procedure Text3DClick(Sender: TObject); procedure Viewport3D1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure ListFrameChange(Sender: TObject); procedure ListTextChange(Sender: TObject); procedure ColorPanelTextChange(Sender: TObject); procedure ColorPanelBackgroudChange(Sender: TObject); procedure CornerListChange(Sender: TObject); procedure SBUpClick(Sender: TObject); procedure SBDownClick(Sender: TObject); procedure SBLeftClick(Sender: TObject); procedure SBRightClick(Sender: TObject); procedure TrackBarObjectDepthChange(Sender: TObject); procedure ExpanderFrameCheckChange(Sender: TObject); procedure CornerButton1Click(Sender: TObject); procedure FrameTextureClick(Sender: TObject); procedure CleanFrameTextureClick(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure FloatAnimationCameraYProcess(Sender: TObject); procedure FloatAnimationCameraYFinish(Sender: TObject); procedure SBFontClick(Sender: TObject); private { Private declarations } Down: TPointF; FSelectObject: TShape3D; procedure SetFrameWidth(const Value: Single); function GetFrameWidth: Single; function GetFrameHeight: Single; procedure SetFrameHeight(const Value: Single); function GetFrameDepth: Single; procedure SetFrameDepth(const Value: Single); function GetFrameCorners: TCorners; procedure SetFrameCorners(const Value: TCorners); function GetFrameRadius: Single; procedure SetFrameRadius(const Value: Single); function GetTextDepth: Single; procedure SetTextDepth(const Value: Single); procedure SetFrameVisible(const Value: Boolean); function GetFrameVisible: Boolean; procedure InitalizeColorPanels; procedure IntializeMainControls; public { Public declarations } MouseUp, isAnimationRunning: Boolean; property FrameWidth: Single read GetFrameWidth write SetFrameWidth; property FrameHeight: Single read GetFrameHeight write SetFrameHeight; property FrameDepth: Single read GetFrameDepth write SetFrameDepth; property FrameCorners: TCorners read GetFrameCorners write SetFrameCorners; property FrameRadius: Single read GetFrameRadius write SetFrameRadius; property FrameVisible: Boolean read GetFrameVisible write SetFrameVisible; property SelectedObject: TShape3D read FSelectObject write FSelectObject; property TextDepth: Single read GetTextDepth write SetTextDepth; procedure InitalizeText; procedure InitializeControls; procedure ResetAll; function GetMaterialSource(AList: TListBox; AnObject: TObject): TLightMaterialSource; end; var FrmMain: TFrmMain; Const MFRONT = 1; MLEFT = 2; MBACK = 3; implementation {$R *.fmx} procedure TFrmMain.InitalizeText; begin MemoText.Text := Text3D.Text; end; procedure TFrmMain.CheckBottomLeftChange(Sender: TObject); begin if CheckBottomLeft.IsChecked then FrameCorners := FrameCorners + [TCorner.crBottomLeft] else FrameCorners := FrameCorners - [TCorner.crBottomLeft]; end; procedure TFrmMain.CheckBottomRightChange(Sender: TObject); begin if CheckBottomRight.IsChecked then FrameCorners := FrameCorners + [TCorner.crBottomRight] else FrameCorners := FrameCorners - [TCorner.crBottomRight]; end; procedure TFrmMain.CheckTopLeftChange(Sender: TObject); begin if CheckTopLeft.IsChecked then FrameCorners := FrameCorners + [TCorner.crTopLeft] else FrameCorners := FrameCorners - [TCorner.crTopLeft]; end; procedure TFrmMain.CheckTopRightChange(Sender: TObject); begin if CheckTopRight.IsChecked then FrameCorners := FrameCorners + [TCorner.crTopRight] else FrameCorners := FrameCorners - [TCorner.crTopRight]; end; procedure TFrmMain.ColorPanelFrameChange(Sender: TObject); begin case ListFrame.ItemByIndex(ListFrame.ItemIndex).Tag of MFRONT: RectangleMaterialSource.Diffuse := ColorPanelFrame.Color; MLEFT: RectangleMaterialShaftSource.Diffuse := ColorPanelFrame.Color; MBACK: RectangleMaterialBackSource.Diffuse := ColorPanelFrame.Color; end; end; procedure TFrmMain.ColorPanelTextChange(Sender: TObject); begin case ListText.ItemByIndex(ListText.ItemIndex).Tag of MFRONT: Text3DMaterialSource.Diffuse := ColorPanelText.Color; MLEFT: Text3DMaterialShaftSource.Diffuse := ColorPanelText.Color; MBACK: Text3DMaterialBackSource.Diffuse := ColorPanelText.Color; end; end; procedure TFrmMain.ColorPanelBackgroudChange(Sender: TObject); begin Color := ColorPanelBackgroud.Color; end; procedure TFrmMain.FloatAnimationCameraYFinish(Sender: TObject); begin isAnimationRunning := False end; procedure TFrmMain.FloatAnimationCameraYProcess(Sender: TObject); begin isAnimationRunning := True; end; procedure TFrmMain.FormCreate(Sender: TObject); begin InitializeControls; end; procedure TFrmMain.FrameTextureClick(Sender: TObject); var FileName: String; Obj: TExtrudedShape3D; List: TListBox; TempLightMaterial: TLightMaterialSource; begin Obj := nil; List := nil; if Sender = TextTexture then begin Obj := Text3D; List := ListText; end else begin if Sender = FrameTexture then begin Obj := Rectangle; List := ListFrame; end; end; TempLightMaterial := GetMaterialSource(List, Obj); if OpenDialogImages.Execute then FileName := OpenDialogImages.FileName; if Assigned(Obj) and Assigned(List) then begin TempLightMaterial.Texture.LoadFromFile(FileName); TImage(Sender).Bitmap.LoadFromFile(FileName); end; end; function TFrmMain.GetFrameCorners: TCorners; begin Result := Rectangle.Corners; end; function TFrmMain.GetFrameDepth: Single; begin Result := Rectangle.Depth; end; function TFrmMain.GetFrameHeight: Single; begin Result := Rectangle.Height; end; function TFrmMain.GetFrameRadius: Single; begin Result := Rectangle.XRadius end; function TFrmMain.GetFrameVisible: Boolean; begin Result := (Rectangle.Sides = [TExtrudedShapeSide.esFront, TExtrudedShapeSide.esBack, TExtrudedShapeSide.esShaft]) end; function TFrmMain.GetFrameWidth: Single; begin Result := Rectangle.Width; end; function TFrmMain.GetMaterialSource(AList: TListBox; AnObject: TObject): TLightMaterialSource; begin if AnObject = Rectangle then begin case AList.ItemByIndex(AList.ItemIndex).Tag of MFRONT: Result := RectangleMaterialSource; MLEFT: Result := RectangleMaterialShaftSource; MBACK: Result := RectangleMaterialBackSource; end; end; if AnObject = Text3d then begin case AList.ItemByIndex(AList.ItemIndex).Tag of MFRONT: Result := Text3dMaterialSource; MLEFT: Result := Text3dMaterialShaftSource; MBACK: Result := Text3dMaterialBackSource; end; end; end; function TFrmMain.GetTextDepth: Single; begin Result := Text3D.Depth end; procedure TFrmMain.HorizMarginChange(Sender: TObject); begin FrameWidth := HorizMargin.Value; end; procedure TFrmMain.InitializeControls; Const SFilter : String = 'All Images (%s)|%s'; var ImageType : String; begin ExpanderFrame.IsChecked := FrameVisible; ImageType := fmx.Types.TBitmapCodecManager.GetFileTypes; OpenDialogImages.Filter := Format(SFilter, [ImageType, ImageType]); IntializeMainControls; InitalizeColorPanels; TrackBarObjectDepth.Value := -Camera.Position.Z; InitalizeText; end; procedure TFrmMain.CornerButton1Click(Sender: TObject); var Image: TBitmap; begin if Trim(EdFileName.Text) = EmptyStr then begin EdFileName.SetFocus; raise Exception.Create('Please, inform the image filename'); end; Cursor := crHourGlass; Image := TBitmap.Create(0, 0); try MainDummy.CreateHighMultisampleSnapshot(Image, Round(MainDummy.ScreenBounds.Width), Round(MainDummy.ScreenBounds.Height), TAlphaColors.Null, 4); Image.SaveToFile(EdFileName.Text); if FileExists(EdFileName.Text) then MessageDlg('File generated at ' + EdFileName.Text, TMsgDlgType.mtWarning, [TMsgDlgBtn.MbOk], 0) else MessageDlg('File could not be saved on this folder', TMsgDlgType.mtError, [TMsgDlgBtn.MbOk], 0); finally Image.Free; Cursor := crDefault; end; end; procedure TFrmMain.CornerListChange(Sender: TObject); begin Rectangle.CornerType := TCornerType(CornerList.ItemIndex); end; procedure TFrmMain.ExpanderFrameCheckChange(Sender: TObject); begin FrameVisible := ExpanderFrame.IsChecked; end; procedure TFrmMain.ListFrameChange(Sender: TObject); begin case ListFrame.ItemByIndex(ListFrame.ItemIndex).Tag of MFRONT: begin ColorPanelFrame.Color := RectangleMaterialSource.Diffuse; FrameTexture.Bitmap := RectangleMaterialSource.Texture; end; MLEFT: begin ColorPanelFrame.Color := RectangleMaterialShaftSource.Diffuse; FrameTexture.Bitmap := RectangleMaterialShaftSource.Texture; end; MBACK: begin ColorPanelFrame.Color := RectangleMaterialBackSource.Diffuse; FrameTexture.Bitmap := RectangleMaterialBackSource.Texture; end; end; end; procedure TFrmMain.ListTextChange(Sender: TObject); begin case ListText.ItemByIndex(ListText.ItemIndex).Tag of MFRONT: begin ColorPanelText.Color := Text3DMaterialSource.Diffuse; TextTexture.Bitmap := Text3DMaterialSource.Texture; end; MLEFT: begin ColorPanelText.Color := Text3DMaterialShaftSource.Diffuse; TextTexture.Bitmap := Text3DMaterialShaftSource.Texture; end; MBACK: begin ColorPanelText.Color := Text3DMaterialBackSource.Diffuse; TextTexture.Bitmap := Text3DMaterialShaftSource.Texture; end; end; end; procedure TFrmMain.MemoTextChange(Sender: TObject); var Str: String; begin if MemoText.Text = EmptyStr then Str := ' ' else Str := MemoText.Text; Text3D.Text := Str; FrameWidth := Text3D.GetTextBounds.Width * 13; FrameHeight := Text3D.GetTextBounds.Height * 13; // MainDummy.Width := Rectangle.Width; // MainDummy.Height := Rectangle.Height; MainDummy.Depth := Rectangle.Depth + Text3D.Depth; end; procedure TFrmMain.RectDepthChange(Sender: TObject); begin FrameDepth := RectDepth.Value; end; procedure TFrmMain.RectRadiusChange(Sender: TObject); begin FrameRadius := RectRadius.Value; end; procedure TFrmMain.ResetAll; begin FrameWidth := 19; FrameHeight := 5; FrameDepth := 3; FrameRadius := 2; FrameVisible := True; TextDepth := 3; MemoText.Lines.Text := '3D Text'; FrameCorners := [TCorner.crTopLeft, TCorner.crBottomRight]; CornerList.ItemIndex := 0; RectangleMaterialSource.Texture.SetSize(0, 0); RectangleMaterialShaftSource.Texture.SetSize(0, 0); RectangleMaterialBackSource.Texture.SetSize(0, 0); RectangleMaterialSource.Diffuse := TAlphaColorRec.Null; RectangleMaterialShaftSource.Diffuse := TAlphaColorRec.White; RectangleMaterialBackSource.Diffuse := TAlphaColorRec.White; Text3DMaterialSource.Texture.SetSize(0, 0); Text3DMaterialShaftSource.Texture.SetSize(0, 0); Text3DMaterialBackSource.Texture.SetSize(0, 0); Text3DMaterialSource.Diffuse := TAlphaColorRec.White; Text3DMaterialShaftSource.Diffuse := TAlphaColorRec.Darkgray; Text3DMaterialBackSource.Diffuse := TAlphaColorRec.White; DummyY.AnimateFloat('RotationAngle.Y', 0, 1.5, TAnimationType.atInOut, TInterpolationType.itSinusoidal); DummyX.AnimateFloat('RotationAngle.X', 0, 1.5); Camera.AnimateFloat('Position.Z', -30, 1.5); Camera.Position.Vector := Vector3D(0, 0, 0); Camera.ResetRotationAngle; end; procedure TFrmMain.IntializeMainControls; begin // Text3DDepth.Max := TextDepth * 2; // Text3DDepth.Value := TextDepth; // SetTextDepth(Text3DDepth.Value); RectRadius.Value := FrameRadius; RectDepth.Value := FrameDepth; VertMargin.Value := FrameHeight; HorizMargin.Value := FrameWidth; CheckTopLeft.IsChecked := TCorner.crTopLeft in FrameCorners; CheckTopRight.IsChecked := TCorner.crTopRight in FrameCorners; CheckBottomLeft.IsChecked := TCorner.crBottomLeft in FrameCorners; CheckBottomRight.IsChecked := TCorner.crBottomRight in FrameCorners; end; procedure TFrmMain.InitalizeColorPanels; begin ColorPanelFrame.Color := RectangleMaterialSource.Diffuse; ColorPanelText.Color := Text3DMaterialSource.Diffuse; ColorPanelBackgroud.Color := Self.Color; end; procedure TFrmMain.SetFrameCorners(const Value: TCorners); begin Rectangle.Corners := Value; end; procedure TFrmMain.SetFrameDepth(const Value: Single); begin Rectangle.Depth := Value; MainDummy.Depth := Value + TextDepth; end; procedure TFrmMain.SetFrameHeight(const Value: Single); begin Rectangle.Height := Value; Text3D.Height := Value; MainDummy.Height := Rectangle.Height; end; procedure TFrmMain.SetFrameRadius(const Value: Single); begin Rectangle.XRadius := Value; Rectangle.YRadius := Value; end; procedure TFrmMain.SetFrameVisible(const Value: Boolean); begin if Value then begin Rectangle.Sides := [TExtrudedShapeSide.esFront, TExtrudedShapeSide.esBack, TExtrudedShapeSide.esShaft] end else begin Rectangle.Sides := [] end; end; procedure TFrmMain.SetFrameWidth(const Value: Single); begin Rectangle.Width := Value; Text3D.Width := Value; MainDummy.Width := Rectangle.Width; end; procedure TFrmMain.SetTextDepth(const Value: Single); begin Text3D.Depth := Value; Text3D.Position.Z := (Value / 2) * -1; MainDummy.Depth := FrameDepth + TextDepth; end; procedure TFrmMain.SpeedButton1Click(Sender: TObject); begin ResetAll; InitializeControls; end; procedure TFrmMain.SpeedButton2Click(Sender: TObject); begin FloatAnimationCameraY.Start; FloatAnimationCameraX1.Start; FloatAnimationCameraX2.Start; FloatAnimationCameraX3.Start; end; procedure TFrmMain.CleanFrameTextureClick(Sender: TObject); var Obj: TExtrudedShape3D; List: TListBox; Sample: TImage; TempMaterialSource: TLightMaterialSource; begin Obj := nil; List := nil; Sample := nil; if Sender = CleanTextTexture then begin Obj := Text3D; List := ListText; Sample := TextTexture; end else begin if Sender = CleanFrameTexture then begin Obj := Rectangle; List := ListFrame; Sample := FrameTexture; end; end; if Assigned(Obj) and Assigned(List) then begin TempMaterialSource := GetMaterialSource(List, Obj); TempMaterialSource.Texture.SetSize(0, 0); Sample.Bitmap.SetSize(0, 0); end; end; procedure TFrmMain.SBDownClick(Sender: TObject); begin MainDummy.RotationAngle.X := MainDummy.RotationAngle.X + 1; end; procedure TFrmMain.SBFontClick(Sender: TObject); begin // not implemented yet end; procedure TFrmMain.SBLeftClick(Sender: TObject); begin MainDummy.RotationAngle.Y := MainDummy.RotationAngle.Y + 1; end; procedure TFrmMain.SBRightClick(Sender: TObject); begin MainDummy.RotationAngle.Y := MainDummy.RotationAngle.Y - 1; end; procedure TFrmMain.SBUpClick(Sender: TObject); begin MainDummy.RotationAngle.X := MainDummy.RotationAngle.X - 1; end; procedure TFrmMain.Text3DClick(Sender: TObject); begin SelectedObject := Sender as TShape3D; end; procedure TFrmMain.Text3DDepthChange(Sender: TObject); begin TextDepth := Text3DDepth.Value; end; procedure TFrmMain.TrackBarObjectDepthChange(Sender: TObject); begin Camera.Position.Z := - TrackBarObjectDepth.Value; end; procedure TFrmMain.VertMarginChange(Sender: TObject); begin FrameHeight := VertMargin.Value; end; procedure TFrmMain.Viewport3D1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin if not isAnimationRunning then begin Down := PointF(X, Y); MouseUp := True end; end; procedure TFrmMain.Viewport3D1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); begin if (ssLeft in Shift) and (MouseUp) and (not isAnimationRunning) then begin DummyX.RotationAngle.X := DummyX.RotationAngle.X - ((Y - Down.Y) * 0.3); DummyY.RotationAngle.Y := DummyY.RotationAngle.Y + ((X - Down.X) * 0.3); Down := PointF(X, Y); end; end; procedure TFrmMain.Viewport3D1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin MouseUp := False; end; procedure TFrmMain.Viewport3D1MouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); var AVector: TVector3D; begin if not isAnimationRunning then begin AVector := Vector3D(0, 0, 1); Camera.Position.Vector.AddVector3D( AVector.Scale((WheelDelta / 120) * 0.3)); TrackBarObjectDepth.Value := -Camera.Position.Z; end; end; end.
unit fos_firmbox_fileserver_mod; {$mode objfpc}{$H+} {$modeswitch nestedprocvars} interface uses Classes, SysUtils, FRE_SYSTEM, FOS_TOOL_INTERFACES, FRE_DB_INTERFACE, FRE_DB_COMMON, fre_accesscontrol_common, fos_infrastructure_if_mod, fre_zfs,fre_hal_schemes; type { TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD } TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD = class (TFRE_DB_APPLICATION_MODULE) private function _addGFSChooseZone (const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const panelId: String): IFRE_DB_Object; function _addVFSChooseZone (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const panelId: String): IFRE_DB_Object; function _addModifyFS (const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const service: IFRE_DB_Object; const panelId: String; const global: Boolean): IFRE_DB_Object; public class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override; class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override; procedure MySessionInitializeModule (const session : TFRE_DB_UserSession);override; function canAddService (const conn: IFRE_DB_CONNECTION; const global: Boolean): Boolean; function canAddService (const conn: IFRE_DB_CONNECTION; const zone: TFRE_DB_ZONE; const global: Boolean): Boolean; function canModifyService (const conn: IFRE_DB_CONNECTION): Boolean; function canModifyService (const conn: IFRE_DB_CONNECTION; const dbo: IFRE_DB_Object): Boolean; function canEnableService (const conn: IFRE_DB_CONNECTION): Boolean; function canEnableService (const conn: IFRE_DB_CONNECTION; const dbo: IFRE_DB_Object): Boolean; function canDisableService (const conn: IFRE_DB_CONNECTION): Boolean; function canDisableService (const conn: IFRE_DB_CONNECTION; const dbo: IFRE_DB_Object): Boolean; function canDeleteService (const conn: IFRE_DB_CONNECTION): Boolean; function canDeleteService (const conn: IFRE_DB_CONNECTION; const dbo: IFRE_DB_Object): Boolean; function canApplyService (const conn: IFRE_DB_CONNECTION): Boolean; function canApplyService (const conn: IFRE_DB_CONNECTION; const dbo: IFRE_DB_Object): Boolean; function applyConfig (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const service: IFRE_DB_Object):IFRE_DB_Object; function enableService (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const service: IFRE_DB_Object):IFRE_DB_Object; function disableService (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const service: IFRE_DB_Object):IFRE_DB_Object; function modifyService (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const service: IFRE_DB_Object; const panelId: String):IFRE_DB_Object; function addService (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const global: Boolean):IFRE_DB_Object; function deleteService (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const service: IFRE_DB_Object):IFRE_DB_Object; procedure deleteServiceConfiguration (const conn: IFRE_DB_CONNECTION; const ses: IFRE_DB_Usersession; service: IFRE_DB_Object); procedure deleteShare (const conn: IFRE_DB_CONNECTION; shareId: TFRE_DB_GUID); published function WEB_AddService (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_StoreService (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_ApplyConfigConfirmed (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_DeleteServiceConfirmed (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; end; { TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD } TFILESHARE_ROLETYPE = (rtRead,rtWrite); TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD = class (TFRE_DB_APPLICATION_MODULE) private fServiceIFMod : TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD; fInfrastructureIFMod : TFOS_INFRASTRUCTURE_IF_MOD; procedure _setConfigChanged (const conn: IFRE_DB_CONNECTION; const ses: IFRE_DB_Usersession; const service: IFRE_DB_Object); protected procedure SetupAppModuleStructure ; override; public class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override; class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override; class procedure InstallUserDBObjects (const conn: IFRE_DB_CONNECTION; currentVersionId: TFRE_DB_NameType); override; procedure CalculateReadWriteAccess (const conn : IFRE_DB_CONNECTION ; const dependency_input : IFRE_DB_Object; const input_object : IFRE_DB_Object ; const transformed_object : IFRE_DB_Object); procedure MySessionInitializeModule (const session : TFRE_DB_UserSession);override; published function WEB_Content (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;override; function WEB_ContentGeneral (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_ContentVFShares (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_ContentSnapshots (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_AddVFS (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_DeleteFS (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_ApplyConfig (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_EnableFS (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_DisableFS (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_VFSSC (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_ServiceMenu (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_ServiceObjChanged (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_DSObjChanged (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_VFSDelete (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_VFSDeleteConfirmed (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_AddVFSShare (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_StoreVFSShare (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; procedure CCB_SetupQuotaAndUpdate (const ses: IFRE_DB_UserSession; const new_input: IFRE_DB_Object; const status: TFRE_DB_COMMAND_STATUS; const ocid: Qword; const opaquedata: IFRE_DB_Object); function WEB_VFSShareMenu (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_VFSShareContent (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_VFSShareSC (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_VFSShareObjChanged (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_VFSShareDelete (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_VFSShareDeleteConfirmed (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_VFSShareUser (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_VFSShareDelegationGroups (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_VFSShareSnapshots (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_GridUOSC (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_GridUISC (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_GridUOMenu (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_GridUIMenu (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_AddUser (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_RemoveUser (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_GridGOSC (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_GridGISC (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_GridGOMenu (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_GridGIMenu (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_AddGroup (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_RemoveGroup (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; end; procedure Register_DB_Extensions; implementation procedure Register_DB_Extensions; begin fre_zfs.Register_DB_Extensions; fre_hal_schemes.Register_DB_Extensions; GFRE_DBI.RegisterObjectClassEx(TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD); GFRE_DBI.RegisterObjectClassEx(TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD); //GFRE_DBI.Initialize_Extension_Objects; end; { TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD } function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD._addVFSChooseZone(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const panelId: String): IFRE_DB_Object; var res: TFRE_DB_FORM_DESC; sf : TFRE_DB_SERVER_FUNC_DESC; dc : IFRE_DB_DERIVED_COLLECTION; begin dc:=ses.FetchDerivedCollection('VFS_ZONE_CHOOSER'); if dc.ItemCount=0 then begin Result:=TFRE_DB_MESSAGE_DESC.Create.Describe(FetchModuleTextShort(ses,'vfs_create_error_no_zone_cap'),FetchModuleTextShort(ses,'vfs_create_error_no_zone_msg'),fdbmt_error); end else begin sf:=CWSF(@WEB_AddService); if panelId='' then begin res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(FetchModuleTextShort(ses,'vfs_add_diag_cap'),600,true,true,false); end else begin res:=TFRE_DB_FORM_PANEL_DESC.create.Describe('',false); res.contentId:=panelId; sf.AddParam.Describe('panelId',panelId); end; res.AddChooser.Describe(FetchModuleTextShort(ses,'zone_chooser_label'),'zone',dc.GetStoreDescription.Implementor_HC as TFRE_DB_STORE_DESC,dh_chooser_combo,true); res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit); Result:=res; end; end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.canAddService(const conn: IFRE_DB_CONNECTION; const zone: TFRE_DB_ZONE; const global: Boolean): Boolean; begin if global then begin Result:=conn.sys.CheckClassRight4DomainId(sr_STORE,TFRE_DB_GLOBAL_FILESERVER,zone.DomainID); end else begin Result:=conn.sys.CheckClassRight4DomainId(sr_STORE,TFRE_DB_VIRTUAL_FILESERVER,zone.DomainID); end; end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.canModifyService(const conn: IFRE_DB_CONNECTION): Boolean; begin Result:=conn.sys.CheckClassRight4AnyDomain(sr_UPDATE,TFRE_DB_VIRTUAL_FILESERVER); end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.canModifyService(const conn: IFRE_DB_CONNECTION; const dbo: IFRE_DB_Object): Boolean; var domain_id: TFRE_DB_GUID; begin domain_id:=dbo.DomainID; Result:=conn.sys.CheckClassRight4DomainId(sr_UPDATE,dbo.SchemeClass,domain_id); end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.canEnableService(const conn: IFRE_DB_CONNECTION): Boolean; begin Result:=canModifyService(conn); end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.canEnableService(const conn: IFRE_DB_CONNECTION; const dbo: IFRE_DB_Object): Boolean; var splugin: TFRE_DB_SERVICE_STATUS_PLUGIN; begin dbo.GetPlugin(TFRE_DB_SERVICE_STATUS_PLUGIN,splugin); Result:=canModifyService(conn,dbo) and splugin.isServiceDisabled; end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.canDisableService(const conn: IFRE_DB_CONNECTION): Boolean; begin Result:=canModifyService(conn); end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.canDisableService(const conn: IFRE_DB_CONNECTION; const dbo: IFRE_DB_Object): Boolean; var splugin: TFRE_DB_SERVICE_STATUS_PLUGIN; begin dbo.GetPlugin(TFRE_DB_SERVICE_STATUS_PLUGIN,splugin); Result:=canModifyService(conn,dbo) and not splugin.isServiceDisabled; end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.canDeleteService(const conn: IFRE_DB_CONNECTION): Boolean; begin Result:=conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_VIRTUAL_FILESERVER) and conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_VIRTUAL_FILESHARE); end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.canDeleteService(const conn: IFRE_DB_CONNECTION; const dbo: IFRE_DB_Object): Boolean; var domain_id: TFRE_DB_GUID; begin domain_id:=dbo.DomainID; Result:=conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_VIRTUAL_FILESERVER,domain_id) and conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_VIRTUAL_FILESHARE,domain_id); end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.canApplyService(const conn: IFRE_DB_CONNECTION): Boolean; begin Result:=canModifyService(conn); end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.canApplyService(const conn: IFRE_DB_CONNECTION; const dbo: IFRE_DB_Object): Boolean; var splugin: TFRE_DB_SERVICE_STATUS_PLUGIN; begin dbo.GetPlugin(TFRE_DB_SERVICE_STATUS_PLUGIN,splugin); Result:=canModifyService(conn,dbo) and not splugin.isConfigApplied; end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD._addModifyFS(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const service: IFRE_DB_Object; const panelId: String; const global: Boolean): IFRE_DB_Object; var res : TFRE_DB_FORM_DESC; sf : TFRE_DB_SERVER_FUNC_DESC; zone : TFRE_DB_ZONE; scheme : IFRE_DB_SchemeObject; isModify : Boolean; editable : Boolean; caption : TFRE_DB_String; zoneId : TFRE_DB_GUID; langres : TFRE_DB_StringArray; zoneStatusPlugin : TFRE_DB_ZONESTATUS_PLUGIN; group : TFRE_DB_INPUT_GROUP_DESC; servicePlugin : TFRE_DB_SERVICE_STATUS_PLUGIN; pId : TFRE_DB_String; error_cap : TFRE_DB_String; error_msg : TFRE_DB_String; dc : IFRE_DB_DERIVED_COLLECTION; begin CheckClassVisibility4AnyDomain(ses); if input.FieldExists('panelId') then begin pId:=input.Field('panelId').AsString; end else begin pId:=panelId; end; sf:=CWSF(@WEB_StoreService); sf.AddParam.Describe('panelId',pId); sf.AddParam.Describe('global',BoolToStr(global,'true','false')); if Assigned(service) then begin isModify:=true; editable:=canModifyService(conn,service); zoneId:=service.Field('serviceParent').AsObjectLink; CheckDbResult(conn.FetchAs(zoneId,TFRE_DB_ZONE,zone)); sf.AddParam.Describe('serviceId',service.UID_String); if global then begin caption:=FetchModuleTextShort(ses,'gfs_modify_diag_cap'); end else begin caption:=FetchModuleTextShort(ses,'vfs_modify_diag_cap'); end; end else begin isModify:=false; editable:=true; if input.FieldExists('zoneId') or input.FieldPathExists('data.zone') then begin if input.FieldExists('zoneId') then begin zoneId:=FREDB_H2G(input.Field('zoneId').AsString); end else begin zoneId:=FREDB_H2G(input.FieldPath('data.zone').AsString); end; sf.AddParam.Describe('zoneId',zoneId.AsHexString); CheckDbResult(conn.FetchAs(zoneId,TFRE_DB_ZONE,zone)); if not canAddService(conn,zone,global) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); end else begin if global then begin Result:=_addGFSChooseZone(input,ses,app,conn,pId); end else begin Result:=_addVFSChooseZone(input,ses,app,conn,pId); end; exit; end; if global then begin caption:=FetchModuleTextShort(ses,'gfs_add_diag_cap'); end else begin caption:=FetchModuleTextShort(ses,'vfs_add_diag_cap'); end; end; if pId='' then begin res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(caption,600,true,true,false); end else begin res:=TFRE_DB_FORM_PANEL_DESC.create.Describe('',false,editable); res.contentId:=pId; end; dc:=ses.FetchDerivedCollection(CFRE_DB_FILESERVER_IP_CHOOSER_DC); dc.Filters.RemoveFilter('zone'); dc.Filters.AddUIDFieldFilter('zone','zuid',zone.UID,dbnf_OneValueFromFilter); if dc.ItemCount=0 then begin if global then begin error_cap:=FetchModuleTextShort(ses,'gfs_add_diag_error_no_ip_cap'); error_msg:=FetchModuleTextShort(ses,'gfs_add_diag_error_no_ip_msg'); end else begin error_cap:=FetchModuleTextShort(ses,'vfs_add_diag_error_no_ip_cap'); error_msg:=FetchModuleTextShort(ses,'vfs_add_diag_error_no_ip_msg'); end; if pId='' then begin Result:=TFRE_DB_MESSAGE_DESC.create.Describe(error_cap,error_msg,fdbmt_error); end else begin Result:=TFRE_DB_HTML_DESC.create.Describe(error_msg); (Result.Implementor_HC as TFRE_DB_CONTENT_DESC).contentId:=pId; end; exit; end; if global then begin GetSystemScheme(TFRE_DB_GLOBAL_FILESERVER,scheme); end else begin GetSystemScheme(TFRE_DB_VIRTUAL_FILESERVER,scheme); end; res.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses,false,false,'',true,true); if isModify then begin service.GetPlugin(TFRE_DB_SERVICE_STATUS_PLUGIN,servicePlugin); langres:=TFRE_DB_SERVICE_STATUS_PLUGIN.getStatusLangres(conn); CheckDbResult(conn.FetchAs(service.Field('serviceParent').AsObjectLink,TFRE_DB_ZONE,zone)); zone.GetPlugin(TFRE_DB_ZONESTATUS_PLUGIN,zoneStatusPlugin); group:=res.AddGroup.Describe(FetchModuleTextShort(ses,'fs_general_status_group'),false,false); group.AddDescription.Describe(FetchModuleTextShort(ses,'fs_general_status_label'),G_getServiceStatusText(servicePlugin,zoneStatusPlugin,langres),'status'); group.AddDescription.Describe(FetchModuleTextShort(ses,'fs_general_config_status_label'),G_getServiceConfigStatusText(servicePlugin,langres),'config_status'); res.FillWithObjectValues(service,ses); end; if editable then begin res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit); end; Result:=res; end; procedure TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.deleteServiceConfiguration(const conn: IFRE_DB_CONNECTION; const ses: IFRE_DB_Usersession; service: IFRE_DB_Object); var shares : TFRE_DB_GUIDArray; shareIdx : Integer; group : IFRE_DB_GROUP; users : TFRE_DB_GUIDArray; groups : TFRE_DB_GUIDArray; i : Integer; serviceUid : TFRE_DB_GUID; zone : TFRE_DB_ZONE; begin if not canDeleteService(conn,service) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); shares:=conn.GetReferences(service.UID,false,TFRE_DB_VIRTUAL_FILESHARE.ClassName,'fileserver'); for shareIdx := 0 to High(shares) do begin //delete shares deleteShare(conn,shares[shareIdx]); end; //delete the service CheckDbResult(conn.FetchAs(service.Field('serviceParent').AsObjectLink,TFRE_DB_ZONE,zone)); serviceUid:=service.UID; CheckDbResult(conn.Delete(serviceUid)); zone.RemoveServiceEmbedded(conn,ses,serviceUid.AsHexString); end; procedure TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.deleteShare(const conn: IFRE_DB_CONNECTION; shareId: TFRE_DB_GUID); var share : IFRE_DB_Object; group : IFRE_DB_GROUP; users : TFRE_DB_GUIDArray; groups : TFRE_DB_GUIDArray; i : Integer; begin CheckDbResult(conn.Fetch(shareId,share)); CheckDbResult(conn.sys.FetchGroupById(share.Field('group').AsObjectLink,group)); CheckDbResult(conn.Delete(shareId)); //delete the share //remove users and groups from group conn.ExpandReferences(TFRE_DB_GUIDArray.create(group.UID),TFRE_DB_NameTypeRLArray.create('TFRE_DB_USER<USERGROUPIDS'),users); for i := 0 to High(users) do begin CheckDbResult(conn.sys.RemoveUserGroupsById(users[i],TFRE_DB_GUIDArray.Create(group.UID))); end; conn.ExpandReferences(TFRE_DB_GUIDArray.create(group.UID),TFRE_DB_NameTypeRLArray.create('TFRE_DB_GROUP<GROUPIDS'),groups); CheckDbResult(conn.sys.RemoveGroupsFromGroupById(group.ObjectName,group.DomainID,groups,false)); CheckDbResult(conn.sys.DeleteGroupById(group.UID)); //delete the group end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD._addGFSChooseZone(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const panelId: String): IFRE_DB_Object; var res: TFRE_DB_FORM_DESC; sf : TFRE_DB_SERVER_FUNC_DESC; dc : IFRE_DB_DERIVED_COLLECTION; begin dc:=ses.FetchDerivedCollection('GFS_ZONE_CHOOSER'); if dc.ItemCount=0 then begin Result:=TFRE_DB_MESSAGE_DESC.Create.Describe(FetchModuleTextShort(ses,'gfs_create_error_no_zone_cap'),FetchModuleTextShort(ses,'gfs_create_error_no_zone_msg'),fdbmt_error); end else begin sf:=CWSF(@WEB_AddService); if panelId='' then begin res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(FetchModuleTextShort(ses,'gfs_add_diag_cap'),600,true,true,false); end else begin res:=TFRE_DB_FORM_PANEL_DESC.create.Describe('',false); res.contentId:=panelId; sf.AddParam.Describe('panelId',panelId); end; res.AddChooser.Describe(FetchModuleTextShort(ses,'zone_chooser_label'),'zone',dc.GetStoreDescription.Implementor_HC as TFRE_DB_STORE_DESC,dh_chooser_combo,true); res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit); Result:=res; end; end; class procedure TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT); begin inherited RegisterSystemScheme(scheme); scheme.SetParentSchemeByName('TFRE_DB_APPLICATION_MODULE'); end; class procedure TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); begin newVersionId:='1.0'; if currentVersionId='' then begin currentVersionId := '1.0'; CreateModuleText(conn,'vfs_add_diag_cap','New Virtual Fileserver'); CreateModuleText(conn,'vfs_modify_diag_cap','Modfiy Virtual Fileserver'); CreateModuleText(conn,'zone_chooser_value','%zone_str% (%service_obj_str%)'); CreateModuleText(conn,'zone_chooser_value_no_service_obj','%zone_str%'); CreateModuleText(conn,'zone_chooser_label','Zone'); CreateModuleText(conn,'vfs_create_error_exists_cap','Error: Add VFS Service'); CreateModuleText(conn,'vfs_create_error_exists_msg','The Fileserver Service already exists!'); CreateModuleText(conn,'vfs_add_diag_error_no_ip_cap','Error: Add VFS Service'); CreateModuleText(conn,'vfs_add_diag_error_no_ip_msg','No available IP found in the choosen Zone. Please configure the Network of the Zone first.'); CreateModuleText(conn,'vfs_create_error_no_zone_cap','Error: New VFS Service'); CreateModuleText(conn,'vfs_create_error_no_zone_msg','There is no zone available for a new VFS Service. Please use the infrastructure module to create a zone.'); CreateModuleText(conn,'gfs_add_diag_cap','New Global Fileserver'); CreateModuleText(conn,'gfs_modify_diag_cap','Modfiy Global Fileserver'); CreateModuleText(conn,'gfs_create_error_exists_cap','Error: Add GFS Service'); CreateModuleText(conn,'gfs_create_error_exists_msg','The Global Fileserver Service already exists!'); CreateModuleText(conn,'gfs_create_error_no_zone_cap','Error: New GFS Service'); CreateModuleText(conn,'gfs_create_error_no_zone_msg','There is no zone available for a new GFS Service.'); CreateModuleText(conn,'gfs_add_diag_error_no_ip_cap','Error: Add GFS Service'); CreateModuleText(conn,'gfs_add_diag_error_no_ip_msg','No available IP found in the choosen Zone. Please configure the Network of the Zone first.'); CreateModuleText(conn,'apply_service_diag_cap','Apply Configuration'); CreateModuleText(conn,'apply_service_diag_msg','This will apply the Fileserver "%service_str%" configuration and restart the service! Are you sure?'); CreateModuleText(conn,'delete_service_diag_cap','Delete Fileserver'); CreateModuleText(conn,'delete_service_diag_msg','This will delete the Fileserver "%service_str%" service and its configuration. This operation is irreversible! Are you sure?'); CreateModuleText(conn,'fs_general_status_group','Status Information'); CreateModuleText(conn,'fs_general_status_label','Service Status'); CreateModuleText(conn,'fs_general_config_status_label','Configuration Status'); end; end; procedure TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.MySessionInitializeModule(const session: TFRE_DB_UserSession); var app : TFRE_DB_APPLICATION; conn : IFRE_DB_CONNECTION; transform: IFRE_DB_SIMPLE_TRANSFORM; dc : IFRE_DB_DERIVED_COLLECTION; procedure _setCaption(const input,transformed_object : IFRE_DB_Object;const langres: TFRE_DB_StringArray); var str: String; begin if transformed_object.Field('serviceObj').AsString<>'' then begin str:=StringReplace(langres[0],'%zone_str%',transformed_object.Field('objname').AsString,[rfReplaceAll]); str:=StringReplace(str,'%service_obj_str%',transformed_object.Field('serviceObj').AsString,[rfReplaceAll]); end else begin str:=StringReplace(langres[1],'%zone_str%',transformed_object.Field('objname').AsString,[rfReplaceAll]); end; transformed_object.Field('label').AsString:=str; end; begin inherited MySessionInitializeModule(session); if session.IsInteractiveSession then begin app := GetEmbeddingApp; conn := session.GetDBConnection; GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform); with transform do begin AddOneToOnescheme('objname'); AddOneToOnescheme('label'); AddMatchingReferencedField(['<SERVICEDOMAIN'],'objname','serviceObj','',true,dt_string,true,true,1,'','',nil,'',false,'domainid'); AddMatchingReferencedField(['TEMPLATEID>TFRE_DB_FBZ_TEMPLATE'],'serviceclasses'); AddMatchingReferencedField(['TFRE_DB_VIRTUAL_FILESERVER<SERVICEPARENT'],'uid','vfs','',false,dt_string,false,false,1,'','OK'); AddOneToOnescheme('disabledSCs'); SetSimpleFuncTransformNested(@_setCaption,[FetchModuleTextShort(session,'zone_chooser_value'),FetchModuleTextShort(session,'zone_chooser_value_no_service_obj')]); end; dc := session.NewDerivedCollection('VFS_ZONE_CHOOSER'); with dc do begin SetDeriveParent(conn.GetCollection(CFOS_DB_ZONES_COLLECTION)); SetDeriveTransformation(transform); SetDisplayType(cdt_Chooser,[],''); SetDefaultOrderField('objname',true); Filters.AddStdClassRightFilter('rights','domainid','','',TFRE_DB_VIRTUAL_FILESERVER.ClassName,[sr_STORE],session.GetDBConnection.SYS.GetCurrentUserTokenClone); Filters.AddStringFieldFilter('serviceclasses','serviceclasses',TFRE_DB_VIRTUAL_FILESERVER.ClassName,dbft_EXACTVALUEINARRAY); Filters.AddStringFieldFilter('disabledSCs','disabledSCs',TFRE_DB_VIRTUAL_FILESERVER.ClassName,dbft_EXACTVALUEINARRAY,false,true); Filters.AddStringFieldFilter('used','vfs','OK',dbft_EXACT); end; GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform); with transform do begin AddOneToOnescheme('objname'); AddOneToOnescheme('label'); AddMatchingReferencedField(['<SERVICEDOMAIN'],'objname','serviceObj','',true,dt_string,true,true,1,'','',nil,'',false,'domainid'); AddMatchingReferencedField(['TEMPLATEID>TFRE_DB_FBZ_TEMPLATE'],'serviceclasses'); AddMatchingReferencedField(['TFRE_DB_GLOBAL_FILESERVER<SERVICEPARENT'],'uid','gfs','',false,dt_string,false,false,1,'','OK'); AddOneToOnescheme('disabledSCs'); SetSimpleFuncTransformNested(@_setCaption,[FetchModuleTextShort(session,'zone_chooser_value'),FetchModuleTextShort(session,'zone_chooser_value_no_service_obj')]); end; dc := session.NewDerivedCollection('GFS_ZONE_CHOOSER'); with dc do begin SetDeriveParent(conn.GetCollection(CFOS_DB_ZONES_COLLECTION)); SetDeriveTransformation(transform); SetDisplayType(cdt_Chooser,[],''); SetDefaultOrderField('objname',true); Filters.AddStdClassRightFilter('rights','domainid','','',TFRE_DB_VIRTUAL_FILESERVER.ClassName,[sr_STORE],session.GetDBConnection.SYS.GetCurrentUserTokenClone); Filters.AddStringFieldFilter('serviceclasses','serviceclasses',TFRE_DB_VIRTUAL_FILESERVER.ClassName,dbft_EXACTVALUEINARRAY); Filters.AddStringFieldFilter('disabledSCs','disabledSCs',TFRE_DB_VIRTUAL_FILESERVER.ClassName,dbft_EXACTVALUEINARRAY,false,true); Filters.AddStringFieldFilter('used','gfs','OK',dbft_EXACT); end; end; end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.canAddService(const conn: IFRE_DB_CONNECTION; const global: Boolean): Boolean; begin if global then begin Result:=conn.sys.CheckClassRight4AnyDomain(sr_STORE,TFRE_DB_GLOBAL_FILESERVER); end else begin Result:=conn.sys.CheckClassRight4AnyDomain(sr_STORE,TFRE_DB_VIRTUAL_FILESERVER); end; end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.WEB_AddService(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var global : Boolean; begin if input.Field('global').AsString='true' then begin global:=true; end else begin global:=false; end; Result:=_addModifyFS(input,ses,app,conn,nil,'',global); end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.WEB_StoreService(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var scheme : IFRE_DB_SchemeObject; coll : IFRE_DB_COLLECTION; fsService : TFRE_DB_FILESERVER; zoneId : TFRE_DB_String; zone : TFRE_DB_ZONE; fld : IFRE_DB_FIELD; global : Boolean; isModify : Boolean; begin if input.FieldExists('serviceId') then begin CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('serviceId').AsString),TFRE_DB_FILESERVER,fsService)); if not canModifyService(conn,fsService) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); CheckDbResult(conn.FetchAs(fsService.Field('serviceParent').AsObjectLink,TFRE_DB_ZONE,zone)); global:=fsService.Implementor_HC is TFRE_DB_GLOBAL_FILESERVER; isModify:=true; end else begin if input.FieldPathExists('data.zone') then begin zoneId:=input.FieldPath('data.zone').AsString; input.Field('data').AsObject.DeleteField('zone'); end else begin if input.FieldExists('zoneId') then begin zoneId:=input.Field('zoneId').AsString; end else begin raise EFRE_DB_Exception.Create('Missing parameter: data.zone or zoneId'); end; end; global:=input.FieldOnlyExisting('global',fld) and (fld.AsString='true'); CheckDbResult(conn.FetchAs(FREDB_H2G(zoneId),TFRE_DB_ZONE,zone)); if not canAddService(conn,zone,global) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); if global then begin GetSystemScheme(TFRE_DB_GLOBAL_FILESERVER,scheme); fsService:=TFRE_DB_GLOBAL_FILESERVER.CreateForDB; end else begin GetSystemScheme(TFRE_DB_VIRTUAL_FILESERVER,scheme); fsService:=TFRE_DB_VIRTUAL_FILESERVER.CreateForDB; end; fsService.SetDomainID(zone.DomainID); fsService.Field('serviceParent').AsObjectLink:=zone.UID; fsService.setMachineId(zone.MachineID); fsService.setDataset(zone.GetVFilerDataset(conn)); fsService.ObjectName:=input.FieldPath('data.objname').AsString; fsService.UCT:=fsService.SchemeClass + '@' + zone.UID_String; coll:=conn.GetCollection(CFOS_DB_SERVICES_COLLECTION); if coll.ExistsIndexedFieldval(fsService.field('UCT'))>0 then begin if global then begin Result:=TFRE_DB_MESSAGE_DESC.Create.Describe(FetchModuleTextShort(ses,'gfs_create_error_exists_cap'),FetchModuleTextShort(ses,'gfs_create_error_exists_msg'),fdbmt_error); end else begin Result:=TFRE_DB_MESSAGE_DESC.Create.Describe(FetchModuleTextShort(ses,'vfs_create_error_exists_cap'),FetchModuleTextShort(ses,'vfs_create_error_exists_msg'),fdbmt_error); end; exit; end; isModify:=false; end; if global then begin GetSystemScheme(TFRE_DB_GLOBAL_FILESERVER,scheme); end else begin GetSystemScheme(TFRE_DB_VIRTUAL_FILESERVER,scheme); end; scheme.SetObjectFieldsWithScheme(input.Field('data').AsObject,fsService,not isModify,conn); if isModify then begin G_setServiceConfigChanged(conn,ses,fsService); CheckDbResult(conn.Update(fsService)); end else begin CheckDbResult(coll.Store(fsService)); end; if input.Field('panelId').AsString='' then begin Result:=TFRE_DB_CLOSE_DIALOG_DESC.create.Describe(); end else begin Result:=GFRE_DB_NIL_DESC; end; end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.applyConfig(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const service: IFRE_DB_Object): IFRE_DB_Object; var sf: TFRE_DB_SERVER_FUNC_DESC; begin if not canApplyService(conn,service) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); sf:=CWSF(@WEB_ApplyConfigConfirmed); sf.AddParam.Describe('serviceId',service.UID_String); Result:=TFRE_DB_MESSAGE_DESC.create.Describe(FetchModuleTextShort(ses,'apply_service_diag_cap'),StringReplace(FetchModuleTextShort(ses,'apply_service_diag_msg'),'%service_str%',service.Field('objname').AsString,[rfReplaceAll]),fdbmt_confirm,sf); end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.enableService(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const service: IFRE_DB_Object): IFRE_DB_Object; var servicePlugin: TFRE_DB_SERVICE_STATUS_PLUGIN; begin if not canEnableService(conn,service) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); service.GetPlugin(TFRE_DB_SERVICE_STATUS_PLUGIN,servicePlugin); servicePlugin.setEnabled; CheckDbResult(conn.Update(service)); Result:=GFRE_DB_NIL_DESC; end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.disableService(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const service: IFRE_DB_Object): IFRE_DB_Object; var servicePlugin: TFRE_DB_SERVICE_STATUS_PLUGIN; begin if not canDisableService(conn,service) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); service.GetPlugin(TFRE_DB_SERVICE_STATUS_PLUGIN,servicePlugin); servicePlugin.setDisabled; CheckDbResult(conn.Update(service)); Result:=GFRE_DB_NIL_DESC; end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.modifyService(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const service: IFRE_DB_Object; const panelId: String): IFRE_DB_Object; begin Result:=_addModifyFS(input,ses,app,conn,service,panelId,service.Implementor_HC is TFRE_DB_GLOBAL_FILESERVER); end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.addService(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const global: Boolean): IFRE_DB_Object; begin Result:=_addModifyFS(input,ses,app,conn,nil,'',global); end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.deleteService(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION; const service: IFRE_DB_Object): IFRE_DB_Object; var sf: TFRE_DB_SERVER_FUNC_DESC; begin if not canDeleteService(conn,service) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); sf:=CWSF(@WEB_DeleteServiceConfirmed); sf.AddParam.Describe('serviceId',service.UID_String); Result:=TFRE_DB_MESSAGE_DESC.create.Describe(FetchModuleTextShort(ses,'delete_service_diag_cap'),StringReplace(FetchModuleTextShort(ses,'delete_service_diag_msg'),'%service_str%',service.Field('objname').AsString,[rfReplaceAll]),fdbmt_confirm,sf); end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.WEB_ApplyConfigConfirmed(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var service : TFRE_DB_FILESERVER; servicePlugin : TFRE_DB_SERVICE_STATUS_PLUGIN; zone : TFRE_DB_ZONE; begin if input.field('confirmed').AsBoolean then begin CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('serviceId').AsString),TFRE_DB_FILESERVER,service)); if not canApplyService(conn,service) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); service.GetPlugin(TFRE_DB_SERVICE_STATUS_PLUGIN,servicePlugin); servicePlugin.setConfigApplied; CheckDbResult(conn.Update(service.CloneToNewObject())); CheckDbResult(conn.FetchAs(service.Field('serviceParent').AsObjectLink,TFRE_DB_ZONE,zone)); zone.UpdateServiceEmbedded(conn,ses,service); end; Result:=GFRE_DB_NIL_DESC; end; function TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.WEB_DeleteServiceConfirmed(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var service : IFRE_DB_Object; begin Result:=GFRE_DB_NIL_DESC; if input.field('confirmed').AsBoolean then begin CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('serviceId').AsString),service)); deleteServiceConfiguration(conn,ses,service); Result:=GFRE_DB_NIL_DESC; end; end; { TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD } class procedure TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT); begin inherited RegisterSystemScheme(scheme); scheme.SetParentSchemeByName('TFRE_DB_APPLICATION_MODULE'); end; procedure TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD._setConfigChanged(const conn: IFRE_DB_CONNECTION; const ses: IFRE_DB_Usersession; const service: IFRE_DB_Object); var servicePlugin: TFRE_DB_SERVICE_STATUS_PLUGIN; begin service.GetPlugin(TFRE_DB_SERVICE_STATUS_PLUGIN,servicePlugin); if servicePlugin.isConfigApplied then begin servicePlugin.setConfigModified; CheckDbResult(conn.Update(service.CloneToNewObject())); end; end; procedure TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.SetupAppModuleStructure; begin inherited SetupAppModuleStructure; InitModuleDesc('fileserver_virtual_description'); fServiceIFMod:=TFRE_FIRMBOX_FILESERVER_SERVICE_IF_MOD.create; AddApplicationModule(fServiceIFMod); fInfrastructureIFMod:=TFOS_INFRASTRUCTURE_IF_MOD.create; AddApplicationModule(fInfrastructureIFMod); end; class procedure TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); begin newVersionId:='1.0'; if currentVersionId='' then begin currentVersionId := '1.0'; CreateModuleText(conn,'fileserver_virtual_description','Virtual NAS','Virtual NAS','Virtual NAS'); CreateModuleText(conn,'tb_delete_vfs','Delete'); CreateModuleText(conn,'cm_delete_vfs','Delete'); CreateModuleText(conn,'storage_virtual_filer_general','General'); CreateModuleText(conn,'storage_virtual_filer_shares','Shares'); CreateModuleText(conn,'storage_virtual_filer_snapshots','Snapshots'); CreateModuleText(conn,'vfs_delete_diag_cap','Confirm: Delete Virtual Fileserver'); CreateModuleText(conn,'vfs_delete_diag_msg','The virtual fileserver %vfs_str% will be deleted permanently! Please confirm to continue.'); CreateModuleText(conn,'vfs_share_create_error_exists_cap','Error: Add Share'); CreateModuleText(conn,'vfs_share_create_error_exists_msg','The Share already exists!'); CreateModuleText(conn,'vfs_share','Share'); CreateModuleText(conn,'vfs_share_refer','Refer'); CreateModuleText(conn,'vfs_share_used','Used'); CreateModuleText(conn,'vfs_share_quota','Quota'); CreateModuleText(conn,'tb_create_vfs_share','Create'); CreateModuleText(conn,'tb_delete_vfs_share','Delete'); CreateModuleText(conn,'cm_delete_vfs_share','Delete'); CreateModuleText(conn,'storage_virtual_filer_share_properties','Share Properties'); CreateModuleText(conn,'storage_virtual_filer_share_snapshots','Snapshots'); CreateModuleText(conn,'storage_virtual_filer_share_browser','Browser'); CreateModuleText(conn,'vfs_share_add_diag_cap','New Fileshare'); CreateModuleText(conn,'vfs_share_add_no_fs_msg','Please select a virtual NAS first before adding a share.'); CreateModuleText(conn,'vfs_share_delete_diag_cap','Confirm: Delete share'); CreateModuleText(conn,'vfs_share_delete_diag_msg','The share %share_str% will be deleted permanently! Please confirm to continue.'); CreateModuleText(conn,'error_delete_single_select','Exactly one object has to be selected for deletion.'); CreateModuleText(conn,'tb_create_vfs','Add'); CreateModuleText(conn,'tb_delete_fs','Delete'); CreateModuleText(conn,'cm_delete_fs','Delete'); CreateModuleText(conn,'tb_apply_config','Apply Configuration'); CreateModuleText(conn,'tb_enable_fs','Enable'); CreateModuleText(conn,'tb_disable_fs','Disable'); CreateModuleText(conn,'cm_apply_config','Apply Configuration'); CreateModuleText(conn,'cm_enable_fs','Enable'); CreateModuleText(conn,'cm_disable_fs','Disable'); CreateModuleText(conn,'service_grid_objname','Name'); CreateModuleText(conn,'service_grid_status','Status'); CreateModuleText(conn,'service_grid_zone','Zone'); CreateModuleText(conn,'vfs_details_select_one','Please select a virtual fileserver service to get detailed information'); CreateModuleText(conn,'vfs_share_details_select_one','Please select a share to get detailed information'); CreateModuleText(conn,'storage_virtual_filer_share_user','User'); CreateModuleText(conn,'storage_virtual_filer_share_delegation_groups','Delegation Groups'); CreateModuleText(conn,'vfs_share_modify_error_exists_cap','Error: Modfiy Share'); CreateModuleText(conn,'vfs_share_modify_error_exists_msg','The Share already exists!'); CreateModuleText(conn,'fs_share_group_description','Share %share_str% (FS %fs_str% - %zone_str%) Users'); CreateModuleText(conn,'fs_share_group_description_short','Share %share_str% (FS %fs_str% - %zone_str%) Users'); CreateModuleText(conn,'tb_add_user','Add'); CreateModuleText(conn,'tb_remove_user','Remove'); CreateModuleText(conn,'cm_add_user','Add'); CreateModuleText(conn,'cm_remove_user','Remove'); CreateModuleText(conn,'user_grid_uname','User'); CreateModuleText(conn,'tb_add_group','Add'); CreateModuleText(conn,'tb_remove_group','Remove'); CreateModuleText(conn,'cm_add_group','Add'); CreateModuleText(conn,'cm_remove_group','Remove'); CreateModuleText(conn,'delegation_group_grid_gname','Group'); end; end; class procedure TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.InstallUserDBObjects(const conn: IFRE_DB_CONNECTION; currentVersionId: TFRE_DB_NameType); var coll : IFRE_DB_COLLECTION; begin inherited InstallUserDBObjects(conn, currentVersionId); if currentVersionId='' then begin currentVersionId := '1.0'; coll:=conn.CreateCollection(CFRE_DB_FILESHARE_COLLECTION); coll.DefineIndexOnField('uct',fdbft_String,true,true,'def',false); end; end; procedure TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.CalculateReadWriteAccess(const conn: IFRE_DB_CONNECTION; const dependency_input: IFRE_DB_Object; const input_object: IFRE_DB_Object; const transformed_object: IFRE_DB_Object); var sel_guid,rr,wr : string; sel_guidg : TFRE_DB_GUID; group_id : TFRE_DB_GUID; true_icon : string; false_icon : string; begin abort; // rethink sel_guid := dependency_input.FieldPath('UIDS_REF.FILTERVALUES').AsString; //FIXXME - may not be set sel_guidg := FREDB_H2G(sel_guid); group_id := input_object.uid; //rr := FREDB_Get_Rightname_UID_STR('FSREAD',sel_guid); //wr := FREDB_Get_Rightname_UID_STR('FSWRITE',sel_guid); true_icon := FREDB_getThemedResource('images_apps/firmbox_storage/access_true.png'); false_icon := FREDB_getThemedResource('images_apps/firmbox_storage/access_false.png'); end; procedure TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.MySessionInitializeModule(const session: TFRE_DB_UserSession); var transform : IFRE_DB_SIMPLE_TRANSFORM; dc : IFRE_DB_DERIVED_COLLECTION; app : TFRE_DB_APPLICATION; conn : IFRE_DB_CONNECTION; shareDC : IFRE_DB_DERIVED_COLLECTION; begin inherited MySessionInitializeModule(session); if session.IsInteractiveSession then begin app := GetEmbeddingApp; conn := session.GetDBConnection; GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform); with transform do begin AddOneToOnescheme('objname','',FetchModuleTextShort(session,'service_grid_objname'),dt_string,true,false,false,true,3); AddMatchingReferencedFieldArray(['SERVICEPARENT>TFRE_DB_ZONE'],'objname','zone',FetchModuleTextShort(session,'service_grid_zone'),true,dt_string,false,false,3); AddOneToOnescheme('status_icons','',FetchModuleTextShort(session,'service_grid_status'),dt_icon,true,false,false,true,1,'','','',nil,'status_icon_tooltips'); AddMatchingReferencedField(['<SERVICEDOMAIN'],'objname','serviceObj','',true,dt_description,false,false,1,'','',nil,'',false,'domainid'); AddMatchingReferencedObjPlugin(['SERVICEPARENT>'],TFRE_DB_ZONESTATUS_PLUGIN,'zplugin'); SetSimpleFuncTransformNested(@G_setServiceStatusAndConfigFields,TFRE_DB_SERVICE_STATUS_PLUGIN.getStatusLangres(conn)); AddFulltextFilterOnTransformed(['objname']); end; dc := session.NewDerivedCollection('VIRTUAL_FILESERVER_MOD_FS_GRID'); with dc do begin SetDeriveParent(conn.GetCollection(CFOS_DB_SERVICES_COLLECTION)); Filters.AddSchemeObjectFilter('service',[TFRE_DB_VIRTUAL_FILESERVER.ClassName,TFRE_DB_GLOBAL_FILESERVER.ClassName]); SetDeriveTransformation(transform); SetDisplayType(cdt_Listview,[cdgf_ShowSearchbox],'',CWSF(@WEB_ServiceMenu),nil,CWSF(@WEB_VFSSC)); end; GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform); with transform do begin AddOneToOnescheme('objname','',FetchModuleTextShort(session,'vfs_share')); AddCollectorscheme('%s',TFRE_DB_NameTypeArray.Create('desc.txt') ,'description', '',true,false,false,dt_description); AddOneToOnescheme('used_mb','used',FetchModuleTextShort(session,'vfs_share_used')); AddOneToOnescheme('refer_mb','refer',FetchModuleTextShort(session,'vfs_share_refer')); AddOneToOnescheme('quota_mb','quota',FetchModuleTextShort(session,'vfs_share_quota')); AddMatchingReferencedFieldArray(['FILESERVER>TFRE_DB_VIRTUAL_FILESERVER'],'uid','vfs_uid','',false); AddFulltextFilterOnTransformed(['objname']); end; shareDC := session.NewDerivedCollection('VIRTUAL_FILESERVER_MOD_SHARE_GRID'); with shareDC do begin SetDeriveParent(conn.GetCollection(CFRE_DB_FILESHARE_COLLECTION)); Filters.AddSchemeObjectFilter('service',['TFRE_DB_VIRTUAL_FILESHARE']); SetUseDependencyAsUidFilter('vfs_uid',false,'uid'); SetDeriveTransformation(transform); SetDisplayType(cdt_Listview,[cdgf_ShowSearchbox],'',CWSF(@WEB_VFSShareMenu),nil,CWSF(@WEB_VFSShareSC)); end; GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform); with transform do begin AddOneToOnescheme('displayname','',FetchModuleTextShort(session,'user_grid_uname'),dt_string,true,false,false,true,1,'icon'); AddConstString('icon',FREDB_getThemedResource('images_apps/share/user_ico.svg')); AddOneToOnescheme('internal','','',dt_boolean,False); AddMatchingReferencedFieldArray(['USERGROUPIDS>TFRE_DB_GROUP','TFRE_DB_VIRTUAL_FILESHARE<GROUP'],'uid','share_id','',false); SetSimpleFuncTransformNested(@G_setDisplaynameUser,[]); AddFulltextFilterOnTransformed(['displayname']); end; dc := session.NewDerivedCollection('SHARE_USERIN_GRID'); with dc do begin SetDeriveParent(conn.AdmGetUserCollection); SetDisplayType(cdt_Listview,[],'',CWSF(@WEB_GridUIMenu),nil,CWSF(@WEB_GridUISC),nil,CWSF(@WEB_AddUser)); Filters.AddBooleanFieldFilter('internal','internal',false); SetDeriveTransformation(transform); SetUseDependencyAsUidFilter('share_id'); shareDC.AddSelectionDependencyEvent(CollectionName); SetDefaultOrderField('displayname',true); end; GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform); with transform do begin AddOneToOnescheme('displayname','',FetchModuleTextShort(session,'user_grid_uname'),dt_string,true,false,false,true,1,'icon'); AddConstString('icon',FREDB_getThemedResource('images_apps/share/user_ico.svg')); AddOneToOnescheme('internal','','',dt_boolean,False); AddMatchingReferencedFieldArray(['USERGROUPIDS>TFRE_DB_GROUP','TFRE_DB_VIRTUAL_FILESHARE<GROUP'],'uid','share_id','',false); AddOneToOnescheme('domainidlink','','',dt_string,False); SetSimpleFuncTransformNested(@G_setDisplaynameUser,[]); AddFulltextFilterOnTransformed(['displayname']); end; dc := session.NewDerivedCollection('SHARE_USEROUT_GRID'); with dc do begin SetDeriveParent(conn.AdmGetUserCollection); SetDisplayType(cdt_Listview,[],'',CWSF(@WEB_GridUOMenu),nil,CWSF(@WEB_GridUOSC),nil,CWSF(@WEB_RemoveUser)); Filters.AddBooleanFieldFilter('internal','internal',false); SetDeriveTransformation(transform); SetUseDependencyAsUidFilter('share_id',true); shareDC.AddSelectionDependencyEvent(CollectionName); SetDefaultOrderField('displayname',true); end; GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform); with transform do begin AddOneToOnescheme('displayname','',FetchModuleTextShort(session,'delegation_group_grid_gname'),dt_string,true,false,false,true,1,'icon'); AddConstString('icon',FREDB_getThemedResource('images_apps/share/dlg_group_ico.svg')); AddOneToOnescheme('internal','','',dt_boolean,False); AddMatchingReferencedFieldArray(['TFRE_DB_GROUP<GROUPIDS','TFRE_DB_VIRTUAL_FILESHARE<GROUP'],'uid','share_id','',false); SetSimpleFuncTransformNested(@G_setDisplaynameGRD,[]); AddFulltextFilterOnTransformed(['displayname']); end; dc := session.NewDerivedCollection('SHARE_GROUPIN_GRID'); with dc do begin SetDeriveParent(conn.AdmGetGroupCollection); SetDisplayType(cdt_Listview,[],'',CWSF(@WEB_GridGIMenu),nil,CWSF(@WEB_GridGISC),nil,CWSF(@WEB_AddGroup)); Filters.AddBooleanFieldFilter('internal','internal',false); SetDeriveTransformation(transform); SetUseDependencyAsUidFilter('share_id'); shareDC.AddSelectionDependencyEvent(CollectionName); SetDefaultOrderField('displayname',true); end; GFRE_DBI.NewObjectIntf(IFRE_DB_SIMPLE_TRANSFORM,transform); with transform do begin AddOneToOnescheme('displayname','',FetchModuleTextShort(session,'delegation_group_grid_gname'),dt_string,true,false,false,true,1,'icon'); AddConstString('icon',FREDB_getThemedResource('images_apps/share/dlg_group_ico.svg')); AddOneToOnescheme('internal','','',dt_boolean,False); AddOneToOnescheme('delegation','','',dt_boolean,False); AddOneToOnescheme('protected','','',dt_boolean,False); AddMatchingReferencedFieldArray(['TFRE_DB_GROUP<GROUPIDS','TFRE_DB_VIRTUAL_FILESHARE<GROUP'],'uid','share_id','',false); AddOneToOnescheme('domainidlink','','',dt_string,False); SetSimpleFuncTransformNested(@G_setDisplaynameGRD,[]); AddFulltextFilterOnTransformed(['displayname']); end; dc := session.NewDerivedCollection('SHARE_GROUPOUT_GRID'); with dc do begin SetDeriveParent(conn.AdmGetGroupCollection); SetDisplayType(cdt_Listview,[],'',CWSF(@WEB_GridGOMenu),nil,CWSF(@WEB_GridGOSC),nil,CWSF(@WEB_RemoveGroup)); Filters.AddBooleanFieldFilter('internal','internal',false); Filters.AddBooleanFieldFilter('protected','protected',false); SetDeriveTransformation(transform); SetUseDependencyAsUidFilter('share_id',true); shareDC.AddSelectionDependencyEvent(CollectionName); SetDefaultOrderField('displayname',true); Filters.AddBooleanFieldFilter('delegation','delegation',true); end; end; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_Content(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var sub_sec_fs : TFRE_DB_SUBSECTIONS_DESC; grid_fs : TFRE_DB_VIEW_LIST_DESC; dc_fs : IFRE_DB_DERIVED_COLLECTION; dc_share : IFRE_DB_DERIVED_COLLECTION; begin CheckClassVisibility4AnyDomain(ses); ses.GetSessionModuleData(ClassName).DeleteField('selectedVFS'); sub_sec_fs := TFRE_DB_SUBSECTIONS_DESC.Create.Describe(sec_dt_tab); dc_fs := ses.FetchDerivedCollection('VIRTUAL_FILESERVER_MOD_FS_GRID'); grid_fs := dc_fs.GetDisplayDescription as TFRE_DB_VIEW_LIST_DESC; if fServiceIFMod.canAddService(conn,false) then begin grid_fs.AddButton.Describe(CWSF(@WEB_AddVFS),'',FetchModuleTextShort(ses,'tb_create_vfs')); end; if fServiceIFMod.canDeleteService(conn) then begin grid_fs.AddButton.DescribeManualType('delete_fs',CWSF(@WEB_DeleteFS),'',FetchModuleTextShort(ses,'tb_delete_fs'),'',true); end; dc_share := ses.FetchDerivedCollection('VIRTUAL_FILESERVER_MOD_SHARE_GRID'); grid_fs.AddFilterEvent(dc_share.getDescriptionStoreId(),'uid'); sub_sec_fs.AddSection.Describe(CWSF(@WEB_ContentGeneral),FetchModuleTextShort(ses,'storage_virtual_filer_general'),1); sub_sec_fs.AddSection.Describe(CWSF(@WEB_ContentVFShares),FetchModuleTextShort(ses,'storage_virtual_filer_shares'),2); sub_sec_fs.AddSection.Describe(CWSF(@WEB_ContentSnapshots),FetchModuleTextShort(ses,'storage_virtual_filer_snapshots'),3); Result:=TFRE_DB_LAYOUT_DESC.create.Describe.SetLayout(grid_fs,sub_sec_fs,nil,nil,nil,true,1,3); end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_ContentGeneral(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var service : TFRE_DB_FILESERVER; menu : TFRE_DB_MENU_DESC; addMenu : Boolean; res : TFRE_DB_FORM_PANEL_DESC; ds : TFRE_DB_ZFS_DATASET; begin CheckClassVisibility4AnyDomain(ses); if ses.GetSessionModuleData(ClassName).FieldExists('selectedVFS') and (ses.GetSessionModuleData(ClassName).Field('selectedVFS').ValueCount=1) then begin CheckDbResult(conn.FetchAs(ses.GetSessionModuleData(ClassName).Field('selectedVFS').AsGUID,TFRE_DB_FILESERVER,service)); ds:=service.getDataset(conn); fServiceIFMod.modifyService(input,ses,app,conn,service,'FS_GENERAL').AsClass(TFRE_DB_FORM_PANEL_DESC,res); fInfrastructureIFMod.addSnapshotJobsToForm(ds,res,ses,conn); menu:=TFRE_DB_MENU_DESC.create.Describe; addMenu:=false; if fServiceIFMod.canApplyService(conn) then begin //right in any domain => add button addMenu:=true; menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_apply_config'),'',CWSF(@WEB_ApplyConfig),not fServiceIFMod.canApplyService(conn,service),'apply_config'); end; if fServiceIFMod.canEnableService(conn) then begin //right in any domain => add button addMenu:=true; menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_enable_fs'),'',CWSF(@WEB_EnableFS),not fServiceIFMod.canEnableService(conn,service),'enable_service'); end; if fServiceIFMod.canDisableService(conn) then begin //right in any domain => add button addMenu:=true; menu.AddEntry.Describe(FetchModuleTextShort(ses,'tb_disable_fs'),'',CWSF(@WEB_DisableFS),not fServiceIFMod.canDisableService(conn,service),'disable_service'); end; addMenu:=addMenu and fInfrastructureIFMod.addSnapshotMenu(ds,menu,ses,conn); if addMenu then begin res.SetMenu(menu); end; Result:=res; end else begin Result:=TFRE_DB_HTML_DESC.create.Describe(FetchModuleTextShort(ses,'vfs_details_select_one')); (Result.Implementor_HC as TFRE_DB_CONTENT_DESC).contentId:='FS_GENERAL'; end; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_ContentVFShares(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var sub_sec_share : TFRE_DB_SUBSECTIONS_DESC; dc_share : IFRE_DB_DERIVED_COLLECTION; grid_share : TFRE_DB_VIEW_LIST_DESC; service : IFRE_DB_Object; add_disabled : Boolean; applyDisabled : Boolean; begin CheckClassVisibility4AnyDomain(ses); ses.GetSessionModuleData(ClassName).DeleteField('selectedShare'); add_disabled:=true; if ses.GetSessionModuleData(ClassName).FieldExists('selectedVFS') then begin CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedVFS').AsGUID,service)); if conn.sys.CheckClassRight4DomainId(sr_STORE,TFRE_DB_VIRTUAL_FILESHARE,service.DomainID) then begin add_disabled:=false; end; end else begin service:=nil; end; dc_share := ses.FetchDerivedCollection('VIRTUAL_FILESERVER_MOD_SHARE_GRID'); grid_share := dc_share.GetDisplayDescription as TFRE_DB_VIEW_LIST_DESC; if fServiceIFMod.canApplyService(conn) then begin if Assigned(service) then begin applyDisabled:=not fServiceIFMod.canApplyService(conn,service); end else begin applyDisabled:=true; end; grid_share.AddButton.DescribeManualType('apply_config',CWSF(@WEB_ApplyConfig),'',FetchModuleTextShort(ses,'tb_apply_config'),FetchModuleTextHint(ses,'tb_apply_config'),applyDisabled); end; if conn.sys.CheckClassRight4AnyDomain(sr_STORE,TFRE_DB_VIRTUAL_FILESHARE) then begin grid_share.AddButton.DescribeManualType('add_share',CWSF(@WEB_AddVFSShare),'',FetchModuleTextShort(ses,'tb_create_vfs_share'),FetchModuleTextHint(ses,'tb_create_vfs_share'),add_disabled); end; if conn.sys.CheckClassRight4AnyDomain(sr_DELETE,TFRE_DB_VIRTUAL_FILESHARE) then begin grid_share.AddButton.DescribeManualType('delete_share',CWSF(@WEB_VFSShareDelete),'',FetchModuleTextShort(ses,'tb_delete_vfs_share'),FetchModuleTextHint(ses,'tb_delete_vfs_share'),true); end; sub_sec_share := TFRE_DB_SUBSECTIONS_DESC.Create.Describe(sec_dt_tab); sub_sec_share.AddSection.Describe(CWSF(@WEB_VFSShareContent),FetchModuleTextShort(ses,'storage_virtual_filer_share_properties'),1,'shareproperties'); sub_sec_share.AddSection.Describe(CWSF(@WEB_VFSShareUser),FetchModuleTextShort(ses,'storage_virtual_filer_share_user'),2,'shareuser'); sub_sec_share.AddSection.Describe(CWSF(@WEB_VFSShareDelegationGroups),FetchModuleTextShort(ses,'storage_virtual_filer_share_delegation_groups'),3,'sharegroups'); sub_sec_share.AddSection.Describe(CWSF(@WEB_VFSShareSnapshots),FetchModuleTextShort(ses,'storage_virtual_filer_share_snapshots'),4,'sharesnapshots'); sub_sec_share.AddSection.Describe(CWSF(@fInfrastructureIFMod.WEB_DataSetBrowser),FetchModuleTextShort(ses,'storage_virtual_filer_share_browser'),5,'sharebrowser'); Result:=TFRE_DB_LAYOUT_DESC.create.Describe.SetLayout(grid_share,sub_sec_share,nil,nil,nil,true,2,3); end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_ContentSnapshots(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var service : TFRE_DB_FILESERVER; dsName : TFRE_DB_String; begin if ses.GetSessionModuleData(ClassName).FieldExists('selectedVFS') and (ses.GetSessionModuleData(ClassName).Field('selectedVFS').ValueCount=1) then begin CheckDbResult(conn.FetchAs(ses.GetSessionModuleData(ClassName).Field('selectedVFS').AsGUID,TFRE_DB_FILESERVER,service)); dsName:=service.getDataset(conn).Name; end else begin dsName:=''; end; Result:=fInfrastructureIFMod.getHierarchicalSnapshotsGrid(dsName,input,ses,app,conn); (Result.Implementor_HC as TFRE_DB_CONTENT_DESC).contentId:='FS_SNAPSHOTS'; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_AddVFS(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; begin Result:=fServiceIFMod.addService(input,ses,app,conn,false); end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_DeleteFS(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var service : IFRE_DB_Object; serviceId : TFRE_DB_GUID; begin if input.FieldExists('selected') then begin serviceId:=FREDB_H2G(input.Field('selected').AsString); end else begin serviceId:=ses.GetSessionModuleData(ClassName).Field('selectedVFS').AsGUID; end; CheckDbResult(conn.Fetch(serviceId,service)); Result:=fServiceIFMod.deleteService(input,ses,app,conn,service); end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_ApplyConfig(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var service : IFRE_DB_Object; serviceId : TFRE_DB_GUID; begin if input.FieldExists('selected') then begin serviceId:=FREDB_H2G(input.Field('selected').AsString); end else begin serviceId:=ses.GetSessionModuleData(ClassName).Field('selectedVFS').AsGUID; end; CheckDbResult(conn.Fetch(serviceId,service)); Result:=fServiceIFMod.applyConfig(input,ses,app,conn,service); end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_EnableFS(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var service : IFRE_DB_Object; serviceId : TFRE_DB_GUID; begin if input.FieldExists('selected') then begin serviceId:=FREDB_H2G(input.Field('selected').AsString); end else begin serviceId:=ses.GetSessionModuleData(ClassName).Field('selectedVFS').AsGUID; end; CheckDbResult(conn.Fetch(serviceId,service)); Result:=fServiceIFMod.enableService(input,ses,app,conn,service); end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_DisableFS(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var service : IFRE_DB_Object; serviceId : TFRE_DB_GUID; begin if input.FieldExists('selected') then begin serviceId:=FREDB_H2G(input.Field('selected').AsString); end else begin serviceId:=ses.GetSessionModuleData(ClassName).Field('selectedVFS').AsGUID; end; CheckDbResult(conn.Fetch(serviceId,service)); Result:=fServiceIFMod.disableService(input,ses,app,conn,service); end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_VFSSC(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var add_disabled : Boolean; service : TFRE_DB_FILESERVER; zone : TFRE_DB_ZONE; deleteDisabled : Boolean; applyDisabled : Boolean; ds : TFRE_DB_ZFS_DATASET; dsName : TFRE_DB_String; begin add_disabled:=true; deleteDisabled:=true; applyDisabled:=true; if ses.GetSessionModuleData(ClassName).FieldExists('selectedVFS') then begin ses.UnregisterDBOChangeCB('vfsMod'); end; if input.FieldExists('selected') and (input.Field('selected').ValueCount=1) then begin CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('selected').AsString),TFRE_DB_FILESERVER,service)); ses.GetSessionModuleData(ClassName).Field('selectedVFS').AsGUID:=service.UID; ses.RegisterDBOChangeCB(service.UID,CWSF(@WEB_ServiceObjChanged),'vfsMod'); ds:=service.getDataset(conn); dsName:=ds.Name; ses.RegisterDBOChangeCB(ds.UID,CWSF(@WEB_DSObjChanged),'vfsMod'); CheckDbResult(conn.FetchAs(service.Field('serviceParent').AsObjectLink,TFRE_DB_ZONE,zone)); ses.RegisterDBOChangeCB(zone.UID,CWSF(@WEB_ServiceObjChanged),'vfsMod'); if conn.sys.CheckClassRight4DomainId(sr_STORE,TFRE_DB_VIRTUAL_FILESHARE,service.DomainID) then begin add_disabled:=false; end; deleteDisabled:=not fServiceIFMod.canDeleteService(conn,service); applyDisabled:=not fServiceIFMod.canApplyService(conn,service); end else begin ses.GetSessionModuleData(ClassName).DeleteField('selectedVFS'); dsName:=''; end; if ses.isUpdatableContentVisible('VIRTUAL_SHARE_SNAPSHOTS') then begin fInfrastructureIFMod.updateSnapshotsGridFilter('',ses); end; if ses.isUpdatableContentVisible('FS_SNAPSHOTS') then begin fInfrastructureIFMod.updateHierarchicalSnapshotsGridFilter(dsName,ses); end; ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('delete_fs',deleteDisabled)); ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('add_share',add_disabled)); ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.Create.DescribeStatus('apply_config',applyDisabled)); if ses.isUpdatableContentVisible('FS_GENERAL') then begin Result:=WEB_ContentGeneral(input,ses,app,conn); end else begin Result:=GFRE_DB_NIL_DESC; end; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_ServiceMenu(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var service: IFRE_DB_Object; res : TFRE_DB_MENU_DESC; func : TFRE_DB_SERVER_FUNC_DESC; begin res:=TFRE_DB_MENU_DESC.create.Describe; if input.Field('selected').ValueCount=1 then begin CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),service)); if fServiceIFMod.canApplyService(conn) then begin func:=CWSF(@WEB_ApplyConfig); func.AddParam.Describe('selected',input.Field('selected').AsString); res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_apply_config'),'',func,not fServiceIFMod.canApplyService(conn,service)); end; if fServiceIFMod.canEnableService(conn) then begin func:=CWSF(@WEB_EnableFS); func.AddParam.Describe('selected',input.Field('selected').AsString); res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_enable_fs'),'',func,not fServiceIFMod.canEnableService(conn,service)); end; if fServiceIFMod.canDisableService(conn) then begin func:=CWSF(@WEB_DisableFS); func.AddParam.Describe('selected',input.Field('selected').AsString); res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_disable_fs'),'',func,not fServiceIFMod.canDisableService(conn,service)); end; if fServiceIFMod.canDeleteService(conn) then begin func:=CWSF(@WEB_DeleteFS); func.AddParam.Describe('selected',input.Field('selected').AsString); res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_delete_fs'),'',func,not fServiceIFMod.canDeleteService(conn,service)); end; end; Result:=res; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_ServiceObjChanged(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var service : IFRE_DB_Object; begin Result:=GFRE_DB_NIL_DESC; if input.Field('type').AsString='UPD' then begin if ses.GetSessionModuleData(ClassName).FieldExists('selectedVFS') then begin if not ses.isUpdatableContentVisible('FS_GENERAL') then begin CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedVFS').AsGUID,service)); ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('apply_config',not fServiceIFMod.canApplyService(conn,service))); end; end; if ses.isUpdatableContentVisible('FS_GENERAL') then begin Result:=WEB_ContentGeneral(input,ses,app,conn); end; end; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_DSObjChanged(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; begin Result:=GFRE_DB_NIL_DESC; if input.Field('type').AsString<>'DEL' then begin if ses.isUpdatableContentVisible('FS_GENERAL') then begin Result:=WEB_ContentGeneral(input,ses,app,conn); end; end; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_VFSDelete(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var sf : TFRE_DB_SERVER_FUNC_DESC; fileserver: IFRE_DB_Object; begin if input.Field('selected').ValueCount<>1 then raise EFRE_DB_Exception.Create(FetchModuleTextShort(ses,'error_delete_single_select')); CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsStringArr[0]),fileserver)); if not conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_VIRTUAL_FILESERVER,fileserver.DomainID) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); sf:=CWSF(@WEB_VFSDeleteConfirmed); sf.AddParam.Describe('selected',input.Field('selected').AsStringArr); Result:=TFRE_DB_MESSAGE_DESC.create.Describe(FetchModuleTextShort(ses,'vfs_delete_diag_cap'),StringReplace(FetchModuleTextShort(ses,'vfs_delete_diag_msg'),'%vfs_str%',fileserver.Field('objname').AsString,[rfReplaceAll]),fdbmt_confirm,sf); end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_VFSDeleteConfirmed(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var i : NativeInt; fileserver: IFRE_DB_Object; begin if input.field('confirmed').AsBoolean then begin for i:= 0 to input.Field('selected').ValueCount-1 do begin CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsStringArr[i]),fileserver)); if not conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_VIRTUAL_FILESERVER,fileserver.DomainID) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); CheckDbResult(conn.Delete(fileserver.UID)); end; result := GFRE_DB_NIL_DESC; end else begin Result:=GFRE_DB_NIL_DESC; end; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_AddVFSShare(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var scheme : IFRE_DB_SchemeObject; res : TFRE_DB_FORM_DIALOG_DESC; sf : TFRE_DB_SERVER_FUNC_DESC; fileserver : IFRE_DB_Object; dependend : TFRE_DB_StringArray; begin dependend := GetDependencyFiltervalues(input,'uid_ref'); if length(dependend)=0 then begin Result:=TFRE_DB_MESSAGE_DESC.create.Describe(FetchModuleTextShort(ses,'vfs_share_add_diag_cap'),FetchModuleTextShort(ses,'vfs_share_add_no_fs_msg'),fdbmt_warning,nil); exit; end; CheckDbResult(conn.Fetch(FREDB_H2G(dependend[0]),fileserver)); if not (conn.sys.CheckClassRight4DomainId(sr_STORE,TFRE_DB_VIRTUAL_FILESHARE,fileserver.DomainID) and conn.sys.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESERVER,fileserver.DomainID)) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); GFRE_DBI.GetSystemScheme(TFRE_DB_VIRTUAL_FILESHARE,scheme); res:=TFRE_DB_FORM_DIALOG_DESC.create.Describe(FetchModuleTextShort(ses,'vfs_share_add_diag_cap'),600); res.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses); sf:=CWSF(@WEB_StoreVFSShare); sf.AddParam.Describe('serviceId',fileserver.UID_String); res.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit); Result:=res; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_StoreVFSShare(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var schemeObject : IFRE_DB_SchemeObject; shareObj : TFRE_DB_VIRTUAL_FILESHARE; isNew : Boolean; shareColl : IFRE_DB_COLLECTION; service : TFRE_DB_FILESERVER; zone : TFRE_DB_ZONE; group : IFRE_DB_GROUP; procedure SetupQuotaAndUpdate(const shareObj : TFRE_DB_VIRTUAL_FILESHARE); var inp,opd : IFRE_DB_Object; service : TFRE_DB_FILESERVER; begin conn.FetchAs(shareObj.Field('fileserver').AsObjectLink,TFRE_DB_FILESERVER,service); inp := GFRE_DBI.NewObject; inp.Field('SHARE').AsObject := shareObj.CloneToNewObject(); if ses.InvokeRemoteRequestMachine(service.getMachineId,'TFRE_BOX_FEED_CLIENT','UPDATEDSQUOTA',inp,@CCB_SetupQuotaAndUpdate,shareObj)=edb_OK then { send the share object as opaque data } begin Result := GFRE_DB_SUPPRESS_SYNC_ANSWER; exit; end else begin Result := TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','COULD NOT SET QUOTA',fdbmt_error); { FIXXME } inp.Finalize; end end; begin if not GFRE_DBI.GetSystemScheme(TFRE_DB_VIRTUAL_FILESHARE,schemeObject) then raise EFRE_DB_Exception.Create(edb_ERROR,'the scheme [%s] is unknown!',[TFRE_DB_VIRTUAL_FILESHARE]); shareColl:=conn.GetCollection(CFRE_DB_FILESHARE_COLLECTION); if input.FieldExists('shareId') then begin CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('shareId').AsString),TFRE_DB_VIRTUAL_FILESHARE,shareObj)); if not (conn.sys.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,shareObj.DomainID) and conn.sys.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESERVER,shareObj.DomainID)) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); CheckDbResult(conn.FetchAs(shareObj.Field('fileserver').AsObjectLink,TFRE_DB_FILESERVER,service)); if input.FieldPathExists('data.objname') and (input.FieldPath('data.objname').AsString<>shareObj.ObjectName) then begin shareObj.ObjectName:=input.FieldPath('data.objname').AsString; shareObj.Name:=service.getDataset(conn).Name + '/' + shareObj.ObjectName; shareObj.Setup_UCT_ZDS(service.getMachineId); if shareColl.ExistsIndexedText(shareObj.Field('UCT').AsString)>0 then begin Result:=TFRE_DB_MESSAGE_DESC.Create.Describe(FetchModuleTextShort(ses,'vfs_share_modify_error_exists_cap'),FetchModuleTextShort(ses,'vfs_share_modfiy_error_exists_msg'),fdbmt_error); exit; end; //modify group CheckDbResult(conn.sys.ModifyGroupById(shareObj.Field('group').AsObjectLink,shareObj.field('UCT').AsString,StringReplace(StringReplace(StringReplace(FetchModuleTextShort(ses,'fs_share_group_description'),'%share_str%',shareObj.ObjectName,[rfReplaceAll]),'%fs_str%',service.Field('objname').AsString,[rfReplaceAll]),'%zone_str%',zone.ObjectName,[rfReplaceAll]), StringReplace(StringReplace(StringReplace(FetchModuleTextShort(ses,'fs_share_group_description_short'),'%share_str%',shareObj.ObjectName,[rfReplaceAll]),'%fs_str%',service.Field('objname').AsString,[rfReplaceAll]),'%zone_str%',zone.ObjectName,[rfReplaceAll]))); end; isNew:=false; end else begin CheckDbResult(conn.FetchAS(FREDB_H2G(input.Field('serviceId').AsString),TFRE_DB_FILESERVER,service)); CheckDbResult(conn.FetchAs(service.Field('serviceParent').AsObjectLink,TFRE_DB_ZONE,zone)); if not (conn.sys.CheckClassRight4DomainId(sr_STORE,TFRE_DB_VIRTUAL_FILESHARE,service.DomainID) and conn.sys.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESERVER,service.DomainID)) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); shareObj:=TFRE_DB_VIRTUAL_FILESHARE.CreateForDB; shareObj.ObjectName:=input.FieldPath('data.objname').AsString; shareObj.Name:=service.getDataset(conn).Name + '/' + shareObj.ObjectName; shareObj.Setup_UCT_ZDS(service.getMachineId); if shareColl.ExistsIndexed(shareObj.Field('UCT').AsString) then begin Result:=TFRE_DB_MESSAGE_DESC.Create.Describe(FetchModuleTextShort(ses,'vfs_share_create_error_exists_cap'),FetchModuleTextShort(ses,'vfs_share_create_error_exists_msg'),fdbmt_error); exit; end; shareObj.SetDomainID(service.DomainID); shareObj.ObjectName:=input.FieldPath('data.objname').AsString; //shareObj.Setup_UCT_ZDS(..);:=idx; { FIXXME : UCT : 'ZDS_'+zfs_ds_name } //create group CheckDbResult(conn.SYS.AddGroup(shareObj.field('UCT').AsString,StringReplace(StringReplace(StringReplace(FetchModuleTextShort(ses,'fs_share_group_description'),'%share_str%',shareObj.ObjectName,[rfReplaceAll]),'%fs_str%',service.Field('objname').AsString,[rfReplaceAll]),'%zone_str%',zone.ObjectName,[rfReplaceAll]), StringReplace(StringReplace(StringReplace(FetchModuleTextShort(ses,'fs_share_group_description_short'),'%share_str%',shareObj.ObjectName,[rfReplaceAll]),'%fs_str%',service.Field('objname').AsString,[rfReplaceAll]),'%zone_str%',zone.ObjectName,[rfReplaceAll]),zone.DomainID,true)); CheckDbResult(conn.SYS.FetchGroup(shareObj.field('UCT').AsString,zone.DomainID,group)); shareObj.Field('group').AsObjectLink:=group.UID; isNew:=true; end; schemeObject.SetObjectFieldsWithScheme(input.Field('data').AsObject,shareObj,isNew,conn); _setConfigChanged(conn,ses,service); if isNew then begin shareObj.Field('fileserver').AsObjectLink:=service.UID; CheckDbResult(shareColl.Store(shareObj)); { TODO: Create the Dataset/Share ... / Enter Quota Code here} Result:=TFRE_DB_CLOSE_DIALOG_DESC.Create.Describe(); end else begin CheckDbResult(conn.Update(shareObj.CloneToNewObject())); SetupQuotaAndUpdate(shareObj); { if the update went ok, then setup quota } end; end; procedure TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.CCB_SetupQuotaAndUpdate(const ses: IFRE_DB_UserSession; const new_input: IFRE_DB_Object; const status: TFRE_DB_COMMAND_STATUS; const ocid: Qword; const opaquedata: IFRE_DB_Object); var res : TFRE_DB_MESSAGE_DESC; i : NativeInt; cnt : NativeInt; newnew : IFRE_DB_Object; begin case status of cdcs_OK: begin res:=TFRE_DB_MESSAGE_DESC.create.Describe('QUOTA','SETUP OK',fdbmt_info); end; cdcs_TIMEOUT: begin Res := TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','COMMUNICATION TIMEOUT SET QUOTA',fdbmt_error); { FIXXME } end; cdcs_ERROR: begin Res := TFRE_DB_MESSAGE_DESC.create.Describe('ERROR','COULD NOT SET QUOTA ['+new_input.Field('ERROR').AsString+']',fdbmt_error); { FIXXME } end; end; ses.SendServerClientAnswer(res,ocid); cnt := 0; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_VFSShareMenu(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var res : TFRE_DB_MENU_DESC; func : TFRE_DB_SERVER_FUNC_DESC; dbo : IFRE_DB_Object; begin res:=TFRE_DB_MENU_DESC.create.Describe; if input.Field('selected').ValueCount=1 then begin CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsString),dbo)); if conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_VIRTUAL_FILESHARE,dbo.DomainID) and conn.sys.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESERVER,dbo.DomainID) then begin func:=CWSF(@WEB_VFSShareDelete); func.AddParam.Describe('selected',input.Field('selected').AsStringArr); res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_delete_vfs_share'),'',func); end; end; Result:=res; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_VFSShareContent(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var html : TFRE_DB_HTML_DESC; panel : TFRE_DB_FORM_PANEL_DESC; scheme : IFRE_DB_SchemeObject; share : TFRE_DB_VIRTUAL_FILESHARE; sel_guid : TFRE_DB_GUID; sf : TFRE_DB_SERVER_FUNC_DESC; editable : Boolean; begin CheckClassVisibility4AnyDomain(ses); if ses.GetSessionModuleData(ClassName).FieldExists('selectedShare') and (ses.GetSessionModuleData(ClassName).Field('selectedShare').ValueCount=1) then begin sel_guid := ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID; CheckDbResult(conn.FetchAs(sel_guid,TFRE_DB_VIRTUAL_FILESHARE,share)); editable:=conn.sys.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.sys.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESERVER,share.DomainID); GFRE_DBI.GetSystemSchemeByName(share.SchemeClass,scheme); panel :=TFRE_DB_FORM_PANEL_DESC.Create.Describe('',true,editable); panel.AddSchemeFormGroup(scheme.GetInputGroup('main'),ses); panel.FillWithObjectValues(share,ses); if editable then begin sf:=CWSF(@WEB_StoreVFSShare); sf.AddParam.Describe('shareId',share.UID_String); panel.AddButton.Describe(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('button_save')),sf,fdbbt_submit); end; fInfrastructureIFMod.addSnapshotJobsToForm(share,panel,ses,conn); fInfrastructureIFMod.addSnapshotMenuToForm(share,panel,ses,conn); panel.contentId:='VIRTUAL_SHARE_CONTENT'; Result:=panel; end else begin Result:=TFRE_DB_HTML_DESC.create.Describe(FetchModuleTextShort(ses,'vfs_share_details_select_one')); (Result.Implementor_HC as TFRE_DB_CONTENT_DESC).contentId:='VIRTUAL_SHARE_CONTENT'; end; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_VFSShareSC(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var del_disabled: Boolean; dbo : TFRE_DB_VIRTUAL_FILESHARE; out_dc : IFRE_DB_DERIVED_COLLECTION; disableDrag : Boolean; begin del_disabled:=true; dbo:=nil; if ses.GetSessionModuleData(ClassName).FieldExists('selectedShare') then begin ses.UnregisterDBOChangeCB('fileserverModShare'); end; if input.FieldExists('selected') and (input.Field('selected').ValueCount>0) then begin if (input.Field('selected').ValueCount=1) then begin CheckDbResult(conn.FetchAs(FREDB_H2G(input.Field('selected').AsString),TFRE_DB_VIRTUAL_FILESHARE,dbo)); if conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_VIRTUAL_FILESHARE,dbo.DomainID) and conn.sys.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESERVER,dbo.DomainID) then begin del_disabled:=false; end; end; ses.GetSessionModuleData(ClassName).Field('selectedShare').AsStringArr:=input.Field('selected').AsStringArr; ses.RegisterDBOChangeCB(dbo.UID,CWSF(@WEB_VFSShareObjChanged),'fileserverModShare'); end else begin ses.GetSessionModuleData(ClassName).DeleteField('selectedShare'); end; if ses.IsUpdatableContentVisible('SHARE_USEROUT_GRID') or ses.IsUpdatableContentVisible('SHARE_USERIN_GRID') then begin ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('add_user',true)); ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('remove_user',true)); out_dc:=ses.FetchDerivedCollection('SHARE_USEROUT_GRID'); out_dc.Filters.RemoveFilter('domain'); if Assigned(dbo) then begin out_dc.Filters.AddUIDFieldFilter('domain','domainidlink',dbo.DomainID,dbnf_OneValueFromFilter); disableDrag:=not (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,dbo.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,dbo.DomainID)); ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeDrag('SHARE_USEROUT_GRID',disableDrag)); ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeDrag('SHARE_USERIN_GRID',disableDrag)); end else begin out_dc.Filters.AddUIDFieldFilter('domain','domainidlink',CFRE_DB_NullGUID,dbnf_OneValueFromFilter); end; end; if ses.IsUpdatableContentVisible('SHARE_GROUPOUT_GRID') or ses.IsUpdatableContentVisible('SHARE_GROUPIN_GRID') then begin ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('add_group',true)); ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('remove_remove',true)); out_dc:=ses.FetchDerivedCollection('SHARE_GROUPOUT_GRID'); out_dc.Filters.RemoveFilter('domain'); if Assigned(dbo) then begin out_dc.Filters.AddUIDFieldFilter('domain','domainidlink',dbo.DomainID,dbnf_OneValueFromFilter); disableDrag:=not (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,dbo.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,dbo.DomainID)); ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeDrag('SHARE_GROUPOUT_GRID',disableDrag)); ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeDrag('SHARE_GROUPIN_GRID',disableDrag)); end else begin out_dc.Filters.AddUIDFieldFilter('domain','domainidlink',CFRE_DB_NullGUID,dbnf_OneValueFromFilter); end; end; if ses.isUpdatableContentVisible('VIRTUAL_SHARE_SNAPSHOTS') then begin if Assigned(dbo) then begin fInfrastructureIFMod.updateSnapshotsGridFilter(dbo.Name,ses); end else begin fInfrastructureIFMod.updateSnapshotsGridFilter('',ses); end; end; if Assigned(dbo) then begin fInfrastructureIFMod.setDataSetBrowserRootObj(dbo,ses); end else begin fInfrastructureIFMod.setDataSetBrowserRootObj(nil,ses); end; ses.SendServerClientRequest(TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('delete_share',del_disabled)); if ses.isUpdatableContentVisible('VIRTUAL_SHARE_CONTENT') then begin Result:=WEB_VFSShareContent(input,ses,app,conn); end else begin Result:=GFRE_DB_NIL_DESC; end; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_VFSShareObjChanged(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; begin if ses.isUpdatableContentVisible('VIRTUAL_SHARE_CONTENT') then begin Result:=WEB_VFSShareContent(input,ses,app,conn); end else begin Result:=GFRE_DB_NIL_DESC; end; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_VFSShareDelete(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var sf : TFRE_DB_SERVER_FUNC_DESC; share : IFRE_DB_Object; begin if input.Field('selected').ValueCount<>1 then raise EFRE_DB_Exception.Create(FetchModuleTextShort(ses,'error_delete_single_select')); CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsStringArr[0]),share)); if not (conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.sys.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESERVER,share.DomainID)) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); sf:=CWSF(@WEB_VFSShareDeleteConfirmed); sf.AddParam.Describe('selected',input.Field('selected').AsStringArr); Result:=TFRE_DB_MESSAGE_DESC.create.Describe(FetchModuleTextShort(ses,'vfs_share_delete_diag_cap'),StringReplace(FetchModuleTextShort(ses,'vfs_share_delete_diag_msg'),'%share_str%',share.Field('objname').AsString,[rfReplaceAll]),fdbmt_confirm,sf); end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_VFSShareDeleteConfirmed(const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; var i : NativeInt; share : IFRE_DB_Object; service: IFRE_DB_Object; begin if input.field('confirmed').AsBoolean then begin for i:= 0 to input.Field('selected').ValueCount-1 do begin CheckDbResult(conn.Fetch(FREDB_H2G(input.Field('selected').AsStringArr[i]),share)); if not (conn.sys.CheckClassRight4DomainId(sr_DELETE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.sys.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESERVER,share.DomainID)) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); CheckDbResult(conn.Fetch(share.Field('fileserver').AsObjectLink,service)); _setConfigChanged(conn,ses,service); fServiceIFMod.deleteShare(conn,share.UID); end; result := GFRE_DB_NIL_DESC; end else begin Result:=GFRE_DB_NIL_DESC; end; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_VFSShareUser(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var res : TFRE_DB_LAYOUT_DESC; share : IFRE_DB_Object; uout_dc : IFRE_DB_DERIVED_COLLECTION; uin_dc : IFRE_DB_DERIVED_COLLECTION; uout_grid : TFRE_DB_VIEW_LIST_DESC; uin_grid : TFRE_DB_VIEW_LIST_DESC; begin res:=TFRE_DB_LAYOUT_DESC.create.Describe(); uout_dc:=ses.FetchDerivedCollection('SHARE_USEROUT_GRID'); uin_dc:=ses.FetchDerivedCollection('SHARE_USERIN_GRID'); uout_dc.Filters.RemoveFilter('domain'); if ses.GetSessionModuleData(ClassName).FieldExists('selectedShare') then begin CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID,share)); uout_dc.Filters.AddUIDFieldFilter('domain','domainidlink',share.DomainID,dbnf_OneValueFromFilter); end else begin uout_dc.Filters.AddUIDFieldFilter('domain','domainidlink',CFRE_DB_NullGUID,dbnf_OneValueFromFilter); end; uout_grid:=uout_dc.GetDisplayDescription as TFRE_DB_VIEW_LIST_DESC; uout_grid.contentId:='SHARE_USEROUT_GRID'; uin_grid:=uin_dc.GetDisplayDescription as TFRE_DB_VIEW_LIST_DESC; uin_grid.contentId:='SHARE_USERIN_GRID'; if conn.SYS.CheckClassRight4AnyDomain(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE) and conn.SYS.CheckClassRight4AnyDomain('assignGroup',TFRE_DB_GROUP) then begin uout_grid.AddButton.DescribeManualType('add_user',CWSF(@WEB_AddUser),'',FetchModuleTextShort(ses,'tb_add_user'),'',true); uin_grid.AddButton.DescribeManualType('remove_user',CWSF(@WEB_RemoveUser),'',FetchModuleTextShort(ses,'tb_remove_user'),'',true); uout_grid.SetDropGrid(uin_grid); uin_grid.SetDropGrid(uout_grid); if ses.GetSessionModuleData(ClassName).FieldExists('selectedShare') and not (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,share.DomainID)) then begin uout_grid.disableDrag; uin_grid.disableDrag; end; end; res.SetLayout(nil,uout_grid,nil,uin_grid,nil,true,-1,1,-1,1); Result:=res; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_VFSShareDelegationGroups(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var res : TFRE_DB_LAYOUT_DESC; share : IFRE_DB_Object; gout_dc : IFRE_DB_DERIVED_COLLECTION; gin_dc : IFRE_DB_DERIVED_COLLECTION; gout_grid : TFRE_DB_VIEW_LIST_DESC; gin_grid : TFRE_DB_VIEW_LIST_DESC; begin res:=TFRE_DB_LAYOUT_DESC.create.Describe(); gout_dc:=ses.FetchDerivedCollection('SHARE_GROUPOUT_GRID'); gin_dc:=ses.FetchDerivedCollection('SHARE_GROUPIN_GRID'); gout_dc.Filters.RemoveFilter('domain'); if ses.GetSessionModuleData(ClassName).FieldExists('selectedShare') then begin CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID,share)); gout_dc.Filters.AddUIDFieldFilter('domain','domainidlink',share.DomainID,dbnf_OneValueFromFilter); end else begin gout_dc.Filters.AddUIDFieldFilter('domain','domainidlink',CFRE_DB_NullGUID,dbnf_OneValueFromFilter); end; gout_grid:=gout_dc.GetDisplayDescription as TFRE_DB_VIEW_LIST_DESC; gout_grid.contentId:='SHARE_GROUPOUT_GRID'; gin_grid:=gin_dc.GetDisplayDescription as TFRE_DB_VIEW_LIST_DESC; gin_grid.contentId:='SHARE_GROUPIN_GRID'; if conn.SYS.CheckClassRight4AnyDomain(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE) and conn.SYS.CheckClassRight4AnyDomain('assignGroup',TFRE_DB_GROUP) then begin gout_grid.AddButton.DescribeManualType('add_group',CWSF(@WEB_AddGroup),'',FetchModuleTextShort(ses,'tb_add_group'),'',true); gin_grid.AddButton.DescribeManualType('remove_group',CWSF(@WEB_RemoveGroup),'',FetchModuleTextShort(ses,'tb_remove_group'),'',true); gout_grid.SetDropGrid(gin_grid); gin_grid.SetDropGrid(gout_grid); if ses.GetSessionModuleData(ClassName).FieldExists('selectedShare') and not (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,share.DomainID)) then begin gout_grid.disableDrag; gin_grid.disableDrag; end; end; res.SetLayout(nil,gout_grid,nil,gin_grid,nil,true,-1,1,-1,1); Result:=res; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_VFSShareSnapshots(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var dsName : TFRE_DB_String; share : TFRE_DB_VIRTUAL_FILESHARE; begin if ses.GetSessionModuleData(ClassName).FieldExists('selectedShare') and (ses.GetSessionModuleData(ClassName).Field('selectedShare').ValueCount=1) then begin CheckDbResult(conn.FetchAs(FREDB_H2G(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsString),TFRE_DB_VIRTUAL_FILESHARE,share)); dsName:=share.Name; end else begin dsName:=''; end; Result:=fInfrastructureIFMod.getSnapshotsGrid(dsName,input,ses,app,conn); (Result.Implementor_HC as TFRE_DB_CONTENT_DESC).contentId:='VIRTUAL_SHARE_SNAPSHOTS'; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_GridUOSC(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var share : IFRE_DB_Object; addDisabled: Boolean; begin addDisabled:=true; if ses.GetSessionModuleData(ClassName).FieldExists('selectedShare') then begin CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID,share)); if input.FieldExists('selected') and (input.Field('selected').ValueCount>0) then begin addDisabled:=not (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,share.DomainID)); end; end; Result:=TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('add_user',addDisabled); end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_GridUISC(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var share : IFRE_DB_Object; removeDisabled: Boolean; begin removeDisabled:=true; if ses.GetSessionModuleData(ClassName).FieldExists('selectedShare') then begin CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID,share)); if input.FieldExists('selected') and (input.Field('selected').ValueCount>0) then begin removeDisabled:=not (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,share.DomainID)); end; end; Result:=TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('remove_user',removeDisabled); end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_GridUOMenu(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var res : TFRE_DB_MENU_DESC; share : IFRE_DB_Object; sf : TFRE_DB_SERVER_FUNC_DESC; begin res:=TFRE_DB_MENU_DESC.create.Describe; CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID,share)); if conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,share.DomainID) then begin sf:=CWSF(@WEB_AddUser); sf.AddParam.Describe('selected',input.Field('selected').AsStringArr); res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_add_user'),'',sf); end; Result:=res; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_GridUIMenu(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var res : TFRE_DB_MENU_DESC; share : IFRE_DB_Object; sf : TFRE_DB_SERVER_FUNC_DESC; begin res:=TFRE_DB_MENU_DESC.create.Describe; CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID,share)); if conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,share.DomainID) then begin sf:=CWSF(@WEB_RemoveUser); sf.AddParam.Describe('selected',input.Field('selected').AsStringArr); res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_remove_user'),'',sf); end; Result:=res; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_AddUser(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var share : IFRE_DB_Object; i : Integer; begin CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID,share)); if not (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,share.DomainID)) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); for i := 0 to input.Field('selected').ValueCount - 1 do begin CheckDbResult(conn.SYS.ModifyUserGroupsById(FREDB_H2G(input.Field('selected').AsStringItem[i]),TFRE_DB_GUIDArray.create(share.Field('group').AsObjectLink),true)); end; Result:=GFRE_DB_NIL_DESC; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_RemoveUser(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var share : IFRE_DB_Object; i : Integer; begin CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID,share)); if not (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,share.DomainID)) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); for i := 0 to input.Field('selected').ValueCount - 1 do begin CheckDbResult(conn.SYS.RemoveUserGroupsById(FREDB_H2G(input.Field('selected').AsStringItem[i]),TFRE_DB_GUIDArray.create(share.Field('group').AsObjectLink))); end; Result:=GFRE_DB_NIL_DESC; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_GridGOSC(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var share : IFRE_DB_Object; addDisabled: Boolean; begin addDisabled:=true; if ses.GetSessionModuleData(ClassName).FieldExists('selectedShare') then begin CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID,share)); if input.FieldExists('selected') and (input.Field('selected').ValueCount>0) then begin addDisabled:=not (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,share.DomainID)); end; end; Result:=TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('add_group',addDisabled); end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_GridGISC(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var share : IFRE_DB_Object; removeDisabled: Boolean; begin removeDisabled:=true; if ses.GetSessionModuleData(ClassName).FieldExists('selectedShare') then begin CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID,share)); if input.FieldExists('selected') and (input.Field('selected').ValueCount>0) then begin removeDisabled:=not (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,share.DomainID)); end; end; Result:=TFRE_DB_UPDATE_UI_ELEMENT_DESC.create.DescribeStatus('remove_group',removeDisabled); end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_GridGOMenu(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var res : TFRE_DB_MENU_DESC; share : IFRE_DB_Object; sf : TFRE_DB_SERVER_FUNC_DESC; begin res:=TFRE_DB_MENU_DESC.create.Describe; CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID,share)); if conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,share.DomainID) then begin sf:=CWSF(@WEB_AddGroup); sf.AddParam.Describe('selected',input.Field('selected').AsStringArr); res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_add_group'),'',sf); end; Result:=res; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_GridGIMenu(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var res : TFRE_DB_MENU_DESC; share : IFRE_DB_Object; sf : TFRE_DB_SERVER_FUNC_DESC; begin res:=TFRE_DB_MENU_DESC.create.Describe; CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID,share)); if conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,share.DomainID) then begin sf:=CWSF(@WEB_RemoveGroup); sf.AddParam.Describe('selected',input.Field('selected').AsStringArr); res.AddEntry.Describe(FetchModuleTextShort(ses,'cm_remove_group'),'',sf); end; Result:=res; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_AddGroup(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var share : IFRE_DB_Object; i : Integer; group : IFRE_DB_GROUP; begin CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID,share)); if not (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,share.DomainID)) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); for i := 0 to input.Field('selected').ValueCount - 1 do begin CheckDbResult(conn.sys.FetchGroupById(FREDB_H2G(input.Field('selected').AsStringItem[i]),group)); if group.isProtected then raise EFRE_DB_Exception.Create('You cannot modify a protected group.'); CheckDbResult(conn.SYS.AddGroupsToGroupById(group.ObjectName,group.DomainID,TFRE_DB_GUIDArray.create(share.Field('group').AsObjectLink))); end; Result:=GFRE_DB_NIL_DESC; end; function TFRE_FIRMBOX_VIRTUAL_FILESERVER_MOD.WEB_RemoveGroup(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; var share : IFRE_DB_Object; i : Integer; group : IFRE_DB_GROUP; begin CheckDbResult(conn.Fetch(ses.GetSessionModuleData(ClassName).Field('selectedShare').AsGUID,share)); if not (conn.SYS.CheckClassRight4DomainId(sr_UPDATE,TFRE_DB_VIRTUAL_FILESHARE,share.DomainID) and conn.SYS.CheckClassRight4DomainId('assignGroup',TFRE_DB_GROUP,share.DomainID)) then raise EFRE_DB_Exception.Create(conn.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access'))); for i := 0 to input.Field('selected').ValueCount - 1 do begin CheckDbResult(conn.sys.FetchGroupById(FREDB_H2G(input.Field('selected').AsStringItem[i]),group)); if group.isProtected then raise EFRE_DB_Exception.Create('You cannot modify a protected group.'); CheckDbResult(conn.SYS.RemoveGroupsFromGroupById(group.ObjectName,group.DomainID,TFRE_DB_GUIDArray.create(share.Field('group').AsObjectLink),false)); end; Result:=GFRE_DB_NIL_DESC; end; end.
unit CrudExampleHorseServer.Controller; interface uses CrudExampleHorseServer.Model.Entidade.ConfigApp , CrudExampleHorseServer.Model.Conexao.DB , System.SysUtils , System.JSON {$IFDEF CONSOLE} , Horse {$ELSE} , Horse.ISAPI {$ENDIF} ; type IController = interface ['{AF9ADF59-AD07-4B09-955C-3F997312AC99}'] function ConfigApp: IConfigApp; function ConexaoDB: IModelConexaoDB; function Query: IModelQuery; procedure AppRegister( aApp: THorse ); procedure Status(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); procedure Autorization(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); procedure DeserializeToken(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); procedure RevalidateToken(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); //function CheckToken( const aToken: string ): boolean; overload; //function CheckToken( const aReq: THorseRequest ): boolean; overload; //function CheckToken( const aReq: THorseRequest; const aArrayLevels: array of integer ): boolean; overload; //function Token(const aReq: THorseRequest): string; {procedure ListCadastro(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); procedure ListCadastroByID(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); procedure InsertCadastro(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); procedure UpdateCadastro(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); procedure DeleteCadastro(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc);} procedure DoRequestsCadastro(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); end; TController = class(TInterfacedObject, IController) strict private class var FController: IController; private { private declarations } FConfigApp: IConfigApp; FConexaoDB: IModelConexaoDB; //function CheckToken( const aToken: string ): boolean; overload; //function CheckToken( const aReq: THorseRequest ): boolean; overload; //function CheckToken( const aReq: THorseRequest; const aArrayLevels: array of integer ): boolean; overload; function ValidateToken( const aReq: THorseRequest ): boolean; overload; function ValidateToken( const aReq: THorseRequest; const aArrayLevels: array of integer ): boolean; overload; function Token(const aReq: THorseRequest): string; public { public declarations } class function New: IController; constructor Create; destructor Destroy; override; function ConfigApp: IConfigApp; function ConexaoDB: IModelConexaoDB; function Query: IModelQuery; procedure AppRegister( aApp: THorse ); procedure Status(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); procedure Autorization(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); procedure DeserializeToken(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); procedure RevalidateToken(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); procedure DoRequestsCadastro(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); end; implementation uses CrudExampleHorseServer.Model.Entidade.Autorization {$IFDEF CONSOLE} , VCL.Forms {$ENDIF} , Web.HTTPApp , CrudExampleHorseServer.Model.DAO.Cadastro , Horse.Commons, CrudExampleHorseServer.Controller.Cadastro ; const SECRETSIGNATURE = 'XXXXXXXXXXXXXXXXXXXXXX'; procedure TController.AppRegister(aApp: THorse); begin aApp.Get('/api/v1/status', Status); aApp.Get('/api/v1/dashboard/verifytoken', DeserializeToken); aApp.Get('/api/v1/dashboard/revalidatetoken', RevalidateToken); aApp.Post('/api/v1/dashboard/auth', Autorization); aApp.Get('/user', DoRequestsCadastro); aApp.Get('/user/:id', DoRequestsCadastro); aApp.Post('/user', DoRequestsCadastro); // 201 aApp.Put('/user', DoRequestsCadastro); // 200 aApp.Delete('/user/:id', DoRequestsCadastro); // 200 end; procedure TController.DeserializeToken(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); begin aRes.Send<TJSONObject>( TAutorization.New( SECRETSIGNATURE ).DeserializeToken( Token ( aReq ) ) ) end; procedure TController.Autorization(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); begin aRes.Send<TJSONObject>( TAutorization.New( SECRETSIGNATURE ).SetApplicationName('DashBoard').SetConexaoDB( ConexaoDB ).Login( aReq.Body<TJSONObject> ) ); end; function TController.ConexaoDB: IModelConexaoDB; begin if not Assigned(FConexaoDB) then FConexaoDB:=TModelConexaoDB.New(ConfigApp.ParamConnectionDB); Result:=FConexaoDB; end; function TController.ConfigApp: IConfigApp; begin if not Assigned(FConfigApp) then {$IFDEF CONSOLE} FConfigApp:=TConfigApp.New( ChangeFileExt(Application.ExeName,'.INI') ); {$ELSE} FConfigApp:=TConfigApp.New( ChangeFileExt(GetModuleFile(hInstance),'.INI') ); {$ENDIF} Result:=FConfigApp; end; constructor TController.Create; begin end; destructor TController.Destroy; begin inherited; end; class function TController.New: IController; begin if not Assigned(FController) then FController:=Self.Create; Result := FController; end; function TController.Query: IModelQuery; begin Result:=ConexaoDB.Query; end; procedure TController.DoRequestsCadastro(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); begin if ValidateToken( aReq ) then TControllerCadastro.New(ConexaoDB).DoRequestsCadastro( aReq, aRes ); end; procedure TController.RevalidateToken(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); begin if ValidateToken( aReq ) then aRes.Send<TJSONObject>( TAutorization.New( SECRETSIGNATURE ).RevalidateToken( Token ( aReq ) ) ) else aRes.Send<TJSONObject>( TJSONObject.Create .AddPair( TJSONPair.Create( 'Erro', 'Token inválido' ) ) ); end; procedure TController.Status(aReq: THorseRequest; aRes: THorseResponse; aNext: TProc); begin aRes.Send('Status: Ok '); end; function TController.Token(const aReq: THorseRequest): string; begin Result:=aReq.Headers['TOKEN']; if Result='' then Result:=aReq.CookieFields.Values['TOKEN']; end; function TController.ValidateToken(const aReq: THorseRequest; const aArrayLevels: array of integer): boolean; begin if ConfigApp.ValidateToken then with TAutorization.New( SECRETSIGNATURE ) do Result:=Self.ValidateToken(aReq) and CheckAccessLevel( DeserializeToken( Token( aReq ) ), aArrayLevels ) else Result:=True; end; function TController.ValidateToken(const aReq: THorseRequest): boolean; begin Result:=not ( ConfigApp.ValidateToken ) or TAutorization.New( SECRETSIGNATURE ).ValidateToken( Token ( aReq ) ); end; end.
{Version Delphi} unit Ptext0; { Gestion de fichiers texte avec plus de 255 caractŠres par ligne } INTERFACE uses util1; type TypePseudoText=object buf:PtabChar; taille:integer; f:file; Plec:integer; pPos,pmax:longint; error:integer; constructor init(n:integer); procedure Passign(st:string); procedure Prewrite; procedure Pappend; procedure Preset; procedure Pclose; procedure Pwrite(st:shortString); procedure Pwriteln(st:shortString); function Preadln(var nb:integer):pointer; function Perror:integer; function Peof:boolean; destructor done; end; PpseudoText= ^TypePseudoText; IMPLEMENTATION constructor TypePseudoText.init(n:integer); begin if maxAvail<n then begin taille:=0; error:=-1; exit; end; getmem(buf,n); taille:=n; error:=0; Plec:=0; pmax:=0; end; procedure TypePseudoText.Passign(st:string); begin if error<>0 then exit; assign(f,st); end; procedure TypePseudoText.Prewrite; begin if error<>0 then exit; rewrite(f,1); error:=IOresult; end; procedure TypePseudoText.Pappend; begin if error<>0 then exit; reset(f,1); error:=IOresult; if error=0 then begin pMax:=fileSize(f); error:=IOresult; end; pPos:=pMax; if error=0 then seek(f,pMax); end; procedure TypePseudoText.Preset; var res:intG; begin if error<>0 then exit; reset(f,1); error:=IOresult; if error=0 then begin blockread(f,buf^,taille,res); error:=IOresult; end; if error=0 then begin pmax:=fileSize(f); error:=IOresult; pPos:=0; end; end; procedure TypePseudoText.Pclose; begin if error<>0 then exit; close(f); error:=IOresult; end; procedure TypePseudoText.Pwrite(st:shortString); begin if error<>0 then exit; if Plec+length(st)<taille-2 then begin move(st[1],buf^[Plec],length(st)); inc(Plec,length(st)); end else error:=-2; end; procedure TypePseudoText.Pwriteln(st:shortString); var res:intG; begin Pwrite(st); if error<>0 then exit; buf^[Plec]:=#13; buf^[Plec+1]:=#10; BlockWrite(f,buf^,Plec+2,res); error:=IOresult; Plec:=0; end; function TypePseudoText.Preadln(var nb:integer):pointer; var res:intG; begin if error<>0 then exit; if Plec>0 then move(buf^[Plec],buf^[0],taille-Plec); blockread(f,buf^[taille-Plec],Plec,res); error:=IOresult; if error<>0 then exit; Plec:=0; while (buf^[Plec]<>#10) and (buf^[Plec]<>#13) and (Plec<taille) do inc(Plec); nb:=Plec; if Plec<taille-2 then begin if buf^[Plec]=#13 then begin buf^[Plec]:=#0; if buf^[Plec+1]=#10 then begin buf^[Plec+1]:=#0; inc(Plec); end; end else buf^[Plec]:=#0; inc(pLec); inc(pPos,pLec); end else error:=-3; Preadln:=buf; end; function TypePseudoText.Perror:integer; begin Perror:=error; end; function TypePseudoText.Peof:boolean; begin if error<>0 then exit; Peof:=(Ppos>=pmax); error:=IOresult; end; destructor TypePseudoText.done; begin if taille<>0 then freemem(buf,taille); end; end.
unit ibSHFieldDescrFrm; interface uses SHDesignIntf, SHEvents, ibSHDesignIntf, ibSHComponentFrm, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ToolWin, ExtCtrls, ImgList, ActnList, AppEvnts, SynEdit, pSHSynEdit, VirtualTrees, Menus; type TibSHFieldDescrForm = class(TibBTComponentForm) Panel1: TPanel; Splitter1: TSplitter; Panel2: TPanel; Tree: TVirtualStringTree; pSHSynEdit1: TpSHSynEdit; Panel3: TPanel; ApplicationEvents1: TApplicationEvents; procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); private { Private declarations } FDBTableIntf: IibSHTable; FDBViewIntf: IibSHView; FDBProcedureIntf: IibSHProcedure; { Tree } procedure TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure TreePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); procedure TreeIncrementalSearch(Sender: TBaseVirtualTree; Node: PVirtualNode; const SearchText: WideString; var Result: Integer); procedure TreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure TreeDblClick(Sender: TObject); procedure TreeGetPopupMenu(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; const P: TPoint; var AskParent: Boolean; var PopupMenu: TPopupMenu); procedure TreeCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); procedure TreeFocusChanging(Sender: TBaseVirtualTree; OldNode, NewNode: PVirtualNode; OldColumn, NewColumn: TColumnIndex; var Allowed: Boolean); procedure TreeFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); procedure SetTreeEvents(ATree: TVirtualStringTree); procedure DoOnGetData; procedure ShowSource; procedure InternalRun(ANode: PVirtualNode); protected { ISHRunCommands } function GetCanRun: Boolean; override; function GetCanRefresh: Boolean; override; procedure Run; override; procedure Refresh; override; procedure DoOnIdle; override; function DoOnOptionsChanged: Boolean; override; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; procedure RefreshData; property DBTable: IibSHTable read FDBTableIntf; property DBView: IibSHView read FDBViewIntf; property DBProcedure: IibSHProcedure read FDBProcedureIntf; end; TibSHFieldDescrFormAction_ = class(TSHAction) public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; TibSHFieldDescrFormAction_Run = class(TibSHFieldDescrFormAction_) end; TibSHFieldDescrFormAction_Refresh = class(TibSHFieldDescrFormAction_) end; var ibSHFieldDescrForm: TibSHFieldDescrForm; procedure Register; implementation uses ibSHConsts, ibSHSQLs, ibSHValues, ibSHStrUtil; {$R *.dfm} type PTreeRec = ^TTreeRec; TTreeRec = record Number: string; ImageIndex: Integer; Name: string; Description: string; Input: Boolean; end; procedure Register; begin SHRegisterImage(TibSHFieldDescrFormAction_Run.ClassName, 'Button_Run.bmp'); SHRegisterImage(TibSHFieldDescrFormAction_Refresh.ClassName, 'Button_Refresh.bmp'); SHRegisterActions([ TibSHFieldDescrFormAction_Run, TibSHFieldDescrFormAction_Refresh]); end; { TibSHFieldDescrForm } constructor TibSHFieldDescrForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); begin inherited Create(AOwner, AParent, AComponent, ACallString); Supports(Component, IibSHTable, FDBTableIntf); Supports(Component, IibSHView, FDBViewIntf); Supports(Component, IibSHProcedure, FDBProcedureIntf); Editor := pSHSynEdit1; Editor.Lines.Clear; // Editor.Lines.AddStrings(DBObject.Description); FocusedControl := Tree; SetTreeEvents(Tree); DoOnOptionsChanged; RefreshData; end; destructor TibSHFieldDescrForm.Destroy; begin if GetCanRun then Run; inherited Destroy; end; procedure TibSHFieldDescrForm.RefreshData; begin try Screen.Cursor := crHourGlass; DoOnGetData; finally Screen.Cursor := crDefault; end; end; procedure TibSHFieldDescrForm.SetTreeEvents(ATree: TVirtualStringTree); begin ATree.Images := Designer.ImageList; ATree.OnGetNodeDataSize := TreeGetNodeDataSize; ATree.OnFreeNode := TreeFreeNode; ATree.OnGetImageIndex := TreeGetImageIndex; ATree.OnGetText := TreeGetText; ATree.OnPaintText := TreePaintText; ATree.OnIncrementalSearch := TreeIncrementalSearch; ATree.OnDblClick := TreeDblClick; ATree.OnKeyDown := TreeKeyDown; ATree.OnGetPopupMenu := TreeGetPopupMenu; ATree.OnCompareNodes := TreeCompareNodes; ATree.OnFocusChanging := TreeFocusChanging; ATree.OnFocusChanged := TreeFocusChanged; end; procedure TibSHFieldDescrForm.DoOnGetData; var I: Integer; Node: PVirtualNode; NodeData: PTreeRec; begin Tree.BeginUpdate; Tree.Clear; Editor.Clear; if Assigned(DBTable) then begin for I := 0 to Pred(DBTable.Fields.Count) do begin Node := Tree.AddChild(nil); NodeData := Tree.GetNodeData(Node); NodeData.Number := IntToStr(I + 1); NodeData.ImageIndex := -1; // Designer.GetImageIndex(IibSHField); NodeData.Name := DBTable.Fields[I]; NodeData.Description := TrimRight(DBTable.GetField(I).Description.Text); end; end; if Assigned(DBView) then begin for I := 0 to Pred(DBView.Fields.Count) do begin Node := Tree.AddChild(nil); NodeData := Tree.GetNodeData(Node); NodeData.Number := IntToStr(I + 1); NodeData.ImageIndex := -1; // Designer.GetImageIndex(IibSHField); NodeData.Name := DBView.Fields[I]; NodeData.Description := TrimRight(DBView.GetField(I).Description.Text); end; end; if Assigned(DBProcedure) then begin if DBProcedure.Params.Count > 0 then begin Node := Tree.AddChild(nil); NodeData := Tree.GetNodeData(Node); NodeData.Number := ''; NodeData.ImageIndex := -1; NodeData.Name := 'Input parameters'; end; for I := 0 to Pred(DBProcedure.Params.Count) do begin Node := Tree.AddChild(nil); NodeData := Tree.GetNodeData(Node); NodeData.Number := IntToStr(I + 1); NodeData.ImageIndex := -1; //Designer.GetImageIndex(IibSHField); NodeData.Name := DBProcedure.Params[I]; NodeData.Description := TrimRight(DBProcedure.GetParam(I).Description.Text); NodeData.Input := True; end; if DBProcedure.Returns.Count > 0 then begin Node := Tree.AddChild(nil); NodeData := Tree.GetNodeData(Node); NodeData.Number := ''; NodeData.ImageIndex := -1; NodeData.Name := 'Output parameters'; end; for I := 0 to Pred(DBProcedure.Returns.Count) do begin Node := Tree.AddChild(nil); NodeData := Tree.GetNodeData(Node); NodeData.Number := IntToStr(I + 1); NodeData.ImageIndex := -1; // Designer.GetImageIndex(IibSHField); NodeData.Name := DBProcedure.Returns[I]; NodeData.Description := TrimRight(DBProcedure.GetReturn(I).Description.Text); end; end; Node := Tree.GetFirst; if Assigned(Node) then begin Tree.FocusedNode := Node; Tree.Selected[Tree.FocusedNode] := True; end; Tree.EndUpdate; end; procedure TibSHFieldDescrForm.ShowSource; var Node: PVirtualNode; NodeData: PTreeRec; begin Node := Tree.FocusedNode; NodeData := Tree.GetNodeData(Node); if Assigned(Editor) and Assigned(NodeData) then begin Editor.BeginUpdate; Editor.Lines.Clear; Editor.Lines.Text := NodeData.Description; Editor.EndUpdate; Editor.Visible := Length(NodeData.Number) > 0; end; end; procedure TibSHFieldDescrForm.InternalRun(ANode: PVirtualNode); var NodeData: PTreeRec; begin NodeData := Tree.GetNodeData(ANode); if Assigned(Editor) and Editor.Modified and Assigned(NodeData) then begin NodeData.Description := Editor.Lines.Text; if Assigned(DBTable) then begin DBTable.GetField(Pred(StrToInt(NodeData.Number))).Description.Assign(Editor.Lines); DBTable.GetField(Pred(StrToInt(NodeData.Number))).SetDescription; end; if Assigned(DBView) then begin DBView.GetField(Pred(StrToInt(NodeData.Number))).Description.Assign(Editor.Lines); DBView.GetField(Pred(StrToInt(NodeData.Number))).SetDescription; end; if Assigned(DBProcedure) then begin if NodeData.Input then begin DBProcedure.GetParam(Pred(StrToInt(NodeData.Number))).Description.Assign(Editor.Lines); DBProcedure.GetParam(Pred(StrToInt(NodeData.Number))).SetDescription; end else begin DBProcedure.GetReturn(Pred(StrToInt(NodeData.Number))).Description.Assign(Editor.Lines); DBProcedure.GetReturn(Pred(StrToInt(NodeData.Number))).SetDescription; end; end; Editor.Modified := False; Tree.Invalidate; Tree.Repaint; end; end; function TibSHFieldDescrForm.GetCanRun: Boolean; begin Result := Assigned(Editor) and Editor.Modified; end; function TibSHFieldDescrForm.GetCanRefresh: Boolean; begin Result := True; end; procedure TibSHFieldDescrForm.Run; begin InternalRun(Tree.FocusedNode); end; procedure TibSHFieldDescrForm.Refresh; begin if Assigned(DBTable) then DBTable.Refresh; if Assigned(DBView) then DBView.Refresh; if Assigned(DBProcedure) then DBProcedure.Refresh; RefreshData; end; procedure TibSHFieldDescrForm.DoOnIdle; begin Editor.ReadOnly := not Assigned(Tree.FocusedNode); end; function TibSHFieldDescrForm.DoOnOptionsChanged: Boolean; begin Result := inherited DoOnOptionsChanged; if Result and Assigned(Editor) then begin // Editor.ReadOnly := True; // Editor.Options := Editor.Options + [eoScrollPastEof]; Editor.Highlighter := nil; // Принудительная установка фонта Editor.Font.Charset := 1; Editor.Font.Color := clWindowText; Editor.Font.Height := -13; Editor.Font.Name := 'Courier New'; Editor.Font.Pitch := fpDefault; Editor.Font.Size := 10; Editor.Font.Style := []; end; end; procedure TibSHFieldDescrForm.ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); begin DoOnIdle; end; { Tree } procedure TibSHFieldDescrForm.TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := SizeOf(TTreeRec); end; procedure TibSHFieldDescrForm.TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if Assigned(Data) then Finalize(Data^); end; procedure TibSHFieldDescrForm.TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); //var // Data: PTreeRec; begin // Data := Sender.GetNodeData(Node); // if (Kind = ikNormal) or (Kind = ikSelected) then // begin // case Column of // 1: ImageIndex := Data.ImageIndex; // else // ImageIndex := -1; // end; // end; end; procedure TibSHFieldDescrForm.TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if TextType = ttNormal then begin case Column of 0: CellText := Data.Number; 1: CellText := Data.Name; end; end; end; procedure TibSHFieldDescrForm.TreePaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if TextType = ttNormal then begin case Column of 0: ;// Data.Number; 1: if (Length(Data.Description) = 0) and (Length(Data.Number) > 0) then if Sender.Focused and (vsSelected in Node.States) then TargetCanvas.Font.Color := clWindow else TargetCanvas.Font.Color := clGray; end; end; end; procedure TibSHFieldDescrForm.TreeIncrementalSearch(Sender: TBaseVirtualTree; Node: PVirtualNode; const SearchText: WideString; var Result: Integer); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if Pos(AnsiUpperCase(SearchText), AnsiUpperCase(Data.Name)) <> 1 then Result := 1; end; procedure TibSHFieldDescrForm.TreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // if Key = VK_RETURN then ShowConstraint(csSource); end; procedure TibSHFieldDescrForm.TreeDblClick(Sender: TObject); begin // ShowConstraint(csSource); end; procedure TibSHFieldDescrForm.TreeGetPopupMenu(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; const P: TPoint; var AskParent: Boolean; var PopupMenu: TPopupMenu); var HT: THitInfo; Data: PTreeRec; begin if not Enabled then Exit; PopupMenu := nil; if Assigned(Sender.FocusedNode) then begin Sender.GetHitTestInfoAt(P.X, P.Y, True, HT); Data := Sender.GetNodeData(Sender.FocusedNode); if Assigned(Data) and (Sender.GetNodeLevel(Sender.FocusedNode) = 0) and (HT.HitNode = Sender.FocusedNode) and (hiOnItemLabel in HT.HitPositions) then end; end; procedure TibSHFieldDescrForm.TreeCompareNodes( Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); var Data1, Data2: PTreeRec; begin Data1 := Sender.GetNodeData(Node1); Data2 := Sender.GetNodeData(Node2); Result := CompareStr(Data1.Name, Data2.Name); end; procedure TibSHFieldDescrForm.TreeFocusChanging(Sender: TBaseVirtualTree; OldNode, NewNode: PVirtualNode; OldColumn, NewColumn: TColumnIndex; var Allowed: Boolean); begin InternalRun(OldNode); end; procedure TibSHFieldDescrForm.TreeFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); begin ShowSource; end; { TibSHFieldDescrFormAction_ } constructor TibSHFieldDescrFormAction_.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallToolbar; if Self is TibSHFieldDescrFormAction_Run then Tag := 1; if Self is TibSHFieldDescrFormAction_Refresh then Tag := 2; case Tag of 0: Caption := '-'; // separator 1: begin Caption := Format('%s', ['Run']); ShortCut := TextToShortCut('Ctrl+Enter'); SecondaryShortCuts.Add('F9'); end; 2: begin Caption := Format('%s', ['Refresh']); ShortCut := TextToShortCut('F5'); end; end; if Tag <> 0 then Hint := Caption; end; function TibSHFieldDescrFormAction_.SupportComponent(const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp) or IsEqualGUID(AClassIID, IibSHProcedure); end; procedure TibSHFieldDescrFormAction_.EventExecute(Sender: TObject); begin case Tag of // Run 1: (Designer.CurrentComponentForm as ISHRunCommands).Run; // Refresh 2: (Designer.CurrentComponentForm as ISHRunCommands).Refresh; end; end; procedure TibSHFieldDescrFormAction_.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHFieldDescrFormAction_.EventUpdate(Sender: TObject); begin if Assigned(Designer.CurrentComponentForm) and (AnsiSameText(Designer.CurrentComponentForm.CallString, SCallFieldDescr) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallParamDescr)) then begin case Tag of // Separator 0: begin Visible := True; end; // Run 1: begin Visible := True; Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRun; end; // Refresh 2: begin Visible := True; Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRefresh; end; end; end else Visible := False; end; initialization Register; end.
unit uBackupRestore; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IBX.IBServices, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Buttons,Vcl.FileCtrl, Vcl.ExtCtrls, uClasseBackup; type TfrmBackup = class(TForm) pgControle: TPageControl; tsBackup: TTabSheet; tsRestore: TTabSheet; RestoreBanco: TIBRestoreService; BackupBanco: TIBBackupService; opDiretorio: TOpenDialog; Label1: TLabel; edtDirBanco: TEdit; btnDirBanco: TBitBtn; Label2: TLabel; edtDirBackup: TEdit; Label3: TLabel; edtNomeBanco: TEdit; btnBackup: TBitBtn; btnDirBackup: TBitBtn; Label4: TLabel; mmProgessoBackup: TMemo; mmProgressoRestore: TMemo; Label5: TLabel; Label6: TLabel; edtDirBacRestore: TEdit; edtDirRestore: TEdit; btnDirBacRestore: TBitBtn; btnDirRestore: TBitBtn; btnRestore: TBitBtn; Panel1: TPanel; Label7: TLabel; Label8: TLabel; Label9: TLabel; txtDataRestore: TLabel; txtHoraRestore: TLabel; procedure btnDirBancoClick(Sender: TObject); procedure btnBackupClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnDirBackupClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnDirBacRestoreClick(Sender: TObject); procedure btnDirRestoreClick(Sender: TObject); procedure btnRestoreClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmBackup: TfrmBackup; Bkp : TBackup; implementation {$R *.dfm} uses uClasseException; procedure TfrmBackup.btnBackupClick(Sender: TObject); begin // Passa os paramentros para pode inicia o Backup Bkp.IniciaBackup( edtDirBanco.Text, edtDirBackup.Text, mmProgessoBackup, BackupBanco ); end; procedure TfrmBackup.btnDirBackupClick(Sender: TObject); begin // Seleciona a pasta aonde vai ser gerado o Restore edtDirBackup.Text := Bkp.SelectDir(' Selecione a pasta de Instalação ') + edtNomeBanco.Text; end; procedure TfrmBackup.btnDirBacRestoreClick(Sender: TObject); begin //opDiretorio.InitialDir := ExtractFilePath(Application.ExeName + 'Backup\'); if opDiretorio.Execute then begin edtDirBacRestore.Text := opDiretorio.FileName; end; edtDirRestore.Text := ExtractFilePath(ParamStr(0))+'Dados\Dados.fdb'; btnDirRestore.Enabled := True; btnRestore.Enabled := True; end; procedure TfrmBackup.btnDirBancoClick(Sender: TObject); begin //opDiretorio.InitialDir := ExtractFilePath(Application.ExeName + 'Dados\'); if opDiretorio.Execute then begin edtDirBanco.Text := opDiretorio.FileName; edtNomeBanco.Text := 'Backup'+FormatDateTime('ddmmyy',date)+'.fbk'; btnDirBackup.Enabled := True; edtDirBackup.Text := ExtractFilePath(Application.ExeName)+'Backup\'+edtNomeBanco.Text; end; end; procedure TfrmBackup.btnDirRestoreClick(Sender: TObject); begin //opDiretorio.InitialDir := ExtractFilePath(Application.ExeName); edtDirRestore.Text := Bkp.SelectDir('Selecione a pasta de Instala��o')+'\Dados.fdb'; end; procedure TfrmBackup.btnRestoreClick(Sender: TObject); begin // Passa os paramentros para pode inicia o Restore Bkp.IniciaRestore( edtDirBacRestore.Text, edtDirRestore.Text, mmProgressoRestore, RestoreBanco ); end; procedure TfrmBackup.FormCreate(Sender: TObject); begin // Criar a pasta Backup se não existi if not DirectoryExists(ExtractFilePath(Application.ExeName)+ 'Backup') then begin CreateDir(ExtractFilePath(Application.ExeName)+'Backup'); end; end; procedure TfrmBackup.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key = VK_ESCAPE then Close; end; procedure TfrmBackup.FormShow(Sender: TObject); begin { // Colocar a ultima data e hora no DBText txtData.Caption := Formatacao( 'Data', Bkp.UltimoBkp( 'BK',true ) ); txtHora.Caption := Formatacao( 'Hora', Bkp.UltimoBkp( 'BK',False ) ); txtDataRestore.Caption := Formatacao( 'Data', Bkp.UltimoBkp( 'RT',true ) ); txtHoraRestore.Caption := Formatacao( 'Hora', Bkp.UltimoBkp( 'RT',False ) ); } end; end.
unit UnitInternetUpdate; interface uses System.Classes, System.SysUtils, Winapi.Windows, Winapi.ActiveX, Vcl.Forms, Xml.xmldom, Dmitry.Utils.System, uLogger, uConstants, uShellIntegration, uGOM, uTranslate, uInternetUtils, uDBForm, uActivationUtils, uSettings, uDBThread, uProgramStatInfo, uUpTime; type TInternetUpdate = class(TDBThread) private { Private declarations } FIsBackground: Boolean; StringParam: string; FNotifyHandler: TUpdateNotifyHandler; FOwner: TDBForm; Info: TUpdateInfo; protected function GetThreadID: string; override; procedure Execute; override; procedure ShowUpdates; procedure Inform(Info: string); procedure InformSynch; procedure ParceReply(Reply: string); procedure NotifySync; public constructor Create(Owner: TDBForm; IsBackground: Boolean; NotifyHandler: TUpdateNotifyHandler); end; implementation uses UnitFormInternetUpdating; constructor TInternetUpdate.Create(Owner: TDBForm; IsBackground: Boolean; NotifyHandler: TUpdateNotifyHandler); begin //form synchronization isn't used inherited Create(nil, False); FOwner := Owner; FIsBackground := IsBackground; FNotifyHandler := NotifyHandler; end; procedure TInternetUpdate.Execute; var UpdateFullUrl, UpdateText: string; LastCheckDate: TDateTime; begin inherited; FreeOnTerminate := True; CoInitialize(nil); try if FIsBackground then begin LastCheckDate := AppSettings.ReadDateTime('Updater', 'LastTime', Now - 365); if not (Now - LastCheckDate > 7) then Exit; end; try UpdateFullUrl := ResolveLanguageString(UpdateNotifyURL); UpdateFullUrl := UpdateFullUrl + '?c=' + TActivationManager.Instance.ApplicationCode + '&v=' + ProductVersion + '&ut=' + IntToStr(GetCurrentUpTime) + '&f=' + ProgramStatistics.ToString; UpdateText := DownloadFile(UpdateFullUrl, TEncoding.UTF8); except on E: Exception do EventLog(':TInternetUpdate::Execute() throw exception: ' + E.message); end; ParceReply(UpdateText); if not Terminated and FIsBackground then AppSettings.WriteDateTime('Updater', 'LastTime', Now); finally CoUninitialize; end; end; function TInternetUpdate.GetThreadID: string; begin Result := 'Updates'; end; procedure TInternetUpdate.Inform(Info: string); begin StringParam := Info; Synchronize(InformSynch); end; procedure TInternetUpdate.InformSynch; var ActiveFormHandle: Integer; begin if Screen.ActiveForm <> nil then ActiveFormHandle := Screen.ActiveForm.Handle else ActiveFormHandle := 0; MessageBoxDB(ActiveFormHandle, StringParam, TA('Information'), TD_BUTTON_OK, TD_ICON_INFORMATION); end; procedure TInternetUpdate.NotifySync; begin if (Assigned(FNotifyHandler)) and GOM.IsObj(FOwner) then FNotifyHandler(Self, Info); end; { <update> <release>12</release> <build>250</build> <version>2.3.0.250</version> <release_date>201104312359</release_date> <release_notes>New Database 2.3</release_notes> <release_text>New Database 2.3 release text</release_text> <download_url>http://photodb.illusdolphin.net/en/download.aspx</download_url> </update> } procedure TInternetUpdate.ParceReply(Reply: string); var XmlReply: IDOMDocument; DocumentNode: IDOMNode; I: Integer; DetailName, DetailValue : string; begin XmlReply := GetDOM.createDocument('', '', nil); (XmlReply as IDOMPersist).loadxml(Reply); Info.InfoAvaliable := False; Info.IsNewVersion := False; DocumentNode := XmlReply.documentElement; if DocumentNode <> nil then begin if DocumentNode.nodeName = 'update' then begin for I := 0 to DocumentNode.childNodes.length - 1 do begin DetailName := DocumentNode.childNodes[I].nodeName; DetailValue := ''; if DocumentNode.childNodes[I].childNodes.length = 1 then DetailValue := DocumentNode.childNodes[I].childNodes[0].nodeValue; if DetailName = 'version' then Info.Version := StrToIntDef(DetailValue, 0) else if DetailName = 'build' then Info.Build := StrToIntDef(DetailValue, 0) else if DetailName = 'release' then Info.Release := StringToRelease(DetailValue) else if DetailName = 'release_date' then Info.ReleaseDate := InternetTimeToDateTime(DetailValue) else if DetailName = 'release_notes' then Info.ReleaseNotes := DetailValue else if DetailName = 'release_text' then Info.ReleaseText := DetailValue else if DetailName = 'download_url' then Info.UrlToDownload := DetailValue; end; Info.InfoAvaliable := True; Info.IsNewVersion := IsNewRelease(GetExeVersion(ParamStr(0)), Info.Release); end; end; if not Assigned(FNotifyHandler) then begin if not (FIsBackground and not Info.IsNewVersion) then begin if Info.IsNewVersion then Synchronize(ShowUpdates) else if Info.InfoAvaliable then Inform(L('No new updates are available')) else Inform(L('Unable to check updates! Please, check internet settings in Internet Explorer!')); end; end else Synchronize(NotifySync); end; procedure TInternetUpdate.ShowUpdates; begin ShowAvaliableUpdating(Info); end; end.
unit nifti_loader; {$mode objfpc}{$H+} {$Include opts.inc} //FOREIGNVOL interface uses nifti_foreign, {$ifndef isTerminalApp} dialogs, {$endif} Classes, SysUtils, nifti_types, define_types, zstream; const //(0/1/2 none/smoothMasked/smooth) kNiftiSmoothNone = 0; //no smoothing: raw values kNiftiSmoothMaskZero = 1; //smoothing but ignoring zeros (avoid erosion due to brain mask) kNiftiSmooth = 2; //conventional smoothing type TMatrix = array[1..4, 1..4] of single; TImgRaw = array of byte; TImgScaled= array of single; TNIFTI = class hdr : TNIFTIhdr; mat, invMat: TMatrix; maxInten, minInten: single; isZeroMasked, isLoad4D: boolean; img: TImgScaled;//array of single; private function ImgRawToSingle(imgBytes: TImgRaw; isSwap: boolean): boolean; function readImg(const FileName: string; isSwap: boolean; gzFlag: int64): boolean; procedure setMatrix; procedure SetDescriptives; public isBinary: boolean; procedure reportMat(); procedure mm2(Xmm,Ymm, Zmm: single); function mm2intensity( Xmm, Ymm, Zmm: single; isInterpolate: boolean): single; function mm2vox0(Xmm, Ymm, Zmm: single): TPoint3i; //rounded, voxels indexed from 0! e.g. if dim[0]=50 then output will range 0..49 function validVox0(vox: TPoint3i): boolean; //returns true if voxel [indexed from 0] is inside volume, e.g. if dim[0]=50 then vox.X must be in range 0..49 constructor Create; function LoadFromFile(const FileName: string; smoothMethod: integer): boolean; //smoothMethod is one of kNiftiSmooth... options procedure SmoothMaskZero; procedure Smooth; procedure Close; Destructor Destroy; override; end; function readVoxHeader (var fname: string; var nhdr: TNIFTIhdr; var gzBytes: int64; var swapEndian: boolean; var xDim64: int64): boolean; implementation procedure nifti_quatern_to_mat44( var lR :TMatrix; var qb, qc, qd, qx, qy, qz, dx, dy, dz, qfac : single); var a,b,c,d,xd,yd,zd: double; begin //a := qb; b := qb; c := qc; d := qd; //* last row is always [ 0 0 0 1 ] */ lR[4,1] := 0; lR[4,2] := 0; lR[4,3] := 0; lR[4,4] := 1; //* compute a parameter from b,c,d */ a := 1.0 - (b*b + c*c + d*d) ; if( a < 1.e-7 ) then begin//* special case */ a := 1.0 / sqrt(b*b+c*c+d*d) ; b := b*a ; c := c*a ; d := d*a ;//* normalize (b,c,d) vector */ a := 0.0 ;//* a = 0 ==> 180 degree rotation */ end else begin a := sqrt(a) ; //* angle = 2*arccos(a) */ end; //* load rotation matrix, including scaling factors for voxel sizes */ if dx > 0 then xd := dx else xd := 1; if dy > 0 then yd := dy else yd := 1; if dz > 0 then zd := dz else zd := 1; if( qfac < 0.0 ) then zd := -zd ;//* left handedness? */ lR[1,1]:= (a*a+b*b-c*c-d*d) * xd ; lR[1,2]:= 2.0 * (b*c-a*d ) * yd ; lR[1,3]:= 2.0 * (b*d+a*c ) * zd ; lR[2,1]:= 2.0 * (b*c+a*d ) * xd ; lR[2,2]:= (a*a+c*c-b*b-d*d) * yd ; lR[2,3]:= 2.0 * (c*d-a*b ) * zd ; lR[3,1]:= 2.0 * (b*d-a*c ) * xd ; lR[3,2]:= 2.0 * (c*d+a*b ) * yd ; lR[3,3]:= (a*a+d*d-c*c-b*b) * zd ; //* load offsets */ lR[1,4]:= qx ; lR[2,4]:= qy ; lR[3,4]:= qz ; end; function invertMatrixF(a: TMatrix): TMatrix; //Translated by Chris Rorden, from C function "nifti_mat44_inverse" // Authors: Bob Cox, revised by Mark Jenkinson and Rick Reynolds // License: public domain // http://niftilib.sourceforge.net //Note : For higher performance we could assume the matrix is orthonormal and simply Transpose //Note : We could also compute Gauss-Jordan here var r11,r12,r13,r21,r22,r23,r31,r32,r33,v1,v2,v3 , deti : double; begin r11 := a[1,1]; r12 := a[1,2]; r13 := a[1,3]; //* [ r11 r12 r13 v1 ] */ r21 := a[2,1]; r22 := a[2,2]; r23 := a[2,3]; //* [ r21 r22 r23 v2 ] */ r31 := a[3,1]; r32 := a[3,2]; r33 := a[3,3]; //* [ r31 r32 r33 v3 ] */ v1 := a[1,4]; v2 := a[2,4]; v3 := a[3,4]; //* [ 0 0 0 1 ] */ deti := r11*r22*r33-r11*r32*r23-r21*r12*r33 +r21*r32*r13+r31*r12*r23-r31*r22*r13 ; if( deti <> 0.0 ) then deti := 1.0 / deti ; result[1,1] := deti*( r22*r33-r32*r23) ; result[1,2] := deti*(-r12*r33+r32*r13) ; result[1,3] := deti*( r12*r23-r22*r13) ; result[1,4] := deti*(-r12*r23*v3+r12*v2*r33+r22*r13*v3 -r22*v1*r33-r32*r13*v2+r32*v1*r23) ; result[2,1] := deti*(-r21*r33+r31*r23) ; result[2,2] := deti*( r11*r33-r31*r13) ; result[2,3] := deti*(-r11*r23+r21*r13) ; result[2,4] := deti*( r11*r23*v3-r11*v2*r33-r21*r13*v3 +r21*v1*r33+r31*r13*v2-r31*v1*r23) ; result[3,1] := deti*( r21*r32-r31*r22) ; result[3,2] := deti*(-r11*r32+r31*r12) ; result[3,3] := deti*( r11*r22-r21*r12) ; result[3,4] := deti*(-r11*r22*v3+r11*r32*v2+r21*r12*v3 -r21*r32*v1-r31*r12*v2+r31*r22*v1) ; result[4,1] := 0; result[4,2] := 0; result[4,3] := 0.0 ; if (deti = 0.0) then result[4,4] := 0 else result[4,4] := 1;// failure flag if deti == 0 end; function notZero(v: single): single; //binary result begin if v = 0 then result := 0 else result := 1; end; function TNIfTI.validVox0(vox: TPoint3i): boolean; //returns true if voxel [indexed from 0] is inside volume, e.g. if dim[0]=50 then vox.X must be in range 0..49 begin result := false; if (vox.X < 0) or (vox.Y < 0) or (vox.Z < 0) then exit; if (vox.X >= hdr.dim[1]) or (vox.Y >= hdr.dim[2]) or (vox.Z >= hdr.dim[3]) then exit; result := true; end; procedure rep(s: string; m: TMatrix); begin {$IFDEF UNIX} writeln(format('%s = [%g %g %g %g; %g %g %g %g; %g %g %g %g; 0 0 0 1]', [s, m[1,1], m[1,2], m[1,3], m[1,4], m[2,1], m[2,2], m[2,3], m[2,4], m[3,1], m[3,2], m[3,3], m[3,4] ])); {$ENDIF} end; procedure TNIfTI.mm2(Xmm,Ymm, Zmm: single); var Xvox, Yvox, Zvox: single; begin {$IFDEF UNIX} // Xvox := Xmm*invMat[1,1] + Xmm*invMat[1,2] + Xmm*invMat[1,3] + invMat[1,4]; // Yvox := Ymm*invMat[2,1] + Ymm*invMat[2,2] + Ymm*invMat[2,3] + invMat[2,4]; // Zvox := Zmm*invMat[3,1] + Zmm*invMat[3,2] + Zmm*invMat[3,3] + invMat[3,4]; Xvox := Xmm*invMat[1,1] + Ymm*invMat[1,2] + Zmm*invMat[1,3] + invMat[1,4]; Yvox := Xmm*invMat[2,1] + Ymm*invMat[2,2] + Zmm*invMat[2,3] + invMat[2,4]; Zvox := Xmm*invMat[3,1] + Ymm*invMat[3,2] + Zmm*invMat[3,3] + invMat[3,4]; writeln(format('%g %g %g -> %g %g %g', [Xmm,Ymm, Zmm, Xvox, Yvox, ZVox])); {$ENDIF} end; procedure TNIfTI.reportMat(); begin rep('mat', Mat); rep('inv', invMat); end; function TNIfTI.mm2vox0(Xmm, Ymm, Zmm: single): TPoint3i; //voxels indexed from 0! begin // result.X := round(Xmm*invMat[1,1] + Xmm*invMat[1,2] + Xmm*invMat[1,3] + invMat[1,4]); // result.Y := round(Ymm*invMat[2,1] + Ymm*invMat[2,2] + Ymm*invMat[2,3] + invMat[2,4]); // result.Z := round(Zmm*invMat[3,1] + Zmm*invMat[3,2] + Zmm*invMat[3,3] + invMat[3,4]); result.X := round(Xmm*invMat[1,1] + Ymm*invMat[1,2] + Zmm*invMat[1,3] + invMat[1,4]); result.Y := round(Xmm*invMat[2,1] + Ymm*invMat[2,2] + Zmm*invMat[2,3] + invMat[2,4]); result.Z := round(Xmm*invMat[3,1] + Ymm*invMat[3,2] + Zmm*invMat[3,3] + invMat[3,4]); end; function TNIfTI.mm2intensity( Xmm, Ymm, Zmm: single; isInterpolate: boolean): single; var Xvox, Yvox, Zvox: single; //voxel coordinates indexed from 0 Xfrac1, Yfrac1, Zfrac1, Xfrac0, Yfrac0, Zfrac0, Weight : single; vx, sliceVx: integer; begin if length(img) < 1 then exit(0); result := 0; Xvox := Xmm*invMat[1,1] + Ymm*invMat[1,2] + Zmm*invMat[1,3] + invMat[1,4]; Yvox := Xmm*invMat[2,1] + Ymm*invMat[2,2] + Zmm*invMat[2,3] + invMat[2,4]; Zvox := Xmm*invMat[3,1] + Ymm*invMat[3,2] + Zmm*invMat[3,3] + invMat[3,4]; //Xvox := Xmm*invMat[1,1] + Xmm*invMat[1,2] + Xmm*invMat[1,3] + invMat[1,4]; //Yvox := Ymm*invMat[2,1] + Ymm*invMat[2,2] + Ymm*invMat[2,3] + invMat[2,4]; //Zvox := Zmm*invMat[3,1] + Zmm*invMat[3,2] + Zmm*invMat[3,3] + invMat[3,4]; if (Xvox < 0) or (Yvox < 0) or (Zvox < 0) then exit; if (Xvox >= (hdr.dim[1]-1)) or (Yvox >= (hdr.dim[2]-1)) or (Zvox >= (hdr.dim[3]-1)) then exit; sliceVx := hdr.dim[1] * hdr.dim[2]; //voxels per slice if not isInterpolate then begin vx := round(Xvox) + round(Yvox) * hdr.dim[1] + round(Zvox) * sliceVx; result := img[vx]; exit; end; Xfrac1 := frac(Xvox); Yfrac1 := frac(Yvox); Zfrac1 := frac(Zvox); Xfrac0 := 1 - Xfrac1; Yfrac0 := 1 - Yfrac1; Zfrac0 := 1 - Zfrac1; vx := trunc(Xvox) + trunc(Yvox) * hdr.dim[1] + trunc(Zvox) * sliceVx; weight := Xfrac0 * Yfrac0 * Zfrac0 * notZero(img[vx]) + Xfrac1 * Yfrac0 * Zfrac0 * notZero(img[vx+1]) + Xfrac0 * Yfrac1 * Zfrac0 * notZero(img[vx+hdr.dim[1]]) + Xfrac1 * Yfrac1 * Zfrac0 * notZero(img[vx+1+hdr.dim[1]]) + Xfrac0 * Yfrac0 * Zfrac1 * notZero(img[vx+sliceVx]) + Xfrac1 * Yfrac0 * Zfrac1 * notZero(img[vx+1+sliceVx]) + Xfrac0 * Yfrac1 * Zfrac1 * notZero(img[vx+hdr.dim[1]+sliceVx]) + Xfrac1 * Yfrac1 * Zfrac1 * notZero(img[vx+1+hdr.dim[1]+sliceVx]); if weight = 0 then begin //all zeros result := 0; exit; end; result := Xfrac0 * Yfrac0 * Zfrac0 * img[vx] + Xfrac1 * Yfrac0 * Zfrac0 * img[vx+1] + Xfrac0 * Yfrac1 * Zfrac0 * img[vx+hdr.dim[1]] + Xfrac1 * Yfrac1 * Zfrac0 * img[vx+1+hdr.dim[1]] + Xfrac0 * Yfrac0 * Zfrac1 * img[vx+sliceVx] + Xfrac1 * Yfrac0 * Zfrac1 * img[vx+1+sliceVx] + Xfrac0 * Yfrac1 * Zfrac1 * img[vx+hdr.dim[1]+sliceVx] + Xfrac1 * Yfrac1 * Zfrac1 * img[vx+1+hdr.dim[1]+sliceVx]; result := result / weight; //exclude influence of zero values (e.g. NaN voxels) end; procedure TNIfTI.setMatrix; begin mat[1,1] := Hdr.srow_x[0]; mat[1,2] := hdr.srow_x[1]; mat[1,3] := hdr.srow_x[2]; mat[1,4] := hdr.srow_x[3]; mat[2,1] := hdr.srow_y[0]; mat[2,2] := hdr.srow_y[1]; mat[2,3] := hdr.srow_y[2]; mat[2,4] := hdr.srow_y[3]; mat[3,1] := hdr.srow_z[0]; mat[3,2] := hdr.srow_z[1]; mat[3,3] := hdr.srow_z[2]; mat[3,4] := hdr.srow_z[3]; mat[4,1] := 0; mat[4,2] := 0; mat[4,3] := 0; mat[4,4] := 1; if (Hdr.sform_code <= kNIFTI_XFORM_UNKNOWN) or (Hdr.sform_code > kNIFTI_XFORM_MNI_152) then begin //use quaternion if (Hdr.qform_code > kNIFTI_XFORM_UNKNOWN) and (Hdr.qform_code <= kNIFTI_XFORM_MNI_152) then begin nifti_quatern_to_mat44(mat, Hdr.quatern_b,Hdr.quatern_c,Hdr.quatern_d, Hdr.qoffset_x,Hdr.qoffset_y,Hdr.qoffset_z, Hdr.pixdim[1],Hdr.pixdim[2],Hdr.pixdim[3], Hdr.pixdim[0]); end; end; invMat := invertMatrixF(mat); end; procedure Xswap4r ( var s:single); type swaptype = packed record case byte of 0:(Word1,Word2 : word); //word is 16 bit end; swaptypep = ^swaptype; var inguy:swaptypep; outguy:swaptype; begin inguy := @s; //assign address of s to inguy outguy.Word1 := swap(inguy^.Word2); outguy.Word2 := swap(inguy^.Word1); inguy^.Word1 := outguy.Word1; inguy^.Word2 := outguy.Word2; end; procedure swap4(var s : LongInt); type swaptype = packed record case byte of 0:(Word1,Word2 : word); //word is 16 bit 1:(Long:LongInt); end; swaptypep = ^swaptype; var inguy:swaptypep; outguy:swaptype; begin inguy := @s; //assign address of s to inguy outguy.Word1 := swap(inguy^.Word2); outguy.Word2 := swap(inguy^.Word1); s:=outguy.Long; end; function swapDouble(s : double):double; type swaptype = packed record case byte of 0:(Word1,Word2,Word3,Word4 : word); //word is 16 bit 1:(float:double); end; swaptypep = ^swaptype; var inguy:swaptypep; outguy:swaptype; begin inguy := @s; //assign address of s to inguy outguy.Word1 := swap(inguy^.Word4); outguy.Word2 := swap(inguy^.Word3); outguy.Word3 := swap(inguy^.Word2); outguy.Word4 := swap(inguy^.Word1); try result:=outguy.float; except result := 0; exit; end; end; //func swap8r constructor TNIFTI.Create; begin isZeroMasked := false; isBinary := false; isLoad4D := false; setlength(img,0); // end; // Create() function Swap2(s : SmallInt): smallint; type swaptype = packed record case byte of 0:(Word1 : word); //word is 16 bit 1:(Small1: SmallInt); end; swaptypep = ^swaptype; var inguy:swaptypep; outguy:swaptype; begin inguy := @s; //assign address of s to inguy outguy.Word1 := swap(inguy^.Word1); result :=outguy.Small1; end; procedure NIFTIhdr_SwapBytes (var lAHdr: TNIFTIhdr); //Swap Byte order for the Analyze type var lInc: integer; begin with lAHdr do begin swap4(hdrsz); swap4(extents); session_error := swap2(session_error); for lInc := 0 to 7 do dim[lInc] := swap2(dim[lInc]);//666 Xswap4r(intent_p1); Xswap4r(intent_p2); Xswap4r(intent_p3); intent_code:= swap2(intent_code); datatype:= swap2(datatype); bitpix := swap2(bitpix); slice_start:= swap2(slice_start); for lInc := 0 to 7 do Xswap4r(pixdim[linc]); Xswap4r(vox_offset); {roi scale = 1} Xswap4r(scl_slope); Xswap4r(scl_inter); slice_end := swap2(slice_end); Xswap4r(cal_max); Xswap4r(cal_min); Xswap4r(slice_duration); Xswap4r(toffset); swap4(glmax); swap4(glmin); qform_code := swap2(qform_code); sform_code:= swap2(sform_code); Xswap4r(quatern_b); Xswap4r(quatern_c); Xswap4r(quatern_d); Xswap4r(qoffset_x); Xswap4r(qoffset_y); Xswap4r(qoffset_z); for lInc := 0 to 3 do //alpha Xswap4r(srow_x[lInc]); for lInc := 0 to 3 do //alpha Xswap4r(srow_y[lInc]); for lInc := 0 to 3 do //alpha Xswap4r(srow_z[lInc]); end; //with NIFTIhdr end; //proc NIFTIhdr_SwapBytes function ReadHdrGz(const FileName: string): TNIfTIhdr; var decomp: TGZFileStream; begin decomp := TGZFileStream.create(FileName, gzopenread); decomp.Read(result, sizeof(TNIfTIhdr)); decomp.free; end; function ReadHdr(const FileName: string): TNIfTIhdr; var f: File; begin FileMode := fmOpenRead; AssignFile(f, FileName); FileMode := fmOpenRead; Reset(f,1); blockread(f, result, sizeof(TNIfTIhdr) ); //since these files do not have a file extension, check first 8 bytes "0xFFFFFE creat" CloseFile(f); end; function Nifti2to1(h2 : TNIFTI2hdr): TNIFTIhdr; type tmagic = packed record case byte of 0:(b1,b2,b3,b4 : ansichar); //word is 16 bit 1:(l: longint); end; var h1 : TNIFTIhdr; i: integer; magic: tmagic; begin NII_Clear(h1); magic.b1 := h2.magic[1]; magic.b2 := h2.magic[2]; magic.b3 := h2.magic[3]; magic.b4 := h2.magic[4]; h1.magic := magic.l; h1.dim_info := h2.dim_info; //MRI slice order for i := 0 to 7 do h1.dim[i] := h2.dim[i]; h1.intent_p1 := h2.intent_p1; h1.intent_p2 := h2.intent_p2; h1.intent_p3 := h2.intent_p3; h1.intent_code := h2.intent_code; if (h2.intent_code >= 3000) and (h2.intent_code <= 3012) then begin //https://www.nitrc.org/forum/attachment.php?attachid=342&group_id=454&forum_id=1955 showmessage('NIfTI2 image has CIfTI intent code ('+inttostr(h2.intent_code)+'): open as an overlay with Surfice'); end; h1.datatype := h2.datatype; h1.bitpix := h2.bitpix; h1.slice_start := h2.slice_start; for i := 0 to 7 do h1.pixdim[i] := h2.pixdim[i]; h1.vox_offset := h2.vox_offset; h1.scl_slope := h2.scl_slope; h1.slice_end := h2.slice_end; h1.slice_code := h2.slice_code; //e.g. ascending h1.cal_min:= h2.cal_min; h1.cal_max:= h2.cal_max; h1.xyzt_units := h2.xyzt_units; //e.g. mm and sec h1.slice_duration := h2.slice_duration; //time for one slice h1.toffset := h2.toffset; //time axis to shift for i := 1 to 80 do h1.descrip[i] := h2.descrip[i]; for i := 1 to 24 do h1.aux_file[i] := h2.aux_file[i]; h1.qform_code := h2.qform_code; h1.sform_code := h2.sform_code; h1.quatern_b := h2.quatern_b; h1.quatern_c := h2.quatern_c; h1.quatern_d := h2.quatern_d; h1.qoffset_x := h2.qoffset_x; h1.qoffset_y := h2.qoffset_y; h1.qoffset_z := h2.qoffset_z; for i := 0 to 3 do begin h1.srow_x[i] := h2.srow_x[i]; h1.srow_y[i] := h2.srow_y[i]; h1.srow_z[i] := h2.srow_z[i]; end; for i := 1 to 16 do h1.intent_name[i] := h2.intent_name[i]; h1.HdrSz := 348; result := h1; end; function ReadHdr2Gz(const FileName: string; var xDim64: int64): TNIfTIhdr; var decomp: TGZFileStream; h2: TNIFTI2hdr; begin decomp := TGZFileStream.create(FileName, gzopenread); decomp.Read(h2, sizeof(TNIFTI2hdr)); decomp.free; xDim64 := h2.Dim[1]; result := Nifti2to1(h2); end; function ReadHdr2(const FileName: string; var xDim64: int64): TNIfTIhdr; var f: File; h2: TNIFTI2hdr; begin FileMode := fmOpenRead; AssignFile(f, FileName); FileMode := fmOpenRead; Reset(f,1); blockread(f, h2, sizeof(TNIFTI2hdr) ); //since these files do not have a file extension, check first 8 bytes "0xFFFFFE creat" CloseFile(f); xDim64 := h2.Dim[1]; result := Nifti2to1(h2); end; function FixDataType (var lHdr: TNIFTIhdr): boolean; var ldatatypebpp: integer; begin result := true; //lbitpix := lHdr.bitpix; case lHdr.datatype of kDT_BINARY : ldatatypebpp := 1; kDT_UNSIGNED_CHAR : ldatatypebpp := 8; // unsigned char (8 bits/voxel) kDT_SIGNED_SHORT : ldatatypebpp := 16; // signed short (16 bits/voxel) kDT_SIGNED_INT : ldatatypebpp := 32; // signed int (32 bits/voxel) kDT_FLOAT : ldatatypebpp := 32; // float (32 bits/voxel) kDT_COMPLEX : ldatatypebpp := 64; // complex (64 bits/voxel) kDT_DOUBLE : ldatatypebpp := 64; // double (64 bits/voxel) kDT_RGB : ldatatypebpp := 24; // RGB triple (24 bits/voxel) kDT_INT8 : ldatatypebpp := 8; // signed char (8 bits) kDT_UINT16 : ldatatypebpp := 16; // unsigned short (16 bits) kDT_UINT32 : ldatatypebpp := 32; // unsigned int (32 bits) kDT_INT64 : ldatatypebpp := 64; // long long (64 bits) kDT_UINT64 : ldatatypebpp := 64; // unsigned long long (64 bits) kDT_FLOAT128 : ldatatypebpp := 128; // long double (128 bits) kDT_COMPLEX128 : ldatatypebpp := 128; // double pair (128 bits) kDT_COMPLEX256 : ldatatypebpp := 256; // long double pair (256 bits) else ldatatypebpp := 0; end; if (ldatatypebpp = lHdr.bitpix) and (ldatatypebpp <> 0) then exit; //all OK //showmessage(inttostr(ldatatypebpp)); if (ldatatypebpp <> 0) then begin //use bitpix from datatype... lHdr.bitpix := ldatatypebpp; exit; end; showmessage('Corrupt NIfTI header'); result := false; end; Type WordP = array of Word; SingleP = array of Single; DoubleP = array of Double; function TNIFTI.ImgRawToSingle(imgBytes: TImgRaw; isSwap: boolean): boolean; var i, nVox: integer; l16Buf : WordP; l32Buf : singleP; l64Buf : doubleP; begin result := false; nVox:= hdr.dim[1] * hdr.dim[2] * hdr.dim[3] * hdr.dim[4]; setlength(img, nVox); if hdr.bitpix = 8 then begin for i := 0 to (nVox -1) do img[i] := imgBytes[i] end else if hdr.bitpix = 16 then begin l16Buf := WordP(imgBytes ); if isSwap then for i := 0 to (nVox -1) do l16Buf[i] := swap(l16Buf[i]); if hdr.datatype = kDT_UINT16 then begin for i := 0 to (nVox -1) do img[i] := l16Buf[i]; end else begin for i := 0 to (nVox -1) do img[i] := smallint(l16Buf[i]); end; end else if hdr.bitpix = 32 then begin l32Buf := SingleP(imgBytes ); if isSwap then for i := 0 to (nVox -1) do Xswap4r (l32Buf[i]); if hdr.datatype = kDT_INT32 then begin for i := 0 to (nVox -1) do img[i] := longint(l32Buf[i]); end else begin //assume kDT_FLOAT for i := 0 to (nVox -1) do img[i] := l32Buf[i]; end; end else if hdr.bitpix = 64 then begin l64Buf := DoubleP(imgBytes ); if isSwap then for i := 0 to (nVox -1) do l64Buf[i] := SwapDouble(l64Buf[i]); for i := 0 to (nVox -1) do img[i] := l64Buf[i]; end else exit;//Showmessage('Unsupported NIfTI datatype '+inttostr(hdr.bitpix)+'bpp'); for i := 0 to (nVox -1) do //remove NaN if SpecialSingle(img[i]) then img[i] := 0; if (hdr.scl_slope = 0) or SpecialSingle(hdr.scl_slope) then hdr.scl_slope := 1; for i := 0 to (nVox -1) do //remove NaN img[i] := (img[i] * hdr.scl_slope) + hdr.scl_inter; result := true; end; //readForeignHeader (var lFilename: string; var lHdr: TNIFTIhdr; var gzBytes: int64; var swapEndian: boolean): boolean; // K_gzBytes_headerAndImageCompressed = -2; // K_gzBytes_onlyImageCompressed= -1; // K_gzBytes_headerAndImageUncompressed= 0; function TNIFTI.readImg(const FileName: string; isSwap: boolean; gzFlag: int64): boolean; //read first volume const k0 : single = 0.0; k1 : single = 1.0; var f: File; i,nVol, nVox, nByte: integer; decomp: TGZFileStream; imgBytes: array of byte; begin result := false; nVol := 1; if isLoad4D then begin for i := 4 to 7 do if hdr.dim[i] > 1 then nVol := nVol * hdr.dim[i]; end; hdr.dim[4] := nVol; nVox := hdr.dim[1] * hdr.dim[2] * hdr.dim[3] * hdr.dim[4]; if nVox < 1 then exit; nByte := nVox * (hdr.bitpix div 8); if gzFlag = K_gzBytes_headerAndImageCompressed then begin decomp := TGZFileStream.create(FileName, gzopenread); setlength(imgBytes, round(hdr.vox_offset)); decomp.Read(imgBytes[0], round(hdr.vox_offset)); setlength(imgBytes, nByte); decomp.Read(imgBytes[0], nByte); decomp.free; end else if gzFlag = K_gzBytes_headerAndImageUncompressed then begin setlength(imgBytes, nByte); AssignFile(f, FileName); FileMode := fmOpenRead; Reset(f,1); Seek(f,round(hdr.vox_offset)); BlockRead(f, imgBytes[0],nByte); CloseFile(f); end else begin showmessage('Unable to read compressed images with uncompressed headers!'); exit; end; if not ImgRawToSingle(imgBytes, isSwap) then exit; isBinary := true; //nVox:= hdr.dim[1] * hdr.dim[2] * hdr.dim[3] * hdr.dim[4]; i := 0; while (i < nVox) and (isBinary) do begin if (img[i] <> k0) and (img[i] <> k1) then isBinary := false; i := i + 1; end; result := true; end; procedure TNIFTI.SetDescriptives; var i, numZero: integer; begin isZeroMasked:= false; numZero := 0; if length(img) < 1 then exit; maxInten := img[0]; minInten := maxInten; for i := 0 to (length(img) - 1) do begin if img[i] > maxInten then maxInten := img[i]; if img[i] < minInten then minInten := img[i]; if img[i] = 0 then inc(numZero); end; //showmessage(floattostr(numZero/length(img)) ); isZeroMasked := (numZero/length(img)) > 0.75; end; // SetDescriptives() procedure SmoothFWHM2Vox (var lImg: TImgScaled; lXi,lYi,lZi: integer); const k0=0.45;//weight of center voxel k1=0.225;//weight of nearest neighbors k2=0.05;//weight of subsequent neighbors kWid = 2; //we will look +/- 2 voxels from center var lyPos,lPos,lX,lY,lZ,lXi2,lXY,lXY2: integer; lTemp: TImgScaled; begin if (lXi < 5) or (lYi < 5) or (lZi < 5) then exit; lXY := lXi*lYi; //offset one slice lXY2 := lXY * 2; //offset two slices lXi2 := lXi*2;//offset to voxel two lines above or below setlength(lTemp,lXi*lYi*lZi); lTemp := Copy(lImg, Low(lImg), Length(lImg)); //smooth horizontally for lZ := 0 to (lZi-1) do begin for lY := (0) to (lYi-1) do begin lyPos := (lY*lXi) + (lZ*lXY) ; for lX := (kWid) to (lXi-kWid-1) do begin lPos := lyPos + lX; lTemp[lPos] := lImg[lPos-2]*k2+lImg[lPos-1]*k1 +lImg[lPos]*k0 +lImg[lPos+1]*k1+lImg[lPos+2]*k2; end; {lX} end; {lY} end; //lZi //smooth vertically lImg := Copy(lTemp, Low(lTemp), Length(lTemp)); for lZ := 0 to (lZi-1) do begin for lX := 0 to (lXi-1) do begin for lY := (kWid) to (lYi-kWid-1) do begin lPos := (lY*lXi) + lX + (lZ*lXY) ; lImg[lPos] := lTemp[lPos-lXi2]*k2+lTemp[lPos-lXi]*k1 +lTemp[lPos]*k0 +lTemp[lPos+lXi]*k1+lTemp[lPos+lXi2]*k2; end; {lX} end; //lY end; //lZ //if between slices... lTemp := Copy(lImg, Low(lImg), Length(lImg)); for lZ := (kWid) to (lZi-kWid-1) do begin for lY := 0 to (lYi-1) do begin lyPos := (lY*lXi) + (lZ*lXY) ; for lX := 0 to (lXi-1) do begin lPos := lyPos + lX; lTemp[lPos] := lImg[lPos-lXY2]*k2+lImg[lPos-lXY]*k1 +lImg[lPos]*k0 +lImg[lPos+lXY]*k1+lImg[lPos+lXY2]*k2; end; {lX} end; {lY} end; //lZi lImg := Copy(lTemp, Low(lTemp), Length(lTemp)); SetLength(lTemp,0); end; procedure SmoothFWHM2VoxIgnoreZeros (var lImg: TImgScaled; lXi,lYi,lZi: integer); //blur data, but do not allow zeros to influence values (e.g. brain mask) var lTemp01: TImgScaled; i: integer; begin setlength(lTemp01, Length(lImg)); for i := 0 to (length(lImg)-1) do begin if lImg[i] = 0 then lTemp01[i] := 0 else lTemp01[i] := 1; end; SmoothFWHM2Vox(lTemp01, lXi,lYi,lZi); SmoothFWHM2Vox(lImg, lXi,lYi,lZi); for i := 0 to (length(lImg)-1) do if lTemp01[i] <> 0 then lImg[i] := lImg[i]/lTemp01[i]; end; //function readVoxHeader (var fname: string; var nhdr: TNIFTIhdr; var gzBytes: int64; var swapEndian: boolean; var xDim64: int64): boolean; function readVoxHeader (var fname: string; var nhdr: TNIFTIhdr; var gzBytes: int64; var swapEndian: boolean; var xDim64: int64): boolean; var ext, hdrName, imgName: string; isDimPermute2341: boolean = false; begin result := false; swapEndian := false; //assume native endian gzBytes := K_gzBytes_headerAndImageUncompressed; if not FileExists(fname) then exit; ext := UpperCase(ExtractFileExt(fname)); imgName := fname; hdrName := fname; if (ext = '.GZ') then begin nhdr := ReadHdrGz(fname); xDim64 := nhdr.Dim[1]; gzBytes := K_gzBytes_headerAndImageCompressed; end else if ((ext = '.NII') or (ext = '.HDR') or (ext = '.IMG')) then begin if (ext = '.IMG') then hdrName := ChangeFileExt(fname, '.hdr') else if ext = '.HDR' then imgName := ChangeFileExt(fname, '.img'); nhdr := ReadHdr(hdrName); xDim64 := nhdr.Dim[1]; end else begin if not readForeignHeader (imgName, nhdr, gzBytes, swapEndian, isDimPermute2341, xDim64) then exit; end; //NIfTI2 if (nhdr.HdrSz = SizeOf (TNIFTI2hdr)) then begin if (ext = '.GZ') then nhdr := ReadHdr2Gz(fname, xDim64) else nhdr := ReadHdr2(fname, xDim64); end; if sizeof(TNIfTIhdr) <> nhdr.HdrSz then begin NIFTIhdr_SwapBytes(nhdr); if (nhdr.HdrSz = SizeOf (TNIFTI2hdr)) then begin {$IFDEF ENDIAN_LITTLE} showmessage('Unable to read big-endian NIfTI 2 headers.'); {$ELSE} showmessage('Unable to read little-endian NIfTI 2 headers.'); {$ENDIF} end; swapEndian := true; xDim64 := nhdr.Dim[1]; end; if sizeof(TNIfTIhdr) <> nhdr.HdrSz then exit; //not a valid nifti header if not FixDataType (nhdr) then exit; result := true; end; procedure printf(s: string); begin {$IFDEF UNIX}writeln(s);{$ENDIF} end; function TNIFTI.LoadFromFile(const FileName: string; smoothMethod: integer): boolean; //smoothMethod is one of kNiftiSmooth... options var ext, hdrName, imgName: string; gzFlag, xDim64 : int64; isSwap: boolean; begin (*result := false; isSwap := false; //assume native endian gzFlag := K_gzBytes_headerAndImageUncompressed; if not FileExists(FileName) then exit; ext := UpperCase(ExtractFileExt(Filename)); imgName := Filename; hdrName := Filename; if (ext = '.GZ') then begin hdr := ReadHdrGz(FileName); gzFlag := K_gzBytes_headerAndImageCompressed; end else if ((ext = '.NII') or (ext = '.HDR') or (ext = '.IMG')) then begin if (ext = '.IMG') then hdrName := ChangeFileExt(FileName, '.hdr') else if ext = '.HDR' then imgName := ChangeFileExt(FileName, '.img'); hdr := ReadHdr(hdrName); end else begin {$IFDEF FOREIGNVOL} if not readForeignHeader (imgName, hdr, gzFlag, isSwap) then exit; {$ELSE} exit; {$ENDIF} end; if (hdr.HdrSz = SizeOf (TNIFTI2hdr)) then begin if (ext = '.GZ') then hdr := ReadHdr2Gz(FileName, xDim64) else hdr := ReadHdr2(FileName, xDim64); end; if sizeof(TNIfTIhdr) <> hdr.HdrSz then begin NIFTIhdr_SwapBytes(hdr); if (hdr.HdrSz = SizeOf (TNIFTI2hdr)) then begin {$IFDEF ENDIAN_LITTLE} showmessage('Unable to read big-endian NIfTI 2 headers.'); {$ELSE} showmessage('Unable to read little-endian NIfTI 2 headers.'); {$ENDIF} end; isSwap := true; end; if sizeof(TNIfTIhdr) <> hdr.HdrSz then exit; //not a valid nifti header if not FixDataType (hdr) then exit; *) imgName := FileName; if not readVoxHeader (imgName, hdr, gzFlag, isSwap, xDim64) then begin printf(format('Unable to load as voxelwise data: %s', [FileName])); exit(false); end; printf(format('Voxel dimensions %d %d %d', [hdr.dim[1],hdr.dim[2],hdr.dim[3]])); if (hdr.dim[1] < 2) or (hdr.dim[2] < 2) or (hdr.dim[3] < 2) then begin printf(format('Not a 3D voxel-based image: %s', [FileName])); exit(false); end; if not ReadImg(imgName, isSwap, gzFlag) then exit(false); setMatrix; if smoothMethod = kNiftiSmoothMaskZero then SmoothFWHM2VoxIgnoreZeros (img, hdr.dim[1],hdr.dim[2],hdr.dim[3]) else if smoothMethod = kNiftiSmooth then SmoothFWHM2Vox (img, hdr.dim[1],hdr.dim[2],hdr.dim[3]); //else kNiftiSmoothNone <- no smoothing SetDescriptives; result := true; end; procedure TNIFTI.SmoothMaskZero; begin if (length(img) < 9) or (hdr.dim[1] < 3) or (hdr.dim[2] < 3) or (hdr.dim[3] < 3) then exit; SmoothFWHM2VoxIgnoreZeros (img, hdr.dim[1],hdr.dim[2],hdr.dim[3]) ; end; procedure TNIFTI.Smooth; begin if (length(img) < 9) or (hdr.dim[1] < 3) or (hdr.dim[2] < 3) or (hdr.dim[3] < 3) then exit; SmoothFWHM2Vox (img, hdr.dim[1],hdr.dim[2],hdr.dim[3]); end; procedure TNIFTI.Close; begin setlength(img,0); end; destructor TNIFTI.Destroy; begin Close; inherited; end; end.
unit UHelp; interface uses UIState, Vcl.Forms, Vcl.StdCtrls; type THelp1 = class(TInterfacedObject, IState) private label2: Tlabel; label3: Tlabel; published constructor create(AOwner: TForm); public procedure destroy; end; implementation { Menu } constructor THelp1.create(AOwner: TForm); begin // руководитель label2 := Tlabel.create(AOwner); Label2.Font.Height:=-11; Label2.Font.Name:='Tahoma'; label2.Left:=504; Label2.Top:=360; label2.Parent := AOwner; label2.caption := 'Руководитель: Герасимова М.М.'; //разработчик label3 := Tlabel.create(AOwner); Label3.Font.Height:=-11; Label3.Font.Name:='Tahoma'; Label3.Left:=504; Label3.Top:=400; label3.Parent := AOwner; label3.caption := 'Разработчик: Любезнов И.А'; end; procedure THelp1.destroy; begin label2.Free; label3.Free; end; end.
unit Credit_AE; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxMaskEdit, cxDropDownEdit, cxCalendar, cxContainer, cxEdit, cxTextEdit, cxControls, cxGroupBox, cxCurrencyEdit, ibase, cn_Common_Funcs, cxCheckBox, ActnList, cnConsts, cxButtonEdit, cn_Common_Messages, cn_Common_Types, cn_Common_Loader; type TfrmCredit_AE = class(TForm) cxGroupBox1: TcxGroupBox; Date_Create_Label: TLabel; Num_Doc_Label: TLabel; DateStartCalc_Label: TLabel; Date_Credit_Label: TLabel; lblNote_Label: TLabel; Num_Credit_Edit: TcxTextEdit; Date_Create_Edit: TcxDateEdit; DateStartCalc_Edit: TcxDateEdit; Date_Credit_Edit: TcxDateEdit; Note_Edit: TcxTextEdit; OKButton: TcxButton; CancelButton: TcxButton; SummaLabel: TLabel; SummaEdit: TcxCurrencyEdit; Customer_Label: TLabel; Customer_Edit: TcxTextEdit; lblLimitSum: TLabel; LimitSum_Edit: TcxCurrencyEdit; lblLimitDog: TLabel; LimitDog_Edit: TcxCurrencyEdit; ckbxImagePriority: TcxCheckBox; ord_ae_Comments_Label: TLabel; ord_ae_Comments: TcxTextEdit; StatusEdit: TcxButtonEdit; lblStatus: TLabel; procedure OKButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure act1Execute(Sender: TObject); procedure Num_Credit_EditKeyPress(Sender: TObject; var Key: Char); procedure Date_Create_EditKeyPress(Sender: TObject; var Key: Char); procedure DateStartCalc_EditKeyPress(Sender: TObject; var Key: Char); procedure Date_Credit_EditKeyPress(Sender: TObject; var Key: Char); procedure SummaEditKeyPress(Sender: TObject; var Key: Char); procedure Note_EditKeyPress(Sender: TObject; var Key: Char); procedure Customer_EditKeyPress(Sender: TObject; var Key: Char); procedure LimitSum_EditKeyPress(Sender: TObject; var Key: Char); procedure LimitDog_EditKeyPress(Sender: TObject; var Key: Char); procedure ckbxImagePriorityKeyPress(Sender: TObject; var Key: Char); procedure ord_ae_CommentsKeyPress(Sender: TObject; var Key: Char); procedure TypeLg_EditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure StatusEditKeyPress(Sender: TObject; var Key: Char); private PLanguageIndex :byte; DB_Handle : TISC_DB_HANDLE; procedure FormIniLanguage(); public Id_Status: Int64; constructor Create(Owner: TComponent ; LangIndex : byte; DBHandle: TISC_DB_HANDLE); reintroduce; end; implementation {$R *.dfm} constructor TfrmCredit_AE.Create(Owner: TComponent ; LangIndex : byte; DBHandle: TISC_DB_HANDLE); begin inherited Create(Owner); PLanguageIndex := LangIndex; FormIniLanguage(); DB_Handle:= DBHandle; end; procedure TfrmCredit_AE.FormIniLanguage(); begin // индекс языка (1-укр, 2 - рус) Num_Doc_Label.Caption := cn_FiltrByNum[PLanguageIndex]; Date_Create_Label.Caption := cn_Stamp[PLanguageIndex]; DateStartCalc_Label.Caption := cn_grid_Date_Beg[PLanguageIndex]; Date_Credit_Label.Caption := cn_Date_Opl_Column[PLanguageIndex]; SummaLabel.Caption := cn_Summa_Column[PLanguageIndex]; lblNote_Label.Caption := cn_CreditNote[PLanguageIndex]; Customer_Label.Caption := cn_CreditBank[PLanguageIndex]; lblLimitSum.Caption := cn_LimitSum[PLanguageIndex]; lblLimitDog.Caption := cn_LimitDogs[PLanguageIndex]; ckbxImagePriority.Properties.Caption := cn_CreditImage[PLanguageIndex]; ord_ae_Comments_Label.Caption := cnConsts.cn_CommentDiss[PLanguageIndex]; OKButton.Caption := cn_Accept[PLanguageIndex]; CancelButton.Caption := cn_Cancel[PLanguageIndex]; end; procedure TfrmCredit_AE.OKButtonClick(Sender: TObject); begin if CheckControls(self, PLanguageIndex) then exit; ModalResult:= mrOk; end; procedure TfrmCredit_AE.CancelButtonClick(Sender: TObject); begin Close; end; procedure TfrmCredit_AE.act1Execute(Sender: TObject); {var i: Integer; TabStopper: Integer; IsFocusStop: Boolean;} begin { TabStopper := -100; IsFocusStop := False; for i:=0 to ComponentCount-1 do if Components[i].ClassType <> TLabel then if Components[i].ClassType <> TAction then if Components[i].ClassType <> TActionList then if Components[i].ClassType <> TcxButton then if (Components[i] as TcxControl).IsFocused then begin TabStopper := (Components[i] as TcxControl).TabOrder; Break; end; if TabStopper <> -100 then for i:= 0 to ComponentCount-1 do begin if Components[i].ClassType <> TLabel then if Components[i].ClassType <> TAction then if Components[i].ClassType <> TActionList then if Components[i].ClassType <> TcxButton then if (Components[i] as TcxControl).TabOrder = TabStopper + 1 then begin (Components[i] as TcxControl).SetFocus; IsFocusStop:= True; Break; end; end; if not IsFocusStop then for i:= 0 to ComponentCount-1 do begin if Components[i].ClassType = TcxButton then begin (Components[i] as TcxButton).SetFocus; Break; end; end;} end; procedure TfrmCredit_AE.Num_Credit_EditKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then Self.FindNextControl(Self.ActiveControl,True,true,False).SetFocus; end; procedure TfrmCredit_AE.Date_Create_EditKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then Self.FindNextControl(Self.ActiveControl,True,true,False).SetFocus; end; procedure TfrmCredit_AE.DateStartCalc_EditKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then Self.FindNextControl(Self.ActiveControl,True,true,False).SetFocus; end; procedure TfrmCredit_AE.Date_Credit_EditKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then Self.FindNextControl(Self.ActiveControl,True,true,False).SetFocus; end; procedure TfrmCredit_AE.SummaEditKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then Self.FindNextControl(Self.ActiveControl,True,true,False).SetFocus; end; procedure TfrmCredit_AE.Note_EditKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then Self.FindNextControl(Self.ActiveControl,True,true,False).SetFocus; end; procedure TfrmCredit_AE.Customer_EditKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then Self.FindNextControl(Self.ActiveControl,True,true,False).SetFocus; end; procedure TfrmCredit_AE.LimitSum_EditKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then Self.FindNextControl(Self.ActiveControl,True,true,False).SetFocus; end; procedure TfrmCredit_AE.LimitDog_EditKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then Self.FindNextControl(Self.ActiveControl,True,true,False).SetFocus; end; procedure TfrmCredit_AE.ckbxImagePriorityKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then Self.FindNextControl(Self.ActiveControl,True,true,False).SetFocus; end; procedure TfrmCredit_AE.ord_ae_CommentsKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then Self.FindNextControl(Self.ActiveControl,True,true,False).SetFocus; end; procedure TfrmCredit_AE.TypeLg_EditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var AParameter:TcnSimpleParams; res: Variant; begin AParameter:= TcnSimpleParams.Create; AParameter.Owner:=self; AParameter.Db_Handle:= DB_Handle; AParameter.Formstyle:=fsNormal; AParameter.WaitPakageOwner:=self; if Id_Status <> -1 then AParameter.ID_Locate := Id_Status; res:= RunFunctionFromPackage(AParameter, 'Contracts\cn_sp_CreditStatus.bpl','ShowSPCreditStatus'); if VarArrayDimCount(res)>0 then begin Id_Status := Res[0]; StatusEdit.Text := Res[1]; end; AParameter.Free; end; procedure TfrmCredit_AE.StatusEditKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then Self.FindNextControl(Self.ActiveControl,True,true,False).SetFocus; end; end.
unit BVE.SVGPrintPreviewVCL; // ------------------------------------------------------------------------------ // // SVG Control Package 2.0 // Copyright (c) 2015 Bruno Verhue // // ------------------------------------------------------------------------------ // The SVG Editor need at least version v2.40 update 9 of the SVG library {$Include ContextSettingsVCL.inc} {$IFDEF SVGDirect2d3D11} {$DEFINE SVGSupportsCmdList} {$ENDIF} {$IFDEF SVGGDIP} {$DEFINE SVGSupportsCmdList} {$ENDIF} interface uses Winapi.Windows, Winapi.Messages, System.Types, System.SysUtils, System.Classes, System.Generics.Collections, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.ExtCtrls, Vcl.Printers, BVE.SVG2Types, BVE.SVG2Intf, BVE.SVG2Elements, BVE.SVGToolVCL; type TSVGPrintUnits = (puMm, puCm, puInch, puPixel); TSVGPrintPreview = class(TCustomControl) private // Only one SVG can be printed, however, the SVG can be printer // over multiple pages FRoot: ISVGRoot; FViewportScale: TSVGFloat; FDPIX, FDPIY: Integer; FPrinterPageWidth: TSVGFLoat; FPrinterPageHeight: TSVGFLoat; FPxToPt: TSVGPoint; FPagesVertical: Integer; FPagesHorizontal: Integer; FPreviewPageMargin: Integer; FPreviewPageWidth: Integer; FPreviewPageHeight: Integer; FNeedRecreatePreview: Boolean; {$IFDEF SVGSupportsCmdList} FCmdList: ISVGRenderContextCmdList; {$ENDIF} FCmdListWidth: Integer; FCmdListHeight: Integer; FPrintUnits: TSVGPrintUnits; FMarginLeft: TSVGFloat; FMarginTop: TSVGFloat; FMarginRight: TSVGFloat; FMarginBottom: TSVGFloat; FAutoViewbox: Boolean; FAspectRatioAlign: TSVGAspectRatioAlign; FAspectRatioMeetOrSlice: TSVGAspectRatioMeetOrSlice; FGlueEdge: TSVGFloat; FPagePreviewList: TList<TBitmap>; function CalcRCUnits(const aValue, aDPI: TSVGFloat): TSVGFloat; procedure CalcPrinterDimensions; function CalcViewport: TSVGRect; function CalcViewportMatrix: TSVGMatrix; protected function GetPageCount: Integer; function GetPageViewBox(const aIndex: Integer): TSVGRect; procedure SetAutoViewbox(const Value: Boolean); procedure SetAspectRatioAlign(const Value: TSVGAspectRatioAlign); procedure SetAspectRatioMeetOrSlice( const Value: TSVGAspectRatioMeetOrSlice); procedure SetGlueEdge(const Value: TSVGFloat); procedure SetMarginBottom(const Value: TSVGFloat); procedure SetMarginLeft(const Value: TSVGFloat); procedure SetMarginRight(const Value: TSVGFloat); procedure SetMarginTop(const Value: TSVGFloat); procedure SetRoot(const Value: ISVGRoot); procedure SetPagesHorizontal(const Value: Integer); procedure SetPagesVertical(const Value: Integer); procedure SetPrintUnits(const Value: TSVGPrintUnits); procedure MarginsChange(aSender: TObject); procedure PagePreviewCalcSize; procedure PagePreviewListClear; procedure PagePreviewListCreate; {$IFDEF SVGSupportsCmdList} procedure RenderToCmdList; {$ENDIF} property PageViewbox[const aIndex: Integer]: TSVGRect read GetPageViewBox; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Print(const aPrintJobName: string); procedure Paint; override; procedure Repaint; override; procedure Resize; override; property AutoViewbox: Boolean read FAutoViewbox write SetAutoViewbox; property AspectRatioAlign: TSVGAspectRatioAlign read FAspectRatioAlign write SetAspectRatioAlign; property AspectRatioMeetOrSlice: TSVGAspectRatioMeetOrSlice read FAspectRatioMeetOrSlice write SetAspectRatioMeetOrSlice; property GlueEdge: TSVGFloat read FGlueEdge write SetGlueEdge; property MarginLeft: TSVGFloat read FMarginLeft write SetMarginLeft; property MarginTop: TSVGFloat read FMarginTop write SetMarginTop; property MarginRight: TSVGFloat read FMarginRight write SetMarginRight; property MarginBottom: TSVGFloat read FMarginBottom write SetMarginBottom; property PageCount: Integer read GetPageCount; property PagesHorizontal: Integer read FPagesHorizontal write SetPagesHorizontal; property PagesVertical: Integer read FPagesVertical write SetPagesVertical; property Root: ISVGRoot read FRoot write SetRoot; property Units: TSVGPrintUnits read FPrintUnits write SetPrintUnits; end; implementation uses BVE.SVG2GeomUtility, BVE.SVG2Context, BVE.SVG2Elements.VCL; { TSVGPrintPreview } function TSVGPrintPreview.CalcRCUnits(const aValue, aDPI: TSVGFloat): TSVGFloat; begin if TSVGRenderContextManager.RenderContextType = rcDirect2D then begin // Direct2D coords are in device independent pixels case FPrintUnits of puPixel: begin Result := 96 / aDPI * aValue; end; puMm: begin Result := 96 / 25.4 * aValue; end; puCm: begin Result := 96 / 2.54 * aValue; end; puInch: begin Result := 96 * aValue; end; else Result := aValue; end; end else begin // GDI+ coords are in pixels case FPrintUnits of puPixel: begin Result := aDPI / aDPI * aValue; end; puMm: begin Result := aDPI / 25.4 * aValue; end; puCm: begin Result := aDPI / 2.54 * aValue; end; puInch: begin Result := aValue * aDPI; end; else Result := aValue; end; end; end; procedure TSVGPrintPreview.CalcPrinterDimensions; begin FPrinterPageWidth := Printer.PageWidth; FPrinterPageHeight := Printer.PageHeight; FDPIX := GetDeviceCaps(Printer.Handle, LOGPIXELSX); FDPIY := GetDeviceCaps(Printer.Handle, LOGPIXELSY); if FDPIX = 0 then FDPIX := 96; if FDPIY = 0 then FDPIY := 96; FPxToPt := SVGPoint(FDPIX / 96, FDPIY / 96); if TSVGRenderContextManager.RenderContextType = rcDirect2D then begin // Printer.PageWidth and Printer.PageHeight are in pixels, we need to // convert them to points FPrinterPageWidth := FPrinterPageWidth / FPxToPt.X; FPrinterPageHeight := FPrinterPageHeight / FPxToPt.Y; FPxToPt := SVGPoint(1.0, 1.0); end; end; function TSVGPrintPreview.CalcViewport: TSVGRect; begin Result := SVGRect( CalcRCUnits(FMarginLeft, FDPIX), CalcRCUnits(FMarginTop, FDPIY), PagesHorizontal * FPrinterPageWidth - CalcRCUnits(FMarginRight, FDPIX) - CalcRCUnits(FGlueEdge, FDPIX) * (PagesHorizontal - 1), PagesVertical * FPrinterPageHeight - CalcRCUnits(FMarginBottom, FDPIX) - CalcRCUnits(FGlueEdge, FDPIY) * (PagesVertical - 1)); end; function TSVGPrintPreview.CalcViewportMatrix: TSVGMatrix; var Viewport, Viewbox: TSVGRect; begin if FAutoViewbox then begin // The size of the SVG ViewBox := SVGRect(0, 0, FCmdListWidth, FCmdListHeight); // The available area for the SVG ViewPort := CalcViewport; Result := CreateViewBoxMatrix( Viewport, ViewBox, FAspectRatioAlign, FAspectRatioMeetOrSlice); end else begin Result := TSVGMatrix.CreateTranslation( CalcRCUnits(FMarginLeft, FDPIX), CalcRCUnits(FMarginTop, FDPIY)); Result := TSVGMatrix.Multiply( Result, TSVGMatrix.CreateScaling(FPxToPt.X, FPxToPt.Y)); end; end; constructor TSVGPrintPreview.Create(AOwner: TComponent); begin inherited; FRoot := nil; FPagePreviewList := TList<TBitmap>.Create; FPreviewPageMargin := 10; FViewportScale := 1.0; FPagesHorizontal := 1; FPagesVertical := 1; FPrintUnits := puMM; FMarginLeft := 0; FMarginTop := 0; FMarginRight := 0; FMarginBottom := 0; FGlueEdge := 0; FAutoViewbox := False; FAspectRatioAlign := TSVGAspectRatioAlign.arXMidYMid; FAspectRatioMeetOrSlice := TSVGAspectRatioMeetOrSlice.arMeet; FNeedRecreatePreview := False; end; destructor TSVGPrintPreview.Destroy; begin PagePreviewListClear; FPagePreviewList.Free; inherited; end; function TSVGPrintPreview.GetPageCount: Integer; begin Result := PagesHorizontal * PagesVertical; end; function TSVGPrintPreview.GetPageViewBox(const aIndex: Integer): TSVGRect; var L, T, W, H: TSVGFloat; R, C: Integer; begin Result := TSVGRect.CreateUndefined; if aIndex < PageCount then begin R := aIndex div PagesHorizontal; C := aIndex mod PagesHorizontal; W := FPrinterPageWidth; H := FPrinterPageHeight; L := C * (W - CalcRCUnits(FGlueEdge, FDPIX)); T := R * (H - CalcRCUnits(FGlueEdge, FDPIY)); if C < PagesHorizontal - 1 then W := W - CalcRCUnits(FGlueEdge, FDPIX); if R < PagesVertical - 1 then H := H - CalcRCUnits(FGlueEdge, FDPIY); Result := SVGRect(L, T, L + W, T + H); end; end; procedure TSVGPrintPreview.MarginsChange(aSender: TObject); begin FNeedRecreatePreview := True; Invalidate; end; procedure TSVGPrintPreview.PagePreviewCalcSize; var M: TSVGMatrix; Viewport, Viewbox, R: TSVGRect; begin if (PagesHorizontal <= 0) and (PagesVertical <= 0) then begin FPreviewPageWidth := 0; FPreviewPageHeight := 0; end; // Available space in client area for one page Viewport := SVGRect( 0, 0, Round((ClientWidth - (PagesHorizontal + 1) * FPreviewPageMargin) / PagesHorizontal), Round((ClientHeight - (PagesVertical + 1) * FPreviewPageMargin) / PagesVertical)); // Spcae needed for one page Viewbox := SVGRect( 0, 0, FPrinterPageWidth, FPrinterPageHeight); // Calculate the scale factor M := CreateViewBoxMatrix( Viewport, ViewBox, TSVGAspectRatioAlign.arXMidYMid, TSVGAspectRatioMeetOrSlice.arMeet); FViewportScale := M.m11; R := TransformRect(ViewBox, M); FPreviewPageWidth := Round(R.Width); FPreviewPageHeight := Round(R.Height); end; procedure TSVGPrintPreview.PagePreviewListClear; begin while FPagePreviewList.Count > 0 do begin FPagePreviewList[0].Free; FPagePreviewList.Delete(0); end; end; procedure TSVGPrintPreview.PagePreviewListCreate; var i, Count: Integer; R: TSVGRect; Viewport: TSVGRect; Bitmap: TBitmap; RC: ISVGRenderContext; M, MV: TSVGMatrix; begin FNeedRecreatePreview := False; CalcPrinterDimensions; PagePreviewListClear; {$IFDEF SVGSupportsCmdList} if not assigned(FCmdList) then Exit; {$ENDIF} PagePreviewCalcSize; Count := PageCount; M := CalcViewportMatrix; ViewPort := CalcViewport; for i := 0 to Count - 1 do begin R := PageViewbox[i]; MV := TSVGMatrix.Multiply( TSVGMatrix.CreateTranslation(-R.Left, -R.Top), TSVGMatrix.CreateScaling(FViewportScale, FViewportScale)); Bitmap := TSVGRenderContextManager.CreateCompatibleBitmap(FPreviewPageWidth, FPreviewPageHeight); FPagePreviewList.Add(Bitmap); RC := TSVGRenderContextManager.CreateRenderContextBitmap(Bitmap); RC.BeginScene; try RC.Clear(SVGColorWhite); RC.PushClipRect( TSVGRect.Intersect( TransformRect(Viewport, MV), TransformRect(R, MV) ) ); try // Draw margins RC.ApplyStroke(TSVGSolidBrush.Create(SVGColorGray), 1); RC.DrawRect(TransformRect(ViewPort, MV)); RC.Matrix := TSVGMatrix.Multiply(RC.Matrix, M); RC.Matrix := TSVGMatrix.Multiply(RC.Matrix, MV); // Draw SVG {$IFDEF SVGSupportsCmdList} RC.DrawCmdList(FCmdList, SVGRect(0, 0, FCmdListWidth, FCmdListHeight)); {$ELSE} SVGRenderToRenderContext( FRoot, RC, FCmdListWidth, FCmdListHeight, [sroFilters, sroClippath], False); {$ENDIF} finally RC.PopClipRect; end; finally RC.EndScene; end; end; end; procedure TSVGPrintPreview.Paint; var i: Integer; X, Y: Integer; begin inherited; if FNeedRecreatePreview then PagePreviewListCreate; Canvas.Brush.Color := clGray; Canvas.Brush.Style := bsSolid; Canvas.FillRect(ClientRect); for i := 0 to FPagePreviewList.Count - 1 do begin X := FPreviewPageMargin + (i mod PagesHorizontal) * (FPreviewPageWidth + FPreviewPageMargin); Y := FPreviewPageMargin + (i div PagesHorizontal) * (FPreviewPageHeight + FPreviewPageMargin); Canvas.Draw(X, Y, FPagePreviewList[i]); end; end; procedure TSVGPrintPreview.Print(const aPrintJobName: string); var i, Count: Integer; R: TSVGRect; Viewport: TSVGRect; PrintJob: ISVGPrintJob; RC: ISVGRenderContext; M, MV: TSVGMatrix; begin CalcPrinterDimensions; {$IFDEF SVGSupportsCmdList} if not assigned(FCmdList) then Exit; {$ENDIF} Count := PageCount; M := CalcViewportMatrix; ViewPort := CalcViewport; PrintJob := TSVGRenderContextManager.CreatePrintJob(aPrintJobName); for i := 0 to Count - 1 do begin R := PageViewbox[i]; MV := TSVGMatrix.CreateTranslation(-R.Left, -R.Top); RC := PrintJob.BeginPage(FPrinterPageWidth, FPrinterPageHeight); try RC.BeginScene; try RC.Clear(SVGColorNone); RC.PushClipRect( TSVGRect.Intersect( TransformRect(Viewport, MV), TransformRect(R, MV) ) ); try RC.Matrix := TSVGMatrix.Multiply(RC.Matrix, M); RC.Matrix := TSVGMatrix.Multiply(RC.Matrix, MV); {$IFDEF SVGSupportsCmdList} RC.DrawCmdList(FCmdList, SVGRect(0, 0, FCmdListWidth, FCmdListHeight)); {$ELSE} SVGRenderToRenderContext( FRoot, RC, FCmdListWidth, FCmdListHeight, [sroFilters, sroClippath], False); {$ENDIF} finally RC.PopClipRect; end; finally RC.EndScene; end; finally PrintJob.EndPage; end; end; end; {$IFDEF SVGSupportsCmdList} procedure TSVGPrintPreview.RenderToCmdList; var RC: ISVGRenderContext; begin if not assigned(FRoot) then Exit; CalcPrinterDimensions; FCmdList := TSVGRenderContextManager.CreateCmdList; RC := TSVGRenderContextManager.CreateRenderContextCmdList( FCmdList, FCmdListWidth, FCmdListHeight); RC.BeginScene; try SVGRenderToRenderContext( FRoot, RC, FCmdListWidth, FCmdListHeight, [sroFilters, sroClippath], False); finally RC.EndScene; end; end; {$ENDIF} procedure TSVGPrintPreview.Repaint; begin FNeedRecreatePreview := True; inherited; end; procedure TSVGPrintPreview.Resize; begin inherited; FNeedRecreatePreview := True; end; procedure TSVGPrintPreview.SetAspectRatioAlign( const Value: TSVGAspectRatioAlign); begin if FAspectRatioAlign <> Value then begin FAspectRatioAlign := Value; FNeedRecreatePreview := True; Invalidate; end; end; procedure TSVGPrintPreview.SetAspectRatioMeetOrSlice( const Value: TSVGAspectRatioMeetOrSlice); begin if FAspectRatioMeetOrSlice <> Value then begin FAspectRatioMeetOrSlice := Value; FNeedRecreatePreview := True; Invalidate; end; end; procedure TSVGPrintPreview.SetAutoViewbox(const Value: Boolean); begin if FAutoViewbox <> Value then begin FAutoViewbox := Value; FNeedRecreatePreview := True; Invalidate; end; end; procedure TSVGPrintPreview.SetGlueEdge(const Value: TSVGFloat); begin if FGlueEdge <> Value then begin FGlueEdge := Value; FNeedRecreatePreview := True; Invalidate; end; end; procedure TSVGPrintPreview.SetMarginBottom(const Value: TSVGFloat); begin if FMarginBottom <> Value then begin FMarginBottom := Value; FNeedRecreatePreview := True; Invalidate; end; end; procedure TSVGPrintPreview.SetMarginLeft(const Value: TSVGFloat); begin if FMarginLeft <> Value then begin FMarginLeft := Value; FNeedRecreatePreview := True; Invalidate; end; end; procedure TSVGPrintPreview.SetMarginRight(const Value: TSVGFloat); begin if FMarginRight <> Value then begin FMarginRight := Value; FNeedRecreatePreview := True; Invalidate; end; end; procedure TSVGPrintPreview.SetMarginTop(const Value: TSVGFloat); begin if FMarginTop <> Value then begin FMarginTop := Value; FNeedRecreatePreview := True; Invalidate; end; end; procedure TSVGPrintPreview.SetPagesHorizontal(const Value: Integer); begin if FPagesHorizontal <> Value then begin if Value <= 0 then FPagesHorizontal := 1 else FPagesHorizontal := Value; FNeedRecreatePreview := True; Invalidate; end; end; procedure TSVGPrintPreview.SetPagesVertical(const Value: Integer); begin if FPagesVertical <> Value then begin if Value <= 0 then FPagesVertical := 1 else FPagesVertical := Value; FNeedRecreatePreview := True; Invalidate; end; end; procedure TSVGPrintPreview.SetPrintUnits(const Value: TSVGPrintUnits); begin if FPrintUnits <> Value then begin FPrintUnits := Value; FNeedRecreatePreview := True; Invalidate; end; end; procedure TSVGPrintPreview.SetRoot(const Value: ISVGRoot); var R: TSVGRect; begin FRoot := Value; if assigned(FRoot) then begin R := FRoot.CalcIntrinsicSize(SVGRect(0, 0, FPrinterPageWidth, FPrinterPageHeight)); FCmdListWidth := Round(R.Width); FCmdListHeight := Round(R.Height); {$IFDEF SVGSupportsCmdList} // We render the SVG to a commandlist with the intrinsic size of the SVG // and will later scale the commandlist over the page(s) RenderToCmdList; {$ENDIF} end; FNeedRecreatePreview := True; Invalidate; end; end.
unit uUtils; interface uses Winapi.Windows, System.SysUtils, Vcl.Dialogs, OpenGL1x, GLGraphics, GLColor, GLMaterial, GLVectorFileObjects, GLVectorTypes, GLVectorGeometry, GLWin32Viewer, uMesh; type TCoordinates = record X,Y,Z: Single; end; function WorldToTex (const V: TVector; const Emin, Emax: TVector3f; w,h,d: integer): TVector; function TexToWorld (const V: TVector; const Emin, Emax: TVector3f; w,h,d: integer): TVector; function TestChanse(Sides: Integer): Boolean; function PointInRect(pnt: TVector; x1,y1,x2,y2: Integer): Boolean; overload; function PointInRect(pnt: TVector; r: TRect): Boolean; overload; procedure Pixel322RGB(pix: TGlPixel32; var _r,_g,_b,_a: byte); function RGB2Pixel32(_r,_g,_b,_a: byte): TGlPixel32; function Sign(a: Real): Real; function UpString(Source: AnsiString): AnsiString; function GetStrINstr(Source: AnsiString; St: Char; En: Char): AnsiString; function StrReplace(S,ch1,ch2: AnsiString): AnsiString; function Ang(Angle: Single): Single; procedure ActorAnimation(Actor: TGLActor; Animation: AnsiString); // Matrix function CreateWorldMatrix(Scale, Pos, Axis: TVector; Angle: single): TMatrix; // Mesh procedure CopyMeshObj(SrcFF, DstFF: TMesh; m : TMatrix); implementation // function WorldToTex (const V: TVector; const Emin, Emax: TVector3f; w,h,d: integer): TVector; begin result.X := (v.X-emin.X)/(emax.X-emin.X)*w; result.Y := (v.Y-emin.Y)/(emax.Y-emin.Y)*h; result.Z := (v.Z-emin.Z)/(emax.Z-emin.Z)*d; result.W := 0; end; function TexToWorld (const V: TVector; const Emin, Emax: TVector3f; w,h,d: integer): TVector; begin result.X := (v.X/w)*(emax.X-emin.X)+emin.X; result.Y := (v.Y/h)*(emax.Y-emin.Y)+emin.Y; result.Z := (v.Z/d)*(emax.Z-emin.Z)+emin.Z; result.W := 0; end; // function TestChanse(Sides: Integer): Boolean; var Side: Integer; begin RandomIze; Side:= Random(Sides); Result:= False; if Side = 0 then Result:= True; end; function FullSearchStr(Source: AnsiString; St: Char; En: Char; var Temp: Integer): AnsiString; Var i1,i2:Integer; begin i1:= Pos(St, Source); i2:= Pos(En, Source); if i2 <> 0 then Temp:= i2 + 1 else Temp:= Length(Source); if (i1 <> 0) and (i2 <> 0) then FullSearchStr:= Copy(Source,i1+1,i2-i1-1) else FullSearchStr:= ''; end; function GetStrINstr(Source: AnsiString; St: Char; En: Char): AnsiString; Var A: Integer; begin GetStrinstr:= FullSearchStr(Source,St,En,A); end; function StrReplace(S,ch1,ch2: AnsiString): AnsiString; var S2: AnsiString; i: Integer; begin S2:= ''; for i:= 1 to Length(S) do if Copy(S,i,1) <> ch1 then S2:= S2 + Copy(S,i,1) else S2:= S2 + ch2; Result:= S2; end; function UpString(Source: AnsiString): AnsiString; Var Dest: AnsiString; i: Integer; begin Dest:= ''; for i:= 1 to length(Source) do Dest:= Dest + UpCase(Source[i]); UpString:= Dest; end; function Sign(a: Real): Real; begin if a > 0 then result:= 1 else if a < 0 then result:= -1 else result:= 0; end; procedure Pixel322RGB(pix: TGlPixel32; var _r,_g,_b,_a: byte); begin _r:= pix.r; _g:= pix.g; _b:= pix.b; _a:= pix.a; end; function RGB2Pixel32(_r,_g,_b,_a: byte): TGlPixel32; begin result.r:= _r; result.g:= _g; result.b:= _b; result.a:= _a; end; function PointInRect(pnt: TVector; x1,y1,x2,y2: Integer): Boolean; overload; begin result:= (pnt.X >= x1) and (pnt.Y >= y1) and (pnt.X <= x2) and (pnt.Y <= y2); end; function PointInRect (pnt: TVector; r: TRect): Boolean; overload; begin result:= PointInRect(pnt, r.left, r.top, r.right, r.bottom); end; function Ang(Angle: Single): Single; begin Result:= ((((Round(Angle) mod 360) + 540) mod 360) - 180); end; procedure ActorAnimation(Actor: TGLActor; Animation: AnsiString); begin if Animation <> Actor.CurrentAnimation then Actor.SwitchToAnimation(Animation); end; function CreateWorldMatrix(Scale, Pos, Axis: TVector; Angle: single): TMatrix; var wm, mt, ms, mr: TMatrix; begin ms := CreateScaleMatrix(Scale); mt := CreateTranslationMatrix(Pos); mr := CreateRotationMatrix(Axis, Angle); wm := IdentityHmgMatrix; wm := MatrixMultiply(wm, mr); wm := MatrixMultiply(wm, ms); wm := MatrixMultiply(wm, mt); TransposeMatrix(wm); Result:= wm; end; function Kilo(Value: Single): Single; begin Result:= Value/100; end; procedure CopyMeshObj(SrcFF, DstFF : TMesh; m : TMatrix); var i,j : integer; MObj,SrcMObj : TMeshObject; FG,srcFG : TFGVertexNormalTexIndexList; begin for i := 0 to SrcFF.MeshObjects.Count-1 do begin SrcMObj := SrcFF.MeshObjects[i]; MObj := TMeshObject.CreateOwned(dstFF.MeshObjects); MObj.Mode := SrcMObj.Mode; for j := 0 to SrcMObj.Vertices.Count-1 do MObj.Vertices.Add(VectorTransform(SrcMObj.Vertices[j],m)); for j := 0 to SrcMObj.Normals.Count-1 do MObj.Normals.Add(srcMObj.Normals[j]); MObj.TexCoords.Add(SrcMObj.TexCoords); for j := 0 to SrcFF.MeshObjects[i].FaceGroups.Count-1 do begin SrcFG := TFGVertexNormalTexIndexList(SrcFF.MeshObjects[i].FaceGroups[j]); FG := TFGVertexNormalTexIndexList.CreateOwned(MObj.FaceGroups); FG.Mode := SrcFG.Mode; FG.MaterialName := SrcFF.MaterialData.Name; FG.VertexIndices .Add (SrcFG.VertexIndices); FG.NormalIndices .Add (SrcFG.NormalIndices); FG.TexCoordIndices.Add (SrcFG.TexCoordIndices); end; end; end; end.
/// <summary> 稀疏图 - 邻接表 </summary> unit DSA.Graph.SparseGraph; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DSA.List_Stack_Queue.ArrayList, DSA.List_Stack_Queue.LinkedList, DSA.Interfaces.DataStructure, DSA.Utils; type TSparseGraph = class(TInterfacedObject, IGraph) private type TEdgeType = specialize TLinkedList<integer>; TGraphType = specialize TArrayList<TEdgeType>; var __vertex: integer; // 节点数 __edge: integer; // 边数 __directed: boolean; // 是否为有向图 __graphData: TGraphType; // 图的具体数据 public /// <summary> 向图中添加一个边 </summary> procedure AddEdge(v, w: integer); /// <summary> 验证图中是否有从v到w的边 </summary> function HasEdge(v, w: integer): boolean; /// <summary> 返回节点个数 </summary> function Vertex: integer; /// <summary> 返回边的个数 </summary> function Edge: integer; /// <summary> 返回图中一个顶点的所有邻边 </summary> function AdjIterator(v: integer): TArray_int; procedure Show; constructor Create(n: integer; directed: boolean); destructor Destroy; override; type /// <summary> /// 邻边迭代器, 传入一个图和一个顶点, /// 迭代在这个图中和这个顶点向连的所有顶点 /// </summary> TAdjIterator = class(TInterfacedObject, IIterator) private __sg: TSparseGraph; __v: integer; __index: integer; public constructor Create(const g: TSparseGraph; v: integer); /// <summary> 返回图G中与顶点v相连接的第一个顶点 </summary> function Start: integer; /// <summary> 返回图G中与顶点v相连接的下一个顶点 </summary> function Next: integer; /// <summary> 是否已经迭代完了图G中与顶点v相连接的所有顶点 </summary> function Finished: boolean; end; end; procedure Main; implementation procedure Main; var m, n, a, b, i, v, w: integer; sg: TSparseGraph; adj: IIterator; begin n := 20; m := 100; Randomize; sg := TSparseGraph.Create(n, False); for i := 0 to m - 1 do begin a := Random(n); b := Random(n); sg.AddEdge(a, b); end; for v := 0 to n - 1 do begin Write(v, ' : '); adj := TSparseGraph.TAdjIterator.Create(sg, v); w := adj.Start; while not adj.Finished do begin Write(w, ' '); w := adj.Next; end; Writeln; end; TDSAUtils.DrawLine; for v := 0 to n - 1 do begin Write(v, ' : '); for i in sg.AdjIterator(v) do begin Write(i, ' '); end; Writeln; end; FreeAndNil(sg); TDSAUtils.DrawLine; sg := TSparseGraph.Create(13, False); TDSAUtils.ReadGraph((sg as IGraph), FILE_PATH + GRAPH_FILE_NAME_1); sg.Show; end; { TSparseGraph.TAdjIterator } constructor TSparseGraph.TAdjIterator.Create(const g: TSparseGraph; v: integer); begin __sg := g; __v := v; __index := -1; end; function TSparseGraph.TAdjIterator.Finished: boolean; begin Result := __index >= __sg.__graphData[__v].GetSize; end; function TSparseGraph.TAdjIterator.Next: integer; begin Inc(__index); if __index < __sg.__graphData[__v].GetSize then begin Result := __sg.__graphData[__v][__index]; Exit; end; Result := -1; end; function TSparseGraph.TAdjIterator.Start: integer; begin __index := 0; if __sg.__graphData[__v].GetSize > 0 then begin Result := __sg.__graphData[__v][__index]; Exit; end; Result := -1; // 若没有顶点和v相连接, 则返回-1 end; { TSparseGraph } constructor TSparseGraph.Create(n: integer; directed: boolean); var i: integer; begin Assert(n > 0); __vertex := n; __edge := 0; __directed := directed; __graphData := TGraphType.Create; for i := 0 to n - 1 do __graphData.AddLast(TEdgeType.Create); end; procedure TSparseGraph.AddEdge(v, w: integer); begin Assert((v >= 0) and (v < __vertex)); Assert((w >= 0) and (w < __vertex)); __graphData[v].AddLast(w); if (v <> w) and (__directed = False) then __graphData[w].AddLast(v); __edge += 1; end; function TSparseGraph.AdjIterator(v: integer): TArray_int; var i: integer; ret: TArray_int = nil; begin for i := 0 to __graphData[v].GetSize - 1 do begin SetLength(ret, i + 1); ret[i] := __graphData[v][i]; end; Result := ret; end; destructor TSparseGraph.Destroy; begin FreeAndNil(__graphData); inherited Destroy; end; function TSparseGraph.Edge: integer; begin Result := __edge; end; function TSparseGraph.HasEdge(v, w: integer): boolean; var i: integer; begin Assert((v >= 0) and (v < __vertex)); Assert((w >= 0) and (w < __vertex)); for i := 0 to __graphData[v].GetSize - 1 do begin if (__graphData[v][i] = w) then begin Result := True; Exit; end; end; Result := False; end; procedure TSparseGraph.Show; var v, e: integer; begin for v := 0 to __graphData.GetSize - 1 do begin Write('Vertex ', v, ' : ', #9); for e in AdjIterator(v) do begin Write(e, #9); end; Writeln; end; end; function TSparseGraph.Vertex: integer; begin Result := __vertex; end; end.
program BitmapCollisionTest; uses sgTypes, SwinGame; type MySprite = record x, y: Single; hasAnimation: Boolean; anim: Animation; bmp: Bitmap; end; procedure LoadResources(); begin LoadBitmapNamed('bubble', 'bubble.png'); LoadResourceBundle('dance_bundle.txt'); end; function CreateMySprite(x, y: Single; useFrog: Boolean): MySprite; begin result.x := x; result.y := y; result.hasAnimation := useFrog; if useFrog then begin result.bmp := BitmapNamed('FrogBmp'); result.anim := CreateAnimation('LoopFrontWalk', AnimationScriptNamed('WalkingScript')); end else result.bmp := BitmapNamed('bubble'); end; function MySpritesCollide(const s1, s2: MySprite): Boolean; var c1, c2: Integer; begin if s1.hasAnimation or s2.hasAnimation then begin if s1.hasAnimation then c1 := AnimationCurrentCell(s1.anim) else c1 := 0; if s2.hasAnimation then c2 := AnimationCurrentCell(s2.anim) else c2 := 0; result := CellCollision(s1.bmp, c1, s1.x, s1.y, s2.bmp, c2, s2.x, s2.y); end else result := BitmapCollision(s1.bmp, s1.x, s1.y, s2.bmp, s2.x, s2.y); end; procedure DrawMySprite(const sprt: MySprite); begin if sprt.hasAnimation then DrawAnimation(sprt.anim, sprt.bmp, sprt.x, sprt.y) else DrawBitmap(sprt.bmp, sprt.x, sprt.y); end; procedure UpdateMySprite(var sprt: MySprite); begin if sprt.hasAnimation then begin UpdateAnimation(sprt.anim); end; end; procedure Highlight(const sprt: MySprite); begin DrawRectangle(ColorRed, sprt.x, sprt.y, BitmapCellWidth(sprt.bmp), BitmapCellHeight(sprt.bmp)); end; procedure TestCollisions(const sprites: array of MySprite); var i, j: Integer; begin for i := 0 to High(sprites) - 1 do begin for j := i + 1 to High(sprites) do begin if MySpritesCollide(sprites[i], sprites[j]) then begin Highlight(sprites[i]); Highlight(sprites[j]); end; end; end; end; procedure Main(); var sprites: array [0..2] of MySprite; i: Integer; begin OpenWindow('Bitmap Collision Test', 600, 600); LoadResources(); sprites[0] := CreateMySprite(100, 100, false); sprites[1] := CreateMySprite(300, 100, true); sprites[2] := CreateMySprite(500, 100, false); repeat ProcessEvents(); if KeyDown(LeftKey) then sprites[2].x -= 3; if KeyDown(RightKey) then sprites[2].x += 3; ClearScreen(ColorWhite); for i := 0 to High(sprites) do begin UpdateMySprite(sprites[i]); DrawMySprite(sprites[i]); end; TestCollisions(sprites); RefreshScreen(); until WindowCloseRequested(); end; begin Main(); end.
unit reportlab; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids, StdCtrls, Series, TeEngine, ExtCtrls, TeeProcs, Chart; type TFormResult = class(TForm) ReportL: TStringGrid; Button1: TButton; Chart1: TChart; Series1: TFastLineSeries; Series3: TFastLineSeries; KA: TEdit; Label2: TLabel; Label3: TLabel; Label4: TLabel; KB: TEdit; AverageL: TStringGrid; Label5: TLabel; Label6: TLabel; XAxis: TRadioGroup; YAxis: TRadioGroup; PutGraph: TButton; Label1: TLabel; Label7: TLabel; procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure KAKeyPress(Sender: TObject; var Key: Char); procedure PutGraphClick(Sender: TObject); procedure ChangeAxisClick(Sender: TObject); procedure ChangeKoef(Sender: TObject); private { Private declarations } public { Public declarations } procedure _CalculAverage; end; var FormResult: TFormResult; // константы для столюцов таблицы const _CADR=0; _LPOLINF=1; _LINF=2; _LINFINPOLINF=3; _NPOLINFININF=4; _EXPNPOLINFININF=5; _EXPTIME=6; _ERR=7; _NUMBCOL=7; implementation {$R *.DFM} uses Experiment; var KAs,KBs : array [0.._NUMBCOL*_NUMBCOL-1] of string[6]; // линейные коэф. для графиков procedure TFormResult._CalculAverage; var Xs,Ys : string[6]; i,j,n : integer; findx : boolean; begin AverageL.Cells[0,0]:=ReportL.Cells[XAxis.ItemIndex+1,0]; AverageL.Cells[1,0]:=ReportL.Cells[YAxis.ItemIndex+1,0]; AverageL.Cells[2,0]:='Кол зн'; n:=0; for i:=1 to ReportL.RowCount-1 do begin Xs:=ReportL.Cells[XAxis.ItemIndex+1,i]; Ys:=ReportL.Cells[YAxis.ItemIndex+1,i]; findx:=false; for j:=1 to n do if AverageL.Cells[0,j]=Xs then begin AverageL.Cells[1,j]:=floattostr( strtofloat(AverageL.Cells[1,j])+strtofloat(Ys) ); AverageL.Cells[2,j]:=floattostr( strtofloat(AverageL.Cells[2,j])+1 ); findx:=true; break; end; if not findx then begin inc(n); AverageL.Cells[0,n]:=Xs; AverageL.Cells[1,n]:=Ys; AverageL.Cells[2,n]:='1'; end; end; AverageL.RowCount:=n+1; for j:=1 to n do AverageL.Cells[1,j]:=floattostr( strtofloat(AverageL.Cells[1,j])/strtofloat(AverageL.Cells[2,j]) ); end; procedure TFormResult.FormShow(Sender: TObject); var i : integer; begin ReportL.RowCount:=CurCadr; Series1.Active:=false; Series3.Active:=false; for i:=0 to _NUMBCOL*_NUMBCOL-1 do begin KAs[i]:=''; KBs[i]:=''; end; _CalculAverage; end; procedure TFormResult.Button1Click(Sender: TObject); begin Close; end; procedure TFormResult.FormCreate(Sender: TObject); begin // наименования столбцов таблицы with ReportL do begin Cells[ _CADR,0 ]:='Кадр'; Cells[ _LPOLINF,0 ]:='Дл ПИ'; Cells[ _LINF,0 ]:='Дл КИ'; Cells[ _LINFINPOLINF,0 ]:='Дл КИо'; Cells[ _NPOLINFININF,0 ]:='Кл ПИ'; Cells[ _EXPNPOLINFININF,0 ]:='Кл ПИэ'; Cells[ _EXPTIME,0 ]:='t'; Cells[ _ERR,0 ]:='Ош'; end; end; procedure TFormResult.KAKeyPress(Sender: TObject; var Key: Char); begin if not (Key in ['0'..'9',',','-','+',#8]) then Key:=#27; end; procedure TFormResult.PutGraphClick(Sender: TObject); var i : integer; A,B,x : double; begin Series1.Active:=false; Series3.Active:=false; Series1.Clear; Series3.Clear; with AverageL do For i:=1 to RowCount-1 do Series1.AddXY( strtofloat( Cells[0,i] ), strtofloat( Cells[1,i] ), '', clRed ); Series1.Active:=true; If (KA.Text<>'') and (KA.Text<>'') then begin A:=strtofloat( KA.Text ); B:=strtofloat( KB.Text ); with AverageL do for i:=1 to RowCount-1 do begin x:=strtofloat( Cells[0,i] ); Series3.AddXY( x, A*x+B, '', clGreen ); end; Series3.Active:=true; end; end; procedure TFormResult.ChangeAxisClick(Sender: TObject); var i : integer; begin i:=YAxis.ItemIndex*_NUMBCOL+XAxis.ItemIndex; KA.Text:=KAs[i]; KB.Text:=KBs[i]; _CalculAverage; end; procedure TFormResult.ChangeKoef(Sender: TObject); var i : integer; begin i:=YAxis.ItemIndex*_NUMBCOL+XAxis.ItemIndex; KAs[i]:=KA.Text; KBs[i]:=KB.Text; end; end.
unit PowTest; interface uses DUnitX.TestFramework, // Classes, uEnums, uIntX; type [TestFixture] TPowTest = class(TObject) public [Setup] procedure Setup; [Test] procedure Simple(); [Test] procedure Zero(); [Test] procedure PowZero(); [Test] procedure PowOne(); [Test] procedure Big(); { Simple output (2^65536). Uncomment to see [Test] procedure TwoNOut(); } end; implementation procedure TPowTest.Setup; begin TIntX.GlobalSettings.MultiplyMode := TMultiplyMode.mmClassic; end; [Test] procedure TPowTest.Simple(); var IntX: TIntX; begin IntX := TIntX.Create(-1); Assert.IsTrue(TIntX.Pow(IntX, 17) = -1); Assert.IsTrue(TIntX.Pow(IntX, 18) = 1); end; [Test] procedure TPowTest.Zero(); var IntX: TIntX; begin IntX := TIntX.Create(0); Assert.IsTrue(TIntX.Pow(IntX, 77) = 0); end; [Test] procedure TPowTest.PowZero(); begin Assert.IsTrue(TIntX.Pow(0, 0) = 1); end; [Test] procedure TPowTest.PowOne(); begin Assert.IsTrue(TIntX.Pow(7, 1) = 7); end; [Test] procedure TPowTest.Big(); begin Assert.AreEqual(TIntX.Pow(2, 65).ToString(), '36893488147419103232'); end; // Simple output (2^65536). uncomment to see (* [Test] procedure TPowTest.TwoNOut(); var Writer: TStreamWriter; begin Writer := TStreamWriter.Create('2n65536.txt'); try Writer.WriteLine(TIntX.Pow(2, 65536).ToString); finally Writer.Free; end; end; *) initialization TDUnitX.RegisterTestFixture(TPowTest); end.
// // Generated by JavaToPas v1.5 20140918 - 132048 //////////////////////////////////////////////////////////////////////////////// unit android.bluetooth.BluetoothA2dp; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, android.bluetooth.BluetoothDevice; type JBluetoothA2dp = interface; JBluetoothA2dpClass = interface(JObjectClass) ['{F6615827-0756-40D5-A833-9367EC36FD6B}'] function _GetACTION_CONNECTION_STATE_CHANGED : JString; cdecl; // A: $19 function _GetACTION_PLAYING_STATE_CHANGED : JString; cdecl; // A: $19 function _GetSTATE_NOT_PLAYING : Integer; cdecl; // A: $19 function _GetSTATE_PLAYING : Integer; cdecl; // A: $19 function getConnectedDevices : JList; cdecl; // ()Ljava/util/List; A: $1 function getConnectionState(device : JBluetoothDevice) : Integer; cdecl; // (Landroid/bluetooth/BluetoothDevice;)I A: $1 function getDevicesMatchingConnectionStates(states : TJavaArray<Integer>) : JList; cdecl;// ([I)Ljava/util/List; A: $1 function isA2dpPlaying(device : JBluetoothDevice) : boolean; cdecl; // (Landroid/bluetooth/BluetoothDevice;)Z A: $1 procedure finalize ; cdecl; // ()V A: $1 property ACTION_CONNECTION_STATE_CHANGED : JString read _GetACTION_CONNECTION_STATE_CHANGED;// Ljava/lang/String; A: $19 property ACTION_PLAYING_STATE_CHANGED : JString read _GetACTION_PLAYING_STATE_CHANGED;// Ljava/lang/String; A: $19 property STATE_NOT_PLAYING : Integer read _GetSTATE_NOT_PLAYING; // I A: $19 property STATE_PLAYING : Integer read _GetSTATE_PLAYING; // I A: $19 end; [JavaSignature('android/bluetooth/BluetoothA2dp')] JBluetoothA2dp = interface(JObject) ['{B49A2392-8068-49B9-8DC5-EC498259BD0B}'] function getConnectedDevices : JList; cdecl; // ()Ljava/util/List; A: $1 function getConnectionState(device : JBluetoothDevice) : Integer; cdecl; // (Landroid/bluetooth/BluetoothDevice;)I A: $1 function getDevicesMatchingConnectionStates(states : TJavaArray<Integer>) : JList; cdecl;// ([I)Ljava/util/List; A: $1 function isA2dpPlaying(device : JBluetoothDevice) : boolean; cdecl; // (Landroid/bluetooth/BluetoothDevice;)Z A: $1 procedure finalize ; cdecl; // ()V A: $1 end; TJBluetoothA2dp = class(TJavaGenericImport<JBluetoothA2dpClass, JBluetoothA2dp>) end; const TJBluetoothA2dpACTION_CONNECTION_STATE_CHANGED = 'android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED'; TJBluetoothA2dpACTION_PLAYING_STATE_CHANGED = 'android.bluetooth.a2dp.profile.action.PLAYING_STATE_CHANGED'; TJBluetoothA2dpSTATE_PLAYING = 10; TJBluetoothA2dpSTATE_NOT_PLAYING = 11; implementation end.
unit UContasReceberVO; interface uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO, UUnidadeVO, UHistoricoVO, UCondominioVO, UPlanoContasVO,uContacorrenteVO; type [TEntity] [TTable('ContasReceber')] TContasReceberVO = class(TGenericVO) private FidContasReceber : Integer; FDtCompetencia : TDateTime; FDtVencimento: TDateTime; FNrDocumento : String; FVlValor : Currency; FDsComplemento : String; FIdHistorico : Integer; FFlBaixa : String; FFlGerado : String; FIdConta : Integer; FIdCondominio : Integer; FIdPessoa : Integer; FIdContraPartida : Integer; FIdUnidade : Integer; FVlBaixa : Currency; FVlJuros : Currency; FVlMulta : Currency; FVlDesconto : Currency; FDtBaixa : TDateTime; FIdContaBaixa : Integer; FIdHistoricoBx : Integer; FDescricao : string; FVlPago : currency; public CondominioVO : TCondominioVO; UnidadeVO : TUnidadeVO; PlanoContasContaVO : TPlanoContasVO; PlanoContasContraPartidaVO : TPlanoContasVO; HistoricoVO : THistoricoVO; ItensContaCorrente: TObjectList<TContaCorrenteVO>; [TId('idContasReceber')] [TGeneratedValue(sAuto)] property idContasReceber : Integer read FidContasReceber write FidContasReceber; [TColumn('DtCompetencia','Data Competencia',50,[ldLookup,ldComboBox], False)] property DtCompetencia: TDateTime read FDtCompetencia write FDtCompetencia; [TColumn('DtVencimento','Data Vencimento',50,[ldGrid,ldLookup,ldComboBox], False)] property DtVencimento: TDateTime read FDtVencimento write FDtVencimento; [TColumn('NrDocumento','Documento',100,[ldGrid,ldLookup,ldComboBox], False)] property NrDocumento: string read FNrDocumento write FNrDocumento; [TColumn('DSUNIDADE','Unidade',400,[ldGrid], True, 'Unidade', 'idUnidade', 'idUnidade')] property Descricao: string read FDescricao write FDescricao; [TColumn('VlValor','Valor',100,[ldGrid,ldLookup,ldComboBox], False)] property VlValor: Currency read FVlValor write FVlValor; [TColumn('DsComplemento','Complemento',0,[ldLookup,ldComboBox], False)] property DsComplemento: String read FDsComplemento write FDsComplemento; [TColumn('IdHistorico','Histórico',0,[ldLookup,ldComboBox], False)] property IdHistorico: integer read FIdHistorico write FIdHistorico; [TColumn('IdUnidade','Unidade',0,[ldLookup,ldComboBox], False)] property IdUnidade: integer read FIdUnidade write FIdUnidade; [TColumn('FlBaixa','Situação',10,[ldGrid,ldLookup,ldComboBox], False)] property FlBaixa: String read FFlBaixa write FFlBaixa; [TColumn('IdConta','Id Conta',0,[ldLookup,ldComboBox], False)] property IdConta: Integer read FIdConta write FIdConta; [TColumn('IdCondominio','Id Condominio',0,[ldLookup,ldComboBox], False)] property IdCondominio: Integer read FIdCondominio write FIdCondominio; // [TColumn('IdPessoa','Id Pessoa',50,[ldLookup,ldComboBox], False)] // property IdPessoa: Integer read FIdPessoa write FIdPessoa; [TColumn('IdContraPartida','Id Contra Partida',0,[ldLookup,ldComboBox], False)] property IdContraPartida: Integer read FIdContraPartida write FIdContraPartida; [TColumn('VlBaixa','Valor',100,[ldLookup,ldComboBox], False)] property VlBaixa: Currency read FVlBaixa write FVlBaixa; [TColumn('VlJuros','Juros',100,[ldLookup,ldComboBox], False)] property VlJuros: Currency read FVlJuros write FVlJuros; [TColumn('VlMulta','Multa',100,[ldLookup,ldComboBox], False)] property VlMulta: Currency read FVlMulta write FVlMulta; [TColumn('VlDesconto','Desconto',100,[ldLookup,ldComboBox], False)] property VlDesconto: Currency read FVlDesconto write FVlDesconto; [TColumn('DtBaixa','Data Baixa',50,[ldLookup,ldComboBox], False)] property DtBaixa: TDateTime read FDtBaixa write FDtBaixa; [TColumn('IdContaBaixa','Id Conta',0,[ldLookup,ldComboBox], False)] property IdContaBaixa: Integer read FIdContaBaixa write FIdContaBaixa; [TColumn('IdHistoricoBx','Id Conta',0,[ldLookup,ldComboBox], False)] property IdHistoricoBx: Integer read FIdHistoricoBx write FIdHistoricoBx; [TColumn('VlPago','Valor Pago',100,[ldLookup,ldComboBox], False)] property VlPago: Currency read FVlPago write FVlPago; [TColumn('FlGerado','Gerado',10,[ldGrid,ldLookup,ldComboBox], False)] property FlGerado: String read FFlGerado write FFlGerado; procedure ValidarCampos; procedure ValidarBaixa; end; implementation procedure TContasReceberVO.ValidarBaixa; begin if (Self.FDtBaixa = 0) then raise Exception.Create('O campo Data Baixa é obrigatório!'); if ((Self.FVlBaixa <= 0) or (self.FVlBaixa <> self.VlValor)) then raise Exception.Create('O campo Valor Baixa é obrigatório e não pode ser diferente que o valor!'); if ( Self.FVlPago<=0) then raise Exception.Create('O campo Valor é obrigatório!'); if (self.FDtBaixa < self.DtCompetencia) then raise Exception.Create('A data da baixa não pode ser menor que a data de competencia!'); if (Self.FIdContaBaixa = 0) then raise Exception.Create('O campo Conta é obrigatório!'); if Self.vlpago > self.vlvalor then begin if ((self.vlbaixa + Self.VlJuros + self.VlMulta - self.VlDesconto) <> self.VlPago) then raise Exception.Create('Valor não confere!'); end else if Self.VlPago < self.VlValor then begin if ((self.VlPago + self.vldesconto) <> self.vlValor) then raise Exception.Create('Valor não confere'); end; end; procedure TContasReceberVO.ValidarCampos; begin if (Self.FDtCompetencia = 0 ) then raise Exception.Create('O campo Data Competencia é obrigatório!'); if (Self.FNrDocumento= '') then raise Exception.Create('O campo Documento é obrigatório!'); if (Self.FDtVencimento = 0) then raise Exception.Create('O campo Data Vencimento é obrigatório!'); if (Self.FVlValor<= 0) then raise Exception.Create('O campo Valor é obrigatório!'); if (Self.FDtVencimento < self.FDtCompetencia) then raise Exception.Create('A data de Competencia deve ser menor que a data de Vencimento!'); end; end.
unit u_Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, GLWin32Viewer, GLScene, GLCadencer, GLObjects, GLTexture, GLAsyncTimer, GLHUDObjects, GLShadowVolume, GLContext, GLMaterial, GLColor, GLKeyboard; type TForm1 = class(TForm) procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); public Scene: TGLScene; Camera: TGLCamera; Cad: TGLCadencer; Viewer: TGLSceneViewer; Ast: TGLAsyncTimer; Light: TGLLightSource; Back: TGLHUDSprite; Dummy: TGLDummyCube; Plane: TGLPlane; Sphere: TGLSphere; Cube: TGLCube; Shadow: TGLShadowVolume; Points: TGLPoints; Lines: TGLLines; procedure CadProgress(Sender: TObject; const dt,nt: double); procedure vpMouseDown(Sender: TObject; but: TMouseButton; sh: TShiftState; X,Y: Integer); procedure Time(Sender: TObject); end; var Form1: TForm1; m_pos: TPoint; m_move: boolean; implementation {$R *.dfm} // FormCreate // procedure TForm1.FormCreate(Sender: TObject); var i: Integer; Color : TColor; begin Scene := TGLScene.Create(self); Cad := TGLCadencer.Create(self); cad.Scene := Scene; cad.OnProgress := CadProgress; Viewer := TGLSceneViewer.Create(self); Viewer.Parent := self; Viewer.Buffer.BackgroundColor := $ffffff; Viewer.Buffer.ContextOptions := Viewer.Buffer.ContextOptions + [roNoColorBufferClear, roStencilBuffer]; Viewer.Buffer.AntiAliasing := aa4x; Viewer.Align := alClient; Viewer.SendToBack; Viewer.OnMouseDown := vpMouseDown; Back := TGLHUDSprite.CreateAsChild(scene.Objects); back.Width := Width; back.Height := Height; back.Position.SetPoint(Width div 2, Height div 2, 0); back.Material.Texture.Image.LoadFromFile('back.bmp'); back.Material.Texture.Disabled := false; Dummy := TGLDummyCube.CreateAsChild(Scene.Objects); Light := TGLLightSource.CreateAsChild(Scene.Objects); Light.Position.SetPoint(4, 10, 4); Sphere := TGLSphere.CreateAsChild(Dummy); Sphere.Position.SetPoint(0.2, 1.2, 0); Sphere.Radius := 0.3; Sphere.Slices := 10; Sphere.Stacks := 8; Cube := TGLCube.CreateAsChild(Dummy); cube.CubeDepth := 0.8; cube.CubeHeight := 0.1; cube.CubeWidth := 0.8; cube.Position.SetPoint(1, 0.2, 0); Plane := TGLPlane.CreateAsChild(Dummy); Plane.Direction.SetVector(0.3, 1, 0.1); Plane.Width := 3; Plane.Height := 4; Camera := TGLCamera.CreateAsChild(Dummy); Camera.Position.SetPoint(2, 3, 4); Camera.FocalLength := 75; Camera.TargetObject := Dummy; Viewer.Camera := Camera; Shadow := TGLShadowVolume.CreateAsChild(Dummy); Shadow.Mode := svmDarkening; Shadow.Lights.AddCaster(light); Shadow.Occluders.AddCaster(Sphere); Shadow.Occluders.AddCaster(cube); Ast := TGLAsyncTimer.Create(form1); Ast.Interval := 500; Ast.OnTimer := Time; Ast.Enabled := true; for I := 0 to 10000 do begin Points := TGLPoints.CreateAsChild(Dummy); Points.Style := psSmooth; Points.PointParameters.Enabled := True; Points.PointParameters.MinSize := 1; Points.PointParameters.MaxSize := 4; Points.PointParameters.DistanceAttenuation.SetVector(0, 0.001, 0); Points.Position.X := Random(); Points.Position.Y := Random(); Points.Position.Z := Random(); Points.Colors.AddPoint(Random, Random, Random); // Temporarily random colors end; Lines := TGLLines.CreateAsChild(Dummy); end; procedure TForm1.FormResize(Sender: TObject); begin Viewer.Visible := True; end; // cadProgress // procedure TForm1.CadProgress; begin Dummy.turn(-dt * 10); if m_move then begin with mouse.CursorPos do Camera.MoveAroundTarget((m_pos.Y - y) * 0.3, (m_pos.X - x) * 0.3); m_pos := mouse.CursorPos; // MouseUp if not iskeydown(vk_lbutton) then m_move := false; end; end; // MouseDown // procedure TForm1.vpMouseDown; begin m_pos := mouse.CursorPos; m_move := true; end; // Timer // procedure TForm1.Time(Sender:TObject); begin caption := 'runTime: ' + Viewer.FramesPerSecondText(2); Viewer.ResetPerformanceMonitor; end; end.
(* Copyright (c) 2013 Cary Jensen This sample was designed to accompany the Embarcadero Webinar Universal Enterprise Data Connectivity using FireDAC, presented on October 30th, 2013 by Cary Jensen No guarantees or warranties are expressed or implied concerning the applicability of techniques or code included in this example. If you wish to use techniques or code included in this example, it is your responsibility to test and certify any code, techniques, or design adopted as a result of this project. For consulting, training, and development services, visit http://www.JensenDataSystems.com For information about Delphi Developer Days with Bob Swart and Cary Jensen, visit http://www.DelphiDeveloperDays.com *) unit datamodu; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Datasnap.DBClient, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.Phys.SQLiteVDataSet, FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, FireDAC.Phys.SQLite, FireDAC.Phys.IBBase, FireDAC.Phys.IB, FireDAC.Phys.ODBCBase, FireDAC.Phys.MSAcc, Forms; type TDataModule2 = class(TDataModule) SQLiteConnection: TFDConnection; FDLocalSQL1: TFDLocalSQL; OrdersQuery: TFDQuery; EmployeeCDS: TClientDataSet; LocalQuery: TFDQuery; FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink; FDGUIxWaitCursor1: TFDGUIxWaitCursor; AccessConnection: TFDConnection; FDPhysMSAccessDriverLink1: TFDPhysMSAccessDriverLink; procedure DataModuleCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var DataModule2: TDataModule2; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TDataModule2.DataModuleCreate(Sender: TObject); var DataDir: string; begin DataDir := 'C:\DTOURXE6\data\'; EmployeeCDS.FileName := DataDir + 'employee.xml'; AccessConnection.Params.Clear; AccessConnection.Params.Add('Database=' + DataDir + 'dbdemos.mdb'); AccessConnection.Params.Add('DriverID=MSAcc'); SQLiteConnection.Open; LocalQuery.Open; end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmBrowseFor Purpose : Dialog Wrapper for the Win32 BrowseForFolder API Call. Date : 03-15-1999 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmBrowseFor; interface {$I CompilerDefines.INC} uses Windows,Messages,SysUtils,Classes,Graphics,Controls,Forms,Dialogs, ShlObj; type TbfType = (bftFolders,bftPrinters,bftComputers,bftFileorFolders); TbfRoot = (bfrDesktop,bfrMyComputer,bfrNetworkNeighborhood,bfrPrinters); TrmBrowseForFolder = class(TComponent) private fFolder: string; fBrowseInfo: TBrowseInfo; fRoot: TBFRoot; fType: TBFType; fTitle: string; public function Execute: Boolean; constructor create(AOwner: TComponent); override; property Folder: string read fFolder write fFolder; Published property BrowseForType: TBFType read fType write fType default bftFolders; property RootNode: TBFRoot read fRoot write fRoot default bfrDeskTop; property Title: string read fTitle write fTitle; end; implementation function BrowseCallback(Wnd: HWND; uMsg: UINT; lParam,lpData: LPARAM): Integer stdcall; begin Result := 0; if uMsg = BFFM_Initialized then begin with TrmBrowseForFolder(lpData) do begin if Length(Folder) > 0 then SendMessage(Wnd,BFFM_SetSelection,1,Longint(PChar(Folder))); end; end; end; { TrmBrowseForFolder } constructor TrmBrowseForFolder.create(AOwner: TComponent); begin inherited; fRoot := bfrDesktop; fType := bftFolders; end; function TrmBrowseForFolder.Execute: Boolean; var Buffer: array[0..MAX_PATH] of char; ItemIdList: PItemIDList; begin Result := False; with fBrowseInfo do begin hwndOwner := Application.Handle; pszDisplayName := Buffer; lpszTitle := PChar(FTitle); lpfn := BrowseCallback; lParam := longint(self); case fRoot of bfrDesktop: pidlRoot := nil; bfrMyComputer: SHGetSpecialFolderLocation(application.handle,CSIDL_DRIVES,pidlRoot); bfrNetworkNeighborhood: SHGetSpecialFolderLocation(application.handle,CSIDL_NETWORK,pidlRoot); bfrPrinters: SHGetSpecialFolderLocation(application.handle,CSIDL_PRINTERS,pidlRoot); end; case fType of bftFolders: ulFlags := BIF_RETURNONLYFSDIRS; bftPrinters: ulFlags := BIF_BROWSEFORPRINTER; bftComputers: ulFlags := BIF_BROWSEFORCOMPUTER; bftFileorFolders: ulFlags := BIF_BROWSEINCLUDEFILES; end; end; ItemIdList := ShBrowseForFolder(FBrowseInfo); if ItemIDList = nil then Exit; Result := SHGetPathFromIDList(ItemIDList,Buffer); fFolder := Buffer; end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFStreamReader; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses {$IFDEF DELPHI16_UP} System.Classes, {$ELSE} Classes, {$ENDIF} uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefStreamReaderRef = class(TCefBaseRefCountedRef, ICefStreamReader) protected function Read(ptr: Pointer; size, n: NativeUInt): NativeUInt; function Seek(offset: Int64; whence: Integer): Integer; function Tell: Int64; function Eof: Boolean; function MayBlock: Boolean; public class function UnWrap(data: Pointer): ICefStreamReader; class function CreateForFile(const filename: ustring): ICefStreamReader; class function CreateForCustomStream(const stream: ICefCustomStreamReader): ICefStreamReader; class function CreateForStream(const stream: TSTream; owned: Boolean): ICefStreamReader; class function CreateForData(data: Pointer; size: NativeUInt): ICefStreamReader; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFCustomStreamReader; class function TCefStreamReaderRef.CreateForCustomStream( const stream: ICefCustomStreamReader): ICefStreamReader; begin Result := UnWrap(cef_stream_reader_create_for_handler(CefGetData(stream))) end; class function TCefStreamReaderRef.CreateForData(data: Pointer; size: NativeUInt): ICefStreamReader; begin Result := UnWrap(cef_stream_reader_create_for_data(data, size)) end; class function TCefStreamReaderRef.CreateForFile(const filename: ustring): ICefStreamReader; var f: TCefString; begin f := CefString(filename); Result := UnWrap(cef_stream_reader_create_for_file(@f)) end; class function TCefStreamReaderRef.CreateForStream(const stream: TSTream; owned: Boolean): ICefStreamReader; begin Result := CreateForCustomStream(TCefCustomStreamReader.Create(stream, owned) as ICefCustomStreamReader); end; function TCefStreamReaderRef.Eof: Boolean; begin Result := PCefStreamReader(FData)^.eof(PCefStreamReader(FData)) <> 0; end; function TCefStreamReaderRef.MayBlock: Boolean; begin Result := PCefStreamReader(FData)^.may_block(FData) <> 0; end; function TCefStreamReaderRef.Read(ptr: Pointer; size, n: NativeUInt): NativeUInt; begin Result := PCefStreamReader(FData)^.read(PCefStreamReader(FData), ptr, size, n); end; function TCefStreamReaderRef.Seek(offset: Int64; whence: Integer): Integer; begin Result := PCefStreamReader(FData)^.seek(PCefStreamReader(FData), offset, whence); end; function TCefStreamReaderRef.Tell: Int64; begin Result := PCefStreamReader(FData)^.tell(PCefStreamReader(FData)); end; class function TCefStreamReaderRef.UnWrap(data: Pointer): ICefStreamReader; begin if data <> nil then Result := Create(data) as ICefStreamReader else Result := nil; end; end.
unit ConsoleMsg; interface uses SysUtils; Procedure PrintWarning(Msg: String); Procedure PrintError(Msg: String); Procedure PrintInfo(Msg: String); Procedure PrintMessage(Msg: String); implementation Procedure PrintWarning(Msg: String); Begin Writeln(DateTimeToStr(Now) + ' Warning: ' + Msg); End; Procedure PrintError(Msg: String); Begin Writeln(DateTimeToStr(Now) + ' Error: ' + Msg); End; Procedure PrintInfo(Msg: String); Begin Writeln(DateTimeToStr(Now) + ' Info: ' + Msg); End; Procedure PrintMessage(Msg: String); Begin Writeln(DateTimeToStr(Now) + ' Message: ' + Msg); End; end.
unit UnitWindows; interface uses windows, sysutils, Psapi, Classes, TlHelp32, UnitFuncoesDiversas, UnitConstantes; function WindowList(ShowHidden: Boolean): widestring; function EnableDisableCloseWindowButton(handle: HWND; Enable: boolean): boolean; //function GetProcessNameFromWnd(Wnd: HWND): widestring; implementation threadvar WindowListing: widestring; type tagPROCESSENTRY32 = record dwSize: DWORD; cntUsage: DWORD; th32ProcessID: DWORD; // this process th32DefaultHeapID: DWORD; th32ModuleID: DWORD; // associated exe cntThreads: DWORD; th32ParentProcessID: DWORD; // this process's parent process pcPriClassBase: Longint; // Base priority of process's threads dwFlags: DWORD; szExeFile: array[0..MAX_PATH - 1] of WChar;// Path end; TProcessEntry32 = tagPROCESSENTRY32; function Process32First(hSnapshot: THandle; var lppe: TProcessEntry32): BOOL; stdcall; external 'kernel32.dll' name 'Process32FirstW'; function Process32Next(hSnapshot: THandle; var lppe: TProcessEntry32): BOOL; stdcall; external 'kernel32.dll' name 'Process32NextW'; function IntToStr(i: Int64): WideString; begin Str(i, Result); end; function StrToInt(S: WideString): Int64; var E: integer; begin Val(S, Result, E); end; function EnableDisableCloseWindowButton(handle: HWND; Enable: boolean): boolean; var Flag: UINT; AppSysMenu: THandle; begin if Enable = false then Flag := MF_GRAYED else Flag := MF_ENABLED; AppSysMenu := windows.GetSystemMenu(Handle, False); result := EnableMenuItem(AppSysMenu, SC_CLOSE, MF_BYCOMMAND or Flag); end; function GetClass(Handle: integer): Widestring; var Buf: array[0..255] of Widechar; begin GetClassNameW(Handle,Buf,255); Result := Buf; end; function HandleToPid(Handle: integer): integer; var PID: dword; begin GetWindowThreadProcessId(Handle,Pid); Result := Pid; end; function PidToPath(Pid: integer): widestring; var ProcessHandle: THandle; begin ProcessHandle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False,Pid); SetLength(result, MAX_PATH * 2); if (GetModuleFileNameExW(ProcessHandle, 0, PWideChar(result), MAX_PATH)) > 0 then begin SetLength(result, length(PWideChar(result))); end else begin result := 'System'; end; CloseHandle(ProcessHandle); end; function GetWindowAttr(Handle: integer): widestring; { E = Enabled D = Disabled V = Visible H = Hidden Max = Maximized Min = Minimized } begin if iswindowenabled(Handle) then Result := 'E' else Result := 'D'; if iswindowvisible(Handle) then Result := Result + ' - V' else Result := Result + ' - H'; if iszoomed(Handle) then Result := Result + ' - Max'; if isiconic(Handle) then Result := Result + ' - Min' ; end; function TrimRight(const S: widestring): widestring; var I: Integer; begin I := Length(S); while (I > 0) and (S[I] <= ' ') do Dec(I); Result := Copy(S, 1, I); end; function GetCaption(Handle: integer): widestring; var Title: array[0..255] of WideChar; begin Result := ''; if Handle <> 0 then begin GetWindowTextW(Handle, Title, SizeOf(Title)); Result := Title; Result := TrimRight(Result); end; end; function eWindows(Handle: integer; ShowHidden: Integer): bool; stdcall; begin //if ShowHidden = 1 then if iswindowvisible(Handle) then // mostra somente as visíveis if iswindowvisible(Handle) then // dessa forma sempre mostra as visíveis begin WindowListing := WindowListing + inttostr(Handle) + delimitadorComandos + GetCaption(Handle) + delimitadorComandos + GetClass(Handle) + delimitadorComandos + GetWindowAttr(Handle) + delimitadorComandos + {GetProcessNameFromWnd}PidToPath(HandleToPid(Handle)) + delimitadorComandos + inttostr(HandleToPid(Handle)) + delimitadorComandos + #13#10; end; if ShowHidden = 0 then begin if not iswindowvisible(Handle) then begin WindowListing := WindowListing + inttostr(Handle) + delimitadorComandos + GetCaption(Handle) + delimitadorComandos + GetClass(Handle) + delimitadorComandos + GetWindowAttr(Handle) + delimitadorComandos + {GetProcessNameFromWnd}PidToPath(HandleToPid(Handle)) + delimitadorComandos + inttostr(HandleToPid(Handle)) + delimitadorComandos + #13#10; end; end; Result := True; end; function WindowList(ShowHidden: Boolean): Widestring; var Show: integer; begin if ShowHidden = true then Show := 0 else Show := 1; WindowListing := ''; EnumWindows(@eWindows, Show); Result := WindowListing; end; function ChildWindowList(Ownerhandle: widestring; Number: widestring): widestring; begin WindowListing := ''; EnumChildWindows(strtoint(Ownerhandle),@eWindows,strtoint(Number)); Result := WindowListing; end; function ForceForegroundWindow(wnd: THandle): Boolean; const SPI_GETFOREGROUNDLOCKTIMEOUT = $2000; SPI_SETFOREGROUNDLOCKTIMEOUT = $2001; var ForegroundThreadID: DWORD; ThisThreadID: DWORD; timeout: DWORD; begin Result := False; if IsIconic(wnd) then ShowWindow(wnd, SW_RESTORE); if GetForegroundWindow = wnd then begin Result := True; Exit; end; //if ((Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion > 4)) or ((Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and ((Win32MajorVersion > 4) or ((Win32MajorVersion = 4) and (Win32MinorVersion > 0)))) then begin ForegroundThreadID := GetWindowThreadProcessID(GetForegroundWindow, nil); ThisThreadID := GetWindowThreadPRocessId(wnd, nil); if AttachThreadInput(ThisThreadID, ForegroundThreadID, True) then begin BringWindowToTop(wnd); SetForegroundWindow(wnd); AttachThreadInput(ThisThreadID, ForegroundThreadID, False); Result := (GetForegroundWindow = wnd); end; if not Result then begin SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, @timeout, 0); SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, TObject(0), SPIF_SENDCHANGE); BringWindowToTop(wnd); // IE 5.5 related hack SetForegroundWindow(Wnd); SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, TObject(timeout), SPIF_SENDCHANGE); end; //end else begin //BringWindowToTop(wnd); // IE 5.5 related hack //SetForegroundWindow(wnd); //end; Result := (GetForegroundWindow = wnd); end; procedure SimulateKeyDown(Key : byte); begin keybd_event(Key, 0, 0, 0); end; procedure SimulateKeyUp(Key : byte); begin keybd_event(Key, 0, KEYEVENTF_KEYUP, 0); end; procedure SimulateKeystroke(Key : byte; extra : DWORD); begin keybd_event(Key,extra,0,0); keybd_event(Key,extra,KEYEVENTF_KEYUP,0); end; procedure SendKeys(s : widestring); var i : integer; flag : bool; w : word; begin {Get the state of the caps lock key} flag := not GetKeyState(VK_CAPITAL) and 1 = 0; {If the caps lock key is on then turn it off} if flag then SimulateKeystroke(VK_CAPITAL, 0); for i := 1 to Length(s) do begin if s[i] = '~' then begin SimulateKeyDown(VK_RETURN); continue; end else begin w := VkKeyScanW(s[i]); if ((HiByte(w) <> $FF) and (LoByte(w) <> $FF)) then begin if HiByte(w) and 1 = 1 then SimulateKeyDown(VK_SHIFT); SimulateKeystroke(LoByte(w), 0); if HiByte(w) and 1 = 1 then SimulateKeyUp(VK_SHIFT); end; end; end; if flag then SimulateKeystroke(VK_CAPITAL, 0); end; function KillProc(Pid: integer): Boolean; var Ph: integer; begin Result := False; Ph := OpenProcess(PROCESS_TERMINATE,False,PID); if TerminateProcess(Ph,0) then Result := True; CloseHandle(Ph); end; (* const RsSystemIdleProcess = 'System Idle Process'; RsSystemProcess = 'System Process'; function IsWinXP: Boolean; begin Result := (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion = 5) and (Win32MinorVersion = 1); end; function IsWin2k: Boolean; begin Result := (Win32MajorVersion >= 5) and (Win32Platform = VER_PLATFORM_WIN32_NT); end; function IsWinNT4: Boolean; begin Result := Win32Platform = VER_PLATFORM_WIN32_NT; Result := Result and (Win32MajorVersion = 4); end; function IsWin3X: Boolean; begin Result := Win32Platform = VER_PLATFORM_WIN32_NT; Result := Result and (Win32MajorVersion = 3) and ((Win32MinorVersion = 1) or (Win32MinorVersion = 5) or (Win32MinorVersion = 51)); end; function RunningProcessesList(const List: TStrings; FullPath: Boolean): Boolean; function strlen(lpstr: PWideChar): Integer; var p: PWideChar; begin p := lpstr; while p^ <> #0 do Inc(p); Result := p - lpstr; end; function ProcessFileName(PID: DWORD): Widestring; var Handle: THandle; begin Result := ''; Handle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PID); if Handle <> 0 then try SetLength(Result, MAX_PATH); if FullPath then begin if GetModuleFileNameExW(Handle, 0, PWideChar(Result), MAX_PATH) > 0 then SetLength(Result, StrLen(PWideChar(Result))) else Result := ''; end else begin if GetModuleBaseNameW(Handle, 0, PWideChar(Result), MAX_PATH) > 0 then SetLength(Result, StrLen(PWideChar(Result))) else Result := ''; end; finally CloseHandle(Handle); end; end; function BuildListTH: Boolean; var SnapProcHandle: THandle; ProcEntry: TProcessEntry32; NextProc: Boolean; FileName: Widestring; begin SnapProcHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); Result := (SnapProcHandle <> INVALID_HANDLE_VALUE); if Result then try ProcEntry.dwSize := SizeOf(ProcEntry); NextProc := Process32First(SnapProcHandle, ProcEntry); while NextProc do begin if ProcEntry.th32ProcessID = 0 then begin FileName := RsSystemIdleProcess; end else begin if IsWin2k or IsWinXP then begin FileName := ProcessFileName(ProcEntry.th32ProcessID); if FileName = '' then FileName := ProcEntry.szExeFile; end else begin FileName := ProcEntry.szExeFile; if not FullPath then FileName := ExtractFileName(FileName); end; end; List.AddObject(FileName, Pointer(ProcEntry.th32ProcessID)); NextProc := Process32Next(SnapProcHandle, ProcEntry); end; finally CloseHandle(SnapProcHandle); end; end; function BuildListPS: Boolean; var PIDs: array [0..1024] of DWORD; Needed: DWORD; I: Integer; FileName: widestring; begin Result := EnumProcesses(@PIDs, SizeOf(PIDs), Needed); if Result then begin for I := 0 to (Needed div SizeOf(DWORD)) - 1 do begin case PIDs[I] of 0: FileName := RsSystemIdleProcess; 2: if IsWinNT4 then FileName := RsSystemProcess else FileName := ProcessFileName(PIDs[I]); 8: if IsWin2k or IsWinXP then FileName := RsSystemProcess else FileName := ProcessFileName(PIDs[I]); else FileName := ProcessFileName(PIDs[I]); end; if FileName <> '' then List.AddObject(FileName, Pointer(PIDs[I])); end; end; end; begin if IsWin3X or IsWinNT4 then Result := BuildListPS else Result := BuildListTH; end; function GetProcessNameFromWnd(Wnd: HWND): widestring; var List: TStringList; PID: DWORD; I: Integer; begin Result := ''; if IsWindow(Wnd) then begin PID := INVALID_HANDLE_VALUE; GetWindowThreadProcessId(Wnd, @PID); List := TStringList.Create; try if RunningProcessesList(List, True) then begin I := List.IndexOfObject(Pointer(PID)); if I > -1 then Result := List[I]; end; finally List.Free; end; end; end; *) end.
{----------------------------------------------------------------------------- Unit Name: dlgOptionsEditor Author: Kiriakos Vlahos Date: 10-Mar-2005 Purpose: Generic Options Editor based on JvInspector History: -----------------------------------------------------------------------------} unit dlgOptionsEditor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, JvInspector, JvExControls, SpTBXControls, dlgPyIDEBase, SpTBXItem; type TOption = record PropertyName : string; DisplayName : string; end; TOptionCategory = record DisplayName : string; Options : array of TOption; end; TBaseOptionsClass = class of TBaseOptions; TBaseOptions = class(TPersistent) public constructor Create; virtual; abstract; end; TOptionsInspector = class(TPyIDEDlgBase) Panel1: TSpTBXPanel; Inspector: TJvInspector; Panel2: TSpTBXPanel; OKButton: TSpTBXButton; BitBtn2: TSpTBXButton; HelpButton: TSpTBXButton; procedure OKButtonClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure HelpButtonClick(Sender: TObject); private { Private declarations } fOptionsObject, fTempOptionsObject : TPersistent; public { Public declarations } procedure Setup(OptionsObject : TBaseOptions; Categories : array of TOptionCategory); end; function InspectOptions(OptionsObject : TBaseOptions; Categories : array of TOptionCategory; FormCaption : string; HelpCntxt : integer = 0): boolean; implementation {$R *.dfm} { TIDEOptionsWindow } procedure TOptionsInspector.Setup(OptionsObject: TBaseOptions; Categories: array of TOptionCategory); var i, j : integer; InspCat: TJvInspectorCustomCategoryItem; Item : TJvCustomInspectorItem; begin Inspector.Clear; fOptionsObject := OptionsObject; fTempOptionsObject := TBaseOptionsClass(OptionsObject.ClassType).Create; fTempOptionsObject.Assign(fOptionsObject); for i := Low(Categories) to High(Categories) do with Categories[i] do begin InspCat := TJvInspectorCustomCategoryItem.Create(Inspector.Root, nil); InspCat.DisplayName := DisplayName; for j := Low(Options) to High(Options) do begin Item := TJvInspectorPropData.New(InspCat, fTempOptionsObject, Options[j].PropertyName); Item.DisplayName := Options[j].DisplayName; if Item is TJvInspectorBooleanItem then TJvInspectorBooleanItem(Item).ShowAsCheckbox := True; end; InspCat.Expanded := True; end; Inspector.Root.Sort; end; procedure TOptionsInspector.OKButtonClick(Sender: TObject); begin Inspector.SaveValues; // Save currently editing item fOptionsObject.Assign(fTempOptionsObject); end; procedure TOptionsInspector.FormDestroy(Sender: TObject); begin if Assigned(fTempOptionsObject) then FreeAndNil(fTempOptionsObject); end; function InspectOptions(OptionsObject : TBaseOptions; Categories : array of TOptionCategory; FormCaption : string; HelpCntxt : integer = 0): boolean; begin with TOptionsInspector.Create(Application) do begin Caption := FormCaption; HelpContext := HelpCntxt; Setup(OptionsObject, Categories); Result := ShowModal = mrOK; Release; end; end; procedure TOptionsInspector.HelpButtonClick(Sender: TObject); begin if HelpContext <> 0 then Application.HelpContext(HelpContext); end; end.
unit uClassMatricula; interface type TMatricula = class private FAlunoId: Integer; Fid: Integer; Fano: Integer; procedure SetAlunoId(const Value: Integer); procedure Setano(const Value: Integer); procedure Setid(const Value: Integer); public property id : Integer read Fid write Setid; property AlunoId : Integer read FAlunoId write SetAlunoId; property ano : Integer read Fano write Setano; end; implementation { TMatricula } procedure TMatricula.SetAlunoId(const Value: Integer); begin FAlunoId := Value; end; procedure TMatricula.Setano(const Value: Integer); begin Fano := Value; end; procedure TMatricula.Setid(const Value: Integer); begin Fid := Value; end; end.
(* Category: SWAG Title: STRING HANDLING ROUTINES Original name: 0073.PAS Description: String Comparision Author: GREG ESTABROOKS Date: 02-03-94 09:57 *) {*********************************************************************} PROGRAM StrCompare; { Jan 23/94, Greg Estabrooks. } USES CRT; { IMPORT Clrscr,WriteLn. } VAR SubName :STRING; { Holds the Subject name entered. } FUNCTION StrCmp( Str1,Str2 :STRING ) :BOOLEAN; { Case InSensitive Routine to compare two } { strings. } VAR StrPos :BYTE; { Current position within Strings. } CmpResult:BOOLEAN; { Result of comparison. } BEGIN CmpResult := TRUE; { Initialize 'CmpResult' to TRUE. } IF Length(Str1) <> Length(Str2) THEN { If not same length then don't} CmpResult := FALSE { Bother converting case and } { compareing. } ELSE BEGIN StrPos := 0; { Initialize 'StrPos' to 0. } REPEAT { Loop until every char checked. } INC(StrPos); { Point to next char. } IF UpCase(Str1[StrPos]) <> UpCase(Str2[StrPos]) THEN BEGIN CmpResult := False; { If there not the same then return } { a FALSE result. } StrPos := Length(Str2); { Now set loop exit condition. } END; UNTIL StrPos = Length(Str2); END; StrCmp := CmpResult; END;{StrCmp} BEGIN Clrscr; { Clear away the screen. } Write(' Name of subject ? :');{ Prompt user for subject name. } Readln(SubName); { Now get users input. } IF StrCmp('English',SubName) THEN { If there the same then tell user} Writeln('You chose ENGLISH') ELSE { If not then .............. } Writeln('Unknown Subject!',^G);{Tell user its unknown. } END.{StrCompare} {*********************************************************************} h
{***************************************************************************} { } { 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.Repository.Http; interface uses Generics.Defaults, VSoft.Awaitable, Spring.Collections, DPM.Core.Types, DPM.Core.Dependency.Version, DPM.Core.Logging, DPM.Core.Options.Search, DPM.Core.Options.Push, DPM.Core.Package.Interfaces, DPM.Core.Configuration.Interfaces, DPM.Core.Sources.Interfaces, DPM.Core.Repository.Interfaces, DPM.Core.Repository.Base; type TDPMServerPackageRepository = class(TBaseRepository, IPackageRepository) private FServiceIndex : IServiceIndex; protected procedure Configure(const source : ISourceConfig); override; function GetServiceIndex(const cancellationToken : ICancellationToken) : IServiceIndex; function DownloadPackage(const cancellationToken : ICancellationToken; const packageIdentity : IPackageIdentity; const localFolder : string; var fileName : string) : Boolean; function FindLatestVersion(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const version : TPackageVersion; const platform : TDPMPlatform; const includePrerelease : boolean) : IPackageIdentity; function GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo; function GetPackageVersions(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const preRelease : boolean) : IList<TPackageVersion>; function GetPackageVersionsWithDependencies(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const versionRange : TVersionRange; const preRelease : Boolean) : IList<IPackageInfo>; function List(const cancellationToken : ICancellationToken; const options : TSearchOptions) : IList<IPackageListItem>; overload; function GetPackageFeed(const cancellationToken : ICancellationToken; const options : TSearchOptions; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResult; function GetPackageFeedByIds(const cancellationToken : ICancellationToken; const ids : IList<IPackageId>; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResult; function GetPackageIcon(const cancelToken : ICancellationToken; const packageId : string; const packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageIcon; function GetPackageMetaData(const cancellationToken: ICancellationToken; const packageId: string; const packageVersion: string; const compilerVersion: TCompilerVersion; const platform: TDPMPlatform): IPackageSearchResultItem; //commands function Push(const cancellationToken : ICancellationToken; const pushOptions : TPushOptions) : Boolean; public constructor Create(const logger : ILogger); override; end; implementation uses System.SysUtils, System.IOUtils, System.Classes, JsonDataObjects, VSoft.HttpClient, VSoft.URI, DPM.Core.Spec.Interfaces, DPM.Core.Spec, DPM.Core.Package.Icon, DPM.Core.Constants, DPM.Core.Package.Metadata, DPM.Core.Package.SearchResults, DPM.Core.Sources.ServiceIndex, DPM.Core.Package.ListItem; const cPreReleaseParam = 'prerel'; cCommercialParam = 'commercial'; cTrialParam = 'trial'; //function GetBaseUri(const uri : IUri) : string; //begin // result := uri.Scheme + '://' + uri.Host; // if uri.Scheme = 'http' then // begin // if uri.Port <> 80 then // result := result + ':' + IntToStr(uri.Port); // end // else if uri.Scheme = 'https' then // begin // if uri.Port <> 443 then // result := result + ':' + IntToStr(uri.Port); // end; // //end; { TDPMServerPackageRepository } procedure TDPMServerPackageRepository.Configure(const source: ISourceConfig); begin //if the uri changes service index will be invalid. if source.Source <> Self.SourceUri then FServiceIndex := nil; inherited; end; constructor TDPMServerPackageRepository.Create(const logger : ILogger); begin inherited Create(logger); end; function TDPMServerPackageRepository.DownloadPackage(const cancellationToken : ICancellationToken; const packageIdentity : IPackageIdentity; const localFolder : string; var fileName : string) : Boolean; var httpClient : IHttpClient; request : TRequest; response : IHttpResponse; serviceIndex : IServiceIndex; serviceItem : IServiceIndexItem; path : string; destFile : string; uri : IUri; begin result := false; serviceIndex := GetServiceIndex(cancellationToken); if serviceIndex = nil then exit; serviceItem := serviceIndex.FindItem('PackageDownload'); if serviceItem = nil then begin Logger.Error('Unabled to determine PackageDownload resource from Service Index'); exit; end; uri := TUriFactory.Parse(serviceItem.ResourceUrl); path := Format('%s/%s/%s/%s/%s/dpkg', [uri.AbsolutePath, packageIdentity.Id, CompilerToString(packageIdentity.CompilerVersion), DPMPlatformToString(packageIdentity.Platform),packageIdentity.Version.ToStringNoMeta]); httpClient := THttpClientFactory.CreateClient(uri.BaseUriString); request := httpClient.CreateRequest(path) .WithHeader(cUserAgentHeader,cDPMUserAgent); destFile := IncludeTrailingPathDelimiter(localFolder) + packageIdentity.ToString + cPackageFileExt; request.SaveAsFile := destFile; Logger.Information('GET ' + uri.BaseUriString + path); try response := request.Get(cancellationToken); except on ex : Exception do begin Logger.Error('Error fetching downloading package from server : ' + ex.Message); exit; end; end; if response.StatusCode <> 200 then begin Logger.Error('Error fetching downloading package from server : ' + response.ErrorMessage); exit; end; Logger.Information('OK ' + uri.BaseUriString + path); fileName := destFile; result := true; end; function TDPMServerPackageRepository.FindLatestVersion(const cancellationToken: ICancellationToken; const id: string; const compilerVersion: TCompilerVersion; const version: TPackageVersion; const platform: TDPMPlatform; const includePrerelease : boolean): IPackageIdentity; var httpClient : IHttpClient; request : TRequest; response : IHttpResponse; serviceIndex : IServiceIndex; serviceItem : IServiceIndexItem; jsonObj : TJsonObject; uri : IUri; begin result := nil; serviceIndex := GetServiceIndex(cancellationToken); if serviceIndex = nil then exit; serviceItem := serviceIndex.FindItem('PackageFind'); if serviceItem = nil then begin Logger.Error('Unabled to determine PackageDownload resource from Service Index'); exit; end; uri := TUriFactory.Parse(serviceItem.ResourceUrl); httpClient := THttpClientFactory.CreateClient(uri.BaseUriString); request := httpClient.CreateRequest(uri.AbsolutePath) .WithHeader(cUserAgentHeader,cDPMUserAgent) .WithAccept('application/json') .WithParameter('id', id) .WithParameter('compiler', CompilerToString(compilerVersion)) .WithParameter('platform', DPMPlatformToString(platform)); //this looks odd but if we specify a version then we want that version only! if not version.IsEmpty then request.WithParameter('version', version.ToStringNoMeta) else if includePrerelease then request.WithParameter(cPreReleaseParam, LowerCase(BoolToStr(includePrerelease, true))); try Logger.Information('GET ' + uri.BaseUriString); response := request.Get(cancellationToken); except on ex : Exception do begin Logger.Error('Error finding package identity from server : ' + ex.Message); exit; end; end; //if the package or package version is not on the server this is fine if response.StatusCode = 404 then begin Logger.Information('NOTFOUND ' + uri.BaseUriString); exit; end; if response.StatusCode <> 200 then begin Logger.Error('Error fetching list from server : ' + response.ErrorMessage); exit; end; if response.ContentLength = 0 then begin Logger.Verbose('Server returned no content'); exit; end; Logger.Information('OK ' + uri.BaseUriString); try jsonObj := TJsonBaseObject.Parse(response.Response) as TJsonObject; except on e : Exception do begin Logger.Error('Error parsing json response from server : ' + e.Message); exit; end; end; try TPackageIdentity.TryLoadFromJson(Logger, jsonObj, Self.Name, Result); finally jsonObj.Free; end; end; function TDPMServerPackageRepository.GetPackageFeed(const cancellationToken : ICancellationToken; const options : TSearchOptions; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResult; var httpClient : IHttpClient; request : TRequest; response : IHttpResponse; serviceIndex : IServiceIndex; serviceItem : IServiceIndexItem; jsonObj : TJsonObject; jsonArr : TJsonArray; itemObj : TJsonObject; i: Integer; uri : IUri; resultItem : IPackageSearchResultItem; begin Result := TDPMPackageSearchResult.Create(options.Skip, 0); serviceIndex := GetServiceIndex(cancellationToken); if serviceIndex = nil then exit; serviceItem := serviceIndex.FindItem('PackageSearch'); if serviceItem = nil then begin Logger.Error('Unabled to determine PackageSearch resource from Service Index'); exit; end; uri := TUriFactory.Parse(serviceItem.ResourceUrl); httpClient := THttpClientFactory.CreateClient(uri.BaseUriString); request := httpClient.CreateRequest(uri.AbsolutePath) .WithHeader(cUserAgentHeader,cDPMUserAgent) .WithAccept('application/json'); if options.SearchTerms <> '' then request.WithParameter('q', Trim(options.SearchTerms)); request.WithParameter('compiler', CompilerToString(compilerVersion)); request.WithParameter('platform', DPMPlatformToString(platform)); request.WithParameter(cPreReleaseParam, LowerCase(BoolToStr(options.Prerelease, true))); request.WithParameter(cCommercialParam, LowerCase(BoolToStr(options.Commercial, true))); request.WithParameter(cTrialParam, LowerCase(BoolToStr(options.Trial, true))); if options.Skip <> 0 then request.WithParameter('skip', IntToStr(options.Skip)); if options.Take <> 0 then request.WithParameter('take', IntToStr(options.Take)); try response := request.Get(cancellationToken); except on ex : Exception do begin Logger.Error('Error fetching list from server : ' + ex.Message); exit; end; end; if response.StatusCode <> 200 then begin Logger.Error('Error fetching search result from server : ' + response.ErrorMessage); exit; end; if response.ContentLength = 0 then begin Logger.Verbose('Server returned no content'); exit; end; try jsonObj := TJsonBaseObject.Parse(response.Response) as TJsonObject; except on e : Exception do begin Logger.Error('Error parsing json response from server : ' + e.Message); exit; end; end; try Result.TotalCount := jsonObj.I['totalHits']; if jsonObj.Contains('results') and (not jsonObj.IsNull('results')) then begin jsonArr := jsonObj.A['results']; for i := 0 to jsonArr.Count -1 do begin if cancellationToken.IsCancelled then exit; itemObj := jsonArr.O[i]; resultItem := TDPMPackageSearchResultItem.FromJson(Name, itemObj); Result.Results.Add(resultItem); end; end; finally jsonObj.Free; end; end; function TDPMServerPackageRepository.GetPackageFeedByIds(const cancellationToken: ICancellationToken; const ids: IList<IPackageId>; const compilerVersion: TCompilerVersion; const platform: TDPMPlatform): IPackageSearchResult; var httpClient : IHttpClient; request : TRequest; response : IHttpResponse; serviceIndex : IServiceIndex; serviceItem : IServiceIndexItem; uri : IUri; jsonObj : TJsonObject; itemObj : TJsonObject; idArray : TJsonArray; jsonArr : TJsonArray; sBody : string; jsonId : TJsonObject; i: Integer; resultItem : IPackageSearchResultItem; begin Result := TDPMPackageSearchResult.Create(0, 0); serviceIndex := GetServiceIndex(cancellationToken); if serviceIndex = nil then exit; serviceItem := serviceIndex.FindItem('PackageSearchIds'); if serviceItem = nil then begin Logger.Error('Unabled to determine PackageSearchIds resource from Service Index'); exit; end; uri := TUriFactory.Parse(serviceItem.ResourceUrl); httpClient := THttpClientFactory.CreateClient(uri.BaseUriString); jsonObj := TJsonObject.Create; try jsonObj.S['compiler'] := CompilerToString(compilerVersion); jsonObj.S['platform'] := DPMPlatformToString(platform); idArray := jsonObj.A['packageids']; for i := 0 to ids.Count -1 do begin jsonId := idArray.AddObject; jsonId.S['id'] := ids.Items[i].Id; jsonId.S['version'] := ids.Items[i].Version.ToStringNoMeta(); end; sBody := jsonObj.ToJSON(false); finally jsonObj.Free; end; request := httpClient.CreateRequest(uri.AbsolutePath) .WithHeader(cUserAgentHeader,cDPMUserAgent) .WithBody(sBody, TEncoding.UTF8) .WithContentType('application/json', 'utf-8'); try Logger.Information('POST ' + uri.ToString); response := request.Post(cancellationToken); except on ex : Exception do begin Logger.Error('Error fetching list from server : ' + ex.Message); exit; end; end; if response.StatusCode <> 200 then begin Logger.Error('Error fetching search result from server : ' + response.ErrorMessage); exit; end; if response.ContentLength = 0 then begin Logger.Verbose('Server returned no content'); exit; end; Logger.Information('OK ' + uri.ToString); try jsonObj := TJsonBaseObject.Parse(response.Response) as TJsonObject; except on e : Exception do begin Logger.Error('Error parsing json response from server : ' + e.Message); exit; end; end; try Result.TotalCount := jsonObj.I['totalHits']; if jsonObj.Contains('results') and (not jsonObj.IsNull('results')) then begin jsonArr := jsonObj.A['results']; for i := 0 to jsonArr.Count -1 do begin if cancellationToken.IsCancelled then exit; itemObj := jsonArr.O[i]; resultItem := TDPMPackageSearchResultItem.FromJson(Name, itemObj); Result.Results.Add(resultItem); end; end; finally jsonObj.Free; end; end; function TDPMServerPackageRepository.GetPackageIcon(const cancelToken : ICancellationToken; const packageId, packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageIcon; var httpClient : IHttpClient; request : TRequest; response : IHttpResponse; serviceIndex : IServiceIndex; serviceItem : IServiceIndexItem; path : string; stream : TMemoryStream; uri : IUri; begin result := nil; serviceIndex := GetServiceIndex(cancelToken); if serviceIndex = nil then exit; serviceItem := serviceIndex.FindItem('PackageDownload'); if serviceItem = nil then begin Logger.Error('Unabled to determine PackageDownload resource from Service Index'); exit; end; uri := TUriFactory.Parse(serviceItem.ResourceUrl); path := Format('%s/%s/%s/%s/%s/icon', [uri.AbsolutePath, packageId, CompilerToString(compilerVersion), DPMPlatformToString(platform),packageVersion]); httpClient := THttpClientFactory.CreateClient(uri.BaseUriString); request := httpClient.CreateRequest(path) .WithHeader(cUserAgentHeader,cDPMUserAgent); try response := request.Get(cancelToken); except on ex : Exception do begin Logger.Error('Error fetching list from server : ' + ex.Message); exit; end; end; if response.StatusCode <> 200 then begin Logger.Error('Error fetching list from server : ' + response.ErrorMessage); exit; end; if response.ContentLength = 0 then begin Logger.Verbose('Server returned no content for icon'); exit; end; if SameText(response.ContentType, 'image/png') then begin stream := TMemoryStream.Create; stream.CopyFrom(response.ResponseStream,response.ContentLength); result := CreatePackageIcon(TPackageIconKind.ikPng, stream); end else if SameText(response.ContentType, 'image/svg+xml') then begin stream := TMemoryStream.Create; stream.CopyFrom(response.ResponseStream,response.ContentLength); result := CreatePackageIcon(TPackageIconKind.ikSvg, stream); end; end; function TDPMServerPackageRepository.GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo; var httpClient : IHttpClient; request : TRequest; response : IHttpResponse; serviceIndex : IServiceIndex; serviceItem : IServiceIndexItem; path : string; jsonObj : TJsonObject; uri : IUri; spec : IPackageSpec; begin result := nil; serviceIndex := GetServiceIndex(cancellationToken); if serviceIndex = nil then exit; serviceItem := serviceIndex.FindItem('PackageInfo'); if serviceItem = nil then begin Logger.Error('Unabled to determine PackageInfo resource from Service Index'); exit; end; uri := TUriFactory.Parse(serviceItem.ResourceUrl); path := Format('%s/%s/%s/%s/%s/dspec', [uri.AbsolutePath, packageId.Id, CompilerToString(packageId.CompilerVersion), DPMPlatformToString(packageId.Platform), packageId.Version.ToStringNoMeta]); httpClient := THttpClientFactory.CreateClient(uri.BaseUriString); request := httpClient.CreateRequest(path) .WithHeader(cUserAgentHeader,cDPMUserAgent) .WithHeader(cAcceptHeader, 'application/json'); try Logger.Information('GET ' + uri.BaseUriString + path); response := request.Get(cancellationToken); except on ex : Exception do begin Logger.Error('Error fetching packageinfo from server : ' + ex.Message); exit; end; end; if response.StatusCode <> 200 then begin Logger.Error('Error fetching packageinfo from server : ' + response.ErrorMessage); exit; end; if response.ContentLength = 0 then begin Logger.Error('Server returned empty dspec from : ' + uri.BaseUriString + path); exit; end; Logger.Information('OK ' + uri.BaseUriString + path); try jsonObj := TJsonBaseObject.Parse(response.Response) as TJsonObject; except on e : Exception do begin Logger.Error('Error parsing json response from server : ' + e.Message); exit; end; end; try spec := TSpec.Create(Logger,''); if not spec.LoadFromJson(jsonObj) then begin Logger.Error('Http Repository : Error reading dspec'); exit; end; result := TPackageInfo.CreateFromSpec(Self.Name, spec); except on e : Exception do begin Logger.Error('Error fetching reading json response from server : ' + e.Message); exit; end; end; end; //Note - we are downloading the dpspec file here rather than hitting the database with the /info endpoint. //since the dpsec will be on the CDN - this will be less load on the db. //TODO : profile CDN response times vs hitting the server. function TDPMServerPackageRepository.GetPackageMetaData(const cancellationToken: ICancellationToken; const packageId, packageVersion: string; const compilerVersion: TCompilerVersion; const platform: TDPMPlatform): IPackageSearchResultItem; var httpClient : IHttpClient; request : TRequest; response : IHttpResponse; serviceIndex : IServiceIndex; serviceItem : IServiceIndexItem; path : string; jsonObj : TJsonObject; uri : IUri; begin result := nil; serviceIndex := GetServiceIndex(cancellationToken); if serviceIndex = nil then exit; serviceItem := serviceIndex.FindItem('PackageMetadata'); if serviceItem = nil then begin Logger.Error('Unabled to determine PackageMetadata resource from Service Index'); exit; end; uri := TUriFactory.Parse(serviceItem.ResourceUrl); path := Format('%s/%s/%s/%s/%s/info', [uri.AbsolutePath, packageId, CompilerToString(compilerVersion), DPMPlatformToString(platform), packageVersion]); httpClient := THttpClientFactory.CreateClient(uri.BaseUriString); request := httpClient.CreateRequest(path) .WithHeader(cUserAgentHeader,cDPMUserAgent); Logger.Information('GET ' + uri.BaseUriString + path); try response := request.Get(cancellationToken); except on ex : Exception do begin Logger.Error('Error fetching packageinfo from server : ' + ex.Message); exit; end; end; if response.StatusCode <> 200 then begin Logger.Error('Error fetching packageinfo from server : ' + response.ErrorMessage); exit; end; Logger.Information('OK ' + uri.BaseUriString + path); try jsonObj := TJsonBaseObject.Parse(response.Response) as TJsonObject; except on e : Exception do begin Logger.Error('Error parsing json response from server : ' + e.Message); exit; end; end; try result := TDPMPackageSearchResultItem.FromJson(Name, jsonObj); Logger.Information('OK ' + uri.BaseUriString + path); except on e : Exception do begin Logger.Error('Error deserializing json response from server : ' + e.Message); exit; end; end; end; function TDPMServerPackageRepository.GetPackageVersions(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const preRelease : boolean) : IList<TPackageVersion>; var httpClient : IHttpClient; request : TRequest; response : IHttpResponse; serviceIndex : IServiceIndex; serviceItem : IServiceIndexItem; path : string; jsonObj : TJsonObject; versionsArr : TJsonArray; i : integer; sVersion : string; packageVersion : TPackageVersion; uri : IUri; begin result := TCollections.CreateList<TPackageVersion>; serviceIndex := GetServiceIndex(cancellationToken); if serviceIndex = nil then exit; serviceItem := serviceIndex.FindItem('PackageVersions'); if serviceItem = nil then begin Logger.Error('Unabled to determine PackageVersions resource from Service Index'); exit; end; uri := TUriFactory.Parse(serviceItem.ResourceUrl); path := Format('%s/%s/%s/%s/versions', [uri.AbsolutePath, id, CompilerToString(compilerVersion), DPMPlatformToString(platform)]); httpClient := THttpClientFactory.CreateClient(uri.BaseUriString); request := httpClient.CreateRequest(path) .WithHeader(cUserAgentHeader,cDPMUserAgent) .WithParameter(cPreReleaseParam, Lowercase(BoolToStr(preRelease, true))); try Logger.Information('GET ' + uri.BaseUriString + path); response := request.Get(cancellationToken); except on ex : Exception do begin Logger.Error('Error fetching versions from server : ' + ex.Message); exit; end; end; if response.StatusCode <> 200 then begin Logger.Error('Error fetching versions from server : ' + response.ErrorMessage); exit; end; Logger.Information('OK ' + uri.BaseUriString + path); try jsonObj := TJsonBaseObject.Parse(response.Response) as TJsonObject; except on e : Exception do begin Logger.Error('Error parsing json response from server : ' + e.Message); exit; end; end; if not jsonObj.Contains('versions') then exit; versionsArr := jsonObj.A['versions']; for i := 0 to versionsArr.Count -1 do begin sVersion := versionsArr.Items[i].Value; if TPackageVersion.TryParse(sVersion, packageVersion) then result.Add(packageVersion); end; end; function TDPMServerPackageRepository.GetPackageVersionsWithDependencies(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const versionRange : TVersionRange; const preRelease : Boolean) : IList<IPackageInfo>; var httpClient : IHttpClient; request : TRequest; response : IHttpResponse; serviceIndex : IServiceIndex; serviceItem : IServiceIndexItem; path : string; jsonObj : TJsonObject; versionsArr : TJsonArray; versionObj : TJsonObject; i: Integer; packageInfo : IPackageInfo; uri : IUri; begin result := TCollections.CreateList<IPackageInfo>; serviceIndex := GetServiceIndex(cancellationToken); if serviceIndex = nil then exit; serviceItem := serviceIndex.FindItem('PackageVersionsWithDeps'); if serviceItem = nil then begin Logger.Error('Unabled to determine PackageVersionsWithDeps resource from Service Index'); exit; end; uri := TUriFactory.Parse(serviceItem.ResourceUrl); path := Format('%s/%s/%s/%s/versionswithdependencies', [uri.AbsolutePath, id, CompilerToString(compilerVersion), DPMPlatformToString(platform)]); httpClient := THttpClientFactory.CreateClient(uri.BaseUriString); request := httpClient.CreateRequest(path) .WithHeader(cUserAgentHeader,cDPMUserAgent) .WithAccept('application/json') //parameters can't have spaces.. winhttp will report invalid header! .WithParameter('versionRange', StringReplace(versionRange.ToString, ' ', '', [rfReplaceAll])) .WithParameter('prerel', Lowercase(BoolToStr(preRelease, true))); try Logger.Information('GET ' + uri.BaseUriString + path); response := request.Get(cancellationToken); except on ex : Exception do begin Logger.Error('Error fetching packageinfo from server : ' + ex.Message); exit; end; end; if response.StatusCode <> 200 then begin Logger.Error('Error fetching packageinfo from server : ' + response.ErrorMessage); exit; end; Logger.Information('OK ' + uri.BaseUriString + path); try jsonObj := TJsonBaseObject.Parse(response.Response) as TJsonObject; except on e : Exception do begin Logger.Error('Error parsing json response from server : ' + e.Message); exit; end; end; if not jsonObj.Contains('versions') then exit; versionsArr := jsonObj.A['versions']; for i := 0 to versionsArr.Count -1 do begin versionObj := versionsArr.O[i]; if TPackageInfo.TryLoadFromJson(Logger, versionObj, Name, packageInfo) then result.Add(packageInfo) end; //TODO : should make sure the server returns a sorted result. result.Sort(TComparer<IPackageInfo>.Construct( function(const Left, Right : IPackageInfo) : Integer begin result := right.Version.CompareTo(left.Version); ; end)); end; function TDPMServerPackageRepository.GetServiceIndex(const cancellationToken: ICancellationToken): IServiceIndex; var httpClient : IHttpClient; request : TRequest; response : IHttpResponse; uri : IUri; begin result := FServiceIndex; if result <> nil then exit; uri := TUriFactory.Parse(self.SourceUri); httpClient := THttpClientFactory.CreateClient(uri.BaseUriString); request := httpClient.CreateRequest(uri.AbsolutePath) .WithHeader(cUserAgentHeader,cDPMUserAgent); try response := request.Get(cancellationToken); if response.StatusCode <> 200 then begin if response.StatusCode > 0 then Logger.Error(Format('Error [%d] getting source service index : %s ', [response.StatusCode, response.ErrorMessage])) else Logger.Error(Format('Error [%d] getting source service index : %s ', [response.StatusCode, 'unabled to contact source'])); exit; end; result := TServiceIndex.LoadFromString(response.Response); FServiceIndex := result; except on e : Exception do begin Logger.Error('Error parsing serviceindex json : ' + e.Message); exit; end; end; end; function TDPMServerPackageRepository.List(const cancellationToken : ICancellationToken; const options : TSearchOptions) : IList<IPackageListItem>; var httpClient : IHttpClient; request : TRequest; response : IHttpResponse; serviceIndex : IServiceIndex; serviceItem : IServiceIndexItem; uri : IUri; jsonObj : TJsonObject; jsonArr : TJsonArray; listItem : IPackageListItem; I: Integer; begin result := TCollections.CreateList<IPackageListItem>; if cancellationToken.IsCancelled then exit; serviceIndex := GetServiceIndex(cancellationToken); if serviceIndex = nil then exit; serviceItem := serviceIndex.FindItem('PackageList'); if serviceItem = nil then begin Logger.Error('Unabled to determine PackageList resource from Service Index'); exit; end; uri := TUriFactory.Parse(serviceItem.ResourceUrl); httpClient := THttpClientFactory.CreateClient(uri.BaseUriString); request := httpClient.CreateRequest(uri.AbsolutePath) .WithHeader(cUserAgentHeader,cDPMUserAgent) .WithAccept('application/json'); if options.SearchTerms <> '' then request.WithParameter('q', options.SearchTerms); if options.Prerelease then request.WithParameter('prerel', 'true'); if not options.Commercial then request.WithParameter('commercial','false'); if not options.Trial then request.WithParameter('trial','false'); if options.CompilerVersion <> TCompilerVersion.UnknownVersion then request.WithParameter('compiler', CompilerToString(options.CompilerVersion)); if options.Platforms <> [] then request.WithParameter('platforms', DPMPlatformsToString(options.Platforms)); if options.Skip <> 0 then request.WithParameter('skip', IntToStr(options.Skip)); if options.Take <> 0 then request.WithParameter('take', IntToStr(options.Take)); try response := request.Get(cancellationToken); except on ex : Exception do begin Logger.Error('Error fetching list from server : ' + ex.Message); exit; end; end; if response.StatusCode <> 200 then begin Logger.Error('Error fetching list from server : ' + response.ErrorMessage); exit; end; try jsonObj := TJsonObject.Parse(response.Response) as TJsonObject; except on ex : Exception do begin Logger.Error('Error fetching parsing json response server : ' + ex.Message); exit; end; end; jsonArr := jsonObj.A['results']; if jsonArr.Count > 0 then begin for I := 0 to jsonArr.Count -1 do begin if TPackageListItem.TryLoadFromJson(Logger, jsonArr.O[i], listItem) then Result.Add(listItem) else exit; //error would have been logged in the tryloadfromjson end; end; end; function TDPMServerPackageRepository.Push(const cancellationToken : ICancellationToken; const pushOptions : TPushOptions): Boolean; var httpClient : IHttpClient; request : TRequest; response : IHttpResponse; serviceIndex : IServiceIndex; serviceItem : IServiceIndexItem; uri : IUri; begin result := false; if pushOptions.ApiKey = '' then begin Logger.Error('ApiKey arg required for remote push'); end; pushOptions.PackagePath := TPath.GetFullPath(pushOptions.PackagePath); if not FileExists(pushOptions.PackagePath) then begin Logger.Error('Package file [' + pushOptions.PackagePath + '] not found.'); exit; end; if cancellationToken.IsCancelled then exit; serviceIndex := GetServiceIndex(cancellationToken); if serviceIndex = nil then exit; serviceItem := serviceIndex.FindItem('PackagePublish'); if serviceItem = nil then begin Logger.Error('Unabled to determine PackagePublish resource from Service Index'); exit; end; uri := TUriFactory.Parse(serviceItem.ResourceUrl); //todo: Add BaseUri to Uri class httpClient := THttpClientFactory.CreateClient(uri.BaseUriString); request := httpClient.CreateRequest(uri.AbsolutePath) .WithHeader(cUserAgentHeader,cDPMUserAgent); request.WithHeader('X-ApiKey', pushOptions.ApiKey); request.WithFile(pushOptions.PackagePath); response := request.Put(cancellationToken); Logger.Information(Format('Package Upload [%d] : %s', [response.StatusCode, response.Response])); result := response.StatusCode = 201; end; end.
unit VolumeRGBLongData; interface uses Windows, Graphics, BasicDataTypes, Abstract3DVolumeData, RGBLongDataSet, AbstractDataSet, dglOpenGL, Math; type T3DVolumeRGBLongData = class (TAbstract3DVolumeData) private FDefaultColor: TPixelRGBLongData; // Gets function GetData(_x, _y, _z, _c: integer):longword; function GetDataUnsafe(_x, _y, _z, _c: integer):longword; function GetDefaultColor:TPixelRGBLongData; // Sets procedure SetData(_x, _y, _z, _c: integer; _value: longword); procedure SetDataUnsafe(_x, _y, _z, _c: integer; _value: longword); procedure SetDefaultColor(_value: TPixelRGBLongData); protected // Constructors and Destructors procedure Initialize; override; // Gets function GetBitmapPixelColor(_Position: longword):longword; override; function GetRPixelColor(_Position: longword):byte; override; function GetGPixelColor(_Position: longword):byte; override; function GetBPixelColor(_Position: longword):byte; override; function GetAPixelColor(_Position: longword):byte; override; function GetRedPixelColor(_x,_y,_z: integer):single; override; function GetGreenPixelColor(_x,_y,_z: integer):single; override; function GetBluePixelColor(_x,_y,_z: integer):single; override; function GetAlphaPixelColor(_x,_y,_z: integer):single; override; // Sets procedure SetBitmapPixelColor(_Position, _Color: longword); override; procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override; procedure SetRedPixelColor(_x,_y,_z: integer; _value:single); override; procedure SetGreenPixelColor(_x,_y,_z: integer; _value:single); override; procedure SetBluePixelColor(_x,_y,_z: integer; _value:single); override; procedure SetAlphaPixelColor(_x,_y,_z: integer; _value:single); override; // Copies procedure CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer); override; public // Gets function GetOpenGLFormat:TGLInt; override; // copies procedure Assign(const _Source: TAbstract3DVolumeData); override; // Misc procedure ScaleBy(_Value: single); override; procedure Invert; override; procedure Fill(_Value: longword); // properties property Data[_x,_y,_z,_c:integer]:longword read GetData write SetData; default; property DataUnsafe[_x,_y,_z,_c:integer]:longword read GetDataUnsafe write SetDataUnsafe; property DefaultColor:TPixelRGBLongData read GetDefaultColor write SetDefaultColor; end; implementation // Constructors and Destructors procedure T3DVolumeRGBLongData.Initialize; begin FDefaultColor.r := 0; FDefaultColor.g := 0; FDefaultColor.b := 0; FData := TRGBLongDataSet.Create; end; // Gets function T3DVolumeRGBLongData.GetData(_x, _y, _z, _c: integer):longword; begin if IsPixelValid(_x,_y,_z) and (_c >= 0) and (_c <= 2) then begin case (_c) of 0: Result := (FData as TRGBLongDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x]; 1: Result := (FData as TRGBLongDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x]; else begin Result := (FData as TRGBLongDataSet).Blue[(_z * FYxXSize) + (_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 T3DVolumeRGBLongData.GetDataUnsafe(_x, _y, _z, _c: integer):longword; begin case (_c) of 0: Result := (FData as TRGBLongDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x]; 1: Result := (FData as TRGBLongDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x]; else begin Result := (FData as TRGBLongDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x]; end; end; end; function T3DVolumeRGBLongData.GetDefaultColor:TPixelRGBLongData; begin Result := FDefaultColor; end; function T3DVolumeRGBLongData.GetBitmapPixelColor(_Position: longword):longword; begin Result := RGB((FData as TRGBLongDataSet).Blue[_Position],(FData as TRGBLongDataSet).Green[_Position],(FData as TRGBLongDataSet).Red[_Position]); end; function T3DVolumeRGBLongData.GetRPixelColor(_Position: longword):byte; begin Result := (FData as TRGBLongDataSet).Red[_Position] and $FF; end; function T3DVolumeRGBLongData.GetGPixelColor(_Position: longword):byte; begin Result := (FData as TRGBLongDataSet).Green[_Position] and $FF; end; function T3DVolumeRGBLongData.GetBPixelColor(_Position: longword):byte; begin Result := (FData as TRGBLongDataSet).Blue[_Position] and $FF; end; function T3DVolumeRGBLongData.GetAPixelColor(_Position: longword):byte; begin Result := 0; end; function T3DVolumeRGBLongData.GetRedPixelColor(_x,_y,_z: integer):single; begin Result := (FData as TRGBLongDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x]; end; function T3DVolumeRGBLongData.GetGreenPixelColor(_x,_y,_z: integer):single; begin Result := (FData as TRGBLongDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x]; end; function T3DVolumeRGBLongData.GetBluePixelColor(_x,_y,_z: integer):single; begin Result := (FData as TRGBLongDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x]; end; function T3DVolumeRGBLongData.GetAlphaPixelColor(_x,_y,_z: integer):single; begin Result := 0; end; function T3DVolumeRGBLongData.GetOpenGLFormat:TGLInt; begin Result := GL_RGB; end; // Sets procedure T3DVolumeRGBLongData.SetBitmapPixelColor(_Position, _Color: longword); begin (FData as TRGBLongDataSet).Red[_Position] := GetRValue(_Color); (FData as TRGBLongDataSet).Green[_Position] := GetGValue(_Color); (FData as TRGBLongDataSet).Blue[_Position] := GetBValue(_Color); end; procedure T3DVolumeRGBLongData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); begin (FData as TRGBLongDataSet).Red[_Position] := _r; (FData as TRGBLongDataSet).Green[_Position] := _g; (FData as TRGBLongDataSet).Blue[_Position] := _b; end; procedure T3DVolumeRGBLongData.SetRedPixelColor(_x,_y,_z: integer; _value:single); begin (FData as TRGBLongDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value); end; procedure T3DVolumeRGBLongData.SetGreenPixelColor(_x,_y,_z: integer; _value:single); begin (FData as TRGBLongDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value); end; procedure T3DVolumeRGBLongData.SetBluePixelColor(_x,_y,_z: integer; _value:single); begin (FData as TRGBLongDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value); end; procedure T3DVolumeRGBLongData.SetAlphaPixelColor(_x,_y,_z: integer; _value:single); begin // do nothing end; procedure T3DVolumeRGBLongData.SetData(_x, _y, _z, _c: integer; _value: longword); begin if IsPixelValid(_x,_y,_z) and (_c >= 0) and (_c <= 2) then begin case (_c) of 0: (FData as TRGBLongDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; 1: (FData as TRGBLongDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; 2: (FData as TRGBLongDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; end; end; end; procedure T3DVolumeRGBLongData.SetDataUnsafe(_x, _y, _z, _c: integer; _value: longword); begin case (_c) of 0: (FData as TRGBLongDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; 1: (FData as TRGBLongDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; 2: (FData as TRGBLongDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; end; end; procedure T3DVolumeRGBLongData.SetDefaultColor(_value: TPixelRGBLongData); begin FDefaultColor.r := _value.r; FDefaultColor.g := _value.g; FDefaultColor.b := _value.b; end; // Copies procedure T3DVolumeRGBLongData.Assign(const _Source: TAbstract3DVolumeData); begin inherited Assign(_Source); FDefaultColor.r := (_Source as T3DVolumeRGBLongData).FDefaultColor.r; FDefaultColor.g := (_Source as T3DVolumeRGBLongData).FDefaultColor.g; FDefaultColor.b := (_Source as T3DVolumeRGBLongData).FDefaultColor.b; end; procedure T3DVolumeRGBLongData.CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer); var x,y,z,ZPos,ZDataPos,Pos,maxPos,DataPos,maxX, maxY, maxZ: integer; begin maxX := min(FXSize,_DataXSize)-1; maxY := min(FYSize,_DataYSize)-1; maxZ := min(FZSize,_DataZSize)-1; for z := 0 to maxZ do begin ZPos := z * FYxXSize; ZDataPos := z * _DataYSize * _DataXSize; for y := 0 to maxY do begin Pos := ZPos + (y * FXSize); DataPos := ZDataPos + (y * _DataXSize); maxPos := Pos + maxX; for x := Pos to maxPos do begin (FData as TRGBLongDataSet).Data[x] := (_Data as TRGBLongDataSet).Data[DataPos]; inc(DataPos); end; end; end; end; // Misc procedure T3DVolumeRGBLongData.ScaleBy(_Value: single); var x,maxx: integer; begin maxx := (FYxXSize * FZSize) - 1; for x := 0 to maxx do begin (FData as TRGBLongDataSet).Red[x] := Round((FData as TRGBLongDataSet).Red[x] * _Value); (FData as TRGBLongDataSet).Green[x] := Round((FData as TRGBLongDataSet).Green[x] * _Value); (FData as TRGBLongDataSet).Blue[x] := Round((FData as TRGBLongDataSet).Blue[x] * _Value); end; end; procedure T3DVolumeRGBLongData.Invert; var x,maxx: integer; begin maxx := (FYxXSize * FZSize) - 1; for x := 0 to maxx do begin (FData as TRGBLongDataSet).Red[x] := 255 - (FData as TRGBLongDataSet).Red[x]; (FData as TRGBLongDataSet).Green[x] := 255 - (FData as TRGBLongDataSet).Green[x]; (FData as TRGBLongDataSet).Blue[x] := 255 - (FData as TRGBLongDataSet).Blue[x]; end; end; procedure T3DVolumeRGBLongData.Fill(_value: longword); var x,maxx: integer; begin maxx := (FYxXSize * FZSize) - 1; for x := 0 to maxx do begin (FData as TRGBLongDataSet).Red[x] := _value; (FData as TRGBLongDataSet).Green[x] := _value; (FData as TRGBLongDataSet).Blue[x] := _value; end; end; end.
unit Chapter07._02_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, AI.TreeNode; /// 226. Invert Binary Tree /// https://leetcode.com/problems/invert-binary-tree/description/ /// 时间复杂度: O(n), n为树中节点个数 /// 空间复杂度: O(h), h为树的高度 type TSolution = class(TObject) public function invertTree(root: TTreeNode): TTreeNode; end; implementation { TSolution } function TSolution.invertTree(root: TTreeNode): TTreeNode; var l, r: TTreeNode; begin if root = nil then Exit(nil); l := invertTree(root.Left); r := invertTree(root.Right); root.Right := l; root.Left := r; Result := root; end; end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.ToolWin; type TForm1 = class(TForm) Panel1: TPanel; mmoOutput: TMemo; rgCompression: TRadioGroup; chbVerbose: TCheckBox; chb1252: TCheckBox; chbJpg2Gif: TCheckBox; pbBooks: TProgressBar; chbNoSource: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormPaint(Sender: TObject); private { Private declarations } public procedure DropFiles(var Msg: TMessage); message WM_DROPFILES; function GetBuildParam(): string; procedure DoConvert(const AFileName: string); // procedure OutText(Sender: TObject; st: string); procedure CaptureConsoleOutput(const ACommand, AParameters: String; AMemo: TMemo); procedure ReadConfig(); procedure WriteConfig(); end; var Form1: TForm1; IsDebut: Boolean = True; implementation {$R *.dfm} uses WinAPi.ShellApi, IniFiles; procedure TForm1.CaptureConsoleOutput(const ACommand, AParameters: String; AMemo: TMemo); const CReadBuffer = 4095; var saSecurity: TSecurityAttributes; hRead: THandle; hWrite: THandle; suiStartup: TStartupInfo; piProcess: TProcessInformation; pBuffer: array [0 .. CReadBuffer] of AnsiChar; dRead: DWord; dRunning: DWord; CreateOk: Boolean; begin saSecurity.nLength := SizeOf(TSecurityAttributes); saSecurity.bInheritHandle := True; saSecurity.lpSecurityDescriptor := nil; if CreatePipe(hRead, hWrite, @saSecurity, 0) then begin FillChar(suiStartup, SizeOf(TStartupInfo), #0); suiStartup.cb := SizeOf(TStartupInfo); suiStartup.hStdInput := hRead; suiStartup.hStdOutput := hWrite; suiStartup.hStdError := hWrite; suiStartup.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW; suiStartup.wShowWindow := SW_HIDE; CreateOK := CreateProcess(nil, PChar(ACommand + ' ' + AParameters), @saSecurity, @saSecurity, True, NORMAL_PRIORITY_CLASS, nil, nil, suiStartup, piProcess); // must CLOSE right after createprocess!!! // otherwise ReadFile will never stop. CloseHandle(hWrite); if CreateOK then begin repeat dRunning := WaitForSingleObject(piProcess.hProcess, 100); Application.ProcessMessages(); repeat dRead := 0; ReadFile(hRead, pBuffer[0], CReadBuffer, dRead, nil); pBuffer[dRead] := #0; // OemToAnsi(pBuffer, pBuffer); // may got wired result on utf8 // AMemo.Lines.Add(String(pBuffer)); AMemo.Lines.Add(Utf8ToAnsi(pBuffer)); // UTF8 convertion supports CJK until (dRead < CReadBuffer); until (dRunning <> WAIT_TIMEOUT); CloseHandle(piProcess.hProcess); CloseHandle(piProcess.hThread); end; CloseHandle(hRead); // CloseHandle(hWrite); end; end; procedure TForm1.DoConvert(const AFileName: string); var fn: string; begin fn := '"'+ AFileName + '"' + GetBuildParam(); mmoOutput.Lines.Add(''); mmoOutput.Lines.Add('JOB: '+ fn); CaptureConsoleOutput('kindlegen\kindlegen.exe', fn, mmoOutput); mmoOutput.Lines.Add('Fin'); mmoOutput.Lines.Add(''); mmoOutput.Lines.Add(''); end; procedure TForm1.DropFiles(var Msg: TMessage); var buffer: array[0..MAX_PATH-1] of Char; count: integer; // count of files I: Integer; begin inherited; buffer[0] := #0; count := DragQueryFile(Msg.WParam, $FFFFFFFF, buffer, sizeof(buffer)); //第一个文件 pbBooks.Min := 0; pbBooks.Max := count; pbBooks.Position := 0; for I := 0 to count - 1 do begin if DragQueryFile(Msg.WParam, i, buffer, sizeof(buffer)) = 0 then exit; DoConvert(buffer); pbBooks.Position := i+1; end; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin WriteConfig(); end; procedure TForm1.FormCreate(Sender: TObject); var I: Integer; begin pbBooks.Min := 0; pbBooks.Max := ParamCount(); // accept DropFiles event DragAcceptFiles(handle, true); ReadConfig(); if not FileExists('kindlegen\kindlegen.exe') then begin mmoOutput.Lines.Add('Error: kindlegen\kindlegen.exe not found.'); mmoOutput.Lines.Add(''); end; end; procedure TForm1.FormPaint(Sender: TObject); var i: integer; begin //处理命令行参数。 //不知道放哪里才不影响显示界面 if IsDebut then begin IsDebut := False; // avoid re-enter ... maybe needed. for I := 1 to ParamCount() do begin DoConvert(ParamStr(i)); pbBooks.Position := i; end; end; end; function TForm1.GetBuildParam: string; begin case rgCompression.ItemIndex of 0: Result := ' -c0'; 1: Result := ' -c1'; 2: Result := ' -c2'; end; if chbVerbose.Checked then Result := Result + ' -verbose'; if chb1252.Checked then Result := Result + ' -western'; if chbJpg2Gif.Checked then Result := Result + ' -gif'; if chbNoSource.Checked then Result := Result + ' -dont_append_source'; // Result := Result + ' -locale en'; // 咋显示都有道理的吧? end; procedure TForm1.ReadConfig; var fn: string; ini: TIniFile; begin // get saved status fn := ChangeFileExt(Application.ExeName,'.cfg'); ini := TIniFile.Create(fn); rgCompression.ItemIndex := ini.ReadInteger('cfg','compression',2); chbVerbose.Checked := ini.ReadBool('cfg','verbose',True); chb1252.Checked := ini.ReadBool('cfg','western1252',False); chbJpg2Gif.Checked := ini.ReadBool('cfg', 'Jpg2Gif', False); chbNoSource.Checked := ini.ReadBool('cfg', 'NoSource', False); ini.Destroy; end; procedure TForm1.WriteConfig; var fn: string; ini: TIniFile; begin // save status fn := ChangeFileExt(Application.ExeName,'.cfg'); ini := TIniFile.Create(fn); ini.WriteInteger('cfg', 'compression', rgCompression.ItemIndex); ini.WriteBool('cfg', 'verbose', chbVerbose.Checked); ini.WriteBool('cfg', 'western1252', chb1252.Checked); ini.WriteBool('cfg', 'Jpg2Gif', chbJpg2Gif.Checked); ini.WriteBool('cfg', 'NoSource', chbNoSource.Checked); ini.Destroy; end; end.
unit uSinaisSintomas; {********************************************************************** ** unit uSinaisSintomas ** ** ** ** UNIT DESTINADA A MANIPULAR AS INFORMAÇÕES NO CADASTRO DE PACIENTE ** ** REFERENTE AS INFORMAÇÕES DENTRO DA ABA DE SINAIS E SINTOMAS ** ** ** ***********************************************************************} {$mode objfpc}{$H+} interface uses Classes, SysUtils, uCadPacientes, uClassControlePaciente, uClassSinaisSintomas, uFrmMensagem; type { SinaisSintomas } SinaisSintomas = class public class function CarregaObjSinaisSintomas(objSinaisSintomas: TSinaisSintomas; frm: TfrmCadPaciente): TSinaisSintomas; class procedure InclusaoOuEdicaoSinaisSintomas(frm: TfrmCadPaciente); end; implementation { SinaisSintomas } class function SinaisSintomas.CarregaObjSinaisSintomas(objSinaisSintomas: TSinaisSintomas; frm: TfrmCadPaciente): TSinaisSintomas; begin with objSinaisSintomas do begin idSinaisSintomas := StrToInt(frm.edtCodSinaisSintomas.Text); idTblPaciente := StrToInt(frm.edtCodPaciente.Text); alteracaoApetite := frm.RetornoRadioGroup(frm.rgexAlteracaoApetite.ItemIndex); calorExagerado := frm.RetornoRadioGroup(frm.rgexCalorExagerado.ItemIndex); cansaFacil := frm.RetornoRadioGroup(frm.rgexCansaFacil.ItemIndex); coceiraAnormal := frm.RetornoRadioGroup(frm.rgexCoceiraAnormal.ItemIndex); dificuldadeEngolir := frm.RetornoRadioGroup(frm.rgexDificuldadeEngolir.ItemIndex); dificuldadeMastigar := frm.RetornoRadioGroup(frm.rgexDificuldadeMastigar.ItemIndex); dorFacial := frm.RetornoRadioGroup(frm.rgexDorFacial.ItemIndex); dorFrequenteCabeca := frm.RetornoRadioGroup(frm.rgexDorCabecaFrequente.ItemIndex); dorOuvidoFrequente := frm.RetornoRadioGroup(frm.rgexDorOuvidoFrequente.ItemIndex); emagrecimentoAcentuado := frm.RetornoRadioGroup(frm.rgexEmagrecimentoAcentuado.ItemIndex); estaloMandibula := frm.RetornoRadioGroup(frm.rgexEstaloMandibula.ItemIndex); febreFrequente := frm.RetornoRadioGroup(frm.rgexFebreFrequente.ItemIndex); indigestaoFrequente := frm.RetornoRadioGroup(frm.rgexIndigestaoFrequente.ItemIndex); maCicatrizacao := frm.RetornoRadioGroup(frm.rgexMaCicatrizacao.ItemIndex); miccaoFrequente := frm.RetornoRadioGroup(frm.rgexMiccaoFrequente.ItemIndex); rangeDentes := frm.RetornoRadioGroup(frm.rgexRangeDentes.ItemIndex); respiraPelaBoca := frm.RetornoRadioGroup(frm.rgexRespiraPelaBoca.ItemIndex); sangramentoAnormal := frm.RetornoRadioGroup(frm.rgexSangramentoAnormal.ItemIndex); tonturaDesmaio := frm.RetornoRadioGroup(frm.rgexTonturasDesmaios.ItemIndex); poucaSaliva := frm.RetornoRadioGroup(frm.rgexPoucaSaliva.ItemIndex); end; result := objSinaisSintomas; end; class procedure SinaisSintomas.InclusaoOuEdicaoSinaisSintomas(frm: TfrmCadPaciente); var objSinaisSintomas : TSinaisSintomas; objControlePaciente : TControlePaciente; codSinaisSintomas : integer = 0; begin try objSinaisSintomas := TSinaisSintomas.Create; objControlePaciente := TControlePaciente.Create; codSinaisSintomas := objControlePaciente.InclusaoOuEdicaoSinaisSintomas(CarregaObjSinaisSintomas(objSinaisSintomas, frm)); if codSinaisSintomas > 0 then begin try frmMensagem := TfrmMensagem.Create(nil); frmMensagem.InfoFormMensagem('Cadastro de Sinais & Sintomas', tiInformacao, 'Cadastro dos Sinais & Sintomas realizado com sucesso!'); finally FreeAndNil(frmMensagem); end; end; //DesabilitaControles(pcCadPaciente.ActivePage); estado := teNavegacao; //EstadoBotoes; finally FreeAndNil(objControlePaciente); FreeAndNil(objSinaisSintomas); end; end; end.
unit NtPluralData; //FI:ignore // Generated from CLDR data. Do not edit. interface uses NtPattern; { Get a plural form for Bamanankan, Tibetan, Dzongkha, Indonesian, Igbo, Yi, in, Japanese, jbo, Javanese, jw, Makonde, Kabuverdianu, Khmer, Korean, Lakota, Lao, Malay, Burmese, N'ko, root, Sakha, Koyraboro Senni, Sango, Thai, Tongan, Vietnamese, Wolof, Yoruba, yue, Chinese, Simplified. @param n Absolute value of the source number (integer and decimals) (e.g. 9.870 => 9.87). @param i Integer digits of n (e.g. 9.870 => 9). @param v Number of visible fraction digits in n, with trailing zeros (e.g. 9.870 => 3). @param w Number of visible fraction digits in n, without trailing zeros (e.g. 9.870 => 2). @param f Visible fractional digits in n, with trailing zeros (e.g. 9.870 => 870). @param t Visible fractional digits in n, without trailing zeros (e.g. 9.870 => 87). @return Plural form. } function GetSinglePlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; implementation // Bamanankan, Tibetan, Dzongkha, Indonesian, Igbo, Yi, in, Japanese, jbo, Javanese, jw, Makonde, Kabuverdianu, Khmer, Korean, Lakota, Lao, Malay, Burmese, N'ko, root, Sakha, Koyraboro Senni, Sango, Thai, Tongan, Vietnamese, Wolof, Yoruba, yue, Chinese, Simplified function GetSinglePlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // other: @integer 0~15, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0~1.5, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … Result := pfOther end; // Amharic, Assamese, Bangla, Persian, Gujarati, Hindi, Kannada, Marathi, isiZulu function GetAmPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: i = 0 or n = 1 @integer 0, 1 @decimal 0.0~1.0, 0.00~0.04 // other: @integer 2~17, 100, 1000, 10000, 100000, 1000000, … @decimal 1.1~2.6, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (i = 0) or (n = 1) then Result := pfOne else Result := pfOther end; // Fulah, French, Armenian, Kabyle function GetFfPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: i = 0,1 @integer 0, 1 @decimal 0.0~1.5 // other: @integer 2~17, 100, 1000, 10000, 100000, 1000000, … @decimal 2.0~3.5, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (i in [0,1]) then Result := pfOne else Result := pfOther end; // Asturian, Catalan, German, English, Estonian, Finnish, Western Frisian, Galician, Italian, ji, Dutch, Swedish, Kiswahili, Urdu, Yiddish function GetAstPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: i = 1 and v = 0 @integer 1 // other: @integer 0, 2~16, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0~1.5, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (i = 1) and (v = 0) then Result := pfOne else Result := pfOther end; // Sinhala function GetSinhalaPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: n = 0,1 or i = 0 and f = 1 @integer 0, 1 @decimal 0.0, 0.1, 1.0, 0.00, 0.01, 1.00, 0.000, 0.001, 1.000, 0.0000, 0.0001, 1.0000 // other: @integer 2~17, 100, 1000, 10000, 100000, 1000000, … @decimal 0.2~0.9, 1.1~1.8, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if ((n = 0) or (n = 1)) or (i = 0) and (f = 1) then Result := pfOne else Result := pfOther end; // Akan, bh, guw, Lingala, Malagasy, Sesotho sa Leboa, Punjabi, Tigrinya, wa function GetAkPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: n = 0..1 @integer 0, 1 @decimal 0.0, 1.0, 0.00, 1.00, 0.000, 1.000, 0.0000, 1.0000 // other: @integer 2~17, 100, 1000, 10000, 100000, 1000000, … @decimal 0.1~0.9, 1.1~1.7, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (n >= 0) and (n <= 1) then Result := pfOne else Result := pfOther end; // Central Atlas Tamazight function GetCentralAtlasTamazightPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: n = 0..1 or n = 11..99 @integer 0, 1, 11~24 @decimal 0.0, 1.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0 // other: @integer 2~10, 100~106, 1000, 10000, 100000, 1000000, … @decimal 0.1~0.9, 1.1~1.7, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (n >= 0) and (n <= 1) or (n >= 11) and (n <= 99) then Result := pfOne else Result := pfOther end; // Portuguese function GetPortuguesePlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: n = 0..2 and n != 2 @integer 0, 1 @decimal 0.0, 1.0, 0.00, 1.00, 0.000, 1.000, 0.0000, 1.0000 // other: @integer 2~17, 100, 1000, 10000, 100000, 1000000, … @decimal 0.1~0.9, 1.1~1.7, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (n >= 0) and (n <= 1) then Result := pfOne else Result := pfOther end; // Afrikaans, Asu, Azerbaijani, Latin, Bemba, Bena, Bulgarian, Bodo, Chechen, Chiga, Cherokee, ckb, Divehi, Ewe, Greek, Esperanto, Spanish, Basque, Faroese, Friulian, Swiss German, Hausa, Hawaiian, Hungarian, Ngomba, Machame, Georgian, kaj, kcg, Kazakh, Kako, Greenlandic, Kashmiri, Shambala, Central Kurdish, Kyrgyz, Luxembourgish, Ganda, Masai, Meta', Malayalam, Mongolian, Cyrillic, nah, Norwegian Bokmεl, North Ndebele, Nepali, Norwegian Nynorsk, Ngiemboon, Norwegian, South Ndebele, ny, Nyankole, Oromo, Odia, Ossetic, Papiamento, Pashto, Romansh, Rombo, Rwa, Samburu, sdh, Sena, Shona, Somali, Albanian, siSwati, Saho, Sesotho, Syriac, Tamil, Telugu, Teso, Tigre, Turkmen, Setswana, Turkish, Tsonga, Uyghur, Uzbek, Latin, Venda, Volapόk, Vunjo, Walser, isiXhosa, Soga function GetAfPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: n = 1 @integer 1 @decimal 1.0, 1.00, 1.000, 1.0000 // other: @integer 0, 2~16, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0~0.9, 1.1~1.6, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (n = 1) then Result := pfOne else Result := pfOther end; // Portuguese (Portugal) function GetPortuguesePortugalPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: n = 1 and v = 0 @integer 1 // other: @integer 0, 2~16, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0~1.5, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (n = 1) and (v = 0) then Result := pfOne else Result := pfOther end; // Danish function GetDanishPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: n = 1 or t != 0 and i = 0,1 @integer 1 @decimal 0.1~1.6 // other: @integer 0, 2~16, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0, 2.0~3.4, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (n = 1) or (t <> 0) and (i in [0,1]) then Result := pfOne else Result := pfOther end; // Icelandic function GetIcelandicPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: t = 0 and i % 10 = 1 and i % 100 != 11 or t != 0 @integer 1, 21, 31, 41, 51, 61, 71, 81, 101, 1001, … @decimal 0.1~1.6, 10.1, 100.1, 1000.1, … // other: @integer 0, 2~16, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (t = 0) and (i mod 10 = 1) and (i mod 100 <> 11) or (t <> 0) then Result := pfOne else Result := pfOther end; // Macedonian function GetMacedonianPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: v = 0 and i % 10 = 1 or f % 10 = 1 @integer 1, 11, 21, 31, 41, 51, 61, 71, 101, 1001, … @decimal 0.1, 1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 10.1, 100.1, 1000.1, … // other: @integer 0, 2~10, 12~17, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0, 0.2~1.0, 1.2~1.7, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (v = 0) and (i mod 10 = 1) or (f mod 10 = 1) then Result := pfOne else Result := pfOther end; // Filipino, tl function GetFilipinoPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: v = 0 and i = 1,2,3 or v = 0 and i % 10 != 4,6,9 or v != 0 and f % 10 != 4,6,9 @integer 0~3, 5, 7, 8, 10~13, 15, 17, 18, 20, 21, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0~0.3, 0.5, 0.7, 0.8, 1.0~1.3, 1.5, 1.7, 1.8, 2.0, 2.1, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … // other: @integer 4, 6, 9, 14, 16, 19, 24, 26, 104, 1004, … @decimal 0.4, 0.6, 0.9, 1.4, 1.6, 1.9, 2.4, 2.6, 10.4, 100.4, 1000.4, … if (v = 0) and (i in [1,2,3]) or (v = 0) and not (i mod 10 in [4,6,9]) or (v <> 0) and not (f mod 10 in [4,6,9]) then Result := pfOne else Result := pfOther end; // Latvian, Prussian function GetLatvianPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // zero: n % 10 = 0 or n % 100 = 11..19 or v = 2 and f % 100 = 11..19 @integer 0, 10~20, 30, 40, 50, 60, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … // one: n % 10 = 1 and n % 100 != 11 or v = 2 and f % 10 = 1 and f % 100 != 11 or v != 2 and f % 10 = 1 @integer 1, 21, 31, 41, 51, 61, 71, 81, 101, 1001, … @decimal 0.1, 1.0, 1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 10.1, 100.1, 1000.1, … // other: @integer 2~9, 22~29, 102, 1002, … @decimal 0.2~0.9, 1.2~1.9, 10.2, 100.2, 1000.2, … if (Trunc(n) mod 10 = 0) or (Trunc(n) mod 100 in [11..19]) or (v = 2) and (f mod 100 in [11..19]) then Result := pfZero else if (Trunc(n) mod 10 = 1) and (Trunc(n) mod 100 <> 11) or (v = 2) and (f mod 10 = 1) and (f mod 100 <> 11) or (v <> 2) and (f mod 10 = 1) then Result := pfOne else Result := pfOther end; // Langi function GetLangiPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // zero: n = 0 @integer 0 @decimal 0.0, 0.00, 0.000, 0.0000 // one: i = 0,1 and n != 0 @integer 1 @decimal 0.1~1.6 // other: @integer 2~17, 100, 1000, 10000, 100000, 1000000, … @decimal 2.0~3.5, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (n = 0) then Result := pfZero else if (i in [0,1]) and (n <> 0) then Result := pfOne else Result := pfOther end; // Colognian function GetColognianPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // zero: n = 0 @integer 0 @decimal 0.0, 0.00, 0.000, 0.0000 // one: n = 1 @integer 1 @decimal 1.0, 1.00, 1.000, 1.0000 // other: @integer 2~17, 100, 1000, 10000, 100000, 1000000, … @decimal 0.1~0.9, 1.1~1.7, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (n = 0) then Result := pfZero else if (n = 1) then Result := pfOne else Result := pfOther end; // Inuktitut, Latin, Cornish, Nama, Northern Sami, Sami, Southern, smi, Sami, Lule, Sami, Inari, Sami, Skolt function GetIuPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: n = 1 @integer 1 @decimal 1.0, 1.00, 1.000, 1.0000 // two: n = 2 @integer 2 @decimal 2.0, 2.00, 2.000, 2.0000 // other: @integer 0, 3~17, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0~0.9, 1.1~1.6, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (n = 1) then Result := pfOne else if (n = 2) then Result := pfTwo else Result := pfOther end; // Tachelhit function GetTachelhitPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: i = 0 or n = 1 @integer 0, 1 @decimal 0.0~1.0, 0.00~0.04 // few: n = 2..10 @integer 2~10 @decimal 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00 // other: @integer 11~26, 100, 1000, 10000, 100000, 1000000, … @decimal 1.1~1.9, 2.1~2.7, 10.1, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (i = 0) or (n = 1) then Result := pfOne else if (n >= 2) and (n <= 10) then Result := pfFew else Result := pfOther end; // mo, Romanian function GetRomanianPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: i = 1 and v = 0 @integer 1 // few: v != 0 or n = 0 or n != 1 and n % 100 = 1..19 @integer 0, 2~16, 101, 1001, … @decimal 0.0~1.5, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … // other: @integer 20~35, 100, 1000, 10000, 100000, 1000000, … if (i = 1) and (v = 0) then Result := pfOne else if (v <> 0) or (n = 0) or (n <> 1) and (Trunc(n) mod 100 in [1..19]) then Result := pfFew else Result := pfOther end; // Bosnian, Latin, Croatian, sh, Serbian, Cyrillic function GetBsPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: v = 0 and i % 10 = 1 and i % 100 != 11 or f % 10 = 1 and f % 100 != 11 @integer 1, 21, 31, 41, 51, 61, 71, 81, 101, 1001, … @decimal 0.1, 1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 10.1, 100.1, 1000.1, … // few: v = 0 and i % 10 = 2..4 and i % 100 != 12..14 or f % 10 = 2..4 and f % 100 != 12..14 @integer 2~4, 22~24, 32~34, 42~44, 52~54, 62, 102, 1002, … @decimal 0.2~0.4, 1.2~1.4, 2.2~2.4, 3.2~3.4, 4.2~4.4, 5.2, 10.2, 100.2, 1000.2, … // other: @integer 0, 5~19, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0, 0.5~1.0, 1.5~2.0, 2.5~2.7, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (v = 0) and (i mod 10 = 1) and (i mod 100 <> 11) or (f mod 10 = 1) and (f mod 100 <> 11) then Result := pfOne else if (v = 0) and (i mod 10 in [2..4]) and not (i mod 100 in [12..14]) or (f mod 10 in [2..4]) and not (f mod 100 in [12..14]) then Result := pfFew else Result := pfOther end; // Scottish Gaelic function GetScottishGaelicPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: n = 1,11 @integer 1, 11 @decimal 1.0, 11.0, 1.00, 11.00, 1.000, 11.000, 1.0000 // two: n = 2,12 @integer 2, 12 @decimal 2.0, 12.0, 2.00, 12.00, 2.000, 12.000, 2.0000 // few: n = 3..10,13..19 @integer 3~10, 13~19 @decimal 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 3.00 // other: @integer 0, 20~34, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0~0.9, 1.1~1.6, 10.1, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if ((n = 1) or (n = 11)) then Result := pfOne else if ((n = 2) or (n = 12)) then Result := pfTwo else if ((n >= 3) and (n >= 13) and (n <= 19)) then Result := pfFew else Result := pfOther end; // Slovenian function GetSlovenianPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: v = 0 and i % 100 = 1 @integer 1, 101, 201, 301, 401, 501, 601, 701, 1001, … // two: v = 0 and i % 100 = 2 @integer 2, 102, 202, 302, 402, 502, 602, 702, 1002, … // few: v = 0 and i % 100 = 3..4 or v != 0 @integer 3, 4, 103, 104, 203, 204, 303, 304, 403, 404, 503, 504, 603, 604, 703, 704, 1003, … @decimal 0.0~1.5, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … // other: @integer 0, 5~19, 100, 1000, 10000, 100000, 1000000, … if (v = 0) and (i mod 100 = 1) then Result := pfOne else if (v = 0) and (i mod 100 = 2) then Result := pfTwo else if (v = 0) and (i mod 100 in [3..4]) or (v <> 0) then Result := pfFew else Result := pfOther end; // Lower Sorbian, Upper Sorbian function GetLowerSorbianPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: v = 0 and i % 100 = 1 or f % 100 = 1 @integer 1, 101, 201, 301, 401, 501, 601, 701, 1001, … @decimal 0.1, 1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 10.1, 100.1, 1000.1, … // two: v = 0 and i % 100 = 2 or f % 100 = 2 @integer 2, 102, 202, 302, 402, 502, 602, 702, 1002, … @decimal 0.2, 1.2, 2.2, 3.2, 4.2, 5.2, 6.2, 7.2, 10.2, 100.2, 1000.2, … // few: v = 0 and i % 100 = 3..4 or f % 100 = 3..4 @integer 3, 4, 103, 104, 203, 204, 303, 304, 403, 404, 503, 504, 603, 604, 703, 704, 1003, … @decimal 0.3, 0.4, 1.3, 1.4, 2.3, 2.4, 3.3, 3.4, 4.3, 4.4, 5.3, 5.4, 6.3, 6.4, 7.3, 7.4, 10.3, 100.3, 1000.3, … // other: @integer 0, 5~19, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0, 0.5~1.0, 1.5~2.0, 2.5~2.7, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (v = 0) and (i mod 100 = 1) or (f mod 100 = 1) then Result := pfOne else if (v = 0) and (i mod 100 = 2) or (f mod 100 = 2) then Result := pfTwo else if (v = 0) and (i mod 100 in [3..4]) or (f mod 100 in [3..4]) then Result := pfFew else Result := pfOther end; // Hebrew, iw function GetHebrewPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: i = 1 and v = 0 @integer 1 // two: i = 2 and v = 0 @integer 2 // many: v = 0 and n != 0..10 and n % 10 = 0 @integer 20, 30, 40, 50, 60, 70, 80, 90, 100, 1000, 10000, 100000, 1000000, … // other: @integer 0, 3~17, 101, 1001, … @decimal 0.0~1.5, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (i = 1) and (v = 0) then Result := pfOne else if (i = 2) and (v = 0) then Result := pfTwo else if (v = 0) and (n >= 0) and (n <= 10) and (Trunc(n) mod 10 = 0) then Result := pfMany else Result := pfOther end; // Czech, Slovak function GetCzechPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: i = 1 and v = 0 @integer 1 // few: i = 2..4 and v = 0 @integer 2~4 // many: v != 0 @decimal 0.0~1.5, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … // other: @integer 0, 5~19, 100, 1000, 10000, 100000, 1000000, … if (i = 1) and (v = 0) then Result := pfOne else if (i in [2..4]) and (v = 0) then Result := pfFew else if (v <> 0) then Result := pfMany else Result := pfOther end; // Polish function GetPolishPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: i = 1 and v = 0 @integer 1 // few: v = 0 and i % 10 = 2..4 and i % 100 != 12..14 @integer 2~4, 22~24, 32~34, 42~44, 52~54, 62, 102, 1002, … // many: v = 0 and i != 1 and i % 10 = 0..1 or v = 0 and i % 10 = 5..9 or v = 0 and i % 100 = 12..14 @integer 0, 5~19, 100, 1000, 10000, 100000, 1000000, … // other: @decimal 0.0~1.5, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (i = 1) and (v = 0) then Result := pfOne else if (v = 0) and (i mod 10 in [2..4]) and not (i mod 100 in [12..14]) then Result := pfFew else if (v = 0) and (i <> 1) and (i mod 10 in [0..1]) or (v = 0) and (i mod 10 in [5..9]) or (v = 0) and (i mod 100 in [12..14]) then Result := pfMany else Result := pfOther end; // Belarusian function GetBelarusianPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: n % 10 = 1 and n % 100 != 11 @integer 1, 21, 31, 41, 51, 61, 71, 81, 101, 1001, … @decimal 1.0, 21.0, 31.0, 41.0, 51.0, 61.0, 71.0, 81.0, 101.0, 1001.0, … // few: n % 10 = 2..4 and n % 100 != 12..14 @integer 2~4, 22~24, 32~34, 42~44, 52~54, 62, 102, 1002, … @decimal 2.0, 3.0, 4.0, 22.0, 23.0, 24.0, 32.0, 33.0, 102.0, 1002.0, … // many: n % 10 = 0 or n % 10 = 5..9 or n % 100 = 11..14 @integer 0, 5~19, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … // other: @decimal 0.1~0.9, 1.1~1.7, 10.1, 100.1, 1000.1, … if (Trunc(n) mod 10 = 1) and (Trunc(n) mod 100 <> 11) then Result := pfOne else if (Trunc(n) mod 10 in [2..4]) and not (Trunc(n) mod 100 in [12..14]) then Result := pfFew else if (Trunc(n) mod 10 = 0) or (Trunc(n) mod 10 in [5..9]) or (Trunc(n) mod 100 in [11..14]) then Result := pfMany else Result := pfOther end; // Lithuanian function GetLithuanianPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: n % 10 = 1 and n % 100 != 11..19 @integer 1, 21, 31, 41, 51, 61, 71, 81, 101, 1001, … @decimal 1.0, 21.0, 31.0, 41.0, 51.0, 61.0, 71.0, 81.0, 101.0, 1001.0, … // few: n % 10 = 2..9 and n % 100 != 11..19 @integer 2~9, 22~29, 102, 1002, … @decimal 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 22.0, 102.0, 1002.0, … // many: f != 0 @decimal 0.1~0.9, 1.1~1.7, 10.1, 100.1, 1000.1, … // other: @integer 0, 10~20, 30, 40, 50, 60, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (Trunc(n) mod 10 = 1) and not (Trunc(n) mod 100 in [11..19]) then Result := pfOne else if (Trunc(n) mod 10 in [2..9]) and not (Trunc(n) mod 100 in [11..19]) then Result := pfFew else if (f <> 0) then Result := pfMany else Result := pfOther end; // Maltese function GetMaltesePlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: n = 1 @integer 1 @decimal 1.0, 1.00, 1.000, 1.0000 // few: n = 0 or n % 100 = 2..10 @integer 0, 2~10, 102~107, 1002, … @decimal 0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 10.0, 102.0, 1002.0, … // many: n % 100 = 11..19 @integer 11~19, 111~117, 1011, … @decimal 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 111.0, 1011.0, … // other: @integer 20~35, 100, 1000, 10000, 100000, 1000000, … @decimal 0.1~0.9, 1.1~1.7, 10.1, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (n = 1) then Result := pfOne else if (n = 0) or (Trunc(n) mod 100 in [2..10]) then Result := pfFew else if (Trunc(n) mod 100 in [11..19]) then Result := pfMany else Result := pfOther end; // Russian, Ukrainian function GetRussianPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: v = 0 and i % 10 = 1 and i % 100 != 11 @integer 1, 21, 31, 41, 51, 61, 71, 81, 101, 1001, … // few: v = 0 and i % 10 = 2..4 and i % 100 != 12..14 @integer 2~4, 22~24, 32~34, 42~44, 52~54, 62, 102, 1002, … // many: v = 0 and i % 10 = 0 or v = 0 and i % 10 = 5..9 or v = 0 and i % 100 = 11..14 @integer 0, 5~19, 100, 1000, 10000, 100000, 1000000, … // other: @decimal 0.0~1.5, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (v = 0) and (i mod 10 = 1) and (i mod 100 <> 11) then Result := pfOne else if (v = 0) and (i mod 10 in [2..4]) and not (i mod 100 in [12..14]) then Result := pfFew else if (v = 0) and (i mod 10 = 0) or (v = 0) and (i mod 10 in [5..9]) or (v = 0) and (i mod 100 in [11..14]) then Result := pfMany else Result := pfOther end; // Breton function GetBretonPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: n % 10 = 1 and n % 100 != 11,71,91 @integer 1, 21, 31, 41, 51, 61, 81, 101, 1001, … @decimal 1.0, 21.0, 31.0, 41.0, 51.0, 61.0, 81.0, 101.0, 1001.0, … // two: n % 10 = 2 and n % 100 != 12,72,92 @integer 2, 22, 32, 42, 52, 62, 82, 102, 1002, … @decimal 2.0, 22.0, 32.0, 42.0, 52.0, 62.0, 82.0, 102.0, 1002.0, … // few: n % 10 = 3..4,9 and n % 100 != 10..19,70..79,90..99 @integer 3, 4, 9, 23, 24, 29, 33, 34, 39, 43, 44, 49, 103, 1003, … @decimal 3.0, 4.0, 9.0, 23.0, 24.0, 29.0, 33.0, 34.0, 103.0, 1003.0, … // many: n != 0 and n % 1000000 = 0 @integer 1000000, … @decimal 1000000.0, 1000000.00, 1000000.000, … // other: @integer 0, 5~8, 10~20, 100, 1000, 10000, 100000, … @decimal 0.0~0.9, 1.1~1.6, 10.0, 100.0, 1000.0, 10000.0, 100000.0, … if (Trunc(n) mod 10 = 1) and not (Trunc(n) mod 100 in [11,71,91]) then Result := pfOne else if (Trunc(n) mod 10 = 2) and not (Trunc(n) mod 100 in [12,72,92]) then Result := pfTwo else if (Trunc(n) mod 10 in [3..4,9]) and not (Trunc(n) mod 100 in [10..19,70..79,90..99]) then Result := pfFew else if (n <> 0) and (Trunc(n) mod 1000000 = 0) then Result := pfMany else Result := pfOther end; // Irish function GetIrishPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: n = 1 @integer 1 @decimal 1.0, 1.00, 1.000, 1.0000 // two: n = 2 @integer 2 @decimal 2.0, 2.00, 2.000, 2.0000 // few: n = 3..6 @integer 3~6 @decimal 3.0, 4.0, 5.0, 6.0, 3.00, 4.00, 5.00, 6.00, 3.000, 4.000, 5.000, 6.000, 3.0000, 4.0000, 5.0000, 6.0000 // many: n = 7..10 @integer 7~10 @decimal 7.0, 8.0, 9.0, 10.0, 7.00, 8.00, 9.00, 10.00, 7.000, 8.000, 9.000, 10.000, 7.0000, 8.0000, 9.0000, 10.0000 // other: @integer 0, 11~25, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0~0.9, 1.1~1.6, 10.1, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (n = 1) then Result := pfOne else if (n = 2) then Result := pfTwo else if (n >= 3) and (n <= 6) then Result := pfFew else if (n >= 7) and (n <= 10) then Result := pfMany else Result := pfOther end; // Manx function GetManxPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // one: v = 0 and i % 10 = 1 @integer 1, 11, 21, 31, 41, 51, 61, 71, 101, 1001, … // two: v = 0 and i % 10 = 2 @integer 2, 12, 22, 32, 42, 52, 62, 72, 102, 1002, … // few: v = 0 and i % 100 = 0,20,40,60,80 @integer 0, 20, 40, 60, 80, 100, 120, 140, 1000, 10000, 100000, 1000000, … // many: v != 0 @decimal 0.0~1.5, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … // other: @integer 3~10, 13~19, 23, 103, 1003, … if (v = 0) and (i mod 10 = 1) then Result := pfOne else if (v = 0) and (i mod 10 = 2) then Result := pfTwo else if (v = 0) and (i mod 100 in [0,20,40,60,80]) then Result := pfFew else if (v <> 0) then Result := pfMany else Result := pfOther end; // Arabic, ars function GetArabicPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // zero: n = 0 @integer 0 @decimal 0.0, 0.00, 0.000, 0.0000 // one: n = 1 @integer 1 @decimal 1.0, 1.00, 1.000, 1.0000 // two: n = 2 @integer 2 @decimal 2.0, 2.00, 2.000, 2.0000 // few: n % 100 = 3..10 @integer 3~10, 103~110, 1003, … @decimal 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 103.0, 1003.0, … // many: n % 100 = 11..99 @integer 11~26, 111, 1011, … @decimal 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 111.0, 1011.0, … // other: @integer 100~102, 200~202, 300~302, 400~402, 500~502, 600, 1000, 10000, 100000, 1000000, … @decimal 0.1~0.9, 1.1~1.7, 10.1, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (n = 0) then Result := pfZero else if (n = 1) then Result := pfOne else if (n = 2) then Result := pfTwo else if (Trunc(n) mod 100 in [3..10]) then Result := pfFew else if (Trunc(n) mod 100 in [11..99]) then Result := pfMany else Result := pfOther end; // Welsh function GetWelshPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; begin // zero: n = 0 @integer 0 @decimal 0.0, 0.00, 0.000, 0.0000 // one: n = 1 @integer 1 @decimal 1.0, 1.00, 1.000, 1.0000 // two: n = 2 @integer 2 @decimal 2.0, 2.00, 2.000, 2.0000 // few: n = 3 @integer 3 @decimal 3.0, 3.00, 3.000, 3.0000 // many: n = 6 @integer 6 @decimal 6.0, 6.00, 6.000, 6.0000 // other: @integer 4, 5, 7~20, 100, 1000, 10000, 100000, 1000000, … @decimal 0.1~0.9, 1.1~1.7, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, … if (n = 0) then Result := pfZero else if (n = 1) then Result := pfOne else if (n = 2) then Result := pfTwo else if (n = 3) then Result := pfFew else if (n = 6) then Result := pfMany else Result := pfOther end; initialization TMultiPattern.Register('bm', GetSinglePlural); // Bamanankan TMultiPattern.Register('bo', GetSinglePlural); // Tibetan TMultiPattern.Register('dz', GetSinglePlural); // Dzongkha TMultiPattern.Register('id', GetSinglePlural); // Indonesian TMultiPattern.Register('ig', GetSinglePlural); // Igbo TMultiPattern.Register('ii', GetSinglePlural); // Yi TMultiPattern.Register('in', GetSinglePlural); // in TMultiPattern.Register('ja', GetSinglePlural); // Japanese TMultiPattern.Register('jbo', GetSinglePlural); // jbo TMultiPattern.Register('jv', GetSinglePlural); // Javanese TMultiPattern.Register('jw', GetSinglePlural); // jw TMultiPattern.Register('kde', GetSinglePlural); // Makonde TMultiPattern.Register('kea', GetSinglePlural); // Kabuverdianu TMultiPattern.Register('km', GetSinglePlural); // Khmer TMultiPattern.Register('ko', GetSinglePlural); // Korean TMultiPattern.Register('lkt', GetSinglePlural); // Lakota TMultiPattern.Register('lo', GetSinglePlural); // Lao TMultiPattern.Register('ms', GetSinglePlural); // Malay TMultiPattern.Register('my', GetSinglePlural); // Burmese TMultiPattern.Register('nqo', GetSinglePlural); // N'ko TMultiPattern.Register('root', GetSinglePlural); // root TMultiPattern.Register('sah', GetSinglePlural); // Sakha TMultiPattern.Register('ses', GetSinglePlural); // Koyraboro Senni TMultiPattern.Register('sg', GetSinglePlural); // Sango TMultiPattern.Register('th', GetSinglePlural); // Thai TMultiPattern.Register('to', GetSinglePlural); // Tongan TMultiPattern.Register('vi', GetSinglePlural); // Vietnamese TMultiPattern.Register('wo', GetSinglePlural); // Wolof TMultiPattern.Register('yo', GetSinglePlural); // Yoruba TMultiPattern.Register('yue', GetSinglePlural); // yue TMultiPattern.Register('zh', GetSinglePlural); // Chinese, Simplified TMultiPattern.Register('am', GetAmPlural); // Amharic TMultiPattern.Register('as', GetAmPlural); // Assamese TMultiPattern.Register('bn', GetAmPlural); // Bangla TMultiPattern.Register('fa', GetAmPlural); // Persian TMultiPattern.Register('gu', GetAmPlural); // Gujarati TMultiPattern.Register('hi', GetAmPlural); // Hindi TMultiPattern.Register('kn', GetAmPlural); // Kannada TMultiPattern.Register('mr', GetAmPlural); // Marathi TMultiPattern.Register('zu', GetAmPlural); // isiZulu TMultiPattern.Register('ff', GetFfPlural); // Fulah TMultiPattern.Register('fr', GetFfPlural); // French TMultiPattern.Register('hy', GetFfPlural); // Armenian TMultiPattern.Register('kab', GetFfPlural); // Kabyle TMultiPattern.Register('ast', GetAstPlural); // Asturian TMultiPattern.Register('ca', GetAstPlural); // Catalan TMultiPattern.Register('de', GetAstPlural); // German TMultiPattern.Register('en', GetAstPlural); // English TMultiPattern.Register('et', GetAstPlural); // Estonian TMultiPattern.Register('fi', GetAstPlural); // Finnish TMultiPattern.Register('fy', GetAstPlural); // Western Frisian TMultiPattern.Register('gl', GetAstPlural); // Galician TMultiPattern.Register('it', GetAstPlural); // Italian TMultiPattern.Register('ji', GetAstPlural); // ji TMultiPattern.Register('nl', GetAstPlural); // Dutch TMultiPattern.Register('sv', GetAstPlural); // Swedish TMultiPattern.Register('sw', GetAstPlural); // Kiswahili TMultiPattern.Register('ur', GetAstPlural); // Urdu TMultiPattern.Register('yi', GetAstPlural); // Yiddish TMultiPattern.Register('si', GetSinhalaPlural); // Sinhala TMultiPattern.Register('ak', GetAkPlural); // Akan TMultiPattern.Register('bh', GetAkPlural); // bh TMultiPattern.Register('guw', GetAkPlural); // guw TMultiPattern.Register('ln', GetAkPlural); // Lingala TMultiPattern.Register('mg', GetAkPlural); // Malagasy TMultiPattern.Register('nso', GetAkPlural); // Sesotho sa Leboa TMultiPattern.Register('pa', GetAkPlural); // Punjabi TMultiPattern.Register('ti', GetAkPlural); // Tigrinya TMultiPattern.Register('wa', GetAkPlural); // wa TMultiPattern.Register('tzm', GetCentralAtlasTamazightPlural); // Central Atlas Tamazight TMultiPattern.Register('pt', GetPortuguesePlural); // Portuguese TMultiPattern.Register('af', GetAfPlural); // Afrikaans TMultiPattern.Register('asa', GetAfPlural); // Asu TMultiPattern.Register('az', GetAfPlural); // Azerbaijani, Latin TMultiPattern.Register('bem', GetAfPlural); // Bemba TMultiPattern.Register('bez', GetAfPlural); // Bena TMultiPattern.Register('bg', GetAfPlural); // Bulgarian TMultiPattern.Register('brx', GetAfPlural); // Bodo TMultiPattern.Register('ce', GetAfPlural); // Chechen TMultiPattern.Register('cgg', GetAfPlural); // Chiga TMultiPattern.Register('chr', GetAfPlural); // Cherokee TMultiPattern.Register('ckb', GetAfPlural); // ckb TMultiPattern.Register('dv', GetAfPlural); // Divehi TMultiPattern.Register('ee', GetAfPlural); // Ewe TMultiPattern.Register('el', GetAfPlural); // Greek TMultiPattern.Register('eo', GetAfPlural); // Esperanto TMultiPattern.Register('es', GetAfPlural); // Spanish TMultiPattern.Register('eu', GetAfPlural); // Basque TMultiPattern.Register('fo', GetAfPlural); // Faroese TMultiPattern.Register('fur', GetAfPlural); // Friulian TMultiPattern.Register('gsw', GetAfPlural); // Swiss German TMultiPattern.Register('ha', GetAfPlural); // Hausa TMultiPattern.Register('haw', GetAfPlural); // Hawaiian TMultiPattern.Register('hu', GetAfPlural); // Hungarian TMultiPattern.Register('jgo', GetAfPlural); // Ngomba TMultiPattern.Register('jmc', GetAfPlural); // Machame TMultiPattern.Register('ka', GetAfPlural); // Georgian TMultiPattern.Register('kaj', GetAfPlural); // kaj TMultiPattern.Register('kcg', GetAfPlural); // kcg TMultiPattern.Register('kk', GetAfPlural); // Kazakh TMultiPattern.Register('kkj', GetAfPlural); // Kako TMultiPattern.Register('kl', GetAfPlural); // Greenlandic TMultiPattern.Register('ks', GetAfPlural); // Kashmiri TMultiPattern.Register('ksb', GetAfPlural); // Shambala TMultiPattern.Register('ku', GetAfPlural); // Central Kurdish TMultiPattern.Register('ky', GetAfPlural); // Kyrgyz TMultiPattern.Register('lb', GetAfPlural); // Luxembourgish TMultiPattern.Register('lg', GetAfPlural); // Ganda TMultiPattern.Register('mas', GetAfPlural); // Masai TMultiPattern.Register('mgo', GetAfPlural); // Meta' TMultiPattern.Register('ml', GetAfPlural); // Malayalam TMultiPattern.Register('mn', GetAfPlural); // Mongolian, Cyrillic TMultiPattern.Register('nah', GetAfPlural); // nah TMultiPattern.Register('nb', GetAfPlural); // Norwegian Bokmεl TMultiPattern.Register('nd', GetAfPlural); // North Ndebele TMultiPattern.Register('ne', GetAfPlural); // Nepali TMultiPattern.Register('nn', GetAfPlural); // Norwegian Nynorsk TMultiPattern.Register('nnh', GetAfPlural); // Ngiemboon TMultiPattern.Register('no', GetAfPlural); // Norwegian TMultiPattern.Register('nr', GetAfPlural); // South Ndebele TMultiPattern.Register('ny', GetAfPlural); // ny TMultiPattern.Register('nyn', GetAfPlural); // Nyankole TMultiPattern.Register('om', GetAfPlural); // Oromo TMultiPattern.Register('or', GetAfPlural); // Odia TMultiPattern.Register('os', GetAfPlural); // Ossetic TMultiPattern.Register('pap', GetAfPlural); // Papiamento TMultiPattern.Register('ps', GetAfPlural); // Pashto TMultiPattern.Register('rm', GetAfPlural); // Romansh TMultiPattern.Register('rof', GetAfPlural); // Rombo TMultiPattern.Register('rwk', GetAfPlural); // Rwa TMultiPattern.Register('saq', GetAfPlural); // Samburu TMultiPattern.Register('sdh', GetAfPlural); // sdh TMultiPattern.Register('seh', GetAfPlural); // Sena TMultiPattern.Register('sn', GetAfPlural); // Shona TMultiPattern.Register('so', GetAfPlural); // Somali TMultiPattern.Register('sq', GetAfPlural); // Albanian TMultiPattern.Register('ss', GetAfPlural); // siSwati TMultiPattern.Register('ssy', GetAfPlural); // Saho TMultiPattern.Register('st', GetAfPlural); // Sesotho TMultiPattern.Register('syr', GetAfPlural); // Syriac TMultiPattern.Register('ta', GetAfPlural); // Tamil TMultiPattern.Register('te', GetAfPlural); // Telugu TMultiPattern.Register('teo', GetAfPlural); // Teso TMultiPattern.Register('tig', GetAfPlural); // Tigre TMultiPattern.Register('tk', GetAfPlural); // Turkmen TMultiPattern.Register('tn', GetAfPlural); // Setswana TMultiPattern.Register('tr', GetAfPlural); // Turkish TMultiPattern.Register('ts', GetAfPlural); // Tsonga TMultiPattern.Register('ug', GetAfPlural); // Uyghur TMultiPattern.Register('uz', GetAfPlural); // Uzbek, Latin TMultiPattern.Register('ve', GetAfPlural); // Venda TMultiPattern.Register('vo', GetAfPlural); // Volapόk TMultiPattern.Register('vun', GetAfPlural); // Vunjo TMultiPattern.Register('wae', GetAfPlural); // Walser TMultiPattern.Register('xh', GetAfPlural); // isiXhosa TMultiPattern.Register('xog', GetAfPlural); // Soga TMultiPattern.Register('pt-PT', GetPortuguesePortugalPlural); // Portuguese (Portugal) TMultiPattern.Register('da', GetDanishPlural); // Danish TMultiPattern.Register('is', GetIcelandicPlural); // Icelandic TMultiPattern.Register('mk', GetMacedonianPlural); // Macedonian TMultiPattern.Register('fil', GetFilipinoPlural); // Filipino TMultiPattern.Register('tl', GetFilipinoPlural); // tl TMultiPattern.Register('lv', GetLatvianPlural); // Latvian TMultiPattern.Register('prg', GetLatvianPlural); // Prussian TMultiPattern.Register('lag', GetLangiPlural); // Langi TMultiPattern.Register('ksh', GetColognianPlural); // Colognian TMultiPattern.Register('iu', GetIuPlural); // Inuktitut, Latin TMultiPattern.Register('kw', GetIuPlural); // Cornish TMultiPattern.Register('naq', GetIuPlural); // Nama TMultiPattern.Register('se', GetIuPlural); // Northern Sami TMultiPattern.Register('sma', GetIuPlural); // Sami, Southern TMultiPattern.Register('smi', GetIuPlural); // smi TMultiPattern.Register('smj', GetIuPlural); // Sami, Lule TMultiPattern.Register('smn', GetIuPlural); // Sami, Inari TMultiPattern.Register('sms', GetIuPlural); // Sami, Skolt TMultiPattern.Register('shi', GetTachelhitPlural); // Tachelhit TMultiPattern.Register('mo', GetRomanianPlural); // mo TMultiPattern.Register('ro', GetRomanianPlural); // Romanian TMultiPattern.Register('bs', GetBsPlural); // Bosnian, Latin TMultiPattern.Register('hr', GetBsPlural); // Croatian TMultiPattern.Register('sh', GetBsPlural); // sh TMultiPattern.Register('sr', GetBsPlural); // Serbian, Cyrillic TMultiPattern.Register('gd', GetScottishGaelicPlural); // Scottish Gaelic TMultiPattern.Register('sl', GetSlovenianPlural); // Slovenian TMultiPattern.Register('dsb', GetLowerSorbianPlural); // Lower Sorbian TMultiPattern.Register('hsb', GetLowerSorbianPlural); // Upper Sorbian TMultiPattern.Register('he', GetHebrewPlural); // Hebrew TMultiPattern.Register('iw', GetHebrewPlural); // iw TMultiPattern.Register('cs', GetCzechPlural); // Czech TMultiPattern.Register('sk', GetCzechPlural); // Slovak TMultiPattern.Register('pl', GetPolishPlural); // Polish TMultiPattern.Register('be', GetBelarusianPlural); // Belarusian TMultiPattern.Register('lt', GetLithuanianPlural); // Lithuanian TMultiPattern.Register('mt', GetMaltesePlural); // Maltese TMultiPattern.Register('ru', GetRussianPlural); // Russian TMultiPattern.Register('uk', GetRussianPlural); // Ukrainian TMultiPattern.Register('br', GetBretonPlural); // Breton TMultiPattern.Register('ga', GetIrishPlural); // Irish TMultiPattern.Register('gv', GetManxPlural); // Manx TMultiPattern.Register('ar', GetArabicPlural); // Arabic TMultiPattern.Register('ars', GetArabicPlural); // ars TMultiPattern.Register('cy', GetWelshPlural); // Welsh end.
unit TpPanel; interface uses Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils, Types, ThTag, ThAttributeList, ThPanel, TpControls; type TTpPanel = class(TThPanel) private FHidden: Boolean; FOnGenerate: TTpEvent; public procedure CellTag(inTag: TThTag); override; published property Hidden: Boolean read FHidden write FHidden default false; property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate; end; implementation { TTpPanel } procedure TTpPanel.CellTag(inTag: TThTag); begin inherited; inTag.Add(tpClass, 'TTpPanel'); inTag.Add('tpName', Name); inTag.Attributes.Add('tpHidden', Hidden); inTag.Add('tpOnGenerate', OnGenerate); end; end.
{ * Compressor * } { ****************************************************************************** } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } unit CoreCompress; {$INCLUDE zDefine.inc} interface uses Math, Types, CoreClasses; type PPCCInt8 = ^PCCInt8; PCCInt8 = ^TCCInt8; TCCInt8 = ShortInt; PPCCUInt8 = ^PCCUInt8; PCCUInt8 = ^TCCUInt8; TCCUInt8 = Byte; PCCInt16 = ^TCCInt16; TCCInt16 = SmallInt; PCCUInt16 = ^TCCUInt16; TCCUInt16 = Word; PCCInt32 = ^TCCInt32; TCCInt32 = Integer; PCCUInt32 = ^TCCUInt32; TCCUInt32 = Cardinal; PCCInt64 = ^TCCInt64; TCCInt64 = Int64; PCCUInt64 = ^TCCUInt64; TCCUInt64 = UInt64; PCCPtr = ^TCCPtr; TCCPtr = Pointer; TCCPtrUInt = nativeUInt; TCCPtrInt = NativeInt; PPCCPtrInt = ^PCCPtrInt; PCCPtrUInt = ^TCCPtrUInt; PCCPtrInt = ^TCCPtrInt; PCCSizeUInt = ^TCCSizeUInt; TCCSizeUInt = TCCPtrUInt; PCCSizeInt = ^TCCSizeInt; TCCSizeInt = TCCPtrInt; PCCNativeUInt = ^TCCNativeUInt; TCCNativeUInt = TCCPtrUInt; PCCNativeInt = ^TCCNativeInt; TCCNativeInt = TCCPtrInt; PCCSize = ^TCCSizeUInt; TCCSize = TCCPtrUInt; PCCUInt8Array = ^TCCUInt8Array; TCCUInt8Array = array [0 .. MaxInt div SizeOf(TCCUInt8) - 1] of TCCUInt8; PPCCUInt64Record = ^PCCUInt64Record; PCCUInt64Record = ^TCCUInt64Record; TCCUInt64Record = packed record case Boolean of False: ( {$IFDEF BIG_ENDIAN}Hi, Lo{$ELSE}Lo, Hi{$ENDIF}: TCCUInt32;); True: (Value: TCCUInt64;); end; TCompressor = class(TCoreClassObject) private const ChunkHeadSize = $3000; ChunkSize = $FFFF - ChunkHeadSize; PrepareBuffSize = $FFFF; public constructor Create; reintroduce; virtual; destructor Destroy; override; function Compress(const aInData: TCCPtr; const aInSize: TCCSizeUInt; const aOutData: TCCPtr; const aOutLimit: TCCSizeUInt): TCCSizeUInt; virtual; function Decompress(const aInData: TCCPtr; const aInSize: TCCSizeUInt; const aOutData: TCCPtr; const aOutLimit: TCCSizeUInt): TCCSizeUInt; virtual; procedure CompressStream(sour: TCoreClassStream; StartPos, EndPos: NativeInt; CompressTo: TCoreClassStream); procedure DecompressStream(sour, DecompressTo: TCoreClassStream); end; TCompressorClass = class of TCompressor; TCompressorDeflate = class(TCompressor) private const HashBits = 16; HashSize = 1 shl HashBits; HashMask = HashSize - 1; HashShift = 32 - HashBits; WindowSize = 32768; WindowMask = WindowSize - 1; MinMatch = 3; MaxMatch = 258; MaxOffset = 32768; HashRef_ENDIAN_B30 = {$IF defined(BIG_ENDIAN)}$FFFFFF00{$ELSE}$00FFFFFF{$IFEND}; {$IFNDEF BIG_ENDIAN} MultiplyDeBruijnBytePosition: array [0 .. 31] of TCCUInt8 = (0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1); {$ENDIF} // LengthCodes: array [0 .. 28, 0 .. 3] of TCCUInt32 = ( // Code, ExtraBits, Min, Max (257, 0, 3, 3), (258, 0, 4, 4), (259, 0, 5, 5), (260, 0, 6, 6), (261, 0, 7, 7), (262, 0, 8, 8), (263, 0, 9, 9), (264, 0, 10, 10), (265, 1, 11, 12), (266, 1, 13, 14), (267, 1, 15, 16), (268, 1, 17, 18), (269, 2, 19, 22), (270, 2, 23, 26), (271, 2, 27, 30), (272, 2, 31, 34), (273, 3, 35, 42), (274, 3, 43, 50), (275, 3, 51, 58), (276, 3, 59, 66), (277, 4, 67, 82), (278, 4, 83, 98), (279, 4, 99, 114), (280, 4, 115, 130), (281, 5, 131, 162), (282, 5, 163, 194), (283, 5, 195, 226), (284, 5, 227, 257), (285, 0, 258, 258) ); DistanceCodes: array [0 .. 29, 0 .. 3] of TCCUInt32 = ( // Code, ExtraBits, Min, Max (0, 0, 1, 1), (1, 0, 2, 2), (2, 0, 3, 3), (3, 0, 4, 4), (4, 1, 5, 6), (5, 1, 7, 8), (6, 2, 9, 12), (7, 2, 13, 16), (8, 3, 17, 24), (9, 3, 25, 32), (10, 4, 33, 48), (11, 4, 49, 64), (12, 5, 65, 96), (13, 5, 97, 128), (14, 6, 129, 192), (15, 6, 193, 256), (16, 7, 257, 384), (17, 7, 385, 512), (18, 8, 513, 768), (19, 8, 769, 1024), (20, 9, 1025, 1536), (21, 9, 1537, 2048), (22, 10, 2049, 3072), (23, 10, 3073, 4096), (24, 11, 4097, 6144), (25, 11, 6145, 8192), (26, 12, 8193, 12288), (27, 12, 12289, 16384), (28, 13, 16385, 24576), (29, 13, 24577, 32768) ); MirrorBytes: array [TCCUInt8] of TCCUInt8 = ( $00, $80, $40, $C0, $20, $A0, $60, $E0, $10, $90, $50, $D0, $30, $B0, $70, $F0, $08, $88, $48, $C8, $28, $A8, $68, $E8, $18, $98, $58, $D8, $38, $B8, $78, $F8, $04, $84, $44, $C4, $24, $A4, $64, $E4, $14, $94, $54, $D4, $34, $B4, $74, $F4, $0C, $8C, $4C, $CC, $2C, $AC, $6C, $EC, $1C, $9C, $5C, $DC, $3C, $BC, $7C, $FC, $02, $82, $42, $C2, $22, $A2, $62, $E2, $12, $92, $52, $D2, $32, $B2, $72, $F2, $0A, $8A, $4A, $CA, $2A, $AA, $6A, $EA, $1A, $9A, $5A, $DA, $3A, $BA, $7A, $FA, $06, $86, $46, $C6, $26, $A6, $66, $E6, $16, $96, $56, $D6, $36, $B6, $76, $F6, $0E, $8E, $4E, $CE, $2E, $AE, $6E, $EE, $1E, $9E, $5E, $DE, $3E, $BE, $7E, $FE, $01, $81, $41, $C1, $21, $A1, $61, $E1, $11, $91, $51, $D1, $31, $B1, $71, $F1, $09, $89, $49, $C9, $29, $A9, $69, $E9, $19, $99, $59, $D9, $39, $B9, $79, $F9, $05, $85, $45, $C5, $25, $A5, $65, $E5, $15, $95, $55, $D5, $35, $B5, $75, $F5, $0D, $8D, $4D, $CD, $2D, $AD, $6D, $ED, $1D, $9D, $5D, $DD, $3D, $BD, $7D, $FD, $03, $83, $43, $C3, $23, $A3, $63, $E3, $13, $93, $53, $D3, $33, $B3, $73, $F3, $0B, $8B, $4B, $CB, $2B, $AB, $6B, $EB, $1B, $9B, $5B, $DB, $3B, $BB, $7B, $FB, $07, $87, $47, $C7, $27, $A7, $67, $E7, $17, $97, $57, $D7, $37, $B7, $77, $F7, $0F, $8F, $4F, $CF, $2F, $AF, $6F, $EF, $1F, $9F, $5F, $DF, $3F, $BF, $7F, $FF ); CLCIndex: array [0 .. 18] of TCCUInt8 = (16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15); type PHashTable = ^THashTable; THashTable = array [0 .. HashSize - 1] of PCCUInt8; PChainTable = ^TChainTable; TChainTable = array [0 .. WindowSize - 1] of TCCPtr; PTree = ^TTree; TTree = packed record Table: array [0 .. 15] of TCCUInt16; Translation: array [0 .. 287] of TCCUInt16; end; PBuffer = ^TBuffer; TBuffer = array [0 .. 65535] of TCCUInt8; PLengths = ^TLengths; TLengths = array [0 .. 288 + 32 - 1] of TCCUInt8; POffsets = ^TOffsets; TOffsets = array [0 .. 15] of TCCUInt16; TBits = array [0 .. 29] of TCCUInt8; PBits = ^TBits; TBase = array [0 .. 29] of TCCUInt16; PBase = ^TBase; var fHashTable: THashTable; fChainTable: TChainTable; fLengthCodesLookUpTable: array [0 .. 258] of TCCInt32; fDistanceCodesLookUpTable: array [0 .. 32768] of TCCInt32; fSymbolLengthTree: TTree; fDistanceTree: TTree; fFixedSymbolLengthTree: TTree; fFixedDistanceTree: TTree; fLengthBits: TBits; fDistanceBits: TBits; fLengthBase: TBase; fDistanceBase: TBase; fCodeTree: TTree; fLengths: TLengths; fWithHeader: Boolean; fGreedy: Boolean; fSkipStrength: TCCUInt32; fMaxSteps: TCCUInt32; public constructor Create; override; destructor Destroy; override; function Compress(const aInData: TCCPtr; const aInSize: TCCSizeUInt; const aOutData: TCCPtr; const aOutLimit: TCCSizeUInt): TCCSizeUInt; override; function Decompress(const aInData: TCCPtr; const aInSize: TCCSizeUInt; const aOutData: TCCPtr; const aOutLimit: TCCSizeUInt): TCCSizeUInt; override; property WithHeader: Boolean read fWithHeader write fWithHeader; property Greedy: Boolean read fGreedy write fGreedy; property SkipStrength: TCCUInt32 read fSkipStrength write fSkipStrength; property MaxSteps: TCCUInt32 read fMaxSteps write fMaxSteps; end; TCompressorBRRC = class(TCompressor) private const FlagModel = 0; LiteralModel = 2; SizeModels = 258; public constructor Create; override; destructor Destroy; override; function Compress(const aInData: TCCPtr; const aInSize: TCCSizeUInt; const aOutData: TCCPtr; const aOutLimit: TCCSizeUInt): TCCSizeUInt; override; function Decompress(const aInData: TCCPtr; const aInSize: TCCSizeUInt; const aOutData: TCCPtr; const aOutLimit: TCCSizeUInt): TCCSizeUInt; override; end; function CoreCompressStream(Compressor: TCompressor; sour: TCoreClassStream; ComTo: TCoreClassStream): Boolean; function CoreDecompressStream(Compressor: TCompressor; sour: TCoreClassStream; DeTo: TCoreClassStream): Boolean; function DeflateCompressStream(sour: TCoreClassStream; ComTo: TCoreClassStream): Boolean; function DeflateDecompressStream(sour: TCoreClassStream; DeTo: TCoreClassStream): Boolean; function BRRCCompressStream(sour: TCoreClassStream; ComTo: TCoreClassStream): Boolean; function BRRCDecompressStream(sour: TCoreClassStream; DeTo: TCoreClassStream): Boolean; implementation uses MemoryStream64; function CoreCompressStream(Compressor: TCompressor; sour: TCoreClassStream; ComTo: TCoreClassStream): Boolean; begin try Compressor.CompressStream(sour, 0, sour.Size, ComTo); Result := True; except Result := False; end; end; function CoreDecompressStream(Compressor: TCompressor; sour: TCoreClassStream; DeTo: TCoreClassStream): Boolean; begin try Compressor.DecompressStream(sour, DeTo); Result := True; except Result := False; end; end; function DeflateCompressStream(sour: TCoreClassStream; ComTo: TCoreClassStream): Boolean; var c: TCompressorDeflate; begin c := TCompressorDeflate.Create; Result := CoreCompressStream(c, sour, ComTo); DisposeObject(c); end; function DeflateDecompressStream(sour: TCoreClassStream; DeTo: TCoreClassStream): Boolean; var c: TCompressorDeflate; begin c := TCompressorDeflate.Create; Result := CoreDecompressStream(c, sour, DeTo); DisposeObject(c); end; function BRRCCompressStream(sour: TCoreClassStream; ComTo: TCoreClassStream): Boolean; var c: TCompressorBRRC; begin c := TCompressorBRRC.Create; Result := CoreCompressStream(c, sour, ComTo); DisposeObject(c); end; function BRRCDecompressStream(sour: TCoreClassStream; DeTo: TCoreClassStream): Boolean; var c: TCompressorBRRC; begin c := TCompressorBRRC.Create; Result := CoreDecompressStream(c, sour, DeTo); DisposeObject(c); end; procedure BytewiseMemoryMove(const aSource; var aDestination; const aLength: TCCSizeUInt); var index: TCCSizeUInt; Source, Destination: PCCUInt8Array; begin if aLength > 0 then begin Source := TCCPtr(@aSource); Destination := TCCPtr(@aDestination); for index := 0 to aLength - 1 do begin Destination^[index] := Source^[index]; end; end; end; procedure RLELikeSideEffectAwareMemoryMove(const aSource; var aDestination; const aLength: TCCSizeUInt); begin if aLength > 0 then begin if (TCCSizeUInt(TCCPtr(@aSource)) + aLength) <= TCCSizeUInt(TCCPtr(@aDestination)) then // Non-overlapping, so we an use an optimized memory move function CopyPtr(@aSource, @aDestination, aLength) else // Overlapping, so we must do copy byte-wise for to get the free RLE-like side-effect included BytewiseMemoryMove(aSource, aDestination, aLength); end; end; {$IFDEF RangeCheck}{$R-}{$ENDIF} {$IFNDEF fpc} function BSRDWord(Value: TCCUInt32): TCCUInt32; const BSRDebruijn32Multiplicator = TCCUInt32($07C4ACDD); BSRDebruijn32Shift = 27; BSRDebruijn32Mask = 31; BSRDebruijn32Table: array [0 .. 31] of TCCInt32 = (0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31); begin if Value = 0 then begin Result := 255; end else begin Value := Value or (Value shr 1); Value := Value or (Value shr 2); Value := Value or (Value shr 4); Value := Value or (Value shr 8); Value := Value or (Value shr 16); Result := BSRDebruijn32Table[((Value * BSRDebruijn32Multiplicator) shr BSRDebruijn32Shift) and BSRDebruijn32Mask]; end; end; {$IFEND} function SARLongint(Value, Shift: TCCInt32): TCCInt32; begin Shift := Shift and 31; Result := (TCCUInt32(Value) shr Shift) or (TCCUInt32(TCCInt32(TCCUInt32(-TCCUInt32(TCCUInt32(Value) shr 31)) and TCCUInt32(-TCCUInt32(Ord(Shift <> 0) and 1)))) shl (32 - Shift)); end; function SARInt64(Value: TCCInt64; Shift: TCCInt32): TCCInt64; begin Shift := Shift and 63; Result := (TCCInt64(Value) shr Shift) or (TCCInt64(TCCInt64(TCCInt64(-TCCInt64(TCCInt64(Value) shr 63)) and TCCInt64(-TCCInt64(Ord(Shift <> 0) and 1)))) shl (63 - Shift)); end; constructor TCompressor.Create; begin inherited Create; end; destructor TCompressor.Destroy; begin inherited Destroy; end; function TCompressor.Compress(const aInData: TCCPtr; const aInSize: TCCSizeUInt; const aOutData: TCCPtr; const aOutLimit: TCCSizeUInt): TCCSizeUInt; begin Result := 0; end; function TCompressor.Decompress(const aInData: TCCPtr; const aInSize: TCCSizeUInt; const aOutData: TCCPtr; const aOutLimit: TCCSizeUInt): TCCSizeUInt; begin Result := 0; end; procedure TCompressor.CompressStream(sour: TCoreClassStream; StartPos, EndPos: NativeInt; CompressTo: TCoreClassStream); type TPrepareBuff = array [0 .. PrepareBuffSize + 2] of Byte; PPrepareBuff = ^TPrepareBuff; var buff: array [0 .. ChunkSize] of Byte; PrepareBuffPtr: PPrepareBuff; siz: Int64; j: NativeInt; Num: NativeInt; Rest: NativeInt; begin siz := EndPos - StartPos; if siz > 0 then begin CompressTo.write(siz, 8); sour.Position := StartPos; new(PrepareBuffPtr); if siz > ChunkSize then begin Num := siz div ChunkSize; Rest := siz mod ChunkSize; for j := 0 to Num - 1 do begin sour.read(buff[0], ChunkSize); PWORD(@(PrepareBuffPtr^[0]))^ := Compress(@buff[0], ChunkSize, @PrepareBuffPtr^[2], PrepareBuffSize); CompressTo.write(PrepareBuffPtr^[0], PWORD(@(PrepareBuffPtr^[0]))^ + 2); end; if Rest > 0 then begin sour.read(buff[0], Rest); PWORD(@(PrepareBuffPtr^[0]))^ := Compress(@buff[0], Rest, @PrepareBuffPtr^[2], PrepareBuffSize); CompressTo.write(PrepareBuffPtr^[0], PWORD(@(PrepareBuffPtr^[0]))^ + 2); end; end else begin sour.read(buff[0], siz); PWORD(@(PrepareBuffPtr^[0]))^ := Compress(@buff[0], siz, @PrepareBuffPtr^[2], PrepareBuffSize); CompressTo.write(PrepareBuffPtr^[0], PWORD(@(PrepareBuffPtr^[0]))^ + 2); end; Dispose(PrepareBuffPtr); end; end; procedure TCompressor.DecompressStream(sour, DecompressTo: TCoreClassStream); var siz, cSiz: Int64; bufSiz, deBufSiz: Word; buff, decryptBuff: Pointer; begin if sour.Position + 10 < sour.Size then begin sour.read(siz, 8); cSiz := 0; buff := GetMemory(PrepareBuffSize); decryptBuff := GetMemory(PrepareBuffSize); while cSiz < siz do begin if sour.read(bufSiz, 2) <> 2 then Break; if sour.read(buff^, bufSiz) <> bufSiz then Break; deBufSiz := Decompress(buff, bufSiz, decryptBuff, PrepareBuffSize); DecompressTo.write(decryptBuff^, deBufSiz); inc(cSiz, deBufSiz); end; FreeMemory(buff); FreeMemory(decryptBuff); end; end; constructor TCompressorDeflate.Create; procedure BuildFixedTrees(var aLT, aDT: TTree); var i: TCCInt32; begin for i := 0 to 6 do begin aLT.Table[i] := 0; end; aLT.Table[7] := 24; aLT.Table[8] := 152; aLT.Table[9] := 112; for i := 0 to 23 do aLT.Translation[i] := 256 + i; for i := 0 to 143 do aLT.Translation[24 + i] := i; for i := 0 to 7 do aLT.Translation[168 + i] := 280 + i; for i := 0 to 111 do aLT.Translation[176 + i] := 144 + i; for i := 0 to 4 do aDT.Table[i] := 0; aDT.Table[5] := 32; for i := 0 to 31 do aDT.Translation[i] := i; end; procedure BuildBitsBase(aBits: PCCUInt8Array; aBase: PCCUInt16; aDelta, aFirst: TCCInt32); var i, Sum: TCCInt32; begin for i := 0 to aDelta - 1 do aBits^[i] := 0; for i := 0 to (30 - aDelta) - 1 do aBits^[i + aDelta] := i div aDelta; Sum := aFirst; for i := 0 to 29 do begin aBase^ := Sum; inc(aBase); inc(Sum, 1 shl aBits^[i]); end; end; var index, ValueIndex: TCCInt32; begin inherited Create; for index := 0 to length(LengthCodes) - 1 do for ValueIndex := IfThen(index = 0, 0, LengthCodes[index, 2]) to LengthCodes[index, 3] do fLengthCodesLookUpTable[ValueIndex] := index; for index := 0 to length(DistanceCodes) - 1 do for ValueIndex := IfThen(index = 0, 0, DistanceCodes[index, 2]) to DistanceCodes[index, 3] do fDistanceCodesLookUpTable[ValueIndex] := index; FillPtrByte(@fLengthBits, SizeOf(TBits), 0); FillPtrByte(@fDistanceBits, SizeOf(TBits), 0); FillPtrByte(@fLengthBase, SizeOf(TBase), 0); FillPtrByte(@fDistanceBase, SizeOf(TBase), 0); FillPtrByte(@fFixedSymbolLengthTree, SizeOf(TTree), 0); FillPtrByte(@fFixedDistanceTree, SizeOf(TTree), 0); BuildFixedTrees(fFixedSymbolLengthTree, fFixedDistanceTree); BuildBitsBase(TCCPtr(@fLengthBits[0]), PCCUInt16(TCCPtr(@fLengthBase[0])), 4, 3); BuildBitsBase(TCCPtr(@fDistanceBits[0]), PCCUInt16(TCCPtr(@fDistanceBase[0])), 2, 1); fLengthBits[28] := 0; fLengthBase[28] := 258; fWithHeader := False; fGreedy := False; fSkipStrength := 32; fMaxSteps := 128; end; destructor TCompressorDeflate.Destroy; begin inherited Destroy; end; function TCompressorDeflate.Compress(const aInData: TCCPtr; const aInSize: TCCSizeUInt; const aOutData: TCCPtr; const aOutLimit: TCCSizeUInt): TCCSizeUInt; var OutputBits, CountOutputBits: TCCUInt32; DestLen: TCCSizeUInt; OK: Boolean; procedure DoOutputBits(const aBits, aCountBits: TCCUInt32); begin Assert((CountOutputBits + aCountBits) <= 32); OutputBits := OutputBits or (aBits shl CountOutputBits); inc(CountOutputBits, aCountBits); while CountOutputBits >= 8 do begin if DestLen < aOutLimit then begin PCCUInt8Array(aOutData)^[DestLen] := OutputBits and $FF; inc(DestLen); end else begin OK := False; end; OutputBits := OutputBits shr 8; dec(CountOutputBits, 8); end; end; procedure DoOutputLiteral(const AValue: TCCUInt8); begin case AValue of 0 .. 143: DoOutputBits(MirrorBytes[$30 + AValue], 8); else DoOutputBits((MirrorBytes[$90 + (AValue - 144)] shl 1) or 1, 9); end; end; procedure DoOutputCopy(const aDistance, aLength: TCCUInt32); var Remain, ToDo, index: TCCUInt32; begin Remain := aLength; while Remain > 0 do begin case Remain of 0 .. 258: ToDo := Remain; 259 .. 260: ToDo := Remain - 3; else ToDo := 258; end; dec(Remain, ToDo); index := fLengthCodesLookUpTable[Min(Max(ToDo, 0), 258)]; if LengthCodes[index, 0] <= 279 then DoOutputBits(MirrorBytes[(LengthCodes[index, 0] - 256) shl 1], 7) else DoOutputBits(MirrorBytes[$C0 + (LengthCodes[index, 0] - 280)], 8); if LengthCodes[index, 1] <> 0 then DoOutputBits(ToDo - LengthCodes[index, 2], LengthCodes[index, 1]); index := fDistanceCodesLookUpTable[Min(Max(aDistance, 0), 32768)]; DoOutputBits(MirrorBytes[DistanceCodes[index, 0] shl 3], 5); if DistanceCodes[index, 1] <> 0 then DoOutputBits(aDistance - DistanceCodes[index, 2], DistanceCodes[index, 1]); end; end; procedure OutputStartBlock; begin DoOutputBits(1, 1); // Final block DoOutputBits(1, 2); // Static huffman block end; procedure OutputEndBlock; begin DoOutputBits(0, 7); // Close block DoOutputBits(0, 7); // Make sure all bits are flushed end; function Adler32(const aData: TCCPtr; const aLength: TCCUInt32): TCCUInt32; const Base = 65521; MaximumCountAtOnce = 5552; var Buf: PCCUInt8; Remain, s1, s2, ToDo, index: TCCUInt32; begin s1 := 1; s2 := 0; Buf := aData; Remain := aLength; while Remain > 0 do begin if Remain < MaximumCountAtOnce then ToDo := Remain else ToDo := MaximumCountAtOnce; dec(Remain, ToDo); for index := 1 to ToDo do begin inc(s1, TCCUInt8(Buf^)); inc(s2, s1); inc(Buf); end; s1 := s1 mod Base; s2 := s2 mod Base; end; Result := (s2 shl 16) or s1; end; var CurrentPointer, EndPointer, EndSearchPointer, Head, CurrentPossibleMatch: PCCUInt8; BestMatchDistance, BestMatchLength, MatchLength, CheckSum, Step, Difference, Offset, UnsuccessfulFindMatchAttempts: TCCUInt32; HashTableItem: PPCCUInt8; begin OK := True; DestLen := 0; OutputBits := 0; CountOutputBits := 0; if fWithHeader then begin DoOutputBits($78, 8); // CMF DoOutputBits($9C, 8); // FLG Default Compression end; OutputStartBlock; FillPtrByte(@fHashTable, SizeOf(THashTable), 0); FillPtrByte(@fChainTable, SizeOf(TChainTable), 0); CurrentPointer := aInData; EndPointer := TCCPtr(TCCPtrUInt(TCCPtrUInt(CurrentPointer) + TCCPtrUInt(aInSize))); EndSearchPointer := TCCPtr(TCCPtrUInt((TCCPtrUInt(CurrentPointer) + TCCPtrUInt(aInSize)) - TCCPtrUInt(TCCInt64(Max(TCCInt64(MinMatch), TCCInt64(SizeOf(TCCUInt32))))))); UnsuccessfulFindMatchAttempts := TCCUInt32(1) shl fSkipStrength; while TCCPtrUInt(CurrentPointer) < TCCPtrUInt(EndSearchPointer) do begin HashTableItem := @fHashTable[((((PCCUInt32(TCCPtr(CurrentPointer))^ and TCCUInt32(HashRef_ENDIAN_B30){$IF defined(BIG_ENDIAN)} shr 8{$IFEND})) * TCCUInt32($1E35A7BD)) shr HashShift) and HashMask]; Head := HashTableItem^; CurrentPossibleMatch := Head; BestMatchDistance := 0; BestMatchLength := 1; Step := 0; while Assigned(CurrentPossibleMatch) and (TCCPtrUInt(CurrentPointer) > TCCPtrUInt(CurrentPossibleMatch)) and (TCCPtrInt(TCCPtrUInt(TCCPtrUInt(CurrentPointer) - TCCPtrUInt(CurrentPossibleMatch))) < TCCPtrInt(MaxOffset)) do begin Difference := PCCUInt32(TCCPtr(@PCCUInt8Array(CurrentPointer)^[0]))^ xor PCCUInt32(TCCPtr(@PCCUInt8Array(CurrentPossibleMatch)^[0]))^; if (Difference and TCCUInt32(HashRef_ENDIAN_B30)) = 0 then begin if (BestMatchLength <= (TCCPtrUInt(EndPointer) - TCCPtrUInt(CurrentPointer))) and (PCCUInt8Array(CurrentPointer)^[BestMatchLength - 1] = PCCUInt8Array(CurrentPossibleMatch)^[BestMatchLength - 1]) then begin MatchLength := MinMatch; while ((TCCPtrUInt(@PCCUInt8Array(CurrentPointer)^[MatchLength]) and (SizeOf(TCCUInt32) - 1)) <> 0) and ((TCCPtrUInt(@PCCUInt8Array(CurrentPointer)^[MatchLength]) < TCCPtrUInt(EndPointer))) and (PCCUInt8Array(CurrentPointer)^[MatchLength] = PCCUInt8Array(CurrentPossibleMatch)^[MatchLength]) do inc(MatchLength); while (TCCPtrUInt(@PCCUInt8Array(CurrentPointer)^[MatchLength + (SizeOf(TCCUInt32) - 1)]) < TCCPtrUInt(EndPointer)) do begin Difference := PCCUInt32(TCCPtr(@PCCUInt8Array(CurrentPointer)^[MatchLength]))^ xor PCCUInt32(TCCPtr(@PCCUInt8Array(CurrentPossibleMatch)^[MatchLength]))^; if Difference = 0 then begin inc(MatchLength, SizeOf(TCCUInt32)); end else begin {$IF defined(BIG_ENDIAN)} if (Difference shr 16) <> 0 then inc(MatchLength, not(Difference shr 24)) else inc(MatchLength, 2 + (not(Difference shr 8))); {$ELSE} inc(MatchLength, MultiplyDeBruijnBytePosition[TCCUInt32(TCCUInt32(Difference and (-Difference)) * TCCUInt32($077CB531)) shr 27]); {$IFEND} Break; end; end; if BestMatchLength < MatchLength then begin BestMatchDistance := TCCPtrUInt(TCCPtrUInt(CurrentPointer) - TCCPtrUInt(CurrentPossibleMatch)); BestMatchLength := MatchLength; end; end; end; inc(Step); if Step < fMaxSteps then CurrentPossibleMatch := fChainTable[(TCCPtrUInt(CurrentPossibleMatch) - TCCPtrUInt(aInData)) and WindowMask] else Break; end; if (BestMatchDistance > 0) and (BestMatchLength > 1) then begin DoOutputCopy(BestMatchDistance, BestMatchLength); UnsuccessfulFindMatchAttempts := TCCUInt32(1) shl fSkipStrength; end else begin if fSkipStrength > 31 then begin DoOutputLiteral(CurrentPointer^); end else begin Step := UnsuccessfulFindMatchAttempts shr fSkipStrength; Offset := 0; while (Offset < Step) and ((TCCPtrUInt(CurrentPointer) + Offset) < TCCPtrUInt(EndSearchPointer)) do begin DoOutputLiteral(PCCUInt8Array(CurrentPointer)^[Offset]); inc(Offset); end; BestMatchLength := Offset; inc(UnsuccessfulFindMatchAttempts, Ord(UnsuccessfulFindMatchAttempts < TCCUInt32($FFFFFFFF)) and 1); end; end; if not OK then Break; HashTableItem^ := CurrentPointer; fChainTable[(TCCPtrUInt(CurrentPointer) - TCCPtrUInt(aInData)) and WindowMask] := Head; if fGreedy then begin inc(CurrentPointer); dec(BestMatchLength); while (BestMatchLength > 0) and (TCCPtrUInt(CurrentPointer) < TCCPtrUInt(EndSearchPointer)) do begin HashTableItem := @fHashTable[((((PCCUInt32(TCCPtr(CurrentPointer))^ and TCCUInt32(HashRef_ENDIAN_B30){$IF defined(BIG_ENDIAN)} shr 8{$IFEND})) * TCCUInt32($1E35A7BD)) shr HashShift) and HashMask]; Head := HashTableItem^; HashTableItem^ := CurrentPointer; fChainTable[(TCCPtrUInt(CurrentPointer) - TCCPtrUInt(aInData)) and WindowMask] := Head; inc(CurrentPointer); dec(BestMatchLength); end; end; inc(CurrentPointer, BestMatchLength); end; while TCCPtrUInt(CurrentPointer) < TCCPtrUInt(EndPointer) do begin DoOutputLiteral(CurrentPointer^); if not OK then Break; inc(CurrentPointer); end; OutputEndBlock; if fWithHeader then begin CheckSum := Adler32(aInData, aInSize); if (DestLen + 4) < aOutLimit then begin PCCUInt8Array(aOutData)^[DestLen + 0] := (CheckSum shr 24) and $FF; PCCUInt8Array(aOutData)^[DestLen + 1] := (CheckSum shr 16) and $FF; PCCUInt8Array(aOutData)^[DestLen + 2] := (CheckSum shr 8) and $FF; PCCUInt8Array(aOutData)^[DestLen + 3] := (CheckSum shr 0) and $FF; inc(DestLen, 4); end; end; if OK then Result := DestLen else Result := 0; end; function TCompressorDeflate.Decompress(const aInData: TCCPtr; const aInSize: TCCSizeUInt; const aOutData: TCCPtr; const aOutLimit: TCCSizeUInt): TCCSizeUInt; var Tag, BitCount: TCCUInt32; Source, SourceEnd: PCCUInt8; dest: PCCUInt8; DestLen: TCCSizeUInt; function Adler32(aData: TCCPtr; aLength: TCCUInt32): TCCUInt32; const Base = 65521; NMAX = 5552; var Buf: PCCUInt8; s1, s2, k, i: TCCUInt32; begin s1 := 1; s2 := 0; Buf := aData; while aLength > 0 do begin if aLength < NMAX then k := aLength else k := NMAX; dec(aLength, k); for i := 1 to k do begin inc(s1, TCCUInt8(Buf^)); inc(s2, s1); inc(Buf); end; s1 := s1 mod Base; s2 := s2 mod Base; end; Result := (s2 shl 16) or s1; end; procedure BuildTree(var aTree: TTree; aLengths: PCCUInt8Array; aNum: TCCInt32); var Offsets: TOffsets; i: TCCInt32; Sum: TCCUInt32; begin for i := 0 to 15 do aTree.Table[i] := 0; for i := 0 to aNum - 1 do inc(aTree.Table[TCCUInt8(aLengths^[i])]); aTree.Table[0] := 0; Sum := 0; for i := 0 to 15 do begin Offsets[i] := Sum; inc(Sum, aTree.Table[i]); end; for i := 0 to aNum - 1 do if aLengths^[i] <> 0 then begin aTree.Translation[Offsets[TCCUInt8(aLengths^[i])]] := i; inc(Offsets[TCCUInt8(aLengths^[i])]); end; end; function GetBit: TCCUInt32; begin if BitCount = 0 then begin Tag := TCCUInt8(Source^); inc(Source); BitCount := 7; end else dec(BitCount); Result := Tag and 1; Tag := Tag shr 1; end; function ReadBits(aNum, aBase: TCCUInt32): TCCUInt32; var Limit, Mask: TCCUInt32; begin Result := 0; if aNum <> 0 then begin Limit := 1 shl aNum; Mask := 1; while Mask < Limit do begin if GetBit <> 0 then inc(Result, Mask); Mask := Mask shl 1; end; end; inc(Result, aBase); end; function DecodeSymbol(const aTree: TTree): TCCUInt32; var Sum, c, L: TCCInt32; begin Sum := 0; c := 0; L := 0; repeat c := (c * 2) + TCCInt32(GetBit); inc(L); inc(Sum, aTree.Table[L]); dec(c, aTree.Table[L]); until not(c >= 0); Result := aTree.Translation[Sum + c]; end; procedure DecodeTrees(var aLT, aDT: TTree); var hlit, hdist, hclen, i, Num, Len, clen, Symbol, Prev: TCCUInt32; begin FillPtrByte(@fCodeTree, SizeOf(TTree), 0); FillPtrByte(@fLengths, SizeOf(TLengths), 0); hlit := ReadBits(5, 257); hdist := ReadBits(5, 1); hclen := ReadBits(4, 4); for i := 0 to 18 do fLengths[i] := 0; for i := 1 to hclen do begin clen := ReadBits(3, 0); fLengths[CLCIndex[i - 1]] := clen; end; BuildTree(fCodeTree, TCCPtr(@fLengths[0]), 19); Num := 0; while Num < (hlit + hdist) do begin Symbol := DecodeSymbol(fCodeTree); case Symbol of 16: begin Prev := fLengths[Num - 1]; Len := ReadBits(2, 3); while Len > 0 do begin fLengths[Num] := Prev; inc(Num); dec(Len); end; end; 17: begin Len := ReadBits(3, 3); while Len > 0 do begin fLengths[Num] := 0; inc(Num); dec(Len); end; end; 18: begin Len := ReadBits(7, 11); while Len > 0 do begin fLengths[Num] := 0; inc(Num); dec(Len); end; end; else begin fLengths[Num] := Symbol; inc(Num); end; end; end; BuildTree(aLT, TCCPtr(@fLengths[0]), hlit); BuildTree(aDT, TCCPtr(@fLengths[hlit]), hdist); end; function InflateBlockData(const aLT, aDT: TTree): Boolean; var Symbol: TCCUInt32; Len, Distance, Offset: TCCInt32; t: PCCUInt8; begin Result := False; while (TCCPtrUInt(TCCPtr(Source)) < TCCPtrUInt(TCCPtr(SourceEnd))) or (BitCount > 0) do begin Symbol := DecodeSymbol(aLT); if Symbol = 256 then begin Result := True; Break; end; if Symbol < 256 then begin if (DestLen + 1) <= aOutLimit then begin dest^ := TCCUInt8(Symbol); inc(dest); inc(DestLen); end else Exit; end else begin dec(Symbol, 257); Len := ReadBits(fLengthBits[Symbol], fLengthBase[Symbol]); Distance := DecodeSymbol(aDT); Offset := ReadBits(fDistanceBits[Distance], fDistanceBase[Distance]); if (DestLen + TCCSizeUInt(Len)) <= aOutLimit then begin t := TCCPtr(dest); dec(t, Offset); RLELikeSideEffectAwareMemoryMove(t^, dest^, Len); inc(dest, Len); inc(DestLen, Len); end else Exit; end; end; end; function InflateUncompressedBlock: Boolean; var Len, InvLen: TCCUInt32; begin Result := False; Len := (TCCUInt8(PCCUInt8Array(Source)^[1]) shl 8) or TCCUInt8(PCCUInt8Array(Source)^[0]); InvLen := (TCCUInt8(PCCUInt8Array(Source)^[3]) shl 8) or TCCUInt8(PCCUInt8Array(Source)^[2]); if Len <> ((not InvLen) and $FFFF) then Exit; inc(Source, 4); if Len > 0 then begin if (DestLen + Len) < aOutLimit then begin CopyPtr(Source, dest, Len); inc(Source, Len); inc(dest, Len); end else Exit; end; BitCount := 0; inc(DestLen, Len); Result := True; end; function InflateFixedBlock: Boolean; begin Result := InflateBlockData(fFixedSymbolLengthTree, fFixedDistanceTree); end; function InflateDynamicBlock: Boolean; begin FillPtrByte(@fSymbolLengthTree, SizeOf(TTree), 0); FillPtrByte(@fDistanceTree, SizeOf(TTree), 0); DecodeTrees(fSymbolLengthTree, fDistanceTree); Result := InflateBlockData(fSymbolLengthTree, fDistanceTree); end; function Uncompress: Boolean; var FinalBlock: Boolean; BlockType: TCCUInt32; begin BitCount := 0; repeat FinalBlock := GetBit <> 0; BlockType := ReadBits(2, 0); case BlockType of 0: begin Result := InflateUncompressedBlock; end; 1: begin Result := InflateFixedBlock; end; 2: begin Result := InflateDynamicBlock; end; else begin Result := False; end; end; until FinalBlock or not Result; end; function UncompressZLIB: Boolean; var cmf, flg: TCCUInt8; a32: TCCUInt32; begin Result := False; Source := aInData; cmf := TCCUInt8(PCCUInt8Array(Source)^[0]); flg := TCCUInt8(PCCUInt8Array(Source)^[1]); if ((((cmf shl 8) + flg) mod 31) <> 0) or ((cmf and $F) <> 8) or ((cmf shr 4) > 7) or ((flg and $20) <> 0) then begin Exit; end; a32 := (TCCUInt8(PCCUInt8Array(Source)^[aInSize - 4]) shl 24) or (TCCUInt8(PCCUInt8Array(Source)^[aInSize - 3]) shl 16) or (TCCUInt8(PCCUInt8Array(Source)^[aInSize - 2]) shl 8) or (TCCUInt8(PCCUInt8Array(Source)^[aInSize - 1]) shl 0); inc(Source, 2); SourceEnd := @PCCUInt8Array(Source)^[aInSize - 6]; Result := Uncompress; if not Result then begin Exit; end; Result := Adler32(aOutData, DestLen) = a32; end; function UncompressDirect: Boolean; begin Source := aInData; SourceEnd := @PCCUInt8Array(Source)^[aInSize]; Result := Uncompress; end; begin dest := aOutData; DestLen := 0; Result := 0; if fWithHeader then begin if UncompressZLIB then begin Result := DestLen; end; end else begin if UncompressDirect then begin Result := DestLen; end; end; end; constructor TCompressorBRRC.Create; begin inherited Create; end; destructor TCompressorBRRC.Destroy; begin inherited Destroy; end; function TCompressorBRRC.Compress(const aInData: TCCPtr; const aInSize: TCCSizeUInt; const aOutData: TCCPtr; const aOutLimit: TCCSizeUInt): TCCSizeUInt; var {$IFNDEF CPU64}Code, {$ENDIF}Range, Cache, CountFFBytes: TCCUInt32; {$IFDEF CPU64}Code: TCCUInt64; {$ENDIF} Model: array [0 .. SizeModels - 1] of TCCUInt32; OK, FirstByte{$IFNDEF CPU64}, Carry{$ENDIF} : Boolean; DestLen: TCCInt32; procedure EncoderShift; {$IFDEF CPU64} var Carry: Boolean; {$ENDIF} begin {$IFDEF CPU64} Carry := PCCUInt64Record(TCCPtr(@Code))^.Hi <> 0; // or (Code shr 32)<>0; or also (Code and TCCUInt64($ffffffff00000000))<>0; {$ENDIF} if (Code < $FF000000) or Carry then begin if FirstByte then begin FirstByte := False; end else begin if TCCSizeUInt(DestLen) < TCCSizeUInt(aOutLimit) then begin PCCUInt8Array(aOutData)^[DestLen] := TCCUInt8(Cache + TCCUInt8(Ord(Carry) and 1)); inc(DestLen); end else begin OK := False; Exit; end; end; while CountFFBytes <> 0 do begin dec(CountFFBytes); if TCCSizeUInt(DestLen) < TCCSizeUInt(aOutLimit) then begin PCCUInt8Array(aOutData)^[DestLen] := TCCUInt8($FF + TCCUInt8(Ord(Carry) and 1)); inc(DestLen); end else begin OK := False; Exit; end; end; Cache := (Code shr 24) and $FF; end else begin inc(CountFFBytes); end; Code := (Code shl 8){$IFDEF CPU64} and TCCUInt32($FFFFFFFF){$ENDIF}; Carry := False; end; function EncodeBit(ModelIndex, Move, Bit: TCCInt32): TCCInt32; var Bound{$IFNDEF CPU64}, OldCode{$ENDIF}: TCCUInt32; begin Bound := (Range shr 12) * Model[ModelIndex]; if Bit = 0 then begin Range := Bound; inc(Model[ModelIndex], (4096 - Model[ModelIndex]) shr Move); end else begin {$IFNDEF CPU64} OldCode := Code; {$ENDIF} inc(Code, Bound); {$IFNDEF CPU64} Carry := Carry or (Code < OldCode); {$ENDIF} dec(Range, Bound); dec(Model[ModelIndex], Model[ModelIndex] shr Move); end; while Range < $1000000 do begin Range := Range shl 8; EncoderShift; end; Result := Bit; end; procedure EncoderFlush; var Counter: TCCInt32; begin for Counter := 1 to 5 do EncoderShift; end; procedure EncodeTree(ModelIndex, Bits, Move, Value: TCCInt32); var Context: TCCInt32; begin Context := 1; while Bits > 0 do begin dec(Bits); Context := (Context shl 1) or EncodeBit(ModelIndex + Context, Move, (Value shr Bits) and 1); end; end; var CurrentPointer, EndPointer: PCCUInt8; Len, MinDestLen: TCCInt32; begin DestLen := 0; FirstByte := True; OK := True; CountFFBytes := 0; Range := $FFFFFFFF; Code := 0; for Len := 0 to SizeModels - 1 do begin Model[Len] := 2048; end; CurrentPointer := aInData; EndPointer := TCCPtr(TCCPtrUInt(TCCPtrUInt(CurrentPointer) + TCCPtrUInt(aInSize))); while TCCPtrUInt(CurrentPointer) < TCCPtrUInt(EndPointer) do begin EncodeBit(FlagModel, 1, 1); EncodeTree(LiteralModel, 8, 4, PCCUInt8(CurrentPointer)^); if not OK then begin Break; end; inc(CurrentPointer); end; EncodeBit(FlagModel, 1, 0); MinDestLen := Max(2, DestLen + 1); EncoderFlush; if OK then begin while (DestLen > MinDestLen) and (PCCUInt8Array(aOutData)^[DestLen - 1] = 0) do dec(DestLen); Result := DestLen; end else Result := 0; end; function TCompressorBRRC.Decompress(const aInData: TCCPtr; const aInSize: TCCSizeUInt; const aOutData: TCCPtr; const aOutLimit: TCCSizeUInt): TCCSizeUInt; var Code, Range, Position: TCCUInt32; Model: array [0 .. SizeModels - 1] of TCCUInt32; OK: Boolean; function DecodeBit(ModelIndex, Move: TCCInt32): TCCInt32; var Bound: TCCUInt32; begin Bound := (Range shr 12) * Model[ModelIndex]; if Code < Bound then begin Range := Bound; inc(Model[ModelIndex], (4096 - Model[ModelIndex]) shr Move); Result := 0; end else begin dec(Code, Bound); dec(Range, Bound); dec(Model[ModelIndex], Model[ModelIndex] shr Move); Result := 1; end; while Range < $1000000 do begin if Position < aInSize then Code := (Code shl 8) or PCCUInt8Array(aInData)^[Position] else begin if Position < (aInSize + 4 + 5) then Code := Code shl 8 else begin OK := False; Break; end; end; inc(Position); Range := Range shl 8; end; end; function DecodeTree(ModelIndex, MaxValue, Move: TCCInt32): TCCInt32; begin Result := 1; while OK and (Result < MaxValue) do Result := (Result shl 1) or DecodeBit(ModelIndex + Result, Move); dec(Result, MaxValue); end; var DestLen, Value: TCCInt32; begin Result := 0; if aInSize >= 3 then begin OK := True; Code := (PCCUInt8Array(aInData)^[0] shl 24) or (PCCUInt8Array(aInData)^[1] shl 16) or (PCCUInt8Array(aInData)^[2] shl 8) or (PCCUInt8Array(aInData)^[3] shl 0); Position := 4; Range := $FFFFFFFF; for Value := 0 to SizeModels - 1 do begin Model[Value] := 2048; end; DestLen := 0; repeat Value := DecodeBit(FlagModel, 1); if OK then begin if Value <> 0 then begin Value := DecodeTree(LiteralModel, 256, 4); if OK and (TCCSizeUInt(DestLen) < TCCSizeUInt(aOutLimit)) then begin PCCUInt8Array(aOutData)^[DestLen] := Value; inc(DestLen); end else Exit; end else Break; end else Exit; until False; Result := DestLen; end; end; {$IFDEF RangeCheck}{$R+}{$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.Core.Sources.Manager; interface uses DPM.Core.Logging, DPM.Core.Options.Sources, DPM.Core.Sources.Interfaces, DPM.Core.Configuration.Interfaces; type TSourcesManager = class(TInterfacedObject, ISourcesManager) private FLogger : ILogger; FConfigManager : IConfigurationManager; protected function AddSource(const options : TSourcesOptions) : Boolean; function DisableSource(const options : TSourcesOptions) : Boolean; function EnableSource(const options : TSourcesOptions) : Boolean; function ListSources(const options : TSourcesOptions) : Boolean; function RemoveSource(const options : TSourcesOptions) : Boolean; function UpdateSource(const options : TSourcesOptions) : Boolean; public constructor Create(const logger : ILogger; const configManager : IConfigurationManager); reintroduce; end; implementation uses System.SysUtils, DPM.Core.Utils.System, DPM.Core.Sources.Types, DPM.Core.Constants, DPM.Core.Configuration.Classes; { TSourcesManager } function TSourcesManager.AddSource(const options : TSourcesOptions) : Boolean; var config : IConfiguration; source : ISourceConfig; begin result := false; if options.ConfigFile = '' then begin FLogger.Error('No configuration file specified'); exit; end; config := FConfigManager.LoadConfig(options.ConfigFile); if config = nil then exit; if options.Name = '' then begin FLogger.Error('Required parameter [name] is blank.'); exit; end; if options.Source = '' then begin FLogger.Error('Required parameter [source] is blank.'); exit; end; if config.Sources.Any(function(const item : ISourceConfig) : boolean begin result := SameText(item.Name, options.Name); end) then begin FLogger.Error('Source with name [' + options.Name + '] already exists'); exit; end; source := TSourceConfig.Create(FLogger); source.Name := options.Name; source.Source := options.Source; source.UserName := options.UserName; source.Password := options.Password; source.IsEnabled := true; config.Sources.Add(source); result := FConfigManager.SaveConfig(config); FLogger.Information('Source [' + source.Name + '] added.'); end; constructor TSourcesManager.Create(const logger : ILogger; const configManager : IConfigurationManager); begin FLogger := logger; FConfigManager := configManager; end; function TSourcesManager.DisableSource(const options : TSourcesOptions) : Boolean; var config : IConfiguration; source : ISourceConfig; begin result := false; if options.ConfigFile = '' then begin FLogger.Error('No configuration file specified'); exit; end; config := FConfigManager.LoadConfig(options.ConfigFile); if config = nil then exit; if options.Name = '' then begin FLogger.Error('Required parameter [name] is blank.'); exit; end; source := config.Sources.FirstOrDefault(function(const item : ISourceConfig) : boolean begin result := SameText(item.Name, options.Name); end); if source = nil then begin FLogger.Error('Source with name [' + options.Name + '] not found.'); exit; end; source.IsEnabled := false; result := FConfigManager.SaveConfig(config); if result then FLogger.Information('Disabled Source [' + options.Name + '].', false); end; function TSourcesManager.EnableSource(const options : TSourcesOptions) : Boolean; var config : IConfiguration; source : ISourceConfig; begin result := false; if options.ConfigFile = '' then begin FLogger.Error('No configuration file specified'); exit; end; config := FConfigManager.LoadConfig(options.ConfigFile); if config = nil then exit; if options.Name = '' then begin FLogger.Error('Required parameter [name] is blank.'); exit; end; source := config.Sources.FirstOrDefault(function(const item : ISourceConfig) : boolean begin result := SameText(item.Name, options.Name); end); if source = nil then begin FLogger.Error('Source with name [' + options.Name + '] not found.'); exit; end; source.IsEnabled := true; result := FConfigManager.SaveConfig(config); if result then FLogger.Information('Enabled Source [' + options.Name + '].', false); end; function TSourcesManager.ListSources(const options : TSourcesOptions) : Boolean; var config : IConfiguration; i : integer; function EnabledToString(const enabled : boolean) : string; begin if enabled then result := 'Enabled' else result := 'Disabled'; end; function EnabledToChar(const enabled : boolean) : string; begin if enabled then result := 'E' else result := 'D'; end; begin result := false; if options.ConfigFile = '' then begin FLogger.Error('No configuration file specified'); exit; end; config := FConfigManager.LoadConfig(options.ConfigFile); if config = nil then exit; if options.Format = TSourcesFormat.Short then begin for i := 0 to config.Sources.Count - 1 do FLogger.Information(Format('%s %s', [EnabledToChar(config.Sources[i].IsEnabled), config.Sources[i].Source])); end else begin FLogger.Information('Registered Sources:'); FLogger.Information('', false); for i := 0 to config.Sources.Count - 1 do begin FLogger.Information(Format(' %d. %s [%s]', [i + 1, config.Sources[i].Name, EnabledToString(config.Sources[i].IsEnabled)])); FLogger.Information(Format(' %s', [config.Sources[i].Source]), false); end; end; result := true; end; function TSourcesManager.RemoveSource(const options : TSourcesOptions) : Boolean; var config : IConfiguration; source : ISourceConfig; begin result := false; if options.ConfigFile = '' then begin FLogger.Error('No configuration file specified'); exit; end; config := FConfigManager.LoadConfig(options.ConfigFile); if config = nil then exit; if options.Name = '' then begin FLogger.Error('Required parameter [name] is blank.'); exit; end; source := config.Sources.FirstOrDefault(function(const item : ISourceConfig) : boolean begin result := SameText(item.Name, options.Name); end); if source = nil then begin FLogger.Error('Source with name [' + options.Name + '] not found.'); exit; end; config.Sources.Remove(source); result := FConfigManager.SaveConfig(config); if result then FLogger.Information('Source [' + options.Name + '] removed.', false); end; function TSourcesManager.UpdateSource(const options : TSourcesOptions) : Boolean; var config : IConfiguration; source : ISourceConfig; begin result := false; if options.ConfigFile = '' then begin FLogger.Error('No configuration file specified'); exit; end; config := FConfigManager.LoadConfig(options.ConfigFile); if config = nil then exit; if options.Name = '' then begin FLogger.Error('Required parameter [name] is blank.'); exit; end; source := config.Sources.FirstOrDefault(function(const item : ISourceConfig) : boolean begin result := SameText(item.Name, options.Name); end); if source = nil then begin FLogger.Error('Source with name [' + options.Name + '] not found.'); exit; end; source.Name := options.Name; source.Source := options.Source; source.UserName := options.UserName; source.Password := options.Password; result := FConfigManager.SaveConfig(config); if result then FLogger.Information('Source [' + options.Name + '] updated.', false); end; end.
// // Generated by JavaToPas v1.5 20150830 - 103222 //////////////////////////////////////////////////////////////////////////////// unit java.io.InputStreamReader; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, java.nio.charset.Charset; type JInputStreamReader = interface; JInputStreamReaderClass = interface(JObjectClass) ['{027A938A-43B8-4755-AE55-6B26DA46F078}'] function &read : Integer; cdecl; overload; // ()I A: $1 function &read(buffer : TJavaArray<Char>; offset : Integer; count : Integer) : Integer; cdecl; overload;// ([CII)I A: $1 function getEncoding : JString; cdecl; // ()Ljava/lang/String; A: $1 function init(&in : JInputStream) : JInputStreamReader; cdecl; overload; // (Ljava/io/InputStream;)V A: $1 function init(&in : JInputStream; charset : JCharset) : JInputStreamReader; cdecl; overload;// (Ljava/io/InputStream;Ljava/nio/charset/Charset;)V A: $1 function init(&in : JInputStream; charsetName : JString) : JInputStreamReader; cdecl; overload;// (Ljava/io/InputStream;Ljava/lang/String;)V A: $1 function init(&in : JInputStream; dec : JCharsetDecoder) : JInputStreamReader; cdecl; overload;// (Ljava/io/InputStream;Ljava/nio/charset/CharsetDecoder;)V A: $1 function ready : boolean; cdecl; // ()Z A: $1 procedure close ; cdecl; // ()V A: $1 end; [JavaSignature('java/io/InputStreamReader')] JInputStreamReader = interface(JObject) ['{2B8673FC-3539-4C21-8E04-683B3FFF8173}'] function &read : Integer; cdecl; overload; // ()I A: $1 function &read(buffer : TJavaArray<Char>; offset : Integer; count : Integer) : Integer; cdecl; overload;// ([CII)I A: $1 function getEncoding : JString; cdecl; // ()Ljava/lang/String; A: $1 function ready : boolean; cdecl; // ()Z A: $1 procedure close ; cdecl; // ()V A: $1 end; TJInputStreamReader = class(TJavaGenericImport<JInputStreamReaderClass, JInputStreamReader>) end; implementation end.
unit Dmitry.Controls.Base; interface uses System.Types, System.Classes, Winapi.Windows, Winapi.Messages, Winapi.Dwmapi, Vcl.Graphics, Vcl.Controls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.Forms, Vcl.Themes; type TBaseWinControl = class(TWinControl) private FDisableStyles: Boolean; function GetIsStyleEnabled: Boolean; protected function DrawElement(DC: HDC): Boolean; virtual; procedure WMPrintClient(var Message: TWMPrintClient); message WM_PRINTCLIENT; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; property IsStyleEnabled: Boolean read GetIsStyleEnabled; public { Public declarations } constructor Create(AOwner: TComponent); override; procedure DrawBackground(Canvas: TCanvas); published property DisableStyles: Boolean read FDisableStyles write FDisableStyles default False; end; implementation uses Dmitry.Controls.WebLinkList; type TParentControl = class(TWinControl); { This procedure is copied from RxLibrary VCLUtils } procedure CopyParentImage(Control: TControl; Dest: TCanvas); var I, Count, X, Y, SaveIndex: Integer; DC: HDC; R, SelfR, CtlR: TRect; begin if (Control = nil) OR (Control.Parent = nil) then Exit; Count := Control.Parent.ControlCount; DC := Dest.Handle; with Control.Parent DO ControlState := ControlState + [csPaintCopy]; TRY with Control do begin SelfR := Bounds(Left, Top, Width, Height); X := -Left; Y := -Top; end; { Copy parent control image } SaveIndex := SaveDC(DC); TRY SetViewportOrgEx(DC, X, Y, nil); IntersectClipRect(DC, 0, 0, Control.Parent.ClientWidth, Control.Parent.ClientHeight); with TParentControl(Control.Parent) do begin Perform(WM_ERASEBKGND, WParam(DC), 0); PaintWindow(DC); end; FINALLY RestoreDC(DC, SaveIndex); END; { Copy images of graphic controls } for I := 0 to Count - 1 do begin if Control.Parent.Controls[I] = Control then Break else if (Control.Parent.Controls[I] <> nil) and (Control.Parent.Controls[I] is TGraphicControl) then begin with TGraphicControl(Control.Parent.Controls[I]) do begin CtlR := Bounds(Left, Top, Width, Height); if Bool(IntersectRect(R, SelfR, CtlR)) and Visible then begin ControlState := ControlState + [csPaintCopy]; SaveIndex := SaveDC(DC); try SetViewportOrgEx(DC, Left + X, Top + Y, nil); IntersectClipRect(DC, 0, 0, Width, Height); {$R-} Perform(WM_PAINT, WParam(DC), 0); {$R+} finally RestoreDC(DC, SaveIndex); ControlState := ControlState - [csPaintCopy]; end; end; end; end; end; FINALLY with Control.Parent DO ControlState := ControlState - [csPaintCopy]; end; end; { TBaseWinControl } constructor TBaseWinControl.Create(AOwner: TComponent); begin FDisableStyles := False; inherited; end; procedure TBaseWinControl.DrawBackground(Canvas: TCanvas); begin if IsStyleEnabled then begin //for forms don't use draw parent background //when form is starting - it causing filling it with white color on short time if Parent is TForm then begin Canvas.Brush.Color := StyleServices.GetSystemColor(clBtnFace); Canvas.Pen.Color := StyleServices.GetSystemColor(clBtnFace); Canvas.Rectangle(0, 0, Width, Height); end else if (Parent <> nil) and Parent.HandleAllocated then begin if Parent is TWebLinkList then begin StyleServices.DrawParentBackground(Handle, Canvas.Handle, nil, False); end else begin SetBkMode(Canvas.Handle, TRANSPARENT); StyleServices.DrawParentBackground(Handle, Canvas.Handle, nil, False); end; end; end else begin if (csParentBackground in ControlStyle) and ((Parent is TTabSheet) or (Parent is TWebLinkList) or (Parent is TGroupBox)) then CopyParentImage(Self, Canvas) else begin Canvas.Brush.Color := Color; Canvas.Pen.Color := Color; Canvas.Rectangle(0, 0, Width, Height); end; end; end; function TBaseWinControl.DrawElement(DC: HDC): Boolean; begin Result := False; end; function TBaseWinControl.GetIsStyleEnabled: Boolean; begin Result := StyleServices.Enabled and TStyleManager.IsCustomStyleActive and not FDisableStyles; end; procedure TBaseWinControl.WMPaint(var Message: TWMPaint); var DC: HDC; PS: TPaintStruct; begin if DwmCompositionEnabled and Parent.DoubleBuffered then inherited else begin DC := BeginPaint(Handle, PS); try if not DrawElement(DC) then inherited finally EndPaint(Handle, PS); end; end; end; procedure TBaseWinControl.WMPrintClient(var Message: TWMPrintClient); begin inherited; DrawElement(Message.DC); end; end.
unit uPedidoIt; interface type TPedidoIt = class strict private FPRECO_UNIT: double; FNUM_PEDIDO: integer; FPRODUTO: string; FQTD: double; procedure SetPRECOUNIT(val: double); function GetPRECOUNIT: double; procedure SetNUMPEDIDO(val: integer); function GetNUMPEDIDO: integer; procedure SetPRODUTO(val: String); function GetPRODUTO: String; procedure SetQTD(val: double); function GetQTD: double; public property PRECOUNIT: double read FPRECO_UNIT write FPRECO_UNIT; property NUMPEDIDO: integer read FNUM_PEDIDO write FNUM_PEDIDO; property PRODUTO: string read FPRODUTO write FPRODUTO; property QTD: double read FQTD write FQTD; constructor Create; destructor Destroy; override; end; implementation { TPedidoIt } constructor TPedidoIt.Create; begin inherited Create; end; destructor TPedidoIt.Destroy; begin inherited Destroy; end; function TPedidoIt.GetNUMPEDIDO: integer; begin Result := FNUM_PEDIDO; end; function TPedidoIt.GetPRECOUNIT: double; begin Result := FPRECO_UNIT; end; function TPedidoIt.GetPRODUTO: String; begin Result := FPRODUTO; end; function TPedidoIt.GetQTD: double; begin Result := FQTD; end; procedure TPedidoIt.SetNUMPEDIDO(val: integer); begin FNUM_PEDIDO := val; end; procedure TPedidoIt.SetPRECOUNIT(val: double); begin FPRECO_UNIT := val; end; procedure TPedidoIt.SetPRODUTO(val: String); begin FPRODUTO := val; end; procedure TPedidoIt.SetQTD(val: double); begin FQTD := val; end; end.
unit ModFace; interface uses Classes,SPComm,Windows,SysUtils,StrUtils; const //* CRC 高位字节值表 */ CRCTableHi:array[0..255] of DWORD = ( $00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40, $01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41, $01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41, $00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40, $01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41, $00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40, $00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40, $01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41, $01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41, $00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40, $00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40, $01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41, $00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40, $01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41, $01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41, $00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40 ); //* CRC低位字节值表*/ CRCTableLo:array[0..255] of DWORD = ( $00, $C0, $C1, $01,$C3, $03, $02, $C2,$C6, $06, $07, $C7,$05, $C5, $C4, $04, $CC, $0C, $0D, $CD,$0F, $CF, $CE, $0E,$0A, $CA, $CB, $0B,$C9, $09, $08, $C8, $D8, $18, $19, $D9,$1B, $DB, $DA, $1A,$1E, $DE, $DF, $1F,$DD, $1D, $1C, $DC, $14, $D4, $D5, $15,$D7, $17, $16, $D6,$D2, $12, $13, $D3,$11, $D1, $D0, $10, $F0, $30, $31, $F1,$33, $F3, $F2, $32,$36, $F6, $F7, $37,$F5, $35, $34, $F4, $3C, $FC, $FD, $3D,$FF, $3F, $3E, $FE,$FA, $3A, $3B, $FB,$39, $F9, $F8, $38, $28, $E8, $E9, $29,$EB, $2B, $2A, $EA,$EE, $2E, $2F, $EF,$2D, $ED, $EC, $2C, $E4, $24, $25, $E5,$27, $E7, $E6, $26,$22, $E2, $E3, $23,$E1, $21, $20, $E0, $A0, $60, $61, $A1,$63, $A3, $A2, $62,$66, $A6, $A7, $67,$A5, $65, $64, $A4, $6C, $AC, $AD, $6D,$AF, $6F, $6E, $AE,$AA, $6A, $6B, $AB,$69, $A9, $A8, $68, $78, $B8, $B9, $79,$BB, $7B, $7A, $BA,$BE, $7E, $7F, $BF,$7D, $BD, $BC, $7C, $B4, $74, $75, $B5,$77, $B7, $B6, $76,$72, $B2, $B3, $73,$B1, $71, $70, $B0, $50, $90, $91, $51,$93, $53, $52, $92,$96, $56, $57, $97,$55, $95, $94, $54, $9C, $5C, $5D, $9D,$5F, $9F, $9E, $5E,$5A, $9A, $9B, $5B,$99, $59, $58, $98, $88, $48, $49, $89,$4B, $8B, $8A, $4A,$4E, $8E, $8F, $4F,$8D, $4D, $4C, $8C, $44, $84, $85, $45,$87, $47, $46, $86,$82, $42, $43, $83,$41, $81, $80, $40 ); type // TParity = ( None, Odd, Even, Mark, Space ); // TStopBits = ( _1, _1_5, _2 ); // TByteSize = ( _5, _6, _7, _8 ); TModCallBack = procedure(Comm:string;MacAddress,Address,Value:Integer);stdcall; TModBus = class(TTHread) private Address : array of array of Byte; Values : array of array of Byte; Commands : array of array of Byte; SpComm : TComm; IsWaiting : Boolean; //等待回应标记,暂无等待超时 ActiveIndex: Integer; //活动下标 MyMacAddress : Integer; //从机地址 CommName : string; FCallback: Pointer; WaitTimes : Integer; //等待次数上限,超时时间为ReadTime*WaitTimes ReadTime : Integer; // 读取间隔 HasWaitTimes:Integer; //等待次数累计 procedure CustomReceiveData(Sender: TObject; Buffer: Pointer; BufferLength: Word); function ModBusCRC16(Data: string;var CRC16Hi,CRC16Lo:DWORD): string; procedure ModCrc(Command:array of Byte;var CRC16Hi,CRC16Lo:DWORD); protected procedure getData; procedure Execute;override; public //初始化 串口名、波特、奇偶检验、数据位、停止位、起始地址、结束地址、从机地址 function Init(Comm:string;BaudRate,Parity,ByteSize,StopBits,BeginAddress,EndAddress,MacAddress,PReadTime,PWaitTimes:Integer):Boolean; procedure Start; procedure Stop; procedure SetCallBack(CallBack: Pointer); function CloseComm:Boolean; end; TModBuses = class(TPersistent) private function GetItems(Key: string): TModBus; function GetCount: Integer; public Keys: TStrings; Values: array of TModBus; property Items[Key: string]: TModBus read GetItems; default; property Count: Integer read GetCount; function Add(Key: string; Value: TModBus): Integer; procedure clear; function Remove(Key: string): Integer; constructor Create; overload; end; implementation function TModBus.Init(Comm:string;BaudRate,Parity,ByteSize,StopBits,BeginAddress,EndAddress,MacAddress,PReadTime,PWaitTimes:Integer):Boolean; var I,Index,Count:Integer; CRC16Hi,CRC16Lo:DWORD; begin SpComm := TComm.Create(nil); SpComm.CommName := Comm; SpComm.BaudRate := BaudRate; SpComm.Parity := TParity(Parity); SpComm.ByteSize := TByteSize(ByteSize); SpComm.StopBits := TStopBits(StopBits); SpComm.OnReceiveData := CustomReceiveData; try SpComm.StartComm; Result := True; except Result := False; Exit; end; CommName := Comm; MyMacAddress := MacAddress; Index := 0; Count := 0; SetLength(Address,1); SetLength(Commands,1); SetLength(Values,1); SetLength(Commands[0],8); Commands[0][0] := MacAddress; Commands[0][1] := $03; Commands[0][2] := $00; Commands[0][3] := BeginAddress - 1; Commands[0][4] := $00; for I := BeginAddress to EndAddress do begin if Length(Address[Index]) = 100 then begin Commands[Index][5] := 100; ModCrc(Commands[Index],CRC16Lo,CRC16Hi); Commands[Index][6] := CRC16Lo; Commands[Index][7] := CRC16Hi; Inc(Index); SetLength(Address,Index+1); SetLength(Values,Index+1); SetLength(Commands,Index+1); SetLength(Commands[Index],8); Commands[Index][0] := MacAddress; Commands[Index][1] := $03; Commands[Index][2] := $00; Commands[Index][3] := I - 1; Commands[Index][4] := $00; Count := 0; end; Inc(Count); SetLength(Address[Index],Length(Address[Index]) + 1); SetLength(Values[Index],Length(Values[Index]) + 1); Address[Index][Length(Address[Index]) - 1] := I; end; if Commands[Index][5] = $00 then begin Commands[Index][5] := Count; ModCrc(Commands[Index],CRC16Lo,CRC16Hi); Commands[Index][6] := CRC16Lo; Commands[Index][7] := CRC16Hi; end; IsWaiting := False; ActiveIndex := 0; ReadTime := PReadTime; WaitTimes := PWaitTimes; HasWaitTimes := 0; end; procedure TModBus.Start; begin if Suspended then Resume; end; procedure TModBus.Stop; begin if not Suspended then Suspend; end; procedure TModBus.Execute; begin while not Terminated do begin getData; sleep(ReadTime); end; end; procedure TModBus.getData; begin if not IsWaiting then begin if ActiveIndex >= Length(Address) then ActiveIndex := 0; HasWaitTimes := 0; IsWaiting := True; SpComm.WriteCommData(PChar(Commands[ActiveIndex]),8); end else begin Inc(HasWaitTimes); if HasWaitTimes > WaitTimes then begin Inc(ActiveIndex); IsWaiting := False; end; end; end; function TModBus.ModBusCRC16(Data:String;var CRC16Hi,CRC16Lo:DWORD) : string; var uIndex:Integer; Data1:String; begin CRC16Lo := $FF; //CRC16Lo为CRC寄存器低8位 CRC16Hi := $FF; //CRC16Hi为CRC寄存器高8位 Data1:=Trim(Data); while Length(Data1)>0 do begin uIndex := CRC16Hi xor (StrToInt('$'+(Data1[1])+(Data1[2]))); CRC16Hi := CRC16Lo xor CRCTableHi[uIndex]; CRC16Lo := CRCTableLo[uIndex]; Data1:=Trim(MidStr(Data1,3,Length(Data1))); end; Result := IntToHex(CRC16Hi,2) + IntToHex(CRC16Lo,2); end; procedure TModBus.ModCrc(Command:array of Byte;var CRC16Hi,CRC16Lo:DWORD); var I:Integer; Str:string; begin Str := ''; for I := 0 to 5 do begin Str := Str + ' ' + IntToHex(Command[I],2); end; ModBusCRC16(Str,CRC16Hi,CRC16Lo); end; procedure TModBus.CustomReceiveData(Sender: TObject; Buffer: Pointer; BufferLength: Word); var BufferArr : array of Byte; I,Index :Integer; begin if BufferLength < 5 then begin Inc(ActiveIndex); IsWaiting := False; Exit; end; SetLength(BufferArr, BufferLength); Move(buffer^, PChar(@BufferArr[0])^, BufferLength); if (BufferArr[0] <> MyMacAddress) or (BufferArr[1] <> $03) then begin Inc(ActiveIndex); IsWaiting := False; Exit; end; if BufferArr[2] / 2 <> Length(Address[ActiveIndex]) then begin Inc(ActiveIndex); IsWaiting := False; Exit; end; Index := 0; for I := 4 to BufferLength - 3 do begin if I mod 2 = 0 then begin if BufferArr[I] <> Values[ActiveIndex][Index] then begin Values[ActiveIndex][Index] := BufferArr[I]; if FCallback <> nil then begin try TModCallBack(FCallback)(CommName, MyMacAddress,Address[ActiveIndex][Index] , BufferArr[I]); except end; end; end; Inc(Index); end; end; Inc(ActiveIndex); IsWaiting := False; end; procedure TModBus.SetCallBack(CallBack: Pointer); begin FCallback := CallBack; end; function TModBus.CloseComm:Boolean; begin try SpComm.StopComm; SpComm.Free; SpComm := nil; Result := False; except Result := True; end; end; constructor TModBuses.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TModBuses.clear; begin SetLength(Values, 0); Keys.Clear; end; function TModBuses.GetItems(Key: string): TModBus; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := nil; end; function TModBuses.Add(Key: string; Value: TModBus): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TModBuses.GetCount: Integer; begin Result := Keys.Count; end; function TModBuses.Remove(Key: string): Integer; var Index : Integer; Count : Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; end.
unit VOpDivRecType03Form; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, VCustomRecordForm, ToolEdit, CurrEdit, StdCtrls, Mask, ExtCtrls, COpDivSystemRecord, COpDivRecType03, Menus, Buttons; type TOpDivRecType03Form = class(TCustomRecordForm) Label1: TLabel; IndicadorSubsistemaEdit: TMaskEdit; Label2: TLabel; RefInicialLabel: TLabel; RefInicialEdit: TMaskEdit; refAdeudoLabel: TLabel; refAdeudoEdit: TEdit; NifSufijoLabel: TLabel; nifOrdenanteEdit: TEdit; numChequeLabel: TLabel; numChequeEdit: TMaskEdit; Label7: TLabel; fechaIntercambioEdit: TDateEdit; Label8: TLabel; conceptoOperacionEdit: TMaskEdit; Label9: TLabel; ConceptoComplementaLabel: TLabel; conceptoComplementarioEdit: TEdit; NominalInicialLabel: TLabel; nominaInicialEdit: TRxCalcEdit; ComisionesDevolucionEdit: TRxCalcEdit; ComisionesDevolucionLabel: TLabel; ComisionesReclamacionLabel: TLabel; ComisionesReclamacionEdit: TRxCalcEdit; Sumar2ImporteOpButton: TButton; procedure IndicadorSubsistemaEditExit(Sender: TObject); procedure RefInicialEditExit(Sender: TObject); procedure refAdeudoEditExit(Sender: TObject); procedure nifOrdenanteEditExit(Sender: TObject); procedure numChequeEditExit(Sender: TObject); procedure fechaIntercambioEditExit(Sender: TObject); procedure conceptoOperacionEditExit(Sender: TObject); procedure conceptoComplementarioEditExit(Sender: TObject); procedure nominaInicialEditExit(Sender: TObject); procedure ComisionesDevolucionEditExit(Sender: TObject); procedure ComisionesReclamacionEditExit(Sender: TObject); procedure Sumar2ImporteOpButtonClick(Sender: TObject); procedure IndicadorSubsistemaEditChange(Sender: TObject); private { Private declarations } protected procedure onGeneralChange( SystemRecord: TOpDivSystemRecord ); override; procedure setErrorControlPos(const FieldWithError: String); override; public { Public declarations } end; var OpDivRecType03Form: TOpDivRecType03Form; implementation {$R *.DFM} (** MÉTODOS PROTEGIDOS **) procedure TOpDivRecType03Form.onGeneralChange( SystemRecord: TOpDivSystemRecord ); begin inherited; with TOpDivRecType03( SystemRecord ) do begin IndicadorSubsistemaEdit.Text := IndicadorSubsistema; RefInicialEdit.Text := RefInicial; RefAdeudoEdit.Text := CodOrdenante; nifOrdenanteEdit.Text := NifSufOrdenante; numChequeEdit.Text := NumCheque; if FechaInterInicial < strToDate( '01/01/2001' ) then fechaIntercambioEdit.Text := EmptyStr else fechaIntercambioEdit.Date := FechaInterInicial; ConceptoOperacionEdit.Text := ConceptoOp; conceptoComplementarioEdit.Text := ConceptoComplementa; nominaInicialEdit.Value := NominalInicial; ComisionesDevolucionEdit.Value := ComisionInicial; ComisionesReclamacionEdit.Value := ComisionReclamacion; // se activan/desactivan ciertas entradas dependiendo de los datos RefInicialLabel.Enabled := (IndicadorSubsistema <> '5'); RefInicialEdit.Enabled := (IndicadorSubsistema <> '5'); NifSufijoLabel.Enabled := (IndicadorSubsistema = '5'); NifOrdenanteEdit.Enabled := (IndicadorSubsistema = '5'); RefAdeudoLabel.Enabled := (IndicadorSubsistema = '5'); RefAdeudoEdit.Enabled := (IndicadorSubsistema = '5'); numChequeLabel.Enabled := (IndicadorSubsistema = '4') or (IndicadorSubsistema = '6') or (IndicadorSubsistema = '7') or (IndicadorSubsistema = '8'); numChequeEdit.Enabled := (IndicadorSubsistema = '4') or (IndicadorSubsistema = '6') or (IndicadorSubsistema = '7') or (IndicadorSubsistema = '8'); if (IndicadorSubsistema = '5') then ConceptoComplementaLabel.Caption := 'Nombre del obligado:' else ConceptoComplementaLabel.Caption := 'Concepto complementario:'; ClaveAutorizaLabel.Enabled := (ConceptoOp = '4') or ((ConceptoOp = '3') and (IndicadorSubsistema = '8')); claveAutorizaEdit.Enabled := (ConceptoOp = '4') or ((ConceptoOp = '3') and (IndicadorSubsistema = '8')); // nominaInicialEdit.Enabled := (ConceptoOp = '1') or (ConceptoOp = '4'); // nominalInicialLabel.Enabled := (ConceptoOp = '1') or (ConceptoOp = '4'); ComisionesDevolucionLabel.Enabled := (ConceptoOp = '1') or (ConceptoOp = '4'); ComisionesDevolucionEdit.Enabled := (ConceptoOp = '1') or (ConceptoOp = '4'); ComisionesReclamacionLabel.Enabled := (ConceptoOp = '4'); ComisionesReclamacionEdit.Enabled := (ConceptoOp = '4'); end; end; procedure TOpDivRecType03Form.setErrorControlPos(const FieldWithError: String); begin inherited setErrorControlPos(FieldWithError); if FieldWithError <> k_GenericFieldError then begin if FieldWithError = k03_IndicadorSubsistemaItem then IndicadorSubsistemaEdit.SetFocus() else if FieldWithError = k03_RefInicialItem then RefInicialEdit.SetFocus() else if FieldWithError = k03_CodOrdenanteItem then refAdeudoEdit.SetFocus() else if FieldWithError = k03_NifSufOrdenanteItem then nifOrdenanteEdit.SetFocus() else if FieldWithError = k03_NumChequeItem then numChequeEdit.SetFocus() else if FieldWithError = k03_FechaInterInicialItem then fechaIntercambioEdit.SetFocus() else if FieldWithError = k03_ConceptoOpItem then conceptoOperacionEdit.SetFocus() else if FieldWithError = k03_ConceptoComplementaItem then conceptoComplementarioEdit.SetFocus() else if FieldWithError = k03_NominalInicialItem then nominaInicialEdit.SetFocus() else if FieldWithError = k03_ComisionInicialItem then ComisionesDevolucionEdit.SetFocus() else if FieldWithError = k03_ComisionReclamacionItem then ComisionesReclamacionEdit.SetFocus() end; end; (**** EVENTOS ****) procedure TOpDivRecType03Form.IndicadorSubsistemaEditExit(Sender: TObject); begin inherited; TOpDivRecType03( FSystemRecord ).IndicadorSubsistema := TEdit( Sender ).Text; end; procedure TOpDivRecType03Form.RefInicialEditExit(Sender: TObject); begin inherited; TOpDivRecType03( FSystemRecord ).RefInicial := TEdit( Sender ).Text; end; procedure TOpDivRecType03Form.refAdeudoEditExit(Sender: TObject); begin inherited; TOpDivRecType03( FSystemRecord ).CodOrdenante := TEdit( Sender ).Text; end; procedure TOpDivRecType03Form.nifOrdenanteEditExit(Sender: TObject); begin inherited; TOpDivRecType03( FSystemRecord ).NifSufOrdenante := TEdit( Sender ).Text ; end; procedure TOpDivRecType03Form.numChequeEditExit(Sender: TObject); begin inherited; TOpDivRecType03( FSystemRecord ).NumCheque := TEdit( Sender ).Text; end; procedure TOpDivRecType03Form.fechaIntercambioEditExit(Sender: TObject); begin inherited; TOpDivRecType03( FSystemRecord).FechaInterInicial := TDateEdit( Sender ).Date; end; procedure TOpDivRecType03Form.conceptoOperacionEditExit(Sender: TObject); begin inherited; TOpDivRecType03( FSystemRecord ).ConceptoOp := TEdit( Sender ).Text; end; procedure TOpDivRecType03Form.conceptoComplementarioEditExit( Sender: TObject); begin inherited; TOpDivRecType03( FSystemRecord).ConceptoComplementa := TEdit( Sender ).Text; end; procedure TOpDivRecType03Form.nominaInicialEditExit(Sender: TObject); begin inherited; TOpDivRecType03( FSystemRecord).NominalInicial := TRxCalcEdit( Sender ).Value; end; procedure TOpDivRecType03Form.ComisionesDevolucionEditExit( Sender: TObject); begin inherited; TOpDivRecType03( FSystemRecord ).ComisionInicial := TRxCalcEdit( Sender ).Value; end; procedure TOpDivRecType03Form.ComisionesReclamacionEditExit( Sender: TObject); begin inherited; TOpDivRecType03( FSystemRecord ).ComisionReclamacion := TRxCalcEdit( Sender ).Value; end; procedure TOpDivRecType03Form.Sumar2ImporteOpButtonClick(Sender: TObject); begin inherited; // lo que hacemos es poner como importe principal de la operación la suma de las comisiones... with TOpDivRecType03(FSystemRecord) do begin ImportePrinOp := NominalInicial + ComisionInicial + ComisionReclamacion; if DivisaOperacion = kDivisaPta then ImporteOrigOp := Round(ImportePrinOp * 166.386); end end; procedure TOpDivRecType03Form.IndicadorSubsistemaEditChange( Sender: TObject); begin inherited; if Trim(TEdit(Sender).Text) <> EmptyStr then TOpDivRecType03( FSystemRecord ).IndicadorSubsistema := TEdit( Sender ).Text; end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmDiff Purpose : This is used to do a textfile difference. Date : 12-29-2000 Author : Ryan J. Mills Version : 1.92 Notes : The original engine code came from the diff.c file found on the ftp.cdrom.com site. The original source can be found here: ftp://ftp.cdrom.com/pub/algorithims/c/diff.c The DiffMap code originally came from Bernie Caudry and Guy LeMar. I've only modified the original DiffMap source to work with my rmDiff components. I would like to go back and rewrite the drawing and mapping algorithms because I think they are unnecessarily complex. It also doesn't use any resources where it should. ================================================================================} unit rmDiff; interface {$I CompilerDefines.INC} uses windows, Messages, controls, classes, stdctrls, Grids, extctrls, sysutils, Graphics, rmListControl; type EDiffException = Exception; TrmDiffBlock = record startLine: integer; EndLine: integer; end; TrmDiffObject = class(TObject) private fSource1, fSource2: TrmDiffBlock; public property Source1: TrmDiffBlock read fSource1 write fSource1; property Source2: TrmDiffBlock read fSource2 write fSource2; end; TrmDiffOption = (fdoCaseSensitive, fdoIgnoreCharacters, fdoIgnoreTrailingWhiteSpace, fdoIgnoreLeadingWhiteSpace); TrmDiffOptions = set of TrmDiffOption; TrmDiffProgressEvent = procedure(PercentComplete: integer) of object; TrmDiffMapClickEvent = procedure(Sender: TObject; IndicatorPos: integer) of object; TrmCustomDiffViewer = class; TrmDiffMap = class; TrmCharacterSet = set of char; TrmCustomDiffEngine = class(TComponent) private { Private } fSource1, fSource2: TStringList; fDiffSource1, fDiffSource2 : TStringList; fAttachedViewers : TList; fSource1Count, fSource2Count: integer; fBlankLines1, fBlankLines2: integer; fOptions: TrmDiffOptions; fOnDiffCompleted: TNotifyEvent; fOnProgress: TrmDiffProgressEvent; fMatchDepth: integer; fIgnoreChars: TrmCharacterSet; fMultiLineCommentOpen, fStringOpen: boolean; function AtEOF: boolean; procedure MoveDown(Amount1, Amount2: integer); procedure CompareData; procedure StartCompare; procedure SetMatchDepth(const Value: integer); procedure ClearData; function RemoveCharacters(st:string):string; protected { protected } function MatchLines(level1, level2, MatchDepth: integer): boolean; virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure DiffStarted; virtual; procedure DiffFound(Source1, Source2: TrmDiffBlock); virtual; procedure DiffCompleted; virtual; procedure AttachViewer(viewer:TrmCustomDiffViewer); procedure RemoveViewer(viewer:TrmCustomDiffViewer); property MatchDepth: integer read fMatchDepth write SetMatchDepth default 3; property DiffOptions: TrmDiffOptions read fOptions write fOptions; property OnDiffCompleted: TNotifyEvent read fOnDiffCompleted write fOnDiffCompleted; property OnDiffProgress: TrmDiffProgressEvent read fOnProgress write fOnProgress; property DiffSource1 : TStringList read fDiffSource1; property DiffSource2 : TStringList read fDiffSource2; property IgnoreCharacters : TrmCharacterSet read fIgnoreChars write fIgnoreChars; public { Public } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CompareFiles(file1, file2: string); procedure CompareStreams(Strm1, Strm2: TStream); end; TrmDiffEngine = class(TrmCustomDiffEngine) public property DiffSource1; property DiffSource2; property IgnoreCharacters; published { Published } property MatchDepth; property DiffOptions; property OnDiffCompleted; property OnDiffProgress; end; TrmCustomDiffViewer = class(TCustomControl) private { Private } fDiff: TrmCustomDiffEngine; fDiffMap: TrmDiffMap; fEBGColor: TColor; fDBGColor: TColor; fSimpleViewer: boolean; fITColor: TColor; fDColor: TColor; fCTColor: TColor; procedure SetDBGColor(const Value: TColor); procedure SetEBGColor(const Value: TColor); procedure SetSimpleViewer(const Value: boolean); procedure SetCTColor(const Value: TColor); procedure SetDTColor(const Value: TColor); procedure SetITColor(const Value: TColor); procedure wmEraseBKGrnd(var msg: tmessage); message wm_erasebkgnd; protected { protected } function GetSrc1Label: string; virtual; function GetSrc2Label: string; virtual; procedure SetSrc1Label(const Value: string); virtual; procedure SetSrc2Label(const Value: string); virtual; procedure SetDiff(const Value: TrmCustomDiffEngine); virtual; procedure SetDiffMap(const Value: TrmDiffMap); virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; property DiffEngine: TrmCustomDiffEngine read fDiff write SetDiff; function GetMapData: string; procedure MapClick(Sender: TObject; IndicatorPos: integer); virtual; Abstract; property EmptyBGColor: TColor read fEBGColor write SetEBGColor default clBtnFace; property DiffBGColor: TColor read fDBGColor write SetDBGColor default clYellow; property ChangedTextColor: TColor read fCTColor write SetCTColor default clWindowText; property DeletedTextColor: TColor read fDColor write SetDTColor default clWindowText; property InsertedTextColor: TColor read fITColor write SetITColor default clWindowText; property SimpleDiffViewer: boolean read fSimpleViewer write SetSimpleViewer default true; property DiffMap: TrmDiffMap read fDiffMap write SetDiffMap; property Src1Label : string read GetSrc1Label write SetSrc1Label; property Src2Label : string read GetSrc2Label write SetSrc2Label; public { Public } constructor Create(AOwner: TComponent); override; procedure DiffferenceCompleted; virtual; published { Published } property Align; property Font; end; TrmDiffViewer = class(TrmCustomDiffViewer) private { Private } fDrawing: boolean; fsource1: TrmListControl; fsource2: TrmListControl; fBevel: TBevel; fPanel: TPanel; fLabel1, fLabel2: TLabel; fScrollInProgress: boolean; fIHC: boolean; fLockSelIndex: boolean; procedure UpdateVScrollBar; procedure UpdateHScrollBar; procedure scrollChanged(Sender: TObject; ScrollBar: integer); procedure Drawing(Sender: TObject; Canvas: TCanvas; Selected: boolean; var str: string); procedure cmFontChanged(var Msg: TMessage); message cm_fontchanged; procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL; procedure WMHScroll(var Msg: TWMHScroll); message WM_HSCROLL; procedure SetIHC(const Value: boolean); procedure SetLockSelIndex(const Value: boolean); protected { protected } function GetSrc1Label: string; override; function GetSrc2Label: string; override; procedure SetSrc1Label(const Value: string); override; procedure SetSrc2Label(const Value: string); override; procedure SetDiffMap(const Value: TrmDiffMap); override; procedure Resize; override; procedure CreateParams(var Params: TCreateParams); override; procedure ResetIndex(Index, Pos: integer); procedure MapClick(Sender: TObject; IndicatorPos: integer); override; public { Public } procedure DiffferenceCompleted; override; constructor Create(AOwner: TComponent); override; procedure Loaded; override; published { Published } property TabStop; property DiffEngine; property EmptyBGColor; property DiffBGColor; property ChangedTextColor; property DeletedTextColor; property InsertedTextColor; property DiffMap; property SimpleDiffViewer; property IndependantHorzControl: boolean read fIHC write SetIHC default False; property LockSelectedIndex:boolean read fLockSelIndex write SetLockSelIndex default true; property Src1Label; property Src2Label; end; TrmDiffMergeViewer = class(TrmCustomDiffViewer) private { Private } fDrawing: boolean; fsource1: TrmListControl; fsource2: TrmListControl; fMergeSource: TrmListControl; fBevel, fBevel2: TBevel; fPanel: TPanel; fLabel1, fLabel2, fLabel3: TLabel; fScrollInProgress: boolean; fD1BGColor: TColor; fD2BGColor: TColor; fIHC: boolean; fSourceSide : smallint; procedure UpdateVScrollBar; procedure UpdateHScrollBar; procedure scrollChanged(Sender: TObject; ScrollBar: integer); procedure Drawing(Sender: TObject; Canvas: TCanvas; Selected: boolean; var str: string); procedure cmFontChanged(var Msg: TMessage); message cm_fontchanged; procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL; procedure WMHScroll(var Msg: TWMHScroll); message WM_HSCROLL; procedure SetD1BGColor(const Value: TColor); procedure SetD2BGColor(const Value: TColor); procedure SetIHC(const Value: boolean); procedure SetSourceSide(const Value: smallint); protected { protected } function GetSrc1Label: string; override; function GetSrc2Label: string; override; procedure SetSrc1Label(const Value: string); override; procedure SetSrc2Label(const Value: string); override; function GetMergeLable: string; virtual; procedure SetMergeLabel(const Value: string); virtual; procedure Resize; override; procedure CreateParams(var Params: TCreateParams); override; procedure ResetIndex(Index, Pos: integer); procedure MapClick(Sender: TObject; IndicatorPos: integer); override; public { Public } procedure DiffferenceCompleted; override; constructor Create(AOwner: TComponent); override; procedure Loaded; override; function CanChangeSource: boolean; procedure CopySource(Source1: boolean); procedure ClearSource; procedure SaveMergeToFile(FileName: string); procedure SaveMergeToStream(Strm: TStream); property SelectedSource : smallint read FSourceSide write SetSourceSide default 0; published { Published } property DiffEngine; property TabStop; property IndependantHorzControl: boolean read fIHC write SetIHC default False; property EmptyBGColor; property ChangedTextColor; property DeletedTextColor; property InsertedTextColor; property DiffMap; property SimpleDiffViewer; property Source1DiffBGColor: TColor read fD1BGColor write SetD1BGColor default clAqua; property Source2DiffBGColor: TColor read fD2BGColor write SetD2BGColor default clYellow; property MergeSrcLabel:string read GetMergeLable write SetMergeLabel; property Src1Label; property Src2Label; end; TrmDiffMap = class(TCustomControl) private { Private declarations } FColorDeleted: TColor; FColorInserted: TColor; FColorModified: TColor; FShowIndicator: Boolean; FIndicatorPos: integer; FIndicator: TBitmap; FData: string; FOnMapClick: TrmDiffMapClickEvent; procedure DrawIndicator; procedure SetIndicatorPos(Value: integer); function MapHeight: integer; protected { Protected declarations } procedure Paint; override; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SetData(Value: string); procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; property IndicatorPos: integer read FIndicatorPos write SetIndicatorPos; published { Published declarations } property Color; property Caption; property Align; property ColorDeleted: TColor read FColorDeleted write FColorDeleted; property ColorInserted: TColor read FColorInserted write FColorInserted; property ColorModified: TColor read FColorModified write FColorModified; property ShowIndicator: Boolean read FShowIndicator write FShowIndicator; property OnMapClick: TrmDiffMapClickEvent read FOnMapClick write FOnMapClick; end; implementation uses rmLibrary, math, Forms; {$R *.RES} const NormalLine = #1; DeletedLine = #2; InsertedLine = #3; ChangedLine = #4; EmptyLine = #5; MergeLine1 = #6; MergeLine2 = #7; TOP_MARGIN = 5; BOTTOM_MARGIN = 5; { TrmDiff } constructor TrmCustomDiffEngine.Create; begin inherited; fSource1 := TStringList.Create; fSource2 := TStringList.Create; fDiffSource1 := TStringList.create; fDiffSource2 := TStringList.create; fAttachedViewers := TList.create; fSource1Count := -1; fSource2Count := -1; fMatchDepth := 3; fIgnoreChars := [#0..#32]; fMultiLineCommentOpen:=false; fStringOpen:=false; end; destructor TrmCustomDiffEngine.Destroy; begin fSource1.Free; fSource2.Free; fDiffSource1.free; fDiffSource2.free; fAttachedViewers.Free; inherited; end; procedure TrmCustomDiffEngine.CompareFiles(file1, file2: string); begin ClearData; fSource1.LoadFromFile(File1); fSource2.LoadFromFile(File2); StartCompare; end; procedure TrmCustomDiffEngine.CompareStreams(Strm1, Strm2: TStream); begin ClearData; fSource1.LoadFromStream(Strm1); fSource2.LoadFromStream(Strm2); StartCompare; end; procedure TrmCustomDiffEngine.StartCompare; begin fSource1Count := fSource1.Count; fSource2Count := fSource2.count; DiffStarted; while not AtEOF do CompareData; DiffCompleted; end; procedure TrmCustomDiffEngine.CompareData; var depth, level, tmp: integer; db1, db2: TrmDiffBlock; wEOF: boolean; CheckDepth: integer; begin while (not atEOF) and matchLines(0, 0, 0) do MoveDown(1, 1); if AtEOF then exit; wEOF := false; depth := 0; level := 0; if (fSource1Count = fSource1.count) and (fSource2Count = fSource2.count) then checkdepth := 1 else CheckDepth := fMatchDepth; while true do begin try if MatchLines(level, depth, CheckDepth) then break; if (level <> depth) and (MatchLines(depth, level, CheckDepth)) then break; if (level < depth) then inc(level) else begin inc(depth); level := 0; end; except wEOF := true; level := fSource2.count - 1; depth := fSource1.count - 1; end; end; if not wEOF then begin if MatchLines(level, depth, CheckDepth) then begin tmp := level; level := depth; depth := tmp; end; end; db1.startLine := fSource1Count - fSource1.count; db1.endline := db1.startline + depth; db2.startLine := fSource2Count - fSource2.count; db2.endline := db2.startline + level; try DiffFound(db1, db2); except //Do Nothing end; end; function TrmCustomDiffEngine.AtEOF: boolean; begin result := (fSource1.count = 0) or (fSource2.count = 0); end; function TrmCustomDiffEngine.MatchLines(level1, level2, MatchDepth: integer): boolean; var s1, s2: string; loop: integer; begin result := true; for loop := 0 to MatchDepth do begin if level1 + loop >= fSource1.count then s1 := '' else s1 := fSource1[level1 + loop]; if level2 + loop >= fSource2.count then s2 := '' else s2 := fSource2[level2 + loop]; if (fdoIgnoreCharacters in fOptions) and (fIgnoreChars <> []) then begin s1 := RemoveCharacters(s1); s2 := RemoveCharacters(s2); end; if ((fdoIgnoreTrailingWhiteSpace in fOptions) and (fdoIgnoreLeadingWhiteSpace in fOptions)) then begin s1 := Trim(s1); s2 := Trim(s2); end else if fdoIgnoreTrailingWhiteSpace in fOptions then begin s1 := TrimRight(s1); s2 := TrimRight(s2); end else if fdoIgnoreLeadingWhiteSpace in fOptions then begin s1 := TrimLeft(s1); s2 := TrimLeft(s2); end; if fdoCaseSensitive in fOptions then result := result and (compareStr(s1, s2) = 0) else result := result and (compareStr(lowercase(s1), lowercase(s2)) = 0); if not result then break; end; end; procedure TrmCustomDiffEngine.MoveDown(Amount1, Amount2: integer); begin while Amount1 > 0 do begin dec(Amount1); try fDiffSource1.add(NormalLine + fSource1[0]); fSource1.delete(0); except amount1 := 0; end; end; while Amount2 > 0 do begin dec(Amount2); try fDiffSource2.add(NormalLine + fSource2[0]); fSource2.delete(0); except amount2 := 0; end; end; if assigned(fOnProgress) then begin try fOnProgress(round((((fSource1Count + fSource2Count) - (fSource1.Count + fSource2.count)) / (fSource1Count + fSource2Count)) * 100)); except //Do Nothing... end; end; end; procedure TrmCustomDiffEngine.Notification(AComponent: TComponent; Operation: TOperation); var Index : integer; begin inherited; if operation = opremove then begin index := fAttachedViewers.indexof(AComponent); if index <> -1 then fAttachedViewers.Delete(index); end; end; procedure TrmCustomDiffEngine.SetMatchDepth(const Value: integer); begin if (fMatchDepth <> value) and (value > 0) and (value < 100) then fMatchDepth := Value; end; { TrmCustomDiffViewer } constructor TrmCustomDiffViewer.Create(AOwner: TComponent); begin inherited Create(AOwner); Height := 150; width := 250; ControlStyle := ControlStyle - [csAcceptsControls]; fEBGColor := clBtnFace; fDBGColor := clYellow; fSimpleViewer := true; end; procedure TrmCustomDiffViewer.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (operation = opRemove) then begin if (AComponent = fDiff) then fDiff := nil; if (AComponent = fDiffMap) then fDiffMap := nil; end; end; procedure TrmCustomDiffViewer.SetDiff(const Value: TrmCustomDiffEngine); begin if value <> fDiff then begin if assigned(fDiff) then fDiff.RemoveViewer(self); fDiff := Value; if assigned(fDiff) then begin fDiff.FreeNotification(self); fDiff.AttachViewer(self); end end; end; procedure TrmCustomDiffViewer.SetDBGColor(const Value: TColor); begin fDBGColor := Value; Invalidate; end; procedure TrmCustomDiffViewer.SetEBGColor(const Value: TColor); begin fEBGColor := Value; Invalidate; end; procedure TrmCustomDiffViewer.SetSimpleViewer(const Value: boolean); begin fSimpleViewer := Value; invalidate; end; procedure TrmCustomDiffViewer.SetCTColor(const Value: TColor); begin fCTColor := Value; invalidate; end; procedure TrmCustomDiffViewer.SetDTColor(const Value: TColor); begin fDColor := Value; invalidate; end; procedure TrmCustomDiffViewer.SetITColor(const Value: TColor); begin fITColor := Value; invalidate; end; procedure TrmCustomDiffViewer.SetDiffMap(const Value: TrmDiffMap); begin if fDiffMap <> Value then begin fDiffMap := value; if assigned(fDiffMap) then begin fDiffMap.FreeNotification(self); fDiffMap.SetData(GetMapData); fDiffMap.OnMapClick := MapClick; end; end; end; function TrmCustomDiffViewer.GetMapData: string; var loop: integer; wstr: string; begin wstr := ''; if assigned(DiffEngine) and (DiffEngine.fDiffSource1.count > 0) then begin setlength(wStr, DiffEngine.fDiffSource1.count); for loop := 0 to DiffEngine.fDiffSource1.Count - 1 do begin case DiffEngine.fDiffSource1[loop][1] of NormalLine: wstr[loop + 1] := NormalLine; DeletedLine: wstr[loop + 1] := DeletedLine; ChangedLine: wstr[loop + 1] := ChangedLine; EmptyLine: wstr[loop + 1] := InsertedLine; end; end; end; result := wstr; end; procedure TrmCustomDiffViewer.DiffferenceCompleted; begin if assigned(fDiffMap) then fDiffMap.SetData(GetMapData); end; function TrmCustomDiffViewer.GetSrc1Label: string; begin result := 'Source 1'; end; function TrmCustomDiffViewer.GetSrc2Label: string; begin result := 'Source 2'; end; procedure TrmCustomDiffViewer.SetSrc1Label(const Value: string); begin //do nothing... end; procedure TrmCustomDiffViewer.SetSrc2Label(const Value: string); begin //do nothing... end; procedure TrmCustomDiffViewer.wmEraseBKGrnd(var msg: tmessage); begin msg.result := 1; end; { TrmDiffMergeViewer } function TrmDiffMergeViewer.CanChangeSource: boolean; begin result := (fMergeSource.items.count > 0) and (fMergeSource.Items[fMergeSource.itemindex][1] <> NormalLine); end; procedure TrmDiffMergeViewer.ClearSource; var oldIndex, oldScrollPos: integer; begin oldindex := fMergeSource.ItemIndex; oldScrollPos := fMergeSource.VScrollPos; try fMergeSource.Items[fMergeSource.ItemIndex] := EmptyLine + ''; finally ResetIndex(OldIndex, OldScrollPos); end; invalidate; end; procedure TrmDiffMergeViewer.cmFontChanged(var Msg: TMessage); begin inherited; fsource1.font.Assign(font); fsource2.font.Assign(font); fMergeSource.font.assign(font); end; procedure TrmDiffMergeViewer.CopySource(Source1: boolean); var wstr: string; oldIndex, OldScrollPos, loop: integer; wSource : TrmListControl; begin oldindex := fMergeSource.ItemIndex; oldScrollPos := fMergeSource.VScrollPos; if Source1 then wSource := fSource1 else wSource := fSource2; try for loop := wSource.SelStart to (wSource.SelStart + wSource.SelCount) do begin wstr := wSource.Items[loop]; if wstr[1] <> emptyline then begin delete(wstr, 1, 1); wstr := MergeLine1 + wstr; end else wstr := EmptyLine + ''; fMergeSource.Items[loop] := wstr; end; finally ResetIndex(oldIndex, OldScrollPos); invalidate; end; end; constructor TrmDiffMergeViewer.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle - [csAcceptsControls]; BevelEdges := [beLeft, beTop, beRight, beBottom]; BevelInner := bvLowered; BevelOuter := bvLowered; BevelKind := bkTile; fD1BGColor := clAqua; fD2BGColor := clYellow; fDrawing := false; fScrollInProgress := false; fIHC := false; fSourceSide := 0; fPanel := TPanel.create(self); with fPanel do begin ControlStyle := ControlStyle - [csAcceptsControls]; Parent := self; align := altop; BevelInner := bvlowered; BevelOuter := bvraised; end; fLabel1 := TLabel.create(fPanel); with fLabel1 do begin parent := fPanel; align := alLeft; AutoSize := false; Caption := 'Source 1'; Alignment := taCenter; end; fLabel2 := TLabel.create(fPanel); with fLabel2 do begin parent := fPanel; align := alLeft; AutoSize := false; Caption := 'Merged Source'; Alignment := taCenter; end; fLabel3 := TLabel.create(fPanel); with fLabel3 do begin parent := fPanel; align := alClient; AutoSize := false; Caption := 'Source 2'; Alignment := taCenter; end; fSource1 := TrmListControl.create(self); with fSource1 do begin name := 'SourceList1'; parent := self; align := alLeft; font.assign(self.font); enabled := false; OnFormatDrawing := Drawing; ScrollBars := ssNone; Multiselect := true; Tag := 1; end; fBevel := TBevel.Create(self); with fBevel do begin parent := self; align := alLeft; width := 2; end; fMergeSource := TrmListControl.create(self); with fMergeSource do begin name := 'MergedSourceList'; parent := self; align := alLeft; font.assign(self.font); TabStop := true; OnScroll := ScrollChanged; OnFormatDrawing := Drawing; ScrollBars := ssNone; Multiselect := true; Tag := 0; end; fBevel2 := TBevel.Create(self); with fBevel2 do begin parent := self; align := alLeft; width := 2; end; fSource2 := TrmListControl.create(self); with fSource2 do begin name := 'SourceList2'; parent := self; align := alLeft; enabled := false; font.assign(self.font); OnFormatDrawing := Drawing; ScrollBars := ssNone; Multiselect := true; Tag := 2; end; end; procedure TrmDiffMergeViewer.CreateParams(var Params: TCreateParams); begin inherited; Params.style := Params.style or WS_VSCROLL; if not fIHC then Params.style := Params.style or WS_HSCROLL; end; procedure TrmDiffMergeViewer.DiffferenceCompleted; var loop, wLongLine: integer; begin inherited; fSource1.Items.BeginUpdate; fSource2.Items.BeginUpdate; fMergeSource.Items.BeginUpdate; try fMergeSource.Items.Clear; fSource1.Items.assign(DiffEngine.DiffSource1); fSource2.Items.assign(DiffEngine.DiffSource2); for loop := 0 to fSource1.Items.count - 1 do begin if fSource1.items[loop][1] = NormalLine then fMergeSource.Items.Add(fSource1.items[loop]) else fMergeSource.Items.Add(Emptyline + '') end; UpdateVScrollBar; UpdateHScrollBar; finally fSource1.Items.EndUpdate; fSource2.Items.EndUpdate; fMergeSource.Items.EndUpdate; end; wLongLine := max(fSource1.LongestLineLength, fSource2.LongestLineLength); wLongLine := max(wLongLine, fMergeSource.LongestLineLength); fSource1.LongestLineLength := wLongLine; fSource2.LongestLineLength := wLongLine; fMergeSource.LongestLineLength := wLongLine; invalidate; end; procedure TrmDiffMergeViewer.Drawing(Sender: TObject; Canvas: TCanvas; Selected: boolean; var str: string); var status: char; begin status := str[1]; delete(str, 1, 1); Canvas.Font.Color := clWindowText; case status of NormalLine: Canvas.brush.color := clWindow; ChangedLine, DeletedLine, InsertedLine: begin if Sender = fsource1 then Canvas.Brush.Color := fD1BGColor else if Sender = fsource2 then Canvas.Brush.Color := fD2BGColor; Canvas.Font.Color := ChangedTextColor; if not SimpleDiffViewer then begin case status of DeletedLine: Canvas.Font.Color := DeletedTextColor; InsertedLine: Canvas.Font.Color := InsertedTextColor; end; end; end; EmptyLine: Canvas.Brush.Color := fEBGColor; MergeLine1: Canvas.Brush.Color := fD1BGColor; MergeLine2: Canvas.Brush.Color := fD2BGColor; end; if (Selected) then begin Canvas.font.color := clHighlightText; Canvas.Brush.Color := clHighlight; end; end; function TrmDiffMergeViewer.GetMergeLable: string; begin result := fLabel2.caption; end; function TrmDiffMergeViewer.GetSrc1Label: string; begin result := flabel1.caption; end; function TrmDiffMergeViewer.GetSrc2Label: string; begin result := flabel3.caption; end; procedure TrmDiffMergeViewer.Loaded; begin inherited; fsource1.left := 0; fBevel.left := fsource1.width; fMergeSource.left := fBevel.left + fBevel.width; fBevel2.left := fMergeSource.left + fMergeSource.width; fSource2.left := fBevel2.left + fBevel2.width; fPanel.height := Canvas.TextHeight('X') + 4; Resize; end; procedure TrmDiffMergeViewer.MapClick(Sender: TObject; IndicatorPos: integer); begin ResetIndex(IndicatorPos, IndicatorPos); end; procedure TrmDiffMergeViewer.ResetIndex(Index, Pos: integer); begin fMergeSource.VScrollPos := pos; fMergeSource.ItemIndex := Index; fSource1.VScrollPos := pos; fSource1.ItemIndex := Index; fSource2.VScrollPos := pos; fSource2.ItemIndex := Index; UpdateVScrollBar; end; procedure TrmDiffMergeViewer.Resize; var wcw: integer; begin inherited; wcw := ClientWidth div 3; fLabel1.width := wcw; fLabel2.width := wcw; fLabel3.width := wcw; wcw := ClientWidth - (fBevel.width * 2); fSource1.Width := wcw div 3; fMergeSource.width := fSource1.Width; fSource2.Width := fSource1.Width + (wcw mod 3); UpdateVScrollBar; UpdateHScrollBar; end; procedure TrmDiffMergeViewer.SaveMergeToFile(FileName: string); var fstrm: TFileStream; begin fstrm := TFileStream.create(filename, fmCreate); try SaveMergeToStream(fStrm); finally fstrm.free; end; end; procedure TrmDiffMergeViewer.SaveMergeToStream(Strm: TStream); var wstr: string; loop: integer; begin if assigned(strm) then begin strm.Position := 0; for loop := 0 to fMergeSource.Items.count - 1 do begin wstr := fMergeSource.Items[loop] + #13#10; if wstr[1] <> emptyline then begin delete(wstr, 1, 1); Strm.Write(wstr, length(wstr)); end; end; end else raise EStreamError.create('Stream not open for writing'); end; procedure TrmDiffMergeViewer.scrollChanged(Sender: TObject; ScrollBar: integer); begin if fScrollInProgress then exit; fScrollInProgress := true; try if fIHC and (ScrollBar = sb_Horz) then exit; if ScrollBar = SB_VERT then begin if fSource1.ItemIndex = fMergeSource.ItemIndex then begin fSource1.VScrollPos := fMergeSource.VScrollPos; fSource2.VScrollPos := fMergeSource.VScrollPos; end else begin fSource1.ItemIndex := fMergeSource.ItemIndex; fSource1.SelStart := fMergeSource.SelStart; fSource1.SelCount := fMergeSource.SelCount; fSource2.ItemIndex := fMergeSource.ItemIndex; fSource2.SelStart := fMergeSource.SelStart; fSource2.SelCount := fMergeSource.SelCount; end; UpdateVScrollBar; if assigned(DiffMap) then DiffMap.IndicatorPos := fMergeSource.ItemIndex; end else begin fSource1.HScrollPos := fMergeSource.HScrollPos; fSource2.HScrollPos := fMergeSource.HScrollPos; UpdateHScrollBar; end; finally fScrollInProgress := false; end; end; procedure TrmDiffMergeViewer.SetD1BGColor(const Value: TColor); begin fD1BGColor := Value; invalidate; end; procedure TrmDiffMergeViewer.SetD2BGColor(const Value: TColor); begin fD2BGColor := Value; invalidate; end; procedure TrmDiffMergeViewer.SetIHC(const Value: boolean); begin if fIHC <> Value then begin fIHC := Value; if fIHC then begin fsource1.ScrollBars := ssHorizontal; fsource2.ScrollBars := ssHorizontal; fMergeSource.ScrollBars := ssNone; end else begin fsource1.ScrollBars := ssNone; fsource2.ScrollBars := ssNone; fMergeSource.ScrollBars := ssNone; end; RecreateWnd; end; end; procedure TrmDiffMergeViewer.SetMergeLabel(const Value: string); begin fLabel2.caption := value; end; procedure TrmDiffMergeViewer.SetSourceSide(const Value: smallint); begin if (value >= 0) or (value <= 2) then begin FSourceSide := Value; case fSourceSide of 0: begin fsource1.HideSelection := false; fsource2.HideSelection := false; end; 1: begin fsource1.HideSelection := false; fsource2.HideSelection := true; end; 2: begin fsource1.HideSelection := true; fsource2.HideSelection := false; end; end; end; end; procedure TrmDiffMergeViewer.SetSrc1Label(const Value: string); begin flabel1.caption := value; end; procedure TrmDiffMergeViewer.SetSrc2Label(const Value: string); begin flabel3.caption := value; end; procedure TrmDiffMergeViewer.UpdateHScrollBar; var wScrollInfo: TScrollInfo; begin if fIHC then exit; with wScrollInfo do begin cbSize := sizeof(TScrollInfo); fMask := SIF_POS or SIF_RANGE {or SIF_DISABLENOSCROLL}; nMin := 0; nMax := fMergeSource.HScrollSize; nPos := fMergeSource.HScrollPos; end; SetScrollInfo(Handle, SB_HORZ, wScrollInfo, True); end; procedure TrmDiffMergeViewer.UpdateVScrollBar; var wScrollInfo: TScrollInfo; begin with wScrollInfo do begin cbSize := sizeof(TScrollInfo); fMask := SIF_POS or SIF_RANGE {or SIF_DISABLENOSCROLL}; nMin := 0; nMax := fMergeSource.VScrollSize; nPos := fMergeSource.VScrollPos; end; SetScrollInfo(Handle, SB_VERT, wScrollInfo, True); end; procedure TrmDiffMergeViewer.WMHScroll(var Msg: TWMHScroll); begin inherited; fMergeSource.Dispatch(msg); UpdateHScrollBar; end; procedure TrmDiffMergeViewer.WMVScroll(var Msg: TWMVScroll); begin inherited; fMergeSource.Dispatch(msg); UpdateVScrollBar; end; { TrmDiffViewer } procedure TrmDiffViewer.cmFontChanged(var Msg: TMessage); begin inherited; fsource1.font.Assign(font); fsource2.font.Assign(font); end; constructor TrmDiffViewer.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle - [csAcceptsControls]; BevelEdges := [beLeft, beTop, beRight, beBottom]; BevelInner := bvLowered; BevelOuter := bvLowered; BevelKind := bkTile; fDrawing := false; fScrollInProgress := false; fIHC := false; fLockSelIndex := true; fPanel := TPanel.create(self); with fPanel do begin ControlStyle := ControlStyle - [csAcceptsControls]; Parent := self; align := altop; BevelInner := bvlowered; BevelOuter := bvraised; end; fLabel1 := TLabel.create(fPanel); with fLabel1 do begin parent := fPanel; align := alLeft; AutoSize := false; Caption := 'Source 1'; Alignment := taCenter; end; fLabel2 := TLabel.create(fPanel); with fLabel2 do begin parent := fPanel; align := alClient; AutoSize := false; Caption := 'Source 2'; Alignment := taCenter; end; fSource1 := TrmListControl.create(self); with fSource1 do begin name := 's1'; parent := self; align := alLeft; font.assign(self.font); TabStop := true; OnScroll := ScrollChanged; OnFormatDrawing := Drawing; ScrollBars := ssNone; end; fBevel := TBevel.Create(self); with fBevel do begin parent := self; align := alLeft; width := 2; end; fSource2 := TrmListControl.create(self); with fSource2 do begin name := 's2'; parent := self; align := alLeft; font.assign(self.font); TabStop := true; OnScroll := ScrollChanged; OnFormatDrawing := Drawing; ScrollBars := ssNone; end; end; procedure TrmDiffViewer.CreateParams(var Params: TCreateParams); begin inherited; Params.style := Params.style or WS_VSCROLL; if not fIHC then Params.style := Params.style or WS_HSCROLL; end; procedure TrmDiffViewer.DiffferenceCompleted; var wLongLine : integer; begin inherited; fSource1.Items.BeginUpdate; fSource2.Items.BeginUpdate; try fSource1.Items.assign(DiffEngine.DiffSource1); fSource2.Items.assign(DiffEngine.DiffSource2); UpdateVScrollBar; UpdateHScrollBar; finally fSource1.Items.EndUpdate; fSource2.Items.EndUpdate; end; wLongLine := max(fSource1.LongestLineLength, fSource2.LongestLineLength); fSource1.LongestLineLength := wLongLine; fSource2.LongestLineLength := wLongLine; invalidate; end; procedure TrmDiffViewer.Drawing(Sender: TObject; Canvas: TCanvas; Selected: boolean; var str: string); var status: char; begin status := str[1]; delete(str, 1, 1); Canvas.Font.Color := clWindowText; case status of NormalLine: Canvas.brush.color := clWindow; ChangedLine, DeletedLine, InsertedLine: begin Canvas.Brush.Color := fDBGColor; Canvas.Font.Color := ChangedTextColor; if not SimpleDiffViewer then begin case status of DeletedLine: Canvas.Font.Color := DeletedTextColor; InsertedLine: Canvas.Font.Color := InsertedTextColor; end; end; end; EmptyLine: Canvas.Brush.Color := fEBGColor; end; if (Selected) then begin Canvas.font.color := clHighlightText; Canvas.Brush.Color := clHighlight; end; end; function TrmDiffViewer.GetSrc1Label: string; begin result := fLabel1.Caption; end; function TrmDiffViewer.GetSrc2Label: string; begin result := flabel2.caption; end; procedure TrmDiffViewer.Loaded; begin inherited; fsource1.left := 0; fBevel.left := fsource1.width; fSource2.left := fBevel.left + fBevel.width; fPanel.height := Canvas.TextHeight('X') + 4; Resize; end; procedure TrmDiffViewer.MapClick(Sender: TObject; IndicatorPos: integer); begin ResetIndex(IndicatorPos, IndicatorPos); end; procedure TrmDiffViewer.ResetIndex(Index, Pos: integer); begin fSource1.VScrollPos := pos; fSource1.ItemIndex := Index; fSource2.VScrollPos := pos; fSource2.ItemIndex := Index; UpdateVScrollBar; end; procedure TrmDiffViewer.Resize; var wcw: integer; begin inherited; wcw := ClientWidth div 2; fLabel1.width := wcw; fLabel2.width := wcw; wcw := ClientWidth - fBevel.width; fSource1.Width := wcw div 2; fSource2.Width := fSource1.Width + (wcw mod 2); UpdateVScrollBar; UpdateHScrollBar; end; procedure TrmDiffViewer.scrollChanged(Sender: TObject; ScrollBar: integer); begin if fScrollInProgress then exit; fScrollInProgress := true; try if fIHC and (ScrollBar = sb_Horz) then exit; if (sender = fsource1) then begin if ScrollBar = SB_VERT then begin if fLockSelIndex then begin fSource2.ItemIndex := fSource1.ItemIndex; fSource2.SelCount := fsource1.SelCount; end; fSource2.VScrollPos := fSource1.VScrollPos; end else fSource2.HScrollPos := fSource1.HScrollPos; end else if (sender = fSource2) then begin if ScrollBar = SB_VERT then begin if fLockSelIndex then begin fSource1.ItemIndex := fSource2.ItemIndex; fSource1.SelCount := fSource2.SelCount; end; fSource1.VScrollPos := fSource2.VScrollPos; end else fSource1.HScrollPos := fSource2.HScrollPos; end; if ScrollBar = SB_VERT then UpdateVScrollBar else UpdateHScrollBar; finally fScrollInProgress := false; end; end; procedure TrmDiffViewer.SetDiffMap(const Value: TrmDiffMap); begin inherited; if assigned(DiffMap) then DiffMap.ShowIndicator := false; end; procedure TrmDiffViewer.SetIHC(const Value: boolean); begin if fIHC <> Value then begin fIHC := Value; if fIHC then begin fsource1.ScrollBars := ssHorizontal; fSource2.ScrollBars := ssHorizontal; end else begin fsource1.ScrollBars := ssNone; fSource2.ScrollBars := ssNone; end; RecreateWnd; end; end; procedure TrmDiffViewer.SetLockSelIndex(const Value: boolean); begin if fLockSelIndex <> Value then begin fLockSelIndex := Value; if fLockSelIndex then begin fsource2.VScrollPos := fsource1.VScrollPos; fsource2.ItemIndex := fsource1.itemIndex; end; end; end; procedure TrmDiffViewer.SetSrc1Label(const Value: string); begin fLabel1.caption := value; end; procedure TrmDiffViewer.SetSrc2Label(const Value: string); begin fLabel2.caption := value; end; procedure TrmDiffViewer.UpdateHScrollBar; var wScrollInfo: TScrollInfo; begin if fIHC then exit; with wScrollInfo do begin cbSize := sizeof(TScrollInfo); fMask := SIF_POS or SIF_RANGE {or SIF_DISABLENOSCROLL}; nMin := 0; nMax := fsource1.HScrollSize; nPos := fsource1.HScrollPos; end; SetScrollInfo(Handle, SB_HORZ, wScrollInfo, True); end; procedure TrmDiffViewer.UpdateVScrollBar; var wScrollInfo: TScrollInfo; begin with wScrollInfo do begin cbSize := sizeof(TScrollInfo); fMask := SIF_POS or SIF_RANGE {or SIF_DISABLENOSCROLL}; nMin := 0; nMax := fsource1.VScrollSize; nPos := fsource1.VScrollPos; end; SetScrollInfo(Handle, SB_VERT, wScrollInfo, True); end; procedure TrmDiffViewer.WMHScroll(var Msg: TWMHScroll); begin inherited; if not fIHC then begin fsource1.Dispatch(msg); UpdateHScrollBar; end; end; procedure TrmDiffViewer.WMVScroll(var Msg: TWMVScroll); begin inherited; fsource1.Dispatch(msg); UpdateVScrollBar; end; { TrmDiffMap } constructor TrmDiffMap.Create(AOwner: TComponent); begin inherited; width := 25; height := 200; FIndicator := TBitmap.Create; FIndicator.LoadFromResourceName(HInstance,'DIFFMAP_INDICATOR'); FIndicator.Transparent := True; FColorDeleted := clRed; FColorInserted := clLime; FColorModified := clYellow; FShowIndicator := True; IndicatorPos := 0; end; destructor TrmDiffMap.Destroy; begin FIndicator.Free; inherited; end; procedure TrmDiffMap.SetData(Value: string); begin FData := copy(Value, 1, length(Value)); refresh; end; procedure TrmDiffMap.SetIndicatorPos(Value: integer); begin FIndicatorPos := Value; Refresh; end; procedure TrmDiffMap.Paint; var i: Integer; j: Integer; NrOfDataRows: Integer; Ht: Integer; Ct: Integer; CurrIndex: Integer; PixelPos: Integer; PixelHt: Double; // amount of pixel height for each row - could be a rather small number PixelFrac: Double; // Faction part of pixel - left over from previous PixelPrevHt: Double; // logical height of previous mapped pixel (eg. .92) NrOfPixelRows: Double; // Number of rows that the current pixel is to represent. ExtraPixel: Double; // Left over pixel from when calculating number of rows for the next pixel. // eg. 1/.3 = 3 rows, .1 remaining, next 1.1/.3 = 3 rows, .2 remain, next 1.2/.3 = 4 rows. DrawIt: Boolean; // Drawing flag for each column RowModified: Boolean; RowDeleted: Boolean; RowInserted: Boolean; ExitLoop: Boolean; // loop control // Draws the line between two points on the horizonatal line of i. procedure DrawLine(X1, X2: integer); var k: integer; begin // What colour? Black or Background? if DrawIt then begin if RowModified then begin Canvas.Pen.Color := ColorModified; end else begin if RowInserted then begin Canvas.Pen.Color := ColorInserted; end else begin if RowDeleted then begin Canvas.Pen.Color := ColorDeleted; end; end; end; end else begin Canvas.Pen.Color := Color; end; // Draw the pixels for the map here for k := 0 to Round(NrOfPixelRows) - 1 do begin Canvas.MoveTo(X1, PixelPos + k); Canvas.LineTo(X2, PixelPos + k); end; end; begin inherited; if csDesigning in ComponentState then exit; Ht := MapHeight; Ct := length(fData); if Ct < 1 then begin Ct := 1; end; PixelHt := Ht / Ct; CurrIndex := 1; NrOfPixelRows := 0.0; PixelPrevHt := 0.0; PixelPos := 5; ExtraPixel := 0.0; j := CurrIndex; while j < Ct do begin NrOfDataRows := 0; PixelPrevHt := PixelPrevHt - NrOfPixelRows; // remainder from prevous pixel row (+ or -) PixelFrac := frac(PixelPrevHt); // We want just the fractional part! // Calculate how high the pixel line is to be if PixelHt < 1.0 then begin NrOfPixelRows := 1.0; // Each Pixel line represents one or more rows of data end else begin NrOfPixelRows := Int(PixelHt + ExtraPixel); // We have several pixel lines for each row of data. ExtraPixel := frac(PixelHt + ExtraPixel); // save frac part for next time end; // Calculate the nr of data rows to be represented by the Pixel Line about to be drawn. ExitLoop := False; repeat // the '.../2.0' checks if half a Pixel Ht will fit, else leave remainder for next row. if (PixelFrac + PixelHt <= NrOfPixelRows) or (PixelFrac + PixelHt / 2.0 <= NrOfPixelRows) then begin PixelFrac := PixelFrac + PixelHt; inc(NrOfDataRows); end else begin ExitLoop := True; end; until (PixelFrac >= NrOfPixelRows) or (ExitLoop); // go through each data row, check if a file has been modified. // if any file has been modified then we add to the Mapping. if NrOfDataRows > 0 then begin DrawIt := False; end; RowModified := False; RowInserted := False; RowDeleted := False; for i := j to j + NrOfDataRows - 1 do begin if i < ct then begin case fData[i] of ChangedLine: begin DrawIt := True; RowModified := True; end; InsertedLine: begin DrawIt := True; RowInserted := True; end; DeletedLine: begin DrawIt := True; RowDeleted := True; end; end; end; inc(j); end; // Mapping is drawn here if ShowIndicator then begin DrawLine(FIndicator.Width, Width - FIndicator.Width); end else begin DrawLine(0, Width); end; inc(PixelPos, Trunc(NrOfPixelRows)); // the pixel pos on the map. PixelPrevHt := int(PixelPrevHt) + PixelFrac; end; if ShowIndicator then DrawIndicator; end; procedure TrmDiffMap.DrawIndicator; var Y: integer; begin Canvas.Pen.Color := clBlack; if length(fData) <> 0 then begin Y := TOP_MARGIN + Trunc((IndicatorPos / length(fData)) * MapHeight); Canvas.Draw(0, Y - (FIndicator.Height div 2), FIndicator); end; end; function TrmDiffMap.MapHeight: integer; begin Result := Height - TOP_MARGIN - BOTTOM_MARGIN; if result < 1 then result := 1; //Map calculation correction...if ht < 1 then causes FP overflow...very bad!!! end; procedure TrmDiffMap.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var NewRow: Integer; PixelHt: Double; begin inherited; if Assigned(OnMapClick) and (length(fData) > 0) then begin PixelHt := MapHeight / length(fData); // This is how much of a pixel (or how many pixels), each row represents. // (the pixel clicked) + Half the Pixel Height + 1.0 / the pixel height // eg. Of 1000 rows, in the pixel area height of 500, then pixelHt = .5 (500/1000) // Therefore, if pixel 100 is clicked we get - (100 + .25 + 1) / .5 = 51 // Y-5, we subtract 5 as we start 5 pixels from the top of lblQuickPickArea. NewRow := Round(((Y - TOP_MARGIN) * 1.0 + PixelHt / 2.0 + 1.0) / PixelHt); if NewRow > length(fData) - 1 then NewRow := length(fData) - 1 else begin if NewRow < 1 then NewRow := 1; end; OnMapClick(self, NewRow); IndicatorPos := NewRow; end; //This is a new line... end; procedure TrmCustomDiffEngine.ClearData; begin fDiffSource1.Clear; fDiffSource2.Clear; fSource1.Clear; fSource2.Clear; end; procedure TrmCustomDiffEngine.DiffStarted; begin fBlankLines1 := 0; fBlankLines2 := 0; end; procedure TrmCustomDiffEngine.DiffFound(Source1, Source2: TrmDiffBlock); var s1diff, s2diff: integer; begin Source1.startline := source1.startline + fBlankLines1; Source1.Endline := source1.EndLine + fBlankLines1; Source2.startline := source2.startline + fBlankLines2; Source2.Endline := source2.Endline + fBlankLines2; s1diff := source1.endline - source1.startline; s2diff := source2.endline - source2.startline; if (s1diff = 0) and (s2diff > 0) then begin while s2diff > 0 do begin fDiffSource1.Add(EmptyLine + ' '); Inc(fBlankLines1); fDiffSource2.Add(InsertedLine + fSource2[0]); fSource2.delete(0); dec(s2Diff); end; end else if (s1diff > 0) and (s2diff = 0) then begin while s1diff > 0 do begin fDiffSource1.Add(DeletedLine + fSource1[0]); fSource1.delete(0); fDiffSource2.Add(Emptyline + ''); Inc(fBlankLines2); dec(s1Diff); end; end else if (s1diff > 0) and (s2diff > 0) then begin if s1diff > s2diff then begin while s2diff > 0 do begin fDiffSource1.Add(ChangedLine + fSource1[0]); fSource1.delete(0); fDiffSource2.Add(ChangedLine + fSource2[0]); fSource2.delete(0); dec(s2Diff); dec(s1Diff); end; while s1Diff > 0 do begin fDiffSource1.Add(DeletedLine + fSource1[0]); fSource1.delete(0); fDiffSource2.Add(EmptyLine + ' '); Inc(fBlankLines2); dec(s1Diff); end; end else begin while s1diff > 0 do begin fDiffSource1.Add(ChangedLine + fSource1[0]); fSource1.delete(0); fDiffSource2.Add(ChangedLine + fSource2[0]); fSource2.delete(0); dec(s1Diff); dec(s2Diff); end; while s2Diff > 0 do begin fDiffSource2.Add(InsertedLine + fSource2[0]); fSource2.delete(0); fDiffSource1.Add(EmptyLine + ' '); Inc(fBlankLines1); dec(s2Diff); end; end; end else raise Exception.create('This should never happen'); end; procedure TrmCustomDiffEngine.DiffCompleted; var loop : integer; begin while fSource1.count > 0 do begin fDiffSource1.add(NormalLine + fSource1[0]); fSource1.delete(0); end; while fSource2.count > 0 do begin fDiffSource2.add(NormalLine + fSource2[0]); fSource2.delete(0); end; while fDiffSource1.count < fDiffSource2.count do fDiffSource1.Add(EmptyLine + ' '); while fDiffSource2.count < fDiffSource1.count do fDiffSource2.Add(EmptyLine + ' '); for loop := 0 to fAttachedViewers.count-1 do TrmCustomDiffViewer(fattachedViewers[loop]).DiffferenceCompleted; if assigned(fOnDiffCompleted) then fOnDiffCompleted(self); end; procedure TrmCustomDiffEngine.AttachViewer(viewer: TrmCustomDiffViewer); begin if fAttachedViewers.indexof(viewer) = -1 then fAttachedViewers.add(viewer); end; procedure TrmCustomDiffEngine.RemoveViewer(viewer: TrmCustomDiffViewer); var index : integer; begin index := fAttachedViewers.indexof(viewer); if index <> -1 then fAttachedViewers.Delete(index); end; function TrmCustomDiffEngine.RemoveCharacters(st: string): string; var loop, len : integer; begin len := length(st); result := ''; loop := 0; while loop < len do begin inc(loop); if not (st[loop] in fIgnoreChars) then result := result + st[loop]; end; end; end.
//------------------------------------------------------------------------------ //InterServer UNIT //------------------------------------------------------------------------------ // What it does- // Contains Recv routines. Anything that is received by the inter server. // // Changes - // December 17th, 2006 - RaX - Created Header. // [2007/03/28] CR - Cleaned up uses clauses, using Icarus as a guide. // //------------------------------------------------------------------------------ unit InterRecv; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} //none {Project} PacketTypes, {3rd Party} IdContext ; Procedure RecvGMCommand( const AClient : TIdContext; const InBuffer : TBuffer ); Procedure RecvGMCommandReply( AClient : TIdContext; InBuffer : TBuffer ); Procedure RecvWhisper( AClient : TIdContext; InBuffer : TBuffer ); Procedure RecvWhisperReply( AClient : TIdContext; InBuffer : TBuffer ); Procedure RecvZoneWarpRequest( AClient : TIdContext; ABuffer : TBuffer ); procedure RecvZoneRequestFriend( AClient : TIdContext; ABuffer : TBuffer ); procedure RecvZoneRequestFriendReply( AClient : TIdContext; ABuffer : TBuffer ); procedure RecvZonePlayerOnlineStatus( AClient : TIdContext; ABuffer : TBuffer ); procedure RecvZonePlayerOnlineReply( AClient : TIdContext; ABuffer : TBuffer ); procedure RecvZoneNewMailNotify( AClient : TIdContext; ABuffer : TBuffer ); procedure RecvZoneCreateInstanceMapRequest( AClient : TIdContext; ABuffer : TBuffer ); procedure RecvSetAllowInstance( AClient : TIdContext; InBuffer : TBuffer ); procedure RecvInstanceCreated( AClient : TIdContext; InBuffer : TBuffer ); procedure RecvInstanceList( AClient : TIdContext; InBuffer : TBuffer ); procedure RecvDeleteInstance( AClient : TIdContext; InBuffer : TBuffer ); implementation uses {RTL/VCL} Classes, SysUtils, {Project} BufferIO, Character, Main, ZoneServerInfo, ZoneInterCommunication, InterSend, GameConstants, BeingList, MailBox {3rd Party} //none ; (*- Procedure -----------------------------------------------------------------* RecvGMCommand -------------------------------------------------------------------------------- Overview: -- Gets a GM command from an authenticated zone server N.B: See Notes/GM Command Packets for explanation. -- Revisions: -- (Format: [yyyy/mm/dd] <Author> - <Comment>) [2007/03/19] RaX - Created Header. [2007/06/01] CR - Made all parameters constant. Added try-finally construct around the use of the local TStringList, to safeguard against a memory leak if InterSendGMCommandToZones were to cause errors. [2007/08/08] Aeomin - "upgraded" GM command parsing... *-----------------------------------------------------------------------------*) Procedure RecvGMCommand( const AClient : TIdContext; const InBuffer : TBuffer ); Var GMID : LongWord; CharaID : LongWord; CommandLength : LongWord; CommandString : String; Begin //See Notes/GMCommand Packets.txt GMID := BufferReadLongWord(4, InBuffer); CharaID := BufferReadLongWord(8, InBuffer); CommandLength := BufferReadWord(12,InBuffer); CommandString := BufferReadString(14, CommandLength, InBuffer); InterParseGMCommand(AClient, GMID, CharaID, TZoneServerLink(AClient.Data).Info.ZoneID, CommandString); End; (* Proc RecvGMCommand *-----------------------------------------------------------------------------*) (*- Procedure -----------------------------------------------------------------* TInterServer.RecvGMCommandReply -------------------------------------------------------------------------------- Overview: -- Gets a gm command from an authenticated zone server -- Pre: TODO Post: TODO -- Revisions: -- (Format: [yyyy/mm/dd] <Author> - <Comment>) [2007/03/19] RaX - Created Header. [2007/05/19] CR - Altered header, indent and style changes. Use of new ClientList and ZoneServerLink property and a with clause to make code cleaner to read. [2007/12/23] Tsusai - Variable "Error" changed to "Errors", since there is a TIntList32.Error. *-----------------------------------------------------------------------------*) Procedure RecvGMCommandReply( AClient : TIdContext; InBuffer : TBuffer ); //See Notes/GM Command Packets for explanation. Var CharacterID : LongWord; ZoneID : LongWord; ZoneLink : TZoneServerLink; Index : Integer; ListClient : TIdContext; ErrCount : Word; BufferIndex : Integer; ErrLen : Word; Errors : TStringList; Begin with MainProc.InterServer do begin ErrCount := BufferReadWord(16, InBuffer); if (ErrCount > 0) then begin CharacterID := BufferReadLongWord(8, InBuffer); BufferIndex := 18; Errors := TStringList.Create; for Index := 0 to ErrCount - 1 do begin ErrLen := BufferReadWord(BufferIndex, InBuffer); inc(BufferIndex, 2); Errors.Add(BufferReadString(BufferIndex,ErrLen,InBuffer)); inc(BufferIndex, ErrLen); end; ZoneID := BufferReadLongWord(12, InBuffer); for Index := 0 to (ClientList.Count - 1) do begin ZoneLink := ZoneServerLink[Index]; if (ZoneLink <> NIL) AND (ZoneLink.Info.ZoneID = ZoneID) then begin ListClient := ClientList[Index]; InterSendGMCommandReplyToZone(ListClient, CharacterID, Errors); Break; end; end;//for Errors.Free; end; end; End; (* Func TInterServer.RecvGMCommandReply *-----------------------------------------------------------------------------*) (*- Procedure -----------------------------------------------------------------* TInterServer.RecvWhisper -------------------------------------------------------------------------------- Overview: -- Receives a whisper message from zone server and finds proper zone to direct to. If proper zone not found, an error is sent back. -- Pre: TODO Post: TODO -- Revisions: -- (Format: [yyyy/mm/dd] <Author> - <Comment>) [2007/05/03] Aeomin - Created Header. [2007/05/19] CR - Altered header, indent and style changes. Use of with, and ZoneServerLink to clarify code. *-----------------------------------------------------------------------------*) Procedure RecvWhisper( AClient : TIdContext; InBuffer : TBuffer ); Var Size : Word; FromID : LongWord; FromName : String; TargetName : String; Whisper : String; ACharacter : TCharacter; ZoneID : LongWord; Index : Integer; SentWhisper : Boolean; Begin Size := BufferReadWord(2, InBuffer); FromID := BufferReadLongWord(4, InBuffer); FromName := BufferReadString(8, 24, InBuffer); TargetName := BufferReadString(32, 24, InBuffer); Whisper := BufferReadString(56, (Size - 56), InBuffer); with TZoneServerLink(AClient.Data).DatabaseLink.Character do begin ACharacter := TCharacter.Create(Aclient); ACharacter.Name := TargetName; Load(ACharacter); end; with MainProc.InterServer do begin if (ACharacter.Map <> '') then begin with TZoneServerLink(AClient.Data).DatabaseLink.Map do begin ZoneID := GetZoneID(ACharacter.Map); end; Index := ZoneServerList.IndexOf(ZoneID); SentWhisper := False; if (Index > -1) then begin if Assigned(ZoneServerLink[Index]) AND (ZoneServerLink[Index].Info.ZoneID = ZoneID) then begin RedirectWhisperToZone( ZoneServerInfo[Index].Connection, TZoneServerLink(AClient.Data).Info.ZoneID, FromID, ACharacter.ID, FromName, Whisper ); SentWhisper := True; end; end; //This will fire if can't find any..WHY THE LIST DONT HAVE INDEXOF? if NOT SentWhisper then begin //Well..if zone is disconnected..then just say not online SendWhisperReplyToZone(AClient, FromID, WHISPER_FAILED); end; aCharacter.Free; end else begin SendWhisperReplyToZone(AClient, FromID, WHISPER_FAILED); //Target is not online end; end; End; (* Func TInterServer.RecvWhisper *-----------------------------------------------------------------------------*) (*- Procedure -----------------------------------------------------------------* TInterServer.RecvWhisperReply -------------------------------------------------------------------------------- Overview: -- Receives whisper result from zone, usually is 1 (which is character not online). -- Revisions: -- (Format: [yyyy/mm/dd] <Author> - <Comment>) [2007/05/03] Aeomin - Created Header. [2007/05/19] CR - Alterd Comment Header, indent and style changes. Used ZoneServerLink and ClientLink properties to make code cleaner to read. *-----------------------------------------------------------------------------*) Procedure RecvWhisperReply( AClient : TIdContext; InBuffer : TBuffer ); Var ZoneID : LongWord; CharID : Integer; Flag : Byte; Index : Integer; Begin ZoneID := BufferReadLongWord(2, InBuffer); CharID := BufferReadLongWord(6, InBuffer); Flag := BufferReadByte(10, InBuffer); with MainProc.InterServer do begin for Index := (ClientList.Count - 1) downto 0 do begin if Assigned(ZoneServerLink[Index]) AND (ZoneServerLink[Index].Info.ZoneID = ZoneID) then begin SendWhisperReplyToZone(ClientList[Index], CharID, Flag); Break; end; end; end; End; (* Proc TInterServer.RecvWhisperReply *-----------------------------------------------------------------------------*) (*- Procedure -----------------------------------------------------------------* TInterServer.RecvZoneWarpRequest -------------------------------------------------------------------------------- Overview: -- Receives a zone's warp request, figures out what zone the map is on, and replies. -- Revisions: -- (Format: [yyyy/mm/dd] <Author> - <Comment>) [2007/04/27] RaX - Created. [2007/05/19] CR - Altered Comment Header. Indent and style changes, with clause added to declutter a database value read. *-----------------------------------------------------------------------------*) Procedure RecvZoneWarpRequest( AClient : TIdContext; ABuffer : TBuffer ); Var CharacterID : LongWord; X : Word; Y : Word; MapNameSize : Word; MapName : String; ClientIPSize : Word; ClientIP : String; ZoneID : Integer; ZServerInfo : TZoneServerInfo; ReturnIPCard : LongWord; Zidx : integer; function GetZoneByMap:Boolean; begin with TThreadLink(AClient.Data).DatabaseLink.Map do begin ZoneID := GetZoneID(MapName); Result := True; end; end; function GetZoneByInstanceMap:Boolean; var Index : Integer; begin Result := False; Index := MainProc.InterServer.Instances.IndexOf(MapName); if (Index > -1) then begin ZoneID := TZoneServerLink(MainProc.InterServer.Instances.Objects[Index]).Info.ZoneID; Result := True; end; end; Begin CharacterID := BufferReadLongWord(4, ABuffer); X := BufferReadWord(8, ABuffer); Y := BufferReadWord(10, ABuffer); MapNameSize := BufferReadWord(12, ABuffer); MapName := BufferReadString(14, MapNameSize, ABuffer); ClientIPSize := BufferReadWord(14+MapNameSize, ABuffer); ClientIP := BufferReadString(16+MapNameSize, ClientIPSize, ABuffer); if Pos('#', MapName) > 0 then begin if NOT GetZoneByInstanceMap then GetZoneByMap; end else begin GetZoneByMap; end; ZIdx := MainProc.InterServer.ZoneServerList.IndexOf(ZoneID); //Why warp to a unknown zone..or reply to it. Kill it here. They can walk fine if Zidx > -1 then begin ZServerInfo := MainProc.InterServer.ZoneServerInfo[Zidx]; ReturnIPCard := ZServerInfo.Address(ClientIP); InterSendWarpReplyToZone( AClient, CharacterID, ReturnIPCard, ZServerInfo.Port, MapName, X, Y ); end else begin RedirectWhisperToZone( AClient, 0,0,CharacterID, 'System', Format('The map %s is currently unavailable, please try again later.',[MapName]) ); end; End; (* Proc TInterServer.RecvZoneWarpRequest *-----------------------------------------------------------------------------*) //------------------------------------------------------------------------------ //RecvZoneRequestFriend PROCEDURE //------------------------------------------------------------------------------ // What it does - // Got request from zone server //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/12/7] Aeomin - Created. //------------------------------------------------------------------------------ procedure RecvZoneRequestFriend( AClient : TIdContext; ABuffer : TBuffer ); var ReqAID,ReqID : LongWord; ReqChar : String; TargetChar : LongWord; Index : Integer; ZoneID : LongWord; begin // Get packet data. ReqAID := BufferReadLongWord(2, ABuffer); ReqID := BufferReadLongWord(6, ABuffer); TargetChar:= BufferReadLongWord(10, ABuffer); ZoneID := BufferReadLongWord(14, ABuffer); ReqChar := BufferReadString(18, NAME_LENGTH, ABuffer); with MainProc.InterServer do begin Index := ZoneServerList.IndexOf(ZoneID); if (Index > -1) then begin if Assigned(ZoneServerLink[Index]) AND (ZoneServerLink[Index].Info.ZoneID = ZoneID) then begin InterSendFriendRequest( ZoneServerInfo[Index].Connection, ReqAID, ReqID, ReqChar, TargetChar ); end; end; end; end;{RecvZoneRequestFriend} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //RecvZoneRequestFriendReply PROCEDURE //------------------------------------------------------------------------------ // What it does - // Got a reply, let's find the origin and push to there. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/12/08] Aeomin - Created. //------------------------------------------------------------------------------ procedure RecvZoneRequestFriendReply( AClient : TIdContext; ABuffer : TBuffer ); var OrigID : LongWord; AccID : LongWord; CharID : LongWord; CharName : String; Reply : Byte; ACharacter: TCharacter; Index : Integer; ZoneID : LongWord; begin OrigID := BufferReadLongWord(2, ABuffer); AccID := BufferReadLongWord(6, ABuffer); CharID := BufferReadLongWord(10, ABuffer); Reply := BufferReadByte(14, ABuffer); CharName := BufferReadString(15, NAME_LENGTH, ABuffer); with TZoneServerLink(AClient.Data).DatabaseLink.Character do begin ACharacter := TCharacter.Create(AClient); ACharacter.ID := OrigID; Load(ACharacter); end; with MainProc.InterServer do begin if (ACharacter.Map <> '') then begin with TZoneServerLink(AClient.Data).DatabaseLink.Map do begin ZoneID := GetZoneID(ACharacter.Map); end; Index := ZoneServerList.IndexOf(ZoneID); if (Index > -1) then begin if Assigned(ZoneServerLink[Index]) AND (ZoneServerLink[Index].Info.ZoneID = ZoneID) then begin InterSendFriendRequestReply( ZoneServerInfo[Index].Connection, OrigID, AccID, CharID, CharName, Reply ); end; end; ACharacter.Free; end; end; end;{RecvZoneRequestFriendReply} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //RecvZonePlayerOnlineStatus PROCEDURE //------------------------------------------------------------------------------ // What it does - // A player is online/offline, now inter server need announce to friends, // party member, guild member or whatever is that [Universal procedure] //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/12/??] - Aeomin - Created //------------------------------------------------------------------------------ procedure RecvZonePlayerOnlineStatus( AClient : TIdContext; ABuffer : TBuffer ); var AID : LongWord; CID : LongWord; Offline : Byte; FriendList : TBeingList; ACharacter : TCharacter; Index : Byte; ZoneID : Integer; ZoneIndex : Integer; begin ACharacter := TCharacter.Create(AClient); AID := BufferReadLongWord(2, ABuffer); CID := BufferReadLongWord(6, ABuffer); Offline := BufferReadByte(10, ABuffer); ACharacter.ID := CID; ACharacter.AccountID := AID; with TZoneServerLink(AClient.Data).DatabaseLink.Friend do begin FriendList := TBeingList.Create(TRUE); LoadList(FriendList, ACharacter); end; ACharacter.Free; with MainProc.InterServer do if Assigned(FriendList) then begin if FriendList.Count > 0 then begin for Index := 0 to FriendList.Count - 1 do begin ACharacter := FriendList.Items[Index] as TCharacter; // OK, we got all chars. // let's SPAM 'EM with TZoneServerLink(AClient.Data).DatabaseLink.Map do begin ZoneID := GetZoneID(ACharacter.Map); end; ZoneIndex := ZoneServerList.IndexOf(ZoneID); if ZoneIndex > -1 then begin InterSendFriendOnlineStatus( ZoneServerInfo[ZoneIndex].Connection, AID, CID, ACharacter.AccountID, ACharacter.ID, TZoneServerLink(AClient.Data).Info.ZoneID, Offline ); end; end; end; FriendList.Clear; FriendList.Free; end; end;{RecvZonePlayerOnlineStatus} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //RecvZonePlayerOnlineReply PROCEDURE //------------------------------------------------------------------------------ // What it does - // Target zone replied something, time to send back to origin zone! //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/12/??] - Aeomin - Created //------------------------------------------------------------------------------ procedure RecvZonePlayerOnlineReply( AClient : TIdContext; ABuffer : TBuffer ); var AID : LongWord; CID : LongWord; TargetID: LongWord; Offline : Byte; ZoneID : LongWord; Index : Integer; begin AID := BufferReadLongWord(2, ABuffer); CID := BufferReadLongWord(6, ABuffer); TargetID := BufferReadLongWord(10, ABuffer); OffLine := BufferReadByte(14, ABuffer); ZoneID := BufferReadLongWord(15, ABuffer); with MainProc.InterServer do begin Index := ZoneServerList.IndexOf(ZoneID); if (Index > -1) then begin InterSendFriendStatusReply( ZoneServerInfo[Index].Connection, AID, CID, TargetID, Offline ); end; end; end;{RecvZonePlayerOnlineReply} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //RecvZoneNewMailNotify PROCEDURE //------------------------------------------------------------------------------ // What it does - // Load mail then notify the player (if online) //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/08/11] Aeomin - Created //------------------------------------------------------------------------------ procedure RecvZoneNewMailNotify( AClient : TIdContext; ABuffer : TBuffer ); var MailID : LongWord; Mail : TMail; TargetChara : TCharacter; ZoneID : Integer; ZoneIndex : Integer; begin MailID := BufferReadLongWord(2, ABuffer); Mail := TZoneServerLink(AClient.Data).DatabaseLink.Mail.Get( MailID ); TargetChara := TCharacter.Create(nil); TargetChara.ID := Mail.ReceiverID; try TZoneServerLink(AClient.Data).DatabaseLink.Character.Load( TargetChara ); ZoneID := TZoneServerLink(AClient.Data).DatabaseLink.Map.GetZoneID(TargetChara.Map); if ZoneID > -1 then begin ZoneIndex := MainProc.InterServer.ZoneServerList.IndexOf(ZoneID); if ZoneIndex > -1 then begin InterSendMailNotify( TZoneServerInfo(MainProc.InterServer.ZoneServerList.Objects[ZoneIndex]).Connection, Mail.ReceiverID, Mail.ID, Mail.SenderName, Mail.Title ); end; end; finally Mail.Free; TargetChara.Free; end; end;{RecvZoneNewMailNotify} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //RecvZoneCreateInstanceMapRequest PROCEDURE //------------------------------------------------------------------------------ // What it does - // Want create an instance map? // Changes - // [2008/12/06] Aeomin - Created //------------------------------------------------------------------------------ procedure RecvZoneCreateInstanceMapRequest( AClient : TIdContext; ABuffer : TBuffer ); var Size : Word; Identifier : String; MapName : String; CharID : LongWord; ScriptID : LongWord; FullName : String; Index : Integer; ZoneServerLink : TZoneServerLink; begin Size := BufferReadWord(2, ABuffer); MapName := BufferReadString(4, 16, Abuffer); CharID := BufferReadLongWord(20, ABuffer); ScriptID := BufferReadLongWord(24, ABuffer); Identifier := BufferReadString(28, Size-28, Abuffer); FullName := Identifier + '#' + MapName; if MainProc.InterServer.InstanceZones.Count > 0 then begin Index := MainProc.InterServer.Instances.IndexOf(FullName); if Index > -1 then begin InterSendInstanceMapResult( AClient, CharID, ScriptID, 1, FullName ); end else begin //Randomly pick one Index := Random(MainProc.InterServer.InstanceZones.Count); ZoneServerLink := MainProc.InterServer.InstanceZones.Items[Index]; //TELL 'EM TELL 'EM, "WE ARE ALIVE" InterSendCreateInstance( ZoneServerLink.Info.Connection, TZoneServerLink(AClient.Data).Info.ZoneID, CharID, ScriptID, Identifier, MapName ); end; end else begin InterSendInstanceMapResult( AClient, CharID, ScriptID, 1, FullName ); end; end;{RecvZoneCreateInstanceMapRequest} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //RecvSetAllowInstance PROCEDURE //------------------------------------------------------------------------------ // What it does - // Is zone server allow instance? // // Changes - // [2008/12/06] Aeomin - Created //------------------------------------------------------------------------------ procedure RecvSetAllowInstance( AClient : TIdContext; InBuffer : TBuffer ); var Flag : Boolean; Index : Integer; begin Flag := Boolean(BufferReadByte(2, InBuffer)); if TZoneServerLink(AClient.Data).Info.AllowInstance and NOT Flag then begin //Clean up Index := MainProc.InterServer.InstanceZones.IndexOf(AClient.Data); if Index > -1 then begin MainProc.InterServer.InstanceZones.Delete(Index); end; Index := MainProc.InterServer.Instances.IndexOfObject(AClient.Data); while Index > -1 do begin MainProc.InterServer.Instances.Delete(Index); Index := MainProc.InterServer.Instances.IndexOfObject(AClient.Data); end; end else if NOT TZoneServerLink(AClient.Data).Info.AllowInstance AND Flag then begin //Add to record MainProc.InterServer.InstanceZones.Add(AClient.Data); end; TZoneServerLink(AClient.Data).Info.AllowInstance := Flag; end;{RecvSetAllowInstance} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //RecvInstanceCreated PROCEDURE //------------------------------------------------------------------------------ // What it does - // So instance created eh? let's do something about it... // // Changes - // [2008/12/07] Aeomin - Created //------------------------------------------------------------------------------ procedure RecvInstanceCreated( AClient : TIdContext; InBuffer : TBuffer ); var Size : Word; ZoneID : LongWord; CharID : LongWord; ScriptID : LongWord; FullName : String; Index : Integer; begin Size := BufferReadWord(2, InBuffer); ZoneID := BufferReadLongWord(4, InBuffer); CharID := BufferReadLongWord(8, InBuffer); ScriptID := BufferReadLongWord(12, InBuffer); FullName := BufferReadString(16, Size - 16, InBuffer); with MainProc.InterServer do begin Index := ZoneServerList.IndexOf(ZoneID); if (Index > -1) then begin if Assigned(ZoneServerLink[Index]) AND (ZoneServerLink[Index].Info.ZoneID = ZoneID) then begin Instances.AddObject(FullName,AClient.Data); InterSendInstanceMapResult( ZoneServerInfo[Index].Connection, CharID, ScriptID, 0, FullName ); end; end; end; end;{RecvInstanceCreated} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //RecvInstanceList PROCEDURE //------------------------------------------------------------------------------ // What it does - // Instance list, this should NOT commonly occur! // // Changes - // [2008/12/09] Aeomin - Created //------------------------------------------------------------------------------ procedure RecvInstanceList( AClient : TIdContext; InBuffer : TBuffer ); var Count : Byte; Index : Byte; OffSet : Word; NameLen : Byte; Name : String; begin Count := BufferReadByte(4, InBuffer); OffSet := 5; for Index := 1 to Count do begin NameLen := BufferReadByte(OffSet, InBuffer); Name := BufferReadString(OffSet+1,NameLen,InBuffer); Inc(OffSet, NameLen + 1 ); MainProc.InterServer.Instances.AddObject(Name,AClient.Data); end; end;{RecvInstanceList} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //RecvDeleteInstance PROCEDURE //------------------------------------------------------------------------------ // What it does - // Delete instance. // // Changes - // [2009/04/17] Aeomin - Created //------------------------------------------------------------------------------ procedure RecvDeleteInstance( AClient : TIdContext; InBuffer : TBuffer ); var Index : Integer; NameLen : Byte; Name : String; begin NameLen := BufferReadByte(4, InBuffer); Name := BufferReadString(5,NameLen,InBuffer); Index := MainProc.InterServer.Instances.IndexOf(Name); if Index > -1 then begin MainProc.InterServer.Instances.Delete(Index); end; end;{RecvDeleteInstance} //------------------------------------------------------------------------------ end.
unit core; {$mode objfpc} {$H+} {$codepage UTF8} // Ядро интерепретатора языка программирования Валентина interface uses {$IFNDEF WINDOWS} cwstring, {$ENDIF}lazutf8, lazutf8classes, Classes, SysUtils, parser, storage; // Константы для хранения внешнезависимой информации Const DialectPath='dct/main.dct'; // Парсер type TPar=record Parser: TParse; // Парсер NameLang: UnicodeString; // Имя файла с описанием языковых конструкций end; //////////////////////////////////////////////////////////////////////////////////////// // Формат ошибки исходного текста программы type TErr=record SourceId: Integer; // Исходник с ошибкой Line: Integer; // Номер строки с ошибкой Id: Integer; // Код ошибки Message: UnicodeString; // Сообщение об ошибке Param: UnicodeString; // Дополнительная служебная информация о проблеме end; //////////////////////////////////////////////////////////////////////////////////////// // Структура промежуточного разбора секции общих параметров системы type TTempOptionSystem=record Type_system: UnicodeString; // Информация о типе системы External_Systems: TStrMass; // Ссылки на внешние модули (TStrMass объявлен в Parser.pas) Flag_external_systems: Boolean; // Признак рассмотрения ссылок на внешние модули Start_Point: UnicodeString; // Функция - точка входа в программу Flag_start_point: Boolean; // Признак рассмотрения функции, точки входа в программу Constructor_system: UnicodeString; // Функция - конструктор системы Flag_constructor_system: Boolean; // Признак рассмотрения флага конструкции Flag_i18: Boolean; // Признак рассмотрения таблицы интернационализации IdSource: Integer; // Идентификатор исходника в хранилище Position: Integer; // Указатель на текущую строку в исходнике end; //////////////////////////////////////////////////////////////////////////////////////// // Описание исходных текстов type TSource=record Source: TStringList; // Исходный код Name: UnicodeString; // Обозначение в программе NameFile: UnicodeString; // Имя файла, в котором содержится исходный код программы NameLang: UnicodeString; // Имя файла с описанием языковых конструкций end; //////////////////////////////////////////////////////////////////////////////////////// // Описание виртуальной машины type TVm = class private ForbbidenSymbols2: UnicodeString; // Список запрещенных к использованию символов ForbbidenSymbols: UnicodeString; // Список запрещенных к использованию символов Storage: TStorage; // Хранилище иерархии Parser: Array of TPar; // Парсер Source: Array of TSource; // Исходные коды модулей с системами Errors: Array of TErr; // Список сообщений об ошибках // Служебные методы function SkipEmptyLines(Line: TStringList; Start: Integer): Integer; // Указывает на первую не пустую строку в тексте procedure InitStorage(); // Инцииализация хранилища систем procedure InitSource(); // Инициализация хранилища исходных текстов procedure InitParsers(); // Инциализация парсеров procedure ClearErrors(); // Очистка списка сообщений об ошибках function AddError(): Integer; // Добавить структуру ошибки в конец function GetError(Index: Integer): UnicodeString; // Упаковывает ошибку в текстовую строку procedure GenerateError(Id, Line, SourceId: Integer; Mess, Param: UnicodeString); // Генерация ошибки procedure InitOption(var Option: TTempOptionSystem); // Подготовка опций первой секции function DeclarationSystem(var Option: TTempOptionSystem): Integer; // Описание системы из внешнего модуля function ManageFirstSection(var Option: TTempOptionSystem): Integer; // Чтение параметров первой сеции описания procedure DecompositeLine(Id, LineCode: Integer; Line: UnicodeString; var Mass: TStrMass); // Разложение строки на элементы массива function CheckCyrillic(Line: UnicodeString): Integer; // Проверяет состоит ли данная строка сплошь из символов кириллицы function Parse_i18(var Option: TTempOptionSystem): Integer; // Разбор и проверка секции интернационализации function CheckFirstOption(Option: TTempOptionSystem): Integer; // Проверка все ли компоненты первой секции были введены // Проверка имени системы function CheckFirstNumber(Line: UnicodeString): Integer; // Проверка, начинается ли строка с цифры function CheckForbbidenSymb(Line: UnicodeString): Integer; // Поиск в имени запрещенных символов (точку можно) function CheckForbbidenSymb2(Line: UnicodeString): Integer; // Поиск в имени запрещенных символов (точку нельзя) function FormalCheckName(Line: UnicodeString): Integer; // Формальная проверка имени системы (точку можно) function FormalCheckName2(Line: UnicodeString): Integer; // Формальная проверка имени системы (точку нельзя) // Методы по изменению внутренного состояния виртуальной машины function AddNewDeclaraionSystem(NameSystem, Module: UnicodeString): Integer; // Добавление новой системы в раздел ОПИСАНИЙ СИСТЕМ function InsertStartPoint(Name, Module, StartPoint: UnicodeString): Integer; // Вставка стартовой точки системы function InsertConstructor(Name, Module, NameConstr: UnicodeString): Integer; // Вставка конструктора системы function IncludeExternal(NameModule, NameSystem, NameExternalModule: UnicodeString): Integer; // Подключение внешнего модуля public // Служебные constructor Create; // Конструктор класса procedure Init(); // Инциализация виртуальной машины // Вспомогательные function LoadSyntax(NameFile: UnicodeString; ParserID: Integer): Integer; // Загрузка синтаксиса function LoadSourceUnit(NameFile: UnicodeString; SourceId: Integer): Integer; // Загрузка исходного текста программы procedure SmallErorrsReport(var Rep: TStringList); // Выводит краткий отчет по ошибкам function ReadSource(var Txt: TStringList; Index: Integer): Integer; // Передает исходник // Пользовательские function LoadProgram(NameFile: UnicodeString): Integer; // Загрузка исходника function GetErrorCount(): Integer; // Передает количество записей в журнале ошибок function LoadProgram(StringList: TStringList; NameSource: UnicodeString): Integer; // Загрузка исходника // Отчеты procedure ReportStorage(var Rep: TStringList); // Отчет о внутреннем состоянии хранилища систем // В разработке function Analisys(): Integer; // Разбор программы function ParseModule(Id: Integer): Integer; // Разбор конкретного модуля function ReadFirstSectionModule(Id, start: Integer; var finish: Integer): Integer; // Разбор секции настроек системы function EnterFirstOption(Option: TTempOptionSystem): Integer; // Ввод данных первой опции в описание систем end; //////////////////////////////////////////////////////////////////////////////////////// implementation // Разбор программы // NameFile - имя файла с текстом программы // 0 - Операция прошла успешно // -1 - в хода выполнения функции возникли ошибки (смотреть Errors) function TVm.Analisys(): Integer; var Msg: Integer; begin // Инцииализация Result:=-1; // Разбор главного модуля Msg:=ParseModule(0); Result:=Msg; end; //////////////////////////////////////////////////////////////////////////////////////// // Разбор конкретного модуля // Id - идентификатор загруженного исходника // 0 - Операция прошла успешно // -1 - Во время выполнения функции возникли ошибки (смотреть Errors) // -2 - Исходник с таким идентификатором не существует function TVm.ParseModule(Id: Integer): Integer; var Msg: Integer; // Сообщения об результатах выполнения функций Uk: Integer; // Указатель на текущую строку в исходном тексте begin // Инициализация Result:=-2; Uk:=0; // Проверка входящего параметра If Id>Length(Source)-1 Then Exit; Result:=-1; // Читаем первую секцию (Общие параметры) Msg:=ReadFirstSectionModule(0, uk, uk); if Msg<0 then Exit; // Читаем вторую секцию (Состав и структура системы) // Читаем третью секцию (Описание функций) end; //////////////////////////////////////////////////////////////////////////////////////// // Разбор секции настроек системы // Id - идентификатор разбираемого исходного текста // start - указатель на текущую рассматриваемую строку // finish - указатель на строку, на которой остановился разбор // 0 - Операция прошла успешно // -1 - В ходе выполнения работы возникли ошибки (смотреть в Errors) function TVm.ReadFirstSectionModule(Id, start: Integer; var finish: Integer): Integer; var uk: Integer; // Указатель на строку Msg: Integer; Option: TTempOptionSystem; // Опции, загрузки секции begin // Инициализация result:=-1; InitOption(Option); // Пропустим все пустые строки в тексте модуля uk:=SkipEmptyLines(Source[id].Source, start); // Файл состит из пустых строк? If uk<0 then Exit; // Информация о исходнике и позиции для поиска Option.IdSource:=Id; Option.Position:=uk; // Пытаемся добавить объявление системы из описания Msg:=DeclarationSystem(Option); If Msg<0 Then Exit; // На выбор, но не более одного раза! Msg:=ManageFirstSection(Option); If Msg<0 then Exit; // Есть ошибки? If getErrorCount()>0 Then Exit; // Внесем сведения, полученные при чтении секции EnterFirstOption(Option); // Указатель на последнюю строку для дальнейшего разбора finish:=Option.Position; end; //////////////////////////////////////////////////////////////////////////////////////// // Ввод данных первой опции в описание систем // Option - Опции системы // 0 - Операция прошла успешно // -1 - В ходе работы функции возникли проблемы (смотреть Errors) function TVm.EnterFirstOption(Option: TTempOptionSystem): Integer; var Msg: Integer; // Сообщения от функций begin // Создаем систему по указанному описанию Msg:=AddNewDeclaraionSystem(Option.Type_system, Source[Option.IdSource].Name); If Msg<0 Then begin // Селектор ошибки case Msg of -1: GenerateError(5, Option.IdSource, Option.Position, '[Описание системы]: Описание системы уже сущесвует', Option.Type_system); // Повторная декларация -2: GenerateError(6, Option.IdSource, Option.Position, '[Описание системы]: Некорректное имя системы', Option.Type_system); // Некорректное имя системы -3: GenerateError(7, Option.IdSource, Option.Position, '[Описание системы]: Имя системы начинается с цифры', Option.Type_system); // Имя начинается с цифры -4: GenerateError(8, Option.IdSource, Option.Position, '[Описание системы]: Требуется указать имя объявляемой системы', Option.Type_system); // Требуется указать имя системы end; // Сообщим о проблеме Result:=-1; Exit; end; // Вносим точку входа в систему Msg:=InsertStartPoint(Option.Type_system, Source[Option.IdSource].Name, Option.Start_Point); If Msg<0 Then begin // Селектор ошибки case Msg of -1: GenerateError(8, Option.IdSource, Option.Position, '[Точка входа]: Требуется указать объект', Option.Type_system); -2: GenerateError(7, Option.IdSource, Option.Position, '[Точка входа]: Имя начинается с цифры', Option.Start_Point); -3: GenerateError(7, Option.IdSource, Option.Position, '[Точка входа]: Имя содержит некорректные символы', Option.Start_Point); end; // Сообщим о проблеме Result:=-1; Exit; end; // Вносим конструктор системы Msg:=InsertConstructor(Option.Type_system, Source[Option.IdSource].Name, Option.Constructor_system); If Msg<0 Then begin // Селектор ошибки case Msg of -1: GenerateError(8, Option.IdSource, Option.Position, '[Конструктор системы]: Требуется указать объект', Option.Type_system); -2: GenerateError(7, Option.IdSource, Option.Position, '[Конструктор системы]: Имя начинается с цифры', Option.Start_Point); -3: GenerateError(7, Option.IdSource, Option.Position, '[Конструктор системы]: Имя содержит некорректные символы', Option.Start_Point); end; // Сообщим о проблеме Result:=-1; Exit; end; // Подключаем внешние модули end; //////////////////////////////////////////////////////////////////////////////////////// // Подключение внешнего модуля // Module - имя подключаемого модуля // 0 - Операция прошла успешно // -1 - Файловая ошибка function TVm.IncludeExternal(NameModule, NameSystem, NameExternalModule: UnicodeString): Integer; begin // Проверим - модуль уже загружен? if Storage.FindExtModules(NameModule, NameSystem, NameExternalModule)>-1 then begin // Уже загружен, ничего делать не надо end; // Загружаем исходник // Разбираем исходник end; //////////////////////////////////////////////////////////////////////////////////////// // Вставка конструктора системы // Name - имя описания системы // Module - модуль, где находится описание системы // StartPoint - функция, стартовая точка системы // 0 - Операция прошла успешно // -1 - Функция не указана // -2 - Имя функции начинается с цифры // -3 - Имя функции содержит недопустимые символы function TVm.InsertConstructor(Name, Module, NameConstr: UnicodeString): Integer; begin // Инициализация Result:=0; // Формальная проверка имени конструктора объявляемой системы Result:=FormalCheckName(NameConstr); If Result<0 then Exit; // Добавляем конструкто в систему Storage.Add_Constructor_In_Declaration(Module, Name, NameConstr); end; //////////////////////////////////////////////////////////////////////////////////////// // Вставка стартовой точки системы // Name - имя описания системы // Module - модуль, где находится описание системы // StartPoint - функция, стартовая точка системы // 0 - Операция прошла успешно // -1 - Функция не указана // -2 - Имя функции начинается с цифры // -3 - Имя функции содержит недопустимые символы function TVm.InsertStartPoint(Name, Module, StartPoint: UnicodeString): Integer; Begin // Инициализация Result:=0; // Формальная проверка имени стартовой функции Result:=FormalCheckName(StartPoint); If Result<0 then Exit; // Добавляем стартовую точку к системе Storage.Add_StartPoint_In_Declaration(Module, Name, StartPoint); end; //////////////////////////////////////////////////////////////////////////////////////// // Формальная проверка имени системы // ФУНКЦИЯ НЕ ПОЗВОЛЯЕТ ИСПОЛЬЗОВАТЬ СОСТАВНЫЕ ИМЕНА!!!! ТОЧКА В ИМЕНИ ЗАПРЕЩЕНА!!!! // Line - проверяемая последовательность (имя функции/системы) // 0 - Line формально синтаксически корректное имя функции/системы // -1 - Имя не задано // -2 - Начинается с цифры // -3 - Содержит недопустимые символы function TVm.FormalCheckName2(Line: UnicodeString): Integer; begin // Инициализация Result:=0; // Имя указано? If UTF8Length(Line)<1 then Result:=-1; // Имя начинается с цифры? If CheckFirstNumber(Line)<0 then Result:=-2; // Имя содержит недопустимые символы? If CheckForbbidenSymb2(Line)<0 then Result:=-3; end; //////////////////////////////////////////////////////////////////////////////////////// // Формальная проверка имени системы // ФУНКЦИЯ НЕ ПРОВЕРЯЕТ СОСТАВНОЕ ИМЯ, НЕ ИЩЕТ ТОЧКУ // Line - проверяемая последовательность (имя функции/системы) // 0 - Line формально синтаксически корректное имя функции/системы // -1 - Имя не задано // -2 - Начинается с цифры // -3 - Содержит недопустимые символы function TVm.FormalCheckName(Line: UnicodeString): Integer; begin // Инициализация Result:=0; // Имя указано? If UTF8Length(Line)<1 then Result:=-1; // Имя начинается с цифры? If CheckFirstNumber(Line)<0 then Result:=-2; // Имя содержит недопустимые символы? If CheckForbbidenSymb(Line)<0 then Result:=-3; end; //////////////////////////////////////////////////////////////////////////////////////// // Поиск в имени запрещенных символов /*-+()'". и пробел с табуляцией // ФУНКЦИЯ НЕ ДОПУСКАЕТ СОСТАВНЫХ ИМЕН!!! ТОЧКА СЧИТАЕТСЯ ЗАПРЕЩЕННЫМ СИМВОЛОМ! // Line - проверяемая последовательность (имя функции/системы) // 0 - Line не содержит запрещенных символов, все ОК // -1 - Line содержит недопустимые символы function TVm.CheckForbbidenSymb2(Line: UnicodeString): Integer; var symb: UnicodeString; count, i, position: Integer; begin // Инициализация Result:=0; // Общее количество символов в переданной строке count:=Utf8Length(Line); // Сканируем строку for i:=1 to count do begin // Получим очередной символ из юникодной строки Symb:=Utf8Copy(Line, i, 1); // Поиск символа в шаблоне с запрещенными символами position:=UTF8Pos(Symb, ForbbidenSymbols2); // Найдено среди запрещенных? If position>0 then begin // Найдены запретные символы Result:=-1; Exit; end; end; end; //////////////////////////////////////////////////////////////////////////////////////// // Поиск в имени запрещенных символов /*-+()'" и пробел с табуляцией // ФУНКЦИЯ НЕ ИЩЕТ ТОЧКУ!!!! ДОПУСКАЕТ ИСПОЛЬЗОВАНИЕ СОСТАВНЫХ ИМЕН СИСТЕМ И ФУНКЦИЙ // Line - проверяемая последовательность (имя функции/системы) // 0 - Line не содержит запрещенных символов, все ОК // -1 - Line содержит недопустимые символы function TVm.CheckForbbidenSymb(Line: UnicodeString): Integer; var symb: UnicodeString; count, i, position: Integer; begin // Инициализация Result:=0; // Общее количество символов в переданной строке count:=Utf8Length(Line); // Сканируем строку for i:=1 to count do begin // Получим очередной символ из юникодной строки Symb:=Utf8Copy(Line, i, 1); // Поиск символа в шаблоне с запрещенными символами position:=UTF8Pos(Symb, ForbbidenSymbols); // Найдено среди запрещенных? If position>0 then begin // Найдены запретные символы Result:=-1; Exit; end; end; end; //////////////////////////////////////////////////////////////////////////////////////// // Проверка, начинается ли строка с цифры // Line - проверяемая последовательность (имя функции/системы) // 0 - Line начниается не с цифры // -1 - Line начинается с цифры function TVm.CheckFirstNumber(Line: UnicodeString): Integer; var temp, symb: Unicodestring; count: Integer; begin // Инициализация Result:=0; temp:='0123456789'; // Число символов в строке Count:=UTF8Length(Line); // Символы имеются? If count<1 then Exit; // Получим первый символ строки symb:=Utf8Copy(Line, 1, 1); // Поиск среди цифр If Utf8Pos(symb, temp)>0 Then Result:=-1; end; //////////////////////////////////////////////////////////////////////////////////////// // Добавление новой системы в раздел ОПИСАНИЙ СИСТЕМ // NameSystem - имя добавляемой системы // 0 - операция прошла успешно // -1 - повторная декларация системы // -2 - имя системы не является корректным // -3 - имя начинается с цифры // -4 - имя отсутствует // Положительное число - идентификатор системы в хранилище function TVm.AddNewDeclaraionSystem(NameSystem, Module: UnicodeString): Integer; var Msg: Integer; // Сообщения от функций begin // Проверим имя системы на недопустимые символы Msg:=FormalCheckName(NameSystem); // Анализ проблем If Msg<0 Then begin // Сообщим о проблеме case Msg of -1: Result:=-4; -2: Result:=-3; -3: Result:=-2; end; Exit; end; // Пытаемся внести систему (В РАЗДЕЛ ОПИСАНИЯ!!!) Msg:=Storage.AddExternalSystem(Module, NameSystem); // Передаем полученный результат Result:=Msg; end; //////////////////////////////////////////////////////////////////////////////////////// // Отчет о внутреннем состоянии хранилища систем // Rep - список для вывода отчета procedure TVm.ReportStorage(var Rep: TStringList); begin // Обертка Storage.FullReportRoot(rep); end; //////////////////////////////////////////////////////////////////////////////////////// // Чтение параметров первой сеции описания // Id - Идентификатор исходного текста в хранилище // Position - Указатель на строку в исходном тексте // Option - структура для сохранения полученных параметров // 0 - Строка распознана успешно // -1 - Возникли проблемы, смотреть Errors function TVm.ManageFirstSection(var Option: TTempOptionSystem): Integer; var uk: Integer; Rez: TInternalConstr; full: Boolean; // Признак полного разбора секции Line: UnicodeString; // Строка для разбора begin // Инцииализация full:=False; uk:=Option.Position; // Цикл разбора секции while full=false do begin // Пропустим все пустые строки в тексте модуля uk:=SkipEmptyLines(Source[Option.IdSource].Source, uk); if uk<0 then begin // Все ОК, просто кончился модуль Break; end; // Читаем строку Line:=Source[Option.IdSource].Source.Strings[uk]; rez:=Parser[Option.IdSource].Parser.Lexer(Line); // Анализ // Перед нами подключение внешних модулей? If rez.id=3 then begin // Уже подключали? If Option.Flag_external_systems=True then begin // Ошибка - Внешние модули уже подключались GenerateError(9, Option.IdSource, uk, '[Секция Внешние модули]: Внешние модули уже объявлены ранее', rez.Param1); Inc(uk); Continue; end; // Внесем данные DecompositeLine(Option.IdSource, Uk, rez.Param1, Option.External_Systems); Option.Flag_external_systems:=True; Inc(uk); Continue; end; // Перед нами точка входа? If rez.id=5 then begin // Уже подключали? If Option.Flag_start_point=True Then begin // Сообщим об ошибке: 13 - Точка входа уже объявлена GenerateError(13, Option.IdSource, uk, '[Точка входа]: Точка входа уже объявлена', rez.Param1); Inc(uk); Continue; end; // Внесем данные о точке входа в систему Option.Start_Point:=rez.Param1; Option.Flag_start_point:=True; Inc(uk); Continue; end; // Перед нами конструктор? If rez.id=4 then begin // Уже подключали? if Option.Flag_constructor_system=True then begin // Сообщим об ошибке: 14 - Конструктор уже объявлен ранее GenerateError(14, Option.IdSource, uk, '[Начальная секция]: Конструктор уже объявлен ранее', rez.Param1); Inc(uk); Continue; end; // Внесем данные о конструкторе Option.Constructor_system:=rez.Param1; Option.Flag_constructor_system:=True; Inc(uk); Continue; end; // Перед нами секция интернационализации? If rez.id=6 then begin // Уже подключали? If Option.Flag_i18=True then begin // Сообщим об ошибке: 15 - Секция интернационализации объявлена ранее GenerateError(15, Option.IdSource, uk, '[Секция интернационализации]: Секция интернационализации объявлена ранее', rez.Param1); Inc(uk); Continue; end; // Внесем данные о секции интернационализации Option.Position:=uk; Parse_i18(Option); uk:=Option.Position; Option.Flag_i18:=True; Continue; end; // Проверим, все ли секции были рассмотрены If CheckFirstOption(Option)>-1 Then Break; // Встретилась неизвестная конструкция if (Rez.id>6) Or (Rez.id<3) Then Break; Inc(Uk); end; // Позиция для следующей секции Option.Position:=uk; Result:=0; end; //////////////////////////////////////////////////////////////////////////////////////// // Проверка все ли компоненты первой секции были введены // Option - Опции первой секции // 0 - Все секции были указаны // -1 - Не все секции были обработаны function TVm.CheckFirstOption(Option: TTempOptionSystem): Integer; var count: Integer; Begin // Инициализация Result:=-1; count:=0; // Считаем опции If Option.Flag_constructor_system=True Then Inc(Count); If Option.Flag_external_systems=True Then Inc(Count); If Option.Flag_i18=True Then Inc(Count); If Option.Flag_start_point=True Then Inc(Count); If Count=4 Then Result:=0; end; //////////////////////////////////////////////////////////////////////////////////////// // Разбор и проверка секции интернационализации // ФУНКЦИЯ НА ДАННЫЙ МОМЕНТ НИГДЕ НЕ СОХРАНЯЕТ СВЕДЕНИЯ О СЕКЦИИ ИНТЕРНАЦИОНАЛИЗАЦИИ!!!!!!!!!!!! // Option - опции для внесения информации о разборе первой секции описания системы // 0 - Операция прошла успешно // -1 - В ходе работы функции вознкла ошибка (подробности в Errors) function TVm.Parse_i18(var Option: TTempOptionSystem): Integer; var uk: Integer; point_divider: Integer; s: TSource; Line: UnicodeString; Key: UnicodeString; begin // Инциализация Result:=0; Uk:=Option.Position+1; // Разбираем код, пока не закончится модуль s:=Source[Option.IdSource]; While uk<s.Source.Count-1 do begin // Пропускаем пустые строки uk:=SkipEmptyLines(Source[Option.IdSource].Source, uk); // Модуль закончился? If uk<0 Then begin // Все отлично Break; end; // Ищем строку вида "Ключ = Значение" Line:=UTF8Trim(s.Source[uk]); // Найдем знак равно point_divider:=UTF8Pos('=', Line, 1); // Есть знак равно? If point_divider<1 then begin // Не найдено, перед нами иная конструкция Break; end; // Ключ указан? If point_divider=1 then begin // Сообщим о ошибке GenerateError(16, Option.IdSource, uk, '[Секция интернационализации]: Пропущено значение', Line); Inc(uk); Continue; end; // Получим отдельно ключ Key:=UTF8Trim(UTF8Copy(Line, 1, point_divider-1)); // Проверим соответствие ключа на русские символы If CheckCyrillic(UTF8UpperCase(Key))<0 then begin // Сообщим об ошибке 17 - Требуется правильное кириллическое обозначение GenerateError(17, Option.IdSource, uk, '[Секция интернационализации]: Требуется правильное кириллическое обозначение', Key); end; // Следующий шаг Inc(Uk); end; // Операция прошла успешно If uk>s.Source.Count-1 Then Uk:=-1; Option.Position:=Uk; If GetErrorCount()<1 then Result:=0; end; //////////////////////////////////////////////////////////////////////////////////////// // Проверяет состоит ли данная строка сплошь из символов кириллицы // Функция позволяет использовать спецзнаки и цифры // 0 - да, состоит // -1 - пусто или имеются иные символы function TVm.CheckCyrillic(Line: UnicodeString): Integer; var template, symb: UnicodeString; count, i: Integer; begin // Инициализация Result:=-1; template:='0123456789!@#$%^&_~?АБВГДЕЁЖЗИКЛМНОПРСТУФХЦЧШЩЪЬЫЭЮЯ'; // Общее количество символов count:=UTF8Length(Line); // Проверяем каждый символ for i:=1 to count do begin // Получим символ symb:=UTF8Copy(Line, i, 1); // Проверим символ If UTF8Pos(symb, template, 1)<1 then begin // Это недопустимый символ Exit; end; end; // Все символы были проверены и корректны Result:=0; end; //////////////////////////////////////////////////////////////////////////////////////// // Разложение строки на элементы массива, разложение происходит // Предыдущее содержимое массива будет удалено // Id - идентификатор парсера для обработки указанного исходника procedure TVm.DecompositeLine(Id, LineCode: Integer; Line: UnicodeString; var Mass: TStrMass); var Msg: Integer; // Сообщения от функций i, count: Integer; begin // Проведем разложение строки Msg:=Parser[Id].Parser.ParseListInLine(Line, Mass); // Анализ проблем case Msg of -1: GenerateError(10, LineCode, Id, 'Встретились два разделителя подряд', Line); -2: GenerateError(11, LineCode, Id, 'При перечислении пропущено последнее слово ', Line); -3: GenerateError(12, LineCode, Id, 'Требуется указать перечисление', Line); end; // Анализ имен добавляемых модулей // Общее число внешних модулей count:=Length(Mass); // Сканируем имена внешних модулей for i:=0 to count-1 do begin // Строгая формальная проверка имени внешнего модуля Msg:=FormalCheckName2(Mass[i]); case Msg of -1: GenerateError(8, LineCode, Id, 'Требуется указать объект', Line); -2: GenerateError(7, LineCode, Id, 'Имя модуля начинается с цифры', Mass[i]); -3: GenerateError(6, LineCode, Id, '[Добавление внешних модулей]: Некорректное имя', Mass[i]); end; end; end; //////////////////////////////////////////////////////////////////////////////////////// // Подготовка опций первой секции // Option - опции первой секции procedure TVm.InitOption(var Option: TTempOptionSystem); begin // Устанавливаем параметры по умолчанию SetLength(Option.External_Systems, 0); Option.Flag_constructor_system:=False; Option.Flag_external_systems:=False; Option.Flag_start_point:=False; Option.Flag_i18:=False; Option.Constructor_system:=''; Option.Start_Point:=''; Option.Type_system:=''; Option.IdSource:=0; Option.Position:=0; end; //////////////////////////////////////////////////////////////////////////////////////// // Описание системы из внешнего модуля // Id - Идентификатор исходного текста в хранилище // Position - Указатель на строку в исходном тексте // 0 - Строка распознана успешно // -1 - Возникли проблемы, смотреть Errors function TVm.DeclarationSystem(var Option: TTempOptionSystem): Integer; Var Msg: Integer; Rez: TInternalConstr; begin // Инцииализация Result:=-1; // Обязательно первым должно идти обозначение системы rez:=Parser[Option.IdSource].Parser.Lexer(Source[Option.IdSource].Source.Strings[Option.Position]); if rez.id<>2 then begin // Сообщение об ошибке GenerateError(4, Option.IdSource, Option.IdSource, '[Имя системы]: Первое объявление должно быть описанием типа системы', Source[Option.IdSource].Source.Strings[Option.Position]); Exit; end; // Внесем имя создаваемой системы в информацию о настройках Option.Type_system:=rez.Param1; // Операция прошла успешно Option.Position:=Option.Position+1; Result:=0; end; //////////////////////////////////////////////////////////////////////////////////////// // Генерация ошибки // Id - код ошибки // Line - Указатель на строку с ошибкой // Mess - Текстовое описание ошибки // Param - Дополнительный параметр описания // Source - Модуль-источник ошибки procedure TVm.GenerateError(Id, Line, SourceID: Integer; Mess, Param: UnicodeString); var ErrPosition: Integer; begin // Добавляем новую ошибку ErrPosition:=AddError(); // Настраиваем поля Errors[ErrPosition].Id:=ID; Errors[ErrPosition].Line:=Line; Errors[ErrPosition].Message:=Mess; Errors[ErrPosition].Param:=Param; Errors[ErrPosition].SourceId:=SourceId; end; //////////////////////////////////////////////////////////////////////////////////////// // Загрузка исходника // 0 - операция прошла успешно // -1 - во время работы возникла ошибка (смотреть в Errors) function TVm.LoadProgram(StringList: TStringList; NameSource: UnicodeString): Integer; var msg: Integer; // Сообщения из других функций uk: Integer; begin // Инициализация ClearErrors; Init(); // Загрузка основного диалекта SetLength(Parser, 1); Parser[0].Parser:=TParse.Create; msg:=LoadSyntax(DialectPath, 0); // Анализ If msg=-1 then begin // Сообщим об ошибке (Ошибка внутри структуры файла синтаксиса) Result:=-1; uk:=AddError(); Errors[uk].Id:=2; Exit; end; If msg=-2 then begin // Сообщим об ошибке (Не удалось загрузить файл синтаксиса) Result:=-1; uk:=AddError(); Errors[uk].Id:=1; Errors[uk].Param:=DialectPath; Exit; end; // Загрузка первого переданного исходного текста программы SetLength(Source, 1); Source[0].Source:=TStringList.Create; Source[0].Source.Text:= StringList.Text; Source[0].NameFile:=NameSource; // Имя исходника Source[0].Name:=ExtractFileName(NameSource); Source[0].Name:=ChangeFileExt(Source[0].Name, ''); // Операция прошла успешно Result:=0; end; //////////////////////////////////////////////////////////////////////////////////////// // Передает исходник // Txt - список строк с исходным текстом // Index - номер исходного текста // 0 - операция прошла успешно // -1 - номер исходного текста указан неверно function TVm.ReadSource(var Txt: TStringList; Index: Integer): Integer; var i, count: Integer; begin // Инициализация Result:=-1; txt.Clear; // Определим количество исходных текстов count:=Source[Index].Source.Count; // Передаем в цикле for i:=0 to count-1 do begin // Каждую строку Txt.Add(Source[Index].Source.Strings[i]); end; // Операция прошла успешно Result:=0; end; //////////////////////////////////////////////////////////////////////////////////////// // Передает количество записей в журнале ошибок function TVm.GetErrorCount(): Integer; begin // Обертка Result:=Length(Errors); end; //////////////////////////////////////////////////////////////////////////////////////// // Загрузка исходника // 0 - операция прошла успешно // -1 - во время работы возникла ошибка (смотреть в Errors) function TVm.LoadProgram(NameFile: UnicodeString): Integer; var msg: Integer; // Сообщения из других функций uk: Integer; begin // Инициализация Init(); // Загрузка основного диалекта SetLength(Parser, 1); Parser[0].Parser:=TParse.Create; msg:=LoadSyntax(DialectPath, 0); // Анализ If msg=-1 then begin // Сообщим об ошибке (Ошибка внутри структуры файла синтаксиса) Result:=-1; uk:=AddError(); Errors[uk].Id:=2; Exit; end; If msg=-2 then begin // Сообщим об ошибке (Не удалось загрузить файл синтаксиса) Result:=-1; uk:=AddError(); Errors[uk].Id:=1; Errors[uk].Param:=DialectPath; Exit; end; // Загрузка первого переданного исходного текста программы SetLength(Source, 1); msg:=LoadSourceUnit(NameFile, 0); // Анализ If msg=-2 then begin // Сообщим об ошибке (не удалось загрузить исходный файл) Result:=-1; uk:=AddError(); Errors[uk].Id:=3; Errors[uk].Param:=NameFile; Exit; end; // Информация о источнике Source[0].NameFile:=NameFile; // Операция прошла успешно Result:=0; end; //////////////////////////////////////////////////////////////////////////////////////// // Выводит краткий отчет по ошибкам // Rep - список строк для вывода отчета procedure TVm.SmallErorrsReport(var Rep: TStringList); var i, count: Integer; begin // Количество записей в журнале ошибок count:=Length(Errors); // Выводим все ошибки for i:=0 to count-1 do begin // Построчно Rep.Add(GetError(i)); end; end; //////////////////////////////////////////////////////////////////////////////////////// // Упаковывает ошибку в текстовую строку // Index - номер ошибки в журнале function TVm.GetError(Index: Integer): UnicodeString; var s: UnicodeString; begin // Инициализация Result:=''; // Исходник загружен? if Errors[Index].SourceId>Length(Source)-1 then begin s:='Не загружен'; end Else begin s:=Source[Errors[Index].SourceId].NameFile; end; // Сборка строки Result:='Исходник: '+s+' | Строка: '; Result:=Result+IntToStr(Errors[Index].Line)+' | Код ошибки: '; Result:=Result+IntToStr(Errors[Index].Id)+ #13+#10+'Сообщение: '; Result:=Result+Errors[Index].Message+#13+#10+ 'Сведения: '; Result:=Result+Errors[Index].Param+#13+#10+'======================================'; end; //////////////////////////////////////////////////////////////////////////////////////// // Добавить структуру ошибки в конец // Возвращает позицию ошибки в журнале function TVm.AddError(): Integer; var count: Integer; begin // Определим количество записей в журнале ошибок count:=Length(Errors); // Добавим запись в конец SetLength(Errors, count+1); // Вернем указатель на последнюю запись Result:=count; end; //////////////////////////////////////////////////////////////////////////////////////// // Инциализация виртуальной машины procedure TVm.Init(); begin // Хранилище систем InitStorage(); // Инцииализация исходных текстов InitSource(); // Инцииализация парсеров InitParsers(); // Список сообщений об ошибках ClearErrors(); end; //////////////////////////////////////////////////////////////////////////////////////// // Очистка списка сообщений об ошибках procedure TVm.ClearErrors(); begin // Обертка SetLength(Errors, 0); end; //////////////////////////////////////////////////////////////////////////////////////// // Инциализация парсеров procedure TVm.InitParsers(); var i, count: Integer; begin // Общее количество открытых парсеров count:=Length(Parser); // Инциализация каждого парсера for i:=0 to count-1 do begin // Освобождение каждого парсера Parser[i].Parser.Free; end; // Удаляем все парсеры Setlength(Parser, 0); end; //////////////////////////////////////////////////////////////////////////////////////// // Инициализация хранилища исходных текстов procedure TVm.InitSource(); var i, count: Integer; begin // Общее количество исходных текстов count:=Length(Source); // Инциализация каждого исходного текста for i:=0 to count-1 do begin // Очистка каждого исходника Source[i].Source.Free; end; // Удаляем все исходники SetLength(Source, 0); end; //////////////////////////////////////////////////////////////////////////////////////// // Инцииализация хранилища систем procedure TVm.InitStorage(); begin // Полная инициализация Storage.Init(); // Инфраструктура для работы виртуальной машины // Storage.AddServiceSystem(); end; //////////////////////////////////////////////////////////////////////////////////////// // Указывает на первую не пустую строку в тексте // Line - Список строк // Start - строка с которой нужно производить поиск // Возвращает указатель на не пустую строку // -1 - конец списка или непустых строк не найдено function TVm.SkipEmptyLines(Line: TStringList; Start: Integer): Integer; var i, count, x: Integer; a: UnicodeString; begin // Инициализация Result:=-1; // Количество строк в списке count:=Line.Count; // Данные указаны верно? If start>count-1 then Exit; // Сканируем поток строк for i:=start to count-1 do begin // Не пустая строка? a:=UTF8Trim(Line[i]); x:=UTF8Length(a); If x>0 then begin // Передаем информацию о первой не пустой строке Result:=i; Exit; end; end; end; //////////////////////////////////////////////////////////////////////////////////////// // Загрузка исходного текста программы // NameFile - имя файла-исходного текста программы // SourceId - идентификатор исходного текста // 0 - Операция прошла успешно // -1 - Неверно указан исходник // -2 - Файловая ошибка function TVm.LoadSourceUnit(NameFile: UnicodeString; SourceId: Integer): Integer; var count: Integer; begin // Инцииализация Result:=-1; // Проверка входящего параметра count:=Length(Source); If (SourceId<0) or (SourceId>count-1) Then begin // Сообщим об ошибке Exit; end; // Проверим иницилиазацию исходника If Source[SourceId].Source=nil then Source[SourceId].Source:=TStringList.Create; // Пытаемся загрузить данные try // Загрузка исходного текста Source[SourceId].Source.LoadFromFile(NameFile); except // Произошла ошибка загрузки файла Result:=-2; Exit; end; // Внесем информацию о имени файла Source[SourceId].NameFile:=NameFile; // Операция прошла успешно Result:=0; end; //////////////////////////////////////////////////////////////////////////////////////// // Загрузка синтаксиса // NameFile - имя файла-синтаксиса для загрузки // ParserId - идентификатор парсера // 0 - операция прошла успешно // -1 - ошибка при загрузке данных // -2 - файловая ошибка // -3 - нет такого парсера function TVm.LoadSyntax(NameFile: UnicodeString; ParserID: Integer): Integer; var count: Integer; begin // Инициализация Result:=-3; // Проверим входящий параметр count:=Length(Parser); if (ParserId<0) or (ParserId>count-1) Then Exit; // Загружаем данные из файла Result:=Parser[ParserId].Parser.LoadConstrSet(NameFile); end; //////////////////////////////////////////////////////////////////////////////////////// // Конструктор класса constructor TVm.Create; begin // Предок Inherited Create; // Создание подсистем SetLength(Parser, 1); Setlength(Source, 1); // Инициализация подсистем Storage:=TStorage.Create; Parser[0].Parser:=TParse.Create(); Source[0].Source:=TStringList.Create(); // Список запрещенных символов ForbbidenSymbols:='/*-+():''" '+#13+#10+#9; ForbbidenSymbols2:='/*-+():''" .'+#13+#10+#9; // Добавлена точка, запрет на использование составных имен end; //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // СПИСОК КОДОВ ОШИБОК, ЗАПИСЫВАЕМЫХ В ERRORS РАЗЛИЧНЫМИ ФУНКЦИЯМИ // LoadProgram - загрузка главного модуля программы // 1 - Не удалось загрузить основной диалект краткой записи main.dct - файловая ошибка // 2 - Диалект краткой записи main.dct содержит ошибки в своей структуре // 3 - Не удалось загрузить файл с исходным текстом программы // ReadFirstSectionModule - разбор секции настроек системы (самая первая секция) // 4 - Первое объявление должно быть описанием типа системы // 5 - Добавляемая система уже существует // 6 - Некорректное имя добавляемой системы // 7 - Имя начинается с цифры // 8 - Имя системы не задано // 9 - Внешние модули уже объявлены // 10 - Два разделителя подряд // 11 - При перечислении пропущено последнее слово // 12 - Требуется указать перечисление // 13 - Точка входа уже объявлена // 14 - Конструктор уже объявлен ранее // 15 - Секция интернационализации объявлена ранее // 16 - Пропущено значение // 17 - Требуется правильное кириллическое обозначение end.
unit ConsoleOoutput; interface uses Winapi.Windows, System.SysUtils, Vcl.Controls, Vcl.Forms; function GetDosOutput(const CommandLine, Directory: string): string; implementation function GetDosOutput(const CommandLine, Directory: string): string; var SA: TSecurityAttributes; SI: TStartupInfo; PI: TProcessInformation; StdOutPipeRead, StdOutPipeWrite: THandle; WasOK: Boolean; Buffer: array[0..255] of AnsiChar; BytesRead: Cardinal; WorkDir, Line: string; begin with SA do begin nLength := SizeOf(SA); bInheritHandle := True; lpSecurityDescriptor := nil; end; // созда¸м пайп для перенаправления стандартного вывода CreatePipe(StdOutPipeRead, // дескриптор чтения StdOutPipeWrite, // дескриптор записи @SA, // аттрибуты безопасности 0 // количество байт принятых для пайпа - 0 по умолчанию ); try // Созда¸м дочерний процесс, используя StdOutPipeWrite в качестве стандартного вывода, // а так же проверяем, чтобы он не показывался на экране. with SI do begin FillChar(SI, SizeOf(SI), 0); cb := SizeOf(SI); dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; wShowWindow := SW_HIDE; hStdInput := GetStdHandle(STD_INPUT_HANDLE); // стандартный ввод не перенаправляем hStdOutput := StdOutPipeWrite; hStdError := StdOutPipeWrite; end; // Запускаем компилятор из командной строки WorkDir := ExtractFilePath(Directory); WasOK := CreateProcess(nil, PChar(CommandLine), nil, nil, True, 0, nil, PChar(WorkDir), SI, PI); // Теперь, когда дескриптор получен, для безопасности закрываем запись. // Нам не нужно, чтобы произошло случайное чтение или запись. CloseHandle(StdOutPipeWrite); // если процесс может быть создан, то дескриптор, это его вывод if not WasOK then raise Exception.Create('Could not execute command line!') else try // получаем весь вывод до тех пор, пока DOS-приложение не будет завершено Line := ''; repeat // читаем блок символов (могут содержать возвраты каретки и переводы строки) WasOK := ReadFile(StdOutPipeRead, Buffer, 1, BytesRead, nil); // есть ли что-нибудь ещ¸ для чтения? if BytesRead > 0 then begin // завершаем буфер PChar-ом Buffer[BytesRead] := #0; // добавляем буфер в общий вывод Line := Buffer; Write(Line); end; until not WasOK or (BytesRead = 0); // жд¸м, пока завершится консольное приложение WaitForSingleObject(PI.hProcess, INFINITE); finally // Закрываем все оставшиеся дескрипторы CloseHandle(PI.hThread); CloseHandle(PI.hProcess); end; finally result := Line; CloseHandle(StdOutPipeRead); end; end; end.
// // Generated by JavaToPas v1.5 20171018 - 171207 //////////////////////////////////////////////////////////////////////////////// unit java.time.chrono.Chronology; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, java.time.chrono.ChronoLocalDate, java.time.chrono.Era, java.time.Duration, java.time.temporal.ChronoField, java.time.format.TextStyle, java.time.format.ResolverStyle; type JChronology = interface; JChronologyClass = interface(JObjectClass) ['{6630F24A-984F-43B2-8D36-1E74A46CCA1D}'] function &of(id : JString) : JChronology; cdecl; // (Ljava/lang/String;)Ljava/time/chrono/Chronology; A: $9 function compareTo(JChronologyparam0 : JChronology) : Integer; cdecl; // (Ljava/time/chrono/Chronology;)I A: $401 function date(Integerparam0 : Integer; Integerparam1 : Integer; Integerparam2 : Integer) : JChronoLocalDate; cdecl; overload;// (III)Ljava/time/chrono/ChronoLocalDate; A: $401 function date(JTemporalAccessorparam0 : JTemporalAccessor) : JChronoLocalDate; cdecl; overload;// (Ljava/time/temporal/TemporalAccessor;)Ljava/time/chrono/ChronoLocalDate; A: $401 function date(era : JEra; yearOfEra : Integer; month : Integer; dayOfMonth : Integer) : JChronoLocalDate; cdecl; overload;// (Ljava/time/chrono/Era;III)Ljava/time/chrono/ChronoLocalDate; A: $1 function dateEpochDay(Int64param0 : Int64) : JChronoLocalDate; cdecl; // (J)Ljava/time/chrono/ChronoLocalDate; A: $401 function dateNow : JChronoLocalDate; cdecl; overload; // ()Ljava/time/chrono/ChronoLocalDate; A: $1 function dateNow(clock : JClock) : JChronoLocalDate; cdecl; overload; // (Ljava/time/Clock;)Ljava/time/chrono/ChronoLocalDate; A: $1 function dateNow(zone : JZoneId) : JChronoLocalDate; cdecl; overload; // (Ljava/time/ZoneId;)Ljava/time/chrono/ChronoLocalDate; A: $1 function dateYearDay(Integerparam0 : Integer; Integerparam1 : Integer) : JChronoLocalDate; cdecl; overload;// (II)Ljava/time/chrono/ChronoLocalDate; A: $401 function dateYearDay(era : JEra; yearOfEra : Integer; dayOfYear : Integer) : JChronoLocalDate; cdecl; overload;// (Ljava/time/chrono/Era;II)Ljava/time/chrono/ChronoLocalDate; A: $1 function equals(JObjectparam0 : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $401 function eraOf(Integerparam0 : Integer) : JEra; cdecl; // (I)Ljava/time/chrono/Era; A: $401 function eras : JList; cdecl; // ()Ljava/util/List; A: $401 function from(temporal : JTemporalAccessor) : JChronology; cdecl; // (Ljava/time/temporal/TemporalAccessor;)Ljava/time/chrono/Chronology; A: $9 function getAvailableChronologies : JSet; cdecl; // ()Ljava/util/Set; A: $9 function getCalendarType : JString; cdecl; // ()Ljava/lang/String; A: $401 function getDisplayName(style : JTextStyle; locale : JLocale) : JString; cdecl;// (Ljava/time/format/TextStyle;Ljava/util/Locale;)Ljava/lang/String; A: $1 function getId : JString; cdecl; // ()Ljava/lang/String; A: $401 function hashCode : Integer; cdecl; // ()I A: $401 function isLeapYear(Int64param0 : Int64) : boolean; cdecl; // (J)Z A: $401 function localDateTime(temporal : JTemporalAccessor) : JChronoLocalDateTime; cdecl;// (Ljava/time/temporal/TemporalAccessor;)Ljava/time/chrono/ChronoLocalDateTime; A: $1 function ofLocale(locale : JLocale) : JChronology; cdecl; // (Ljava/util/Locale;)Ljava/time/chrono/Chronology; A: $9 function period(years : Integer; months : Integer; days : Integer) : JChronoPeriod; cdecl;// (III)Ljava/time/chrono/ChronoPeriod; A: $1 function prolepticYear(JEraparam0 : JEra; Integerparam1 : Integer) : Integer; cdecl;// (Ljava/time/chrono/Era;I)I A: $401 function range(JChronoFieldparam0 : JChronoField) : JValueRange; cdecl; // (Ljava/time/temporal/ChronoField;)Ljava/time/temporal/ValueRange; A: $401 function resolveDate(JMapparam0 : JMap; JResolverStyleparam1 : JResolverStyle) : JChronoLocalDate; cdecl;// (Ljava/util/Map;Ljava/time/format/ResolverStyle;)Ljava/time/chrono/ChronoLocalDate; A: $401 function toString : JString; cdecl; // ()Ljava/lang/String; A: $401 function zonedDateTime(instant : JInstant; zone : JZoneId) : JChronoZonedDateTime; cdecl; overload;// (Ljava/time/Instant;Ljava/time/ZoneId;)Ljava/time/chrono/ChronoZonedDateTime; A: $1 function zonedDateTime(temporal : JTemporalAccessor) : JChronoZonedDateTime; cdecl; overload;// (Ljava/time/temporal/TemporalAccessor;)Ljava/time/chrono/ChronoZonedDateTime; A: $1 end; [JavaSignature('java/time/chrono/Chronology')] JChronology = interface(JObject) ['{626FB63F-4861-41CB-AFBF-F09D05ABB1F1}'] function compareTo(JChronologyparam0 : JChronology) : Integer; cdecl; // (Ljava/time/chrono/Chronology;)I A: $401 function date(Integerparam0 : Integer; Integerparam1 : Integer; Integerparam2 : Integer) : JChronoLocalDate; cdecl; overload;// (III)Ljava/time/chrono/ChronoLocalDate; A: $401 function date(JTemporalAccessorparam0 : JTemporalAccessor) : JChronoLocalDate; cdecl; overload;// (Ljava/time/temporal/TemporalAccessor;)Ljava/time/chrono/ChronoLocalDate; A: $401 function date(era : JEra; yearOfEra : Integer; month : Integer; dayOfMonth : Integer) : JChronoLocalDate; cdecl; overload;// (Ljava/time/chrono/Era;III)Ljava/time/chrono/ChronoLocalDate; A: $1 function dateEpochDay(Int64param0 : Int64) : JChronoLocalDate; cdecl; // (J)Ljava/time/chrono/ChronoLocalDate; A: $401 function dateNow : JChronoLocalDate; cdecl; overload; // ()Ljava/time/chrono/ChronoLocalDate; A: $1 function dateNow(clock : JClock) : JChronoLocalDate; cdecl; overload; // (Ljava/time/Clock;)Ljava/time/chrono/ChronoLocalDate; A: $1 function dateNow(zone : JZoneId) : JChronoLocalDate; cdecl; overload; // (Ljava/time/ZoneId;)Ljava/time/chrono/ChronoLocalDate; A: $1 function dateYearDay(Integerparam0 : Integer; Integerparam1 : Integer) : JChronoLocalDate; cdecl; overload;// (II)Ljava/time/chrono/ChronoLocalDate; A: $401 function dateYearDay(era : JEra; yearOfEra : Integer; dayOfYear : Integer) : JChronoLocalDate; cdecl; overload;// (Ljava/time/chrono/Era;II)Ljava/time/chrono/ChronoLocalDate; A: $1 function equals(JObjectparam0 : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $401 function eraOf(Integerparam0 : Integer) : JEra; cdecl; // (I)Ljava/time/chrono/Era; A: $401 function eras : JList; cdecl; // ()Ljava/util/List; A: $401 function getCalendarType : JString; cdecl; // ()Ljava/lang/String; A: $401 function getDisplayName(style : JTextStyle; locale : JLocale) : JString; cdecl;// (Ljava/time/format/TextStyle;Ljava/util/Locale;)Ljava/lang/String; A: $1 function getId : JString; cdecl; // ()Ljava/lang/String; A: $401 function hashCode : Integer; cdecl; // ()I A: $401 function isLeapYear(Int64param0 : Int64) : boolean; cdecl; // (J)Z A: $401 function localDateTime(temporal : JTemporalAccessor) : JChronoLocalDateTime; cdecl;// (Ljava/time/temporal/TemporalAccessor;)Ljava/time/chrono/ChronoLocalDateTime; A: $1 function period(years : Integer; months : Integer; days : Integer) : JChronoPeriod; cdecl;// (III)Ljava/time/chrono/ChronoPeriod; A: $1 function prolepticYear(JEraparam0 : JEra; Integerparam1 : Integer) : Integer; cdecl;// (Ljava/time/chrono/Era;I)I A: $401 function range(JChronoFieldparam0 : JChronoField) : JValueRange; cdecl; // (Ljava/time/temporal/ChronoField;)Ljava/time/temporal/ValueRange; A: $401 function resolveDate(JMapparam0 : JMap; JResolverStyleparam1 : JResolverStyle) : JChronoLocalDate; cdecl;// (Ljava/util/Map;Ljava/time/format/ResolverStyle;)Ljava/time/chrono/ChronoLocalDate; A: $401 function toString : JString; cdecl; // ()Ljava/lang/String; A: $401 function zonedDateTime(instant : JInstant; zone : JZoneId) : JChronoZonedDateTime; cdecl; overload;// (Ljava/time/Instant;Ljava/time/ZoneId;)Ljava/time/chrono/ChronoZonedDateTime; A: $1 function zonedDateTime(temporal : JTemporalAccessor) : JChronoZonedDateTime; cdecl; overload;// (Ljava/time/temporal/TemporalAccessor;)Ljava/time/chrono/ChronoZonedDateTime; A: $1 end; TJChronology = class(TJavaGenericImport<JChronologyClass, JChronology>) end; implementation end.
namespace org.me.serviceapp; //Sample app by Brian Long (http://blong.com) { This example shows an activity interacting with a service (both ways) via intents and broadcast receivers. This file defines the main activity and its broadcast receiver. The activity invokes the service and can later tell it to stop by sending it an intent. When initially invoked, a value is passed along to the service. The activity's broadcast receiver picks up intent messages from the service when the activity is not stopped. } interface uses java.util, android.os, android.app, android.content, android.util, android.view, android.widget; type ServiceInteractionActivity = public class(Activity) private const TAG = 'SvcAppActivity'; var receiver: ActivityReceiver; var stopServiceButton: Button; public const SAMPLE_ACTIVITY_ACTION = 'SAMPLE_ACTIVITY_ACTION'; method onCreate(savedInstanceState: Bundle); override; method onDestroy; override; method onStart; override; method onStop; override; method stopServiceButtonClick(v: View); end; //Nested broadcast receiver that listens out for messages from the service ActivityReceiver nested in ServiceInteractionActivity = public class(BroadcastReceiver) private owningActivity: ServiceInteractionActivity; public constructor (theActivity: ServiceInteractionActivity); method onReceive(ctx: Context; receivedIntent: Intent); override; end; implementation method ServiceInteractionActivity.onCreate(savedInstanceState: Bundle); begin Log.i(TAG, 'Activity onCreate'); inherited; // Set our view from the "main" layout resource ContentView := R.layout.main; stopServiceButton := Button(findViewById(R.id.stopServiceButton)); if stopServiceButton <> nil then stopServiceButton.OnClickListener := @stopServiceButtonClick; receiver := new ActivityReceiver(self); end; //Make sure that if the activity dies then the service is also stopped method ServiceInteractionActivity.onDestroy; begin stopServiceButtonClick(stopServiceButton); inherited; end; //Note that if the user presses the Home button, this activity will stop, but not (necessarily) be destroyed //If they use a long press on Home to re-visit this app, the activity will start //This means we'll call startService again, despite not having stopped the service //That's ok though - there'll be just one instance of the service, //and it can decide if it needs to do anything in its onStartCommand method ServiceInteractionActivity.onStart; begin Log.i(TAG, 'Activity onStart'); //Register the activity's broadcast receiver which will pick up messages from the service var filter := new IntentFilter; filter.addAction(SampleService.SAMPLE_SERVICE_ACTION); registerReceiver(receiver, filter); //Start the service var serviceIntent := new Intent(self, typeOf(SampleService)); serviceIntent.putExtra(SampleService.ID_INT_START_VALUE, 10); startService(serviceIntent); inherited end; method ServiceInteractionActivity.onStop; begin Log.i(TAG, 'Activity onStop'); //Shut down the broadcast receiver unregisterReceiver(receiver); inherited end; //Send the service a command telling it to shut down method ServiceInteractionActivity.stopServiceButtonClick(v: View); begin var i := new Intent; i.Action := SAMPLE_ACTIVITY_ACTION; i.putExtra(SampleService.ID_INT_COMMAND, SampleService.CMD_STOP_SERVICE); sendBroadcast(i) end; constructor ServiceInteractionActivity.ActivityReceiver(theActivity: ServiceInteractionActivity); begin inherited constructor; owningActivity := theActivity; end; //Receive messages from the service and display a toast describing the passed information method ServiceInteractionActivity.ActivityReceiver.onReceive(ctx: Context; receivedIntent: Intent); begin var iteration := receivedIntent.getIntExtra(SampleService.ID_INT_ITERATION, 0); var calculatedValue := receivedIntent.getIntExtra(SampleService.ID_INT_CALCULATED_VALUE, 0); Toast.makeText(owningActivity, 'Received call ' + String.valueOf(iteration) + ' from service'#10 + 'with calculated value ' + String.valueOf(calculatedValue), Toast.LENGTH_SHORT).show end; end.
unit UnitListarDispositivos; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ImgList, ExtCtrls, UnitPrincipal; type TFormListarDispositivos = class(TForm) tvDevices: TTreeView; lvAdvancedInfo: TListView; Splitter1: TSplitter; ilDevices: TImageList; StatusBar1: TStatusBar; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure lvAdvancedInfoCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); procedure tvDevicesCompare(Sender: TObject; Node1, Node2: TTreeNode; Data: Integer; var Compare: Integer); procedure tvDevicesChange(Sender: TObject; Node: TTreeNode); private { Private declarations } Servidor: PConexao; procedure AtualizarStrings; procedure ListarTodosDispositivos(Lista: string); procedure ListarDispositivosExtras(TempStr: string); procedure InitImageList; procedure ReleaseImageList; function GetDeviceImageIndex(DeviceGUID: TGUID): Integer; public { Public declarations } procedure OnRead(Recebido: String; ConAux: PConexao); overload; constructor Create(aOwner: TComponent; ConAux: PConexao);overload; end; var FormListarDispositivos: TFormListarDispositivos; implementation {$R *.dfm} uses UnitComandos, ListarDispositivos, SetupAPI, UnitStrings, UnitConexao; constructor TFormListarDispositivos.Create(aOwner: TComponent; ConAux: PConexao); begin inherited Create(aOwner); Servidor := ConAux; end; procedure TFormListarDispositivos.OnRead(Recebido: String; ConAux: PConexao); var DeviceClassesCount, DevicesCount: string; begin if copy(recebido, 1, pos('|', recebido) - 1) = LISTADEDISPOSITIVOSPRONTA then begin delete(recebido, 1, pos('|', recebido)); DeviceClassesCount := copy(recebido, 1, pos('|', recebido) - 1); delete(recebido, 1, pos('|', recebido)); DevicesCount := copy(recebido, 1, pos('|', recebido) - 1); delete(recebido, 1, pos('|', recebido)); ListarTodosDispositivos(recebido); StatusBar1.Panels[0].Text := traduzidos[234] + ': ' + DeviceClassesCount; StatusBar1.Panels[1].Text := traduzidos[235] + ': ' + DevicesCount; tvDevices.Enabled := true; end else if copy(recebido, 1, pos('|', recebido) - 1) = LISTADEDISPOSITIVOSEXTRASPRONTA then begin delete(recebido, 1, pos('|', recebido)); ListarDispositivosExtras(recebido); tvDevices.Enabled := true; end else end; procedure TFormListarDispositivos.AtualizarStrings; begin lvAdvancedInfo.Columns.Items[0].Caption := traduzidos[231]; lvAdvancedInfo.Columns.Items[1].Caption := traduzidos[232]; end; procedure TFormListarDispositivos.ListarTodosDispositivos(Lista: string); var dwIndex: DWORD; DeviceInfoData: SP_DEVINFO_DATA; DeviceName, DeviceClassName: String; tvRoot: TTreeNode; ClassGUID: TGUID; DeviceClassesCount, DevicesCount: Integer; tempstr: string; begin tvDevices.Items.BeginUpdate; try while length(Lista) > 2 do // tamanho #13#10 begin DeviceClassName := copy(Lista, 1, pos(Separador, Lista) - 1); delete(Lista, 1, pos(Separador, Lista) + length(Separador) - 1); tvRoot := tvDevices.Items.Add(nil, DeviceClassName); TempStr := copy(Lista, 1, pos('##' + separador, Lista) - 1); delete(Lista, 1, pos('##' + separador, Lista) + 1); delete(Lista, 1, length(Separador)); copymemory(@ClassGUID, @tempstr[1], sizeof(ClassGUID)); tvRoot.ImageIndex := GetDeviceImageIndex(ClassGUID); tvRoot.SelectedIndex := tvRoot.ImageIndex; tvRoot.StateIndex := strtoint(copy(Lista, 1, pos(Separador, Lista) - 1)); delete(Lista, 1, pos(Separador, Lista) + length(Separador) - 1); delete(Lista, 1, 2); // #13#10 while pos('@@', Lista) = 1 do begin delete(Lista, 1, 2); // '@@' DeviceName := copy(Lista, 1, pos(Separador, Lista) - 1); delete(Lista, 1, pos(Separador, Lista) + length(Separador) - 1); TempStr := copy(Lista, 1, pos('##' + separador, Lista) - 1); delete(Lista, 1, pos('##' + separador, Lista) + 1); delete(Lista, 1, length(Separador)); copymemory(@DeviceInfoData.ClassGuid, @tempstr[1], sizeof(DeviceInfoData.ClassGuid)); dwIndex := strtoint(copy(Lista, 1, pos(Separador, Lista) - 1)); delete(Lista, 1, pos(Separador, Lista) + length(Separador) - 1); delete(Lista, 1, 2); // #13#10 with tvDevices.Items.AddChild(tvRoot, DeviceName) do begin ImageIndex := GetDeviceImageIndex(DeviceInfoData.ClassGuid); SelectedIndex := ImageIndex; StateIndex := Integer(dwIndex); end; end; end; tvDevices.AlphaSort; finally tvDevices.Items.EndUpdate; end; end; procedure TFormListarDispositivos.ListarDispositivosExtras(TempStr: string); var ANode: TTreeNode; Item: TListItem; begin lvAdvancedInfo.Clear; lvAdvancedInfo.Items.EndUpdate; try while length(Tempstr) > 2 do begin Item := lvAdvancedInfo.Items.Add; Item.Caption := copy(TempStr, 1, pos(Separador, Tempstr) - 1); delete(TempStr, 1, pos(Separador, Tempstr) + length(Separador) - 1); Item.SubItems.Add(copy(TempStr, 1, pos(Separador, Tempstr) - 1)); delete(TempStr, 1, pos(Separador, Tempstr) + length(Separador) - 1); delete(TempStr, 1, 2); // #13#10 end; finally lvAdvancedInfo.Items.EndUpdate; end; end; function TFormListarDispositivos.GetDeviceImageIndex(DeviceGUID: TGUID): Integer; begin Result := -1; SetupDiGetClassImageIndex(ClassImageListData, DeviceGUID, Result); end; procedure TFormListarDispositivos.InitImageList; begin ZeroMemory(@ClassImageListData, SizeOf(TSPClassImageListData)); ClassImageListData.cbSize := SizeOf(TSPClassImageListData); if SetupDiGetClassImageList(ClassImageListData) then ilDevices.Handle := ClassImageListData.ImageList; end; procedure TFormListarDispositivos.ReleaseImageList; begin if not SetupDiDestroyClassImageList(ClassImageListData) then RaiseLastOSError; end; procedure TFormListarDispositivos.FormCreate(Sender: TObject); begin InitImageList; end; procedure TFormListarDispositivos.FormShow(Sender: TObject); begin tvDevices.Enabled := true; lvAdvancedInfo.Clear; tvDevices.Items.Clear; AtualizarStrings; StatusBar1.Panels[0].Text := Traduzidos[164]; StatusBar1.Panels[1].Text := Traduzidos[164]; sleep(10); EnviarString(Servidor.Athread, LISTDEVICES + '|', true); end; procedure TFormListarDispositivos.lvAdvancedInfoCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); begin Compare := CompareText(Item1.Caption, Item2.Caption); end; procedure TFormListarDispositivos.tvDevicesCompare(Sender: TObject; Node1, Node2: TTreeNode; Data: Integer; var Compare: Integer); begin Compare := CompareText(Node1.Text, Node2.Text); end; procedure TFormListarDispositivos.tvDevicesChange(Sender: TObject; Node: TTreeNode); var ANode: TTreeNode; begin ANode := tvDevices.Selected; if Assigned(ANode) then if ANode.StateIndex >= 0 then begin tvDevices.Enabled := false; EnviarString(Servidor.Athread, LISTEXTRADEVICES + '|' + inttostr(ANode.StateIndex) + '|', true); end; end; end.
unit Myloo.Phonetic.Interfaces; interface type IPhoneticMatching = interface function Phonetic(AText:string):string; function Similar(const AText, AOther: string): Boolean; function Compare(const AText, AOther: string): Integer; function Proc(const AText, AOther: string): Boolean; end; implementation end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Dialogs, Vcl.Imaging.jpeg, GLScene, GLVectorFileObjects, GLObjects, GLWin32Viewer, GLCadencer, GLTexture, GLVectorLists, GLVectorGeometry, GLTerrainRenderer, GLHeightData, GLFireFX, GLCoordinates, GLCrossPlatform, GLFile3ds, GLBaseClasses; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLCamera1: TGLCamera; GLDummyCube1: TGLDummyCube; GLFreeForm1: TGLFreeForm; GLLightSource1: TGLLightSource; GLCadencer1: TGLCadencer; Timer1: TTimer; GLTerrainRenderer1: TGLTerrainRenderer; GLBitmapHDS1: TGLBitmapHDS; CheckBox1: TCheckBox; procedure FormCreate(Sender: TObject); procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure GLSceneViewer1AfterRender(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure GLDummyCube1Progress(Sender: TObject; const deltaTime, newTime: Double); private public mx, my, mx2, my2: Integer; end; var Form1: TForm1; angulo: Single; Fig: TAffineVectorList; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var i: Integer; begin GLFreeForm1.LoadFromFile('.\media\dolphin.3ds'); // Guardamos el estado inicial del delfin Fig := TAffineVectorList.Create; Fig.Assign(GLFreeForm1.MeshObjects.Items[0].Vertices); // cargamos el fondo marino... GLBitmapHDS1.MaxPoolSize := 8 * 1024 * 1024; GLBitmapHDS1.Picture.LoadFromFile('.\media\terrain.bmp'); GLTerrainRenderer1.TilesPerTexture := 256 / GLTerrainRenderer1.TileSize; GLTerrainRenderer1.Material.Texture.Image.LoadFromFile('.\media\tex.jpg'); GLTerrainRenderer1.Material.Texture.Disabled := False; GLSceneViewer1.Buffer.BackgroundColor := rgb(0, 0, 160); with GLSceneViewer1.Buffer.FogEnvironment do begin FogColor.AsWinColor := rgb(0, 0, 110 { 160 } ); FogStart := -FogStart; end; end; procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mx := X; my := Y; mx2 := X; my2 := Y; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if ssLeft in Shift then begin mx2 := X; my2 := Y; end; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); const AMPLITUD_ALETAZO = 20; FRECUENCIA_DE_PATADA = 15; var j: Integer; v: TAffineVector; f: Single; begin // Permission to move around target... if ((mx <> mx2) or (my <> my2)) then begin GLCamera1.MoveAroundTarget(my - my2, mx - mx2); mx := mx2; my := my2; end; if CheckBox1.Checked then begin angulo := newTime; // Application of animation for Dolfin... for j := 0 to GLFreeForm1.MeshObjects.Items[0].Vertices.Count - 1 do with GLFreeForm1.MeshObjects.Items[0].Vertices do begin f := sin(angulo * FRECUENCIA_DE_PATADA) * (sqr(Items[j].X) / AMPLITUD_ALETAZO); v.X := 0; v.Y := 0; v.Z := f; TranslateItem(j, v); end; GLFreeForm1.StructureChanged; end; end; procedure TForm1.GLSceneViewer1AfterRender(Sender: TObject); var j: Integer; v: TAffineVector; f: Single; begin // Despues de Presentar un cuadro regresamos al delfín // a su estado inicial... GLFreeForm1.MeshObjects.Items[0].Vertices.Assign(Fig); end; procedure TForm1.FormDestroy(Sender: TObject); begin Fig.Free; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Caption := Format('%.2f FPS Dolphin animation', [GLSceneViewer1.FramesPerSecond]); GLSceneViewer1.ResetPerformanceMonitor; end; procedure TForm1.GLDummyCube1Progress(Sender: TObject; const deltaTime, newTime: Double); begin GLDummyCube1.Move(3); end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2015 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of an Embarcadero developer tools product. // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit fMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.Phys.MongoDBDataSet, FireDAC.Comp.BatchMove.DataSet, FireDAC.Comp.BatchMove, FireDAC.Comp.BatchMove.SQL, FireDAC.Phys.MongoDB, FireDAC.Phys.MongoDBDef, System.Rtti, System.JSON.Types, System.JSON.Readers, System.JSON.BSON, System.JSON.Builders, FireDAC.Phys.MongoDBWrapper, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, FireDAC.Comp.UI; type TfrmMain = class(TForm) FDConnection1: TFDConnection; FDBatchMoveSQLReader1: TFDBatchMoveSQLReader; FDBatchMove1: TFDBatchMove; FDBatchMoveDataSetWriter1: TFDBatchMoveDataSetWriter; FDConnection2: TFDConnection; Button1: TButton; DataSource1: TDataSource; DBGrid1: TDBGrid; FDMongoQuery1: TFDMongoQuery; FDGUIxWaitCursor1: TFDGUIxWaitCursor; FDPhysMongoDriverLink1: TFDPhysMongoDriverLink; FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.dfm} procedure TfrmMain.Button1Click(Sender: TObject); var sCat, sSch, sBase, sObj: string; begin FDConnection1.Connected := True; FDConnection2.Connected := True; // Get MongoDB collection name from source DB table name FDConnection1.DecodeObjectName(FDBatchMoveSQLReader1.TableName, sCat, sSch, sBase, sObj); sObj := StringReplace(sObj, ' ', '_', [rfReplaceAll]); FDMongoQuery1.Active := False; // Specify MongoDB database and collection names FDMongoQuery1.DatabaseName := 'test'; FDMongoQuery1.CollectionName := sObj; // Specify always-False MongoDB condition to avoid not needed documents fetching FDMongoQuery1.QMatch := '{"_id": ""}'; // Delete all documents from specified MongoDB collection FDMongoQuery1.ServerDeleteAll(); // Create and populate MongoDB collection FDBatchMove1.Execute; ShowMessage(Format('%d records inserted', [FDBatchMove1.InsertCount])); // Refresh MongoDB query FDMongoQuery1.Active := False; // Clear all definitions as field definitions may change FDMongoQuery1.IndexDefs.Clear; FDMongoQuery1.Indexes.Clear; FDMongoQuery1.FieldDefs.Clear; FDMongoQuery1.QMatch := ''; FDMongoQuery1.Active := True; end; end.
unit u_Main; interface uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.Imaging.jpeg, GLCrossPlatform, GLBaseClasses, GLScene, GLWin32Viewer, GLMaterial, GLKeyboard, GLObjects, GLCoordinates, GLHUDObjects, GLGeomObjects, GLFBORenderer, GLCadencer, GLRenderContextInfo, GLCustomShader, GLSLShader, GLAsyncTimer, GLSpaceText, GLSLProjectedTextures, GLProjectedTextures, GLVectorGeometry; type TForm1 = class(TForm) vp: TGLSceneViewer; GLScene1: TGLScene; matlib: TGLMaterialLibrary; GLCamera1: TGLCamera; GLHUDSprite1: TGLHUDSprite; GLTorus1: TGLTorus; GLLightSource1: TGLLightSource; GLCamera2: TGLCamera; cad: TGLCadencer; GLSLShader1: TGLSLShader; GLPlane1: TGLPlane; at: TGLAsyncTimer; fbo: TGLFBORenderer; GLCube1: TGLCube; GLCube2: TGLCube; GLSpaceText1: TGLSpaceText; texemit: TGLTextureEmitter; GLProjectedTextures1: TGLProjectedTextures; GLSphere1: TGLSphere; dc_cam: TGLDummyCube; hud_mouse: TGLHUDSprite; dc: TGLDummyCube; procedure cadProgress(Sender: TObject; const deltaTime, newTime: Double); procedure atTimer(Sender: TObject); procedure fboBeforeRender(Sender: TObject; var rci: TGLRenderContextInfo); procedure fboAfterRender(Sender: TObject; var rci: TGLRenderContextInfo); procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); procedure vpMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormCreate(Sender: TObject); public procedure newMat(obj:TGLSceneObject; m:String='' ); end; var Form1: TForm1; zoom: integer = 0; implementation {$R *.dfm} // // setup // procedure TForm1.FormCreate; var f: single; begin f := glcamera1.FocalLength; texemit.FOVy := 2020 / f - 8400 / f / f; end; // // newMat // procedure TForm1.newMat(obj:TGLSceneObject; m:String=''); begin obj.Material.LibMaterialName := m; end; // // fboAfterRender // procedure TForm1.fboAfterRender; begin newMat(glcube1); newMat(glcube2); newMat(gltorus1); newMat(glspacetext1); glplane1.Visible := true; vp.Buffer.BackgroundColor := $f0caa5; end; // // fboBeforeRender // procedure TForm1.fboBeforeRender; begin newMat(glcube1, 'glsl'); newMat(glcube2, 'glsl'); newMat(gltorus1, 'glsl'); newMat(glspacetext1, 'glsl'); glplane1.Visible := false; vp.Buffer.BackgroundColor := $ffffff; end; // // zoom // procedure TForm1.FormMouseWheel; begin zoom := WheelDelta; end; // // navigate // procedure TForm1.vpMouseDown; begin hud_mouse.Position.SetPoint(x,y,0); hud_mouse.Visible := true; end; // // cadProgress // procedure TForm1.cadProgress; var p: TPoint; begin gltorus1.Turn(deltatime * 30); dc_cam.TurnAngle := newtime * 4; texemit.PointTo(dc_cam, vectorNegate(YHmgVector)); if hud_mouse.Visible then begin with hud_mouse.Position do begin p := screentoclient(Mouse.CursorPos); glcamera2.MoveAroundTarget((y - p.Y) * deltatime, (x - p.X) * deltatime); end; if not iskeydown(vk_rbutton) then hud_mouse.Visible := false; end; glcamera2.AdjustDistanceToTarget(1 - zoom * deltatime); zoom := 0; end; // // atTimer // procedure TForm1.atTimer(Sender: TObject); begin caption := 'SimpleShadow: ' + vp.FramesPerSecondText(2); vp.ResetPerformanceMonitor; end; end.
unit Kafka.Helper; interface uses System.SysUtils, System.Classes, Kafka.Types, Kafka.Lib; type EKafkaError = class(Exception); TOnLog = procedure(const Values: TStrings) of object; TKafkaHelper = class private class var FLogStrings: TStringList; class var FOnLog: TOnLog; class procedure CheckKeyValues(const Keys, Values: TArray<String>); static; protected class procedure DoLog(const Text: String; const LogType: TKafkaLogType); public class constructor Create; class destructor Destroy; class procedure Log(const Text: String; const LogType: TKafkaLogType); // Wrappers class function NewConfiguration(const DefaultCallBacks: Boolean = True): prd_kafka_conf_t; overload; static; class function NewConfiguration(const Keys, Values: TArray<String>; const DefaultCallBacks: Boolean = True): prd_kafka_conf_t; overload; static; class procedure SetConfigurationValue(var Configuration: prd_kafka_conf_t; const Key, Value: String); static; class procedure DestroyConfiguration(const Configuration: Prd_kafka_conf_t); static; class function NewTopicConfiguration: prd_kafka_topic_conf_t; overload; static; class function NewTopicConfiguration(const Keys, Values: TArray<String>): prd_kafka_topic_conf_t; overload; static; class procedure SetTopicConfigurationValue(var TopicConfiguration: prd_kafka_topic_conf_t; const Key, Value: String); static; class procedure DestroyTopicConfiguration(const TopicConfiguration: Prd_kafka_topic_conf_t); static; class function NewProducer(const Configuration: prd_kafka_conf_t): prd_kafka_t; overload; static; class function NewProducer(const ConfigKeys, ConfigValues: TArray<String>): prd_kafka_t; overload; static; class function NewConsumer(const Configuration: prd_kafka_conf_t): prd_kafka_t; overload; static; class procedure ConsumerClose(const KafkaHandle: prd_kafka_t); static; class procedure DestroyHandle(const KafkaHandle: prd_kafka_t); static; class function NewTopic(const KafkaHandle: prd_kafka_t; const TopicName: String; const TopicConfiguration: prd_kafka_topic_conf_t = nil): prd_kafka_topic_t; class function Produce(const Topic: prd_kafka_topic_t; const Partition: Int32; const MsgFlags: Integer; const Payload: Pointer; const PayloadLength: NativeUInt; const Key: Pointer; const KeyLen: NativeUInt; const MsgOpaque: Pointer = nil): Integer; overload; class function Produce(const Topic: prd_kafka_topic_t; const Partition: Int32; const MsgFlags: Integer; const Payload: String; const Key: Pointer; const KeyLen: NativeUInt; const MsgOpaque: Pointer = nil): Integer; overload; class function Produce(const Topic: prd_kafka_topic_t; const Partition: Int32; const MsgFlags: Integer; const Payloads: TArray<String>; const Key: Pointer; const KeyLen: NativeUInt; const MsgOpaque: Pointer = nil): Integer; overload; class function Produce(const Topic: prd_kafka_topic_t; const Partition: Int32; const MsgFlags: Integer; const Payloads: TArray<Pointer>; const PayloadLengths: TArray<Integer>; const Key: Pointer; const KeyLen: NativeUInt; const MsgOpaque: Pointer = nil): Integer; overload; class procedure Flush(const KafkaHandle: prd_kafka_t; const Timeout: Integer = 1000); // Helpers class function PointerToStr(const Value: Pointer; const Len: Integer): String; static; class function IsKafkaError(const Error: rd_kafka_resp_err_t): Boolean; static; // Internal class procedure FlushLogs; class property OnLog: TOnLog read FOnLog write FOnLog; end; implementation resourcestring StrLogCallBackFac = 'Log_CallBack - fac = %s, buff = %s'; StrMessageSendResult = 'Message send result = %d'; StrErrorCallBackReaso = 'Error = %s'; StrUnableToCreateKaf = 'Unable to create Kafka Handle - %s'; StrKeysAndValuesMust = 'Keys and Values must be the same length'; StrMessageNotQueued = 'Message not Queued'; StrInvalidConfiguratio = 'Invalid configuration key'; StrInvalidTopicConfig = 'Invalid topic configuration key'; StrCriticalError = 'Critical Error: '; // Global callbacks procedure ProducerCallBackLogger(rk: prd_kafka_t; rkmessage: prd_kafka_message_t; opaque: Pointer); cdecl; begin if rkmessage <> nil then begin TKafkaHelper.Log(format(StrMessageSendResult, [Integer(rkmessage.err)]), TKafkaLogType.kltProducer); end; end; procedure LogCallBackLogger(rk: prd_kafka_t; level: integer; fac: PAnsiChar; buf: PAnsiChar); cdecl; begin TKafkaHelper.Log(format(StrLogCallBackFac, [String(fac), String(buf)]), TKafkaLogType.kltLog); end; procedure ErrorCallBackLogger(rk: prd_kafka_t; err: integer; reason: PAnsiChar; opaque: Pointer); cdecl; begin TKafkaHelper.Log(format(StrErrorCallBackReaso, [String(reason)]), kltError); end; { TKafkaHelper } class procedure TKafkaHelper.ConsumerClose(const KafkaHandle: prd_kafka_t); begin rd_kafka_consumer_close(KafkaHandle); end; class procedure TKafkaHelper.DestroyHandle(const KafkaHandle: prd_kafka_t); begin rd_kafka_destroy(KafkaHandle); end; class constructor TKafkaHelper.Create; begin FLogStrings := TStringList.Create; end; class destructor TKafkaHelper.Destroy; begin FreeAndNil(FLogStrings); end; class procedure TKafkaHelper.DoLog(const Text: String; const LogType: TKafkaLogType); begin TMonitor.Enter(TKafkaHelper.FLogStrings); try TKafkaHelper.FLogStrings.AddObject(Text, TObject(LogType)); finally TMonitor.Exit(TKafkaHelper.FLogStrings); end; end; class procedure TKafkaHelper.Flush(const KafkaHandle: prd_kafka_t; const Timeout: Integer); begin rd_kafka_flush(KafkaHandle, Timeout); end; class procedure TKafkaHelper.FlushLogs; begin TMonitor.Enter(TKafkaHelper.FLogStrings); try if Assigned(FOnLog) then begin FOnLog(TKafkaHelper.FLogStrings); end; TKafkaHelper.FLogStrings.Clear; finally TMonitor.Exit(TKafkaHelper.FLogStrings); end; end; class procedure TKafkaHelper.Log(const Text: String; const LogType: TKafkaLogType); begin DoLog(Text, LogType); end; class procedure TKafkaHelper.DestroyConfiguration(const Configuration: Prd_kafka_conf_t); begin rd_kafka_conf_destroy(Configuration); end; class procedure TKafkaHelper.DestroyTopicConfiguration(const TopicConfiguration: Prd_kafka_topic_conf_t); begin rd_kafka_topic_conf_destroy(TopicConfiguration); end; class function TKafkaHelper.NewConfiguration(const Keys: TArray<String>; const Values: TArray<String>; const DefaultCallBacks: Boolean): prd_kafka_conf_t; var i: Integer; begin CheckKeyValues(Keys, Values); Result := rd_kafka_conf_new(); for i := Low(keys) to High(Keys) do begin SetConfigurationValue( Result, Keys[i], Values[i]); end; if DefaultCallBacks then begin rd_kafka_conf_set_dr_msg_cb(Result, @ProducerCallBackLogger); rd_kafka_conf_set_log_cb(Result, @LogCallBackLogger); rd_kafka_conf_set_error_cb(Result, @ErrorCallBackLogger); end; end; class function TKafkaHelper.NewProducer(const ConfigKeys, ConfigValues: TArray<String>): prd_kafka_t; var Configuration: prd_kafka_conf_t; begin Configuration := TKafkaHelper.NewConfiguration( ConfigKeys, ConfigValues); Result := NewProducer(Configuration); end; class function TKafkaHelper.NewConsumer(const Configuration: prd_kafka_conf_t): prd_kafka_t; var ErrorStr: TKafkaErrorArray; begin Result := rd_kafka_new( RD_KAFKA_CONSUMER, Configuration, ErrorStr, Sizeof(ErrorStr)); if Result = nil then begin raise EKafkaError.CreateFmt(StrUnableToCreateKaf, [String(ErrorStr)]); end; end; class function TKafkaHelper.NewProducer(const Configuration: prd_kafka_conf_t): prd_kafka_t; var ErrorStr: TKafkaErrorArray; begin Result := rd_kafka_new( RD_KAFKA_PRODUCER, Configuration, ErrorStr, Sizeof(ErrorStr)); if Result = nil then begin raise EKafkaError.CreateFmt(StrUnableToCreateKaf, [String(ErrorStr)]); end; end; class function TKafkaHelper.NewTopic(const KafkaHandle: prd_kafka_t; const TopicName: String; const TopicConfiguration: prd_kafka_topic_conf_t): prd_kafka_topic_t; begin Result := rd_kafka_topic_new( KafkaHandle, PAnsiChar(AnsiString(TopicName)), TopicConfiguration); if Result = nil then begin raise EKafkaError.Create(String(rd_kafka_err2str(rd_kafka_last_error))); end; end; class function TKafkaHelper.NewTopicConfiguration: prd_kafka_topic_conf_t; begin Result := NewTopicConfiguration([], []); end; class procedure TKafkaHelper.CheckKeyValues(const Keys, Values: TArray<String>); begin if length(keys) <> length(values) then begin raise EKafkaError.Create(StrKeysAndValuesMust); end; end; class function TKafkaHelper.NewTopicConfiguration(const Keys, Values: TArray<String>): prd_kafka_topic_conf_t; var i: Integer; begin Result := rd_kafka_topic_conf_new; CheckKeyValues(Keys, Values); for i := Low(keys) to High(Keys) do begin SetTopicConfigurationValue( Result, Keys[i], Values[i]); end; end; class function TKafkaHelper.Produce(const Topic: prd_kafka_topic_t; const Partition: Int32; const MsgFlags: Integer; const Payloads: TArray<Pointer>; const PayloadLengths: TArray<Integer>; const Key: Pointer; const KeyLen: NativeUInt; const MsgOpaque: Pointer): Integer; var i: Integer; Msgs: TArray<rd_kafka_message_t>; Msg: rd_kafka_message_t; begin if length(Payloads) = 0 then begin Result := 0; end else begin SetLength(Msgs, length(Payloads)); for i := Low(Payloads) to High(Payloads) do begin Msg.partition := Partition; Msg.rkt := Topic; Msg.payload := Payloads[i]; Msg.len := PayloadLengths[i]; Msg.key := Key; Msg.key_len := KeyLen; Msgs[i] := Msg; end; Result := rd_kafka_produce_batch( Topic, Partition, MsgFlags, @Msgs[0], length(Payloads)); if Result <> length(Payloads) then begin raise EKafkaError.Create(StrMessageNotQueued); end; end; end; class function TKafkaHelper.Produce(const Topic: prd_kafka_topic_t; const Partition: Int32; const MsgFlags: Integer; const Payload: String; const Key: Pointer; const KeyLen: NativeUInt; const MsgOpaque: Pointer): Integer; begin Result := Produce( Topic, Partition, MsgFlags, @PAnsiChar(AnsiString(Payload))[1], Length(Payload), Key, KeyLen, MsgOpaque) end; class function TKafkaHelper.Produce(const Topic: prd_kafka_topic_t; const Partition: Int32; const MsgFlags: Integer; const Payload: Pointer; const PayloadLength: NativeUInt; const Key: Pointer; const KeyLen: NativeUInt; const MsgOpaque: Pointer): Integer; begin Result := rd_kafka_produce( Topic, Partition, MsgFlags, Payload, PayloadLength, Key, KeyLen, MsgOpaque); if Result = -1 then begin raise EKafkaError.Create(StrMessageNotQueued); end; end; class function TKafkaHelper.NewConfiguration(const DefaultCallBacks: Boolean): prd_kafka_conf_t; begin Result := NewConfiguration([], [], DefaultCallBacks); end; class procedure TKafkaHelper.SetConfigurationValue(var Configuration: prd_kafka_conf_t; const Key, Value: String); var ErrorStr: TKafkaErrorArray; begin if Value = '' then begin raise EKafkaError.Create(StrInvalidConfiguratio); end; if rd_kafka_conf_set( Configuration, PAnsiChar(AnsiString(Key)), PAnsiChar(AnsiString(Value)), ErrorStr, Sizeof(ErrorStr)) <> RD_KAFKA_CONF_OK then begin raise EKafkaError.Create(String(ErrorStr)); end; end; class procedure TKafkaHelper.SetTopicConfigurationValue(var TopicConfiguration: prd_kafka_topic_conf_t; const Key, Value: String); var ErrorStr: TKafkaErrorArray; begin if Value = '' then begin raise EKafkaError.Create(StrInvalidTopicConfig); end; if rd_kafka_topic_conf_set( TopicConfiguration, PAnsiChar(AnsiString(Key)), PAnsiChar(AnsiString(Value)), ErrorStr, Sizeof(ErrorStr)) <> RD_KAFKA_CONF_OK then begin raise EKafkaError.Create(String(ErrorStr)); end; end; { TKafkaHelper } class function TKafkaHelper.IsKafkaError(const Error: rd_kafka_resp_err_t): Boolean; begin Result := (Error <> RD_KAFKA_RESP_ERR_NO_ERROR) and (Error <> RD_KAFKA_RESP_ERR__PARTITION_EOF); end; class function TKafkaHelper.PointerToStr(const Value: Pointer; const Len: Integer): String; begin Result := copy(String(PAnsiChar(Value)), 1, len); end; class function TKafkaHelper.Produce(const Topic: prd_kafka_topic_t; const Partition: Int32; const MsgFlags: Integer; const Payloads: TArray<String>; const Key: Pointer; const KeyLen: NativeUInt; const MsgOpaque: Pointer): Integer; var PayloadPointers: TArray<Pointer>; PayloadLengths: TArray<Integer>; i: Integer; TempStr: AnsiString; begin SetLength(PayloadPointers, length(Payloads)); SetLength(PayloadLengths, length(Payloads)); for i := Low(Payloads) to High(Payloads) do begin TempStr := AnsiString(Payloads[i]); PayloadPointers[i] := @TempStr[1]; PayloadLengths[i] := length(TempStr); end; Result := Produce( Topic, Partition, MsgFlags, PayloadPointers, PayloadLengths, Key, KeyLen, MsgOpaque); end; end.
unit uRDMImport; {$WARN SYMBOL_PLATFORM OFF} interface uses Windows, Messages, SysUtils, Classes, ComServ, ComObj, VCLCom, DataBkr, DBClient, MRAppServer_TLB, StdVcl, ADODB, DB, Provider, mrConfigTable; type TRDMImport = class(TRemoteDataModule, IRDMImport) dspLookupStore: TDataSetProvider; dspLookupVendor: TDataSetProvider; dspLookupUser: TDataSetProvider; qryLookupStore: TADOQuery; qryLookupUser: TADOQuery; qryLookupVendor: TADOQuery; private FIRDMApplicationHub: IRDMApplicationHub; FSQLConnection: TADOConnection; procedure SetConnection; protected class procedure UpdateRegistry(Register: Boolean; const ClassID, ProgID: string); override; function Get_RDMApplicationHub: IRDMApplicationHub; safecall; procedure Set_RDMApplicationHub(const Value: IRDMApplicationHub); safecall; function ValidatePurchaseNum(const PurchaseNum, Vendor: WideString): WordBool; safecall; function ImportCatalogTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString): WordBool; safecall; procedure ImportPOTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString); safecall; function ValidatePOTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString; var APassed: WordBool): OleVariant; safecall; procedure ImportPersonTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString); safecall; procedure ImportInventoryTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString); safecall; function ValidateInventoryTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString; var APassed: WordBool): OleVariant; safecall; function ValidateModelsPOTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString; var APassed: WordBool): OleVariant; safecall; function ExistsPONum(const PONumber: WideString): WordBool; safecall; function InsertConfigImport(IDPessoa, ImportType: Integer; const CrossColumn: WideString; CaseCost: WordBool; var AMsgLog: WideString): WordBool; safecall; function GetConfigImport(IDPessoa, ImportType: Integer; var CrossColumn: WideString; var CaseCost: WordBool; var AmsgLog: WideString): WordBool; safecall; { Alex 03/04/2011 } function ValidateVCTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AmsgLog: WideString; var APassed: WordBool): OleVariant; safecall; procedure ImportVCTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString); safecall; end; var RDMImport: TRDMImport; RDMImportFactory: TComponentFactory; implementation uses uDMValidateInventoryTextFile, uDMValidatePOTextFile, uDMImportTextFile, uDMImportInventoryTextFile, uDMImportPersonTextFile, uDMImportPoTextFile, uDMValidateTextFile, uDMValidateVCTextFile, uDMImportVCTextFile, uDebugFunctions; {$R *.DFM} class procedure TRDMImport.UpdateRegistry(Register: Boolean; const ClassID, ProgID: string); begin if Register then begin inherited UpdateRegistry(Register, ClassID, ProgID); EnableSocketTransport(ClassID); EnableWebTransport(ClassID); end else begin DisableSocketTransport(ClassID); DisableWebTransport(ClassID); inherited UpdateRegistry(Register, ClassID, ProgID); end; end; function TRDMImport.Get_RDMApplicationHub: IRDMApplicationHub; begin Result := FIRDMApplicationHub; end; procedure TRDMImport.Set_RDMApplicationHub(const Value: IRDMApplicationHub); begin FIRDMApplicationHub := Value; FSQLConnection := TADOConnection(FIRDMApplicationHub.SQLConnection); SetConnection; end; procedure TRDMImport.SetConnection; var i: Integer; begin for i := 0 to Pred(ComponentCount) do if Components[i] is TADOQuery then TADOQuery(Components[i]).Connection := FSQLConnection; end; function TRDMImport.ValidatePurchaseNum(const PurchaseNum, Vendor: WideString): WordBool; begin with TDMValidatePOTextFile.Create(Self) do try SQLConnection := FSQLConnection; Result := NotExistsPurchaseNum(PurchaseNum,Vendor); finally Free; end; end; function TRDMImport.ImportCatalogTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString): WordBool; begin { with TDMImportCatalogTextFile.Create(Self) do try SQLConnection := FSQLConnection; CreateCatalogDB; TextFile.Data := AFile; LinkedColumns.Text := ALinkedColumns; ImpExpConfig.Text := AImportConfig; Result := Import; finally Free; end; } end; procedure TRDMImport.ImportPOTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString); begin with TDMImportPOTextFile.Create(Self) do try SQLConnection := FSQLConnection; TextFile.Data := AFile; LinkedColumns.Text := ALinkedColumns; ImpExpConfig.Text := AImportConfig; Import; AMsgLog := Log.Text; finally Free; end; end; function TRDMImport.ValidatePOTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString; var APassed: WordBool): OleVariant; begin with TDMValidatePOTextFile.Create(Self) do try SQLConnection := FSQLConnection; TextFile.Data := AFile; LinkedColumns.Text := ALinkedColumns; ImpExpConfig.Text := AImportConfig; APassed := Validate; Result := TextFile.Data; finally Free; end; end; procedure TRDMImport.ImportPersonTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString); begin with TDMImportPersonTextFile.Create(Self) do try SQLConnection := FSQLConnection; TextFile.Data := AFile; LinkedColumns.Text := ALinkedColumns; ImpExpConfig.Text := AImportConfig; Import; AMsgLog := Log.Text; finally Free; end; end; procedure TRDMImport.ImportInventoryTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString); begin with TDMImportInventoryTextFile.Create(Self) do try SQLConnection := FSQLConnection; TextFile.Data := AFile; LinkedColumns.Text := ALinkedColumns; ImpExpConfig.Text := AImportConfig; Import; AMsgLog := Log.Text; finally Free; end; end; function TRDMImport.ValidateInventoryTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString; var APassed: WordBool): OleVariant; begin with TDMValidateInventoryTextFile.Create(Self) do try SQLConnection := FSQLConnection; TextFile.Data := AFile; LinkedColumns.Text := ALinkedColumns; ImpExpConfig.Text := AImportConfig; APassed := Validate; Result := TextFile.Data; finally Free; end; end; function TRDMImport.ValidateModelsPOTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString; var APassed: WordBool): OleVariant; begin with TDMValidatePOTextFile.Create(Self) do try SQLConnection := FSQLConnection; TextFile.Data := AFile; LinkedColumns.Text := ALinkedColumns; ImpExpConfig.Text := AImportConfig; APassed := ValidateModels; Result := TextFile.Data; finally Free; end; end; function TRDMImport.ExistsPONum(const PONumber: WideString): WordBool; begin with TDMValidatePOTextFile.Create(Self) do try SQLConnection := FSQLConnection; Result := ExistsPONum(PONumber); finally Free; end; end; function TRDMImport.InsertConfigImport(IDPessoa, ImportType: Integer; const CrossColumn: WideString; CaseCost: WordBool; var AMsgLog: WideString): WordBool; begin with TDMImportTextFile.Create(Self) do try SQLConnection := FSQLConnection; LinkedColumns.Text := CrossColumn; Result := CreateConfigImport(IDPessoa, CaseCost, ImportType); AMsgLog := Log.Text; finally Free; end; end; function TRDMImport.GetConfigImport(IDPessoa, ImportType: Integer; var CrossColumn: WideString; var CaseCost: WordBool; var AmsgLog: WideString): WordBool; var ACrossColumn: WideString; ACaseCost: WordBool; begin with TDMImportTextFile.Create(Self) do try SQLConnection := FSQLConnection; Result := GetConfigImport(IDPessoa, ImportType, ACrossColumn, ACaseCost); CrossColumn := ACrossColumn; CaseCost := ACaseCost; AMsgLog := Log.Text; finally Free; end; end; function TRDMImport.ValidateVCTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AmsgLog: WideString; var APassed: WordBool): OleVariant; begin with TDMValidateVCTextFile.Create(Self) do begin try DebugToFile('On Appserver side >> ValidateVCTextFile'); SQLConnection := FSQLConnection; // debugtofile('SQLconnection = ' + FSQLConnection.ConnectionString); TextFile.Data := AFile; debugtofile('textfile.data - ok'); LinkedColumns.Text := ALinkedColumns; debugtofile('linkedcolumns - ok '); ImpExpConfig.Text := AImportConfig; debugtofile('ImpExpConfig - ok'); APassed := Validate(); debugtofile('validate - ok'); Result := TextFile.Data; finally Free; end; end; end; procedure TRDMImport.ImportVCTextFile(AFile: OleVariant; const ALinkedColumns, AImportConfig: WideString; var AMsgLog: WideString); begin with TDMImportVCTextFile.Create(Self) do try SQLConnection := FSQLConnection; TextFile.Data := AFile; LinkedColumns.Text := ALinkedColumns; ImpExpConfig.Text := AImportConfig; Import; AMsgLog := Log.Text; finally Free; end; end; initialization RDMImportFactory := TComponentFactory.Create(ComServer, TRDMImport, Class_RDMImport, ciInternal, tmApartment); end.
namespace NotificationsExtensions.TileContent; interface uses System, System.Text, BadgeContent, NotificationsExtensions, Windows.Data.Xml.Dom, Windows.UI.Notifications; type TileNotificationBase = assembly abstract class(NotificationBase) public constructor (templateName: System.String; imageCount: System.Int32; textCount: System.Int32); property Branding: TileBranding read m_Branding write set_Branding; method set_Branding(value: TileBranding); method CreateNotification: TileNotification; private var m_Branding: TileBranding := TileBranding.Logo; end; ISquareTileInternal = assembly interface method SerializeBinding(globalLang: System.String; globalBaseUri: System.String; globalBranding: TileBranding): System.String; end; TileSquareBase = assembly class(TileNotificationBase, ISquareTileInternal) public constructor (templateName: System.String; imageCount: System.Int32; textCount: System.Int32); method GetContent: System.String; override; method SerializeBinding(globalLang: System.String; globalBaseUri: System.String; globalBranding: TileBranding): System.String; end; TileWideBase = assembly class(TileNotificationBase) public constructor (templateName: System.String; imageCount: System.Int32; textCount: System.Int32); property SquareContent: ISquareTileNotificationContent read m_SquareContent write m_SquareContent; property RequireSquareContent: System.Boolean read m_RequireSquareContent write m_RequireSquareContent; method GetContent: System.String; override; private var m_SquareContent: ISquareTileNotificationContent := nil; var m_RequireSquareContent: System.Boolean := true; end; TileSquareBlock = assembly class(TileSquareBase, ITileSquareBlock) public constructor ; property TextBlock: INotificationContentText read TextFields[0]; property TextSubBlock: INotificationContentText read TextFields[1]; end; TileSquareImage = assembly class(TileSquareBase, ITileSquareImage) public constructor ; property Image: INotificationContentImage read Images[0]; end; TileSquarePeekImageAndText01 = assembly class(TileSquareBase, ITileSquarePeekImageAndText01) public constructor ; property Image: INotificationContentImage read Images[0]; property TextHeading: INotificationContentText read TextFields[0]; property TextBody1: INotificationContentText read TextFields[1]; property TextBody2: INotificationContentText read TextFields[2]; property TextBody3: INotificationContentText read TextFields[3]; end; TileSquarePeekImageAndText02 = assembly class(TileSquareBase, ITileSquarePeekImageAndText02) public constructor ; property Image: INotificationContentImage read Images[0]; property TextHeading: INotificationContentText read TextFields[0]; property TextBodyWrap: INotificationContentText read TextFields[1]; end; TileSquarePeekImageAndText03 = assembly class(TileSquareBase, ITileSquarePeekImageAndText03) public constructor ; property Image: INotificationContentImage read Images[0]; property TextBody1: INotificationContentText read TextFields[0]; property TextBody2: INotificationContentText read TextFields[1]; property TextBody3: INotificationContentText read TextFields[2]; property TextBody4: INotificationContentText read TextFields[3]; end; TileSquarePeekImageAndText04 = assembly class(TileSquareBase, ITileSquarePeekImageAndText04) public constructor ; property Image: INotificationContentImage read Images[0]; property TextBodyWrap: INotificationContentText read TextFields[0]; end; TileSquareText01 = assembly class(TileSquareBase, ITileSquareText01) public constructor ; property TextHeading: INotificationContentText read TextFields[0]; property TextBody1: INotificationContentText read TextFields[1]; property TextBody2: INotificationContentText read TextFields[2]; property TextBody3: INotificationContentText read TextFields[3]; end; TileSquareText02 = assembly class(TileSquareBase, ITileSquareText02) public constructor ; property TextHeading: INotificationContentText read TextFields[0]; property TextBodyWrap: INotificationContentText read TextFields[1]; end; TileSquareText03 = assembly class(TileSquareBase, ITileSquareText03) public constructor ; property TextBody1: INotificationContentText read TextFields[0]; property TextBody2: INotificationContentText read TextFields[1]; property TextBody3: INotificationContentText read TextFields[2]; property TextBody4: INotificationContentText read TextFields[3]; end; TileSquareText04 = assembly class(TileSquareBase, ITileSquareText04) public constructor ; property TextBodyWrap: INotificationContentText read TextFields[0]; end; TileWideBlockAndText01 = assembly class(TileWideBase, ITileWideBlockAndText01) public constructor ; property TextBody1: INotificationContentText read TextFields[0]; property TextBody2: INotificationContentText read TextFields[1]; property TextBody3: INotificationContentText read TextFields[2]; property TextBody4: INotificationContentText read TextFields[3]; property TextBlock: INotificationContentText read TextFields[4]; property TextSubBlock: INotificationContentText read TextFields[5]; end; TileWideBlockAndText02 = assembly class(TileWideBase, ITileWideBlockAndText02) public constructor ; property TextBodyWrap: INotificationContentText read TextFields[0]; property TextBlock: INotificationContentText read TextFields[1]; property TextSubBlock: INotificationContentText read TextFields[2]; end; TileWideImage = assembly class(TileWideBase, ITileWideImage) public constructor ; property Image: INotificationContentImage read Images[0]; end; TileWideImageAndText01 = assembly class(TileWideBase, ITileWideImageAndText01) public constructor ; property Image: INotificationContentImage read Images[0]; property TextCaptionWrap: INotificationContentText read TextFields[0]; end; TileWideImageAndText02 = assembly class(TileWideBase, ITileWideImageAndText02) public constructor ; property Image: INotificationContentImage read Images[0]; property TextCaption1: INotificationContentText read TextFields[0]; property TextCaption2: INotificationContentText read TextFields[1]; end; TileWideImageCollection = assembly class(TileWideBase, ITileWideImageCollection) public constructor ; property ImageMain: INotificationContentImage read Images[0]; property ImageSmallColumn1Row1: INotificationContentImage read Images[1]; property ImageSmallColumn2Row1: INotificationContentImage read Images[2]; property ImageSmallColumn1Row2: INotificationContentImage read Images[3]; property ImageSmallColumn2Row2: INotificationContentImage read Images[4]; end; TileWidePeekImage01 = assembly class(TileWideBase, ITileWidePeekImage01) public constructor ; property Image: INotificationContentImage read Images[0]; property TextHeading: INotificationContentText read TextFields[0]; property TextBodyWrap: INotificationContentText read TextFields[1]; end; TileWidePeekImage02 = assembly class(TileWideBase, ITileWidePeekImage02) public constructor ; property Image: INotificationContentImage read Images[0]; property TextHeading: INotificationContentText read TextFields[0]; property TextBody1: INotificationContentText read TextFields[1]; property TextBody2: INotificationContentText read TextFields[2]; property TextBody3: INotificationContentText read TextFields[3]; property TextBody4: INotificationContentText read TextFields[4]; end; TileWidePeekImage03 = assembly class(TileWideBase, ITileWidePeekImage03) public constructor ; property Image: INotificationContentImage read Images[0]; property TextHeadingWrap: INotificationContentText read TextFields[0]; end; TileWidePeekImage04 = assembly class(TileWideBase, ITileWidePeekImage04) public constructor ; property Image: INotificationContentImage read Images[0]; property TextBodyWrap: INotificationContentText read TextFields[0]; end; TileWidePeekImage05 = assembly class(TileWideBase, ITileWidePeekImage05) public constructor ; property ImageMain: INotificationContentImage read Images[0]; property ImageSecondary: INotificationContentImage read Images[1]; property TextHeading: INotificationContentText read TextFields[0]; property TextBodyWrap: INotificationContentText read TextFields[1]; end; TileWidePeekImage06 = assembly class(TileWideBase, ITileWidePeekImage06) public constructor ; property ImageMain: INotificationContentImage read Images[0]; property ImageSecondary: INotificationContentImage read Images[1]; property TextHeadingWrap: INotificationContentText read TextFields[0]; end; TileWidePeekImageAndText01 = assembly class(TileWideBase, ITileWidePeekImageAndText01) public constructor ; property Image: INotificationContentImage read Images[0]; property TextBodyWrap: INotificationContentText read TextFields[0]; end; TileWidePeekImageAndText02 = assembly class(TileWideBase, ITileWidePeekImageAndText02) public constructor ; property Image: INotificationContentImage read Images[0]; property TextBody1: INotificationContentText read TextFields[0]; property TextBody2: INotificationContentText read TextFields[1]; property TextBody3: INotificationContentText read TextFields[2]; property TextBody4: INotificationContentText read TextFields[3]; property TextBody5: INotificationContentText read TextFields[4]; end; TileWidePeekImageCollection01 = assembly class(TileWideBase, ITileWidePeekImageCollection01) public constructor ; property ImageMain: INotificationContentImage read Images[0]; property ImageSmallColumn1Row1: INotificationContentImage read Images[1]; property ImageSmallColumn2Row1: INotificationContentImage read Images[2]; property ImageSmallColumn1Row2: INotificationContentImage read Images[3]; property ImageSmallColumn2Row2: INotificationContentImage read Images[4]; property TextHeading: INotificationContentText read TextFields[0]; property TextBodyWrap: INotificationContentText read TextFields[1]; end; TileWidePeekImageCollection02 = assembly class(TileWideBase, ITileWidePeekImageCollection02) public constructor ; property ImageMain: INotificationContentImage read Images[0]; property ImageSmallColumn1Row1: INotificationContentImage read Images[1]; property ImageSmallColumn2Row1: INotificationContentImage read Images[2]; property ImageSmallColumn1Row2: INotificationContentImage read Images[3]; property ImageSmallColumn2Row2: INotificationContentImage read Images[4]; property TextHeading: INotificationContentText read TextFields[0]; property TextBody1: INotificationContentText read TextFields[1]; property TextBody2: INotificationContentText read TextFields[2]; property TextBody3: INotificationContentText read TextFields[3]; property TextBody4: INotificationContentText read TextFields[4]; end; TileWidePeekImageCollection03 = assembly class(TileWideBase, ITileWidePeekImageCollection03) public constructor ; property ImageMain: INotificationContentImage read Images[0]; property ImageSmallColumn1Row1: INotificationContentImage read Images[1]; property ImageSmallColumn2Row1: INotificationContentImage read Images[2]; property ImageSmallColumn1Row2: INotificationContentImage read Images[3]; property ImageSmallColumn2Row2: INotificationContentImage read Images[4]; property TextHeadingWrap: INotificationContentText read TextFields[0]; end; TileWidePeekImageCollection04 = assembly class(TileWideBase, ITileWidePeekImageCollection04) public constructor ; property ImageMain: INotificationContentImage read Images[0]; property ImageSmallColumn1Row1: INotificationContentImage read Images[1]; property ImageSmallColumn2Row1: INotificationContentImage read Images[2]; property ImageSmallColumn1Row2: INotificationContentImage read Images[3]; property ImageSmallColumn2Row2: INotificationContentImage read Images[4]; property TextBodyWrap: INotificationContentText read TextFields[0]; end; TileWidePeekImageCollection05 = assembly class(TileWideBase, ITileWidePeekImageCollection05) public constructor ; property ImageMain: INotificationContentImage read Images[0]; property ImageSmallColumn1Row1: INotificationContentImage read Images[1]; property ImageSmallColumn2Row1: INotificationContentImage read Images[2]; property ImageSmallColumn1Row2: INotificationContentImage read Images[3]; property ImageSmallColumn2Row2: INotificationContentImage read Images[4]; property ImageSecondary: INotificationContentImage read Images[5]; property TextHeading: INotificationContentText read TextFields[0]; property TextBodyWrap: INotificationContentText read TextFields[1]; end; TileWidePeekImageCollection06 = assembly class(TileWideBase, ITileWidePeekImageCollection06) public constructor ; property ImageMain: INotificationContentImage read Images[0]; property ImageSmallColumn1Row1: INotificationContentImage read Images[1]; property ImageSmallColumn2Row1: INotificationContentImage read Images[2]; property ImageSmallColumn1Row2: INotificationContentImage read Images[3]; property ImageSmallColumn2Row2: INotificationContentImage read Images[4]; property ImageSecondary: INotificationContentImage read Images[5]; property TextHeadingWrap: INotificationContentText read TextFields[0]; end; TileWideSmallImageAndText01 = assembly class(TileWideBase, ITileWideSmallImageAndText01) public constructor ; property Image: INotificationContentImage read Images[0]; property TextHeadingWrap: INotificationContentText read TextFields[0]; end; TileWideSmallImageAndText02 = assembly class(TileWideBase, ITileWideSmallImageAndText02) public constructor ; property Image: INotificationContentImage read Images[0]; property TextHeading: INotificationContentText read TextFields[0]; property TextBody1: INotificationContentText read TextFields[1]; property TextBody2: INotificationContentText read TextFields[2]; property TextBody3: INotificationContentText read TextFields[3]; property TextBody4: INotificationContentText read TextFields[4]; end; TileWideSmallImageAndText03 = assembly class(TileWideBase, ITileWideSmallImageAndText03) public constructor ; property Image: INotificationContentImage read Images[0]; property TextBodyWrap: INotificationContentText read TextFields[0]; end; TileWideSmallImageAndText04 = assembly class(TileWideBase, ITileWideSmallImageAndText04) public constructor ; property Image: INotificationContentImage read Images[0]; property TextHeading: INotificationContentText read TextFields[0]; property TextBodyWrap: INotificationContentText read TextFields[1]; end; TileWideText01 = assembly class(TileWideBase, ITileWideText01) public constructor ; property TextHeading: INotificationContentText read TextFields[0]; property TextBody1: INotificationContentText read TextFields[1]; property TextBody2: INotificationContentText read TextFields[2]; property TextBody3: INotificationContentText read TextFields[3]; property TextBody4: INotificationContentText read TextFields[4]; end; TileWideText02 = assembly class(TileWideBase, ITileWideText02) public constructor ; property TextHeading: INotificationContentText read TextFields[0]; property TextColumn1Row1: INotificationContentText read TextFields[1]; property TextColumn2Row1: INotificationContentText read TextFields[2]; property TextColumn1Row2: INotificationContentText read TextFields[3]; property TextColumn2Row2: INotificationContentText read TextFields[4]; property TextColumn1Row3: INotificationContentText read TextFields[5]; property TextColumn2Row3: INotificationContentText read TextFields[6]; property TextColumn1Row4: INotificationContentText read TextFields[7]; property TextColumn2Row4: INotificationContentText read TextFields[8]; end; TileWideText03 = assembly class(TileWideBase, ITileWideText03) public constructor ; property TextHeadingWrap: INotificationContentText read TextFields[0]; end; TileWideText04 = assembly class(TileWideBase, ITileWideText04) public constructor ; property TextBodyWrap: INotificationContentText read TextFields[0]; end; TileWideText05 = assembly class(TileWideBase, ITileWideText05) public constructor ; property TextBody1: INotificationContentText read TextFields[0]; property TextBody2: INotificationContentText read TextFields[1]; property TextBody3: INotificationContentText read TextFields[2]; property TextBody4: INotificationContentText read TextFields[3]; property TextBody5: INotificationContentText read TextFields[4]; end; TileWideText06 = assembly class(TileWideBase, ITileWideText06) public constructor ; property TextColumn1Row1: INotificationContentText read TextFields[0]; property TextColumn2Row1: INotificationContentText read TextFields[1]; property TextColumn1Row2: INotificationContentText read TextFields[2]; property TextColumn2Row2: INotificationContentText read TextFields[3]; property TextColumn1Row3: INotificationContentText read TextFields[4]; property TextColumn2Row3: INotificationContentText read TextFields[5]; property TextColumn1Row4: INotificationContentText read TextFields[6]; property TextColumn2Row4: INotificationContentText read TextFields[7]; property TextColumn1Row5: INotificationContentText read TextFields[8]; property TextColumn2Row5: INotificationContentText read TextFields[9]; end; TileWideText07 = assembly class(TileWideBase, ITileWideText07) public constructor ; property TextHeading: INotificationContentText read TextFields[0]; property TextShortColumn1Row1: INotificationContentText read TextFields[1]; property TextColumn2Row1: INotificationContentText read TextFields[2]; property TextShortColumn1Row2: INotificationContentText read TextFields[3]; property TextColumn2Row2: INotificationContentText read TextFields[4]; property TextShortColumn1Row3: INotificationContentText read TextFields[5]; property TextColumn2Row3: INotificationContentText read TextFields[6]; property TextShortColumn1Row4: INotificationContentText read TextFields[7]; property TextColumn2Row4: INotificationContentText read TextFields[8]; end; TileWideText08 = assembly class(TileWideBase, ITileWideText08) public constructor ; property TextShortColumn1Row1: INotificationContentText read TextFields[0]; property TextColumn2Row1: INotificationContentText read TextFields[1]; property TextShortColumn1Row2: INotificationContentText read TextFields[2]; property TextColumn2Row2: INotificationContentText read TextFields[3]; property TextShortColumn1Row3: INotificationContentText read TextFields[4]; property TextColumn2Row3: INotificationContentText read TextFields[5]; property TextShortColumn1Row4: INotificationContentText read TextFields[6]; property TextColumn2Row4: INotificationContentText read TextFields[7]; property TextShortColumn1Row5: INotificationContentText read TextFields[8]; property TextColumn2Row5: INotificationContentText read TextFields[9]; end; TileWideText09 = assembly class(TileWideBase, ITileWideText09) public constructor ; property TextHeading: INotificationContentText read TextFields[0]; property TextBodyWrap: INotificationContentText read TextFields[1]; end; TileWideText10 = assembly class(TileWideBase, ITileWideText10) public constructor ; property TextHeading: INotificationContentText read TextFields[0]; property TextPrefixColumn1Row1: INotificationContentText read TextFields[1]; property TextColumn2Row1: INotificationContentText read TextFields[2]; property TextPrefixColumn1Row2: INotificationContentText read TextFields[3]; property TextColumn2Row2: INotificationContentText read TextFields[4]; property TextPrefixColumn1Row3: INotificationContentText read TextFields[5]; property TextColumn2Row3: INotificationContentText read TextFields[6]; property TextPrefixColumn1Row4: INotificationContentText read TextFields[7]; property TextColumn2Row4: INotificationContentText read TextFields[8]; end; TileWideText11 = assembly class(TileWideBase, ITileWideText11) public constructor ; property TextPrefixColumn1Row1: INotificationContentText read TextFields[0]; property TextColumn2Row1: INotificationContentText read TextFields[1]; property TextPrefixColumn1Row2: INotificationContentText read TextFields[2]; property TextColumn2Row2: INotificationContentText read TextFields[3]; property TextPrefixColumn1Row3: INotificationContentText read TextFields[4]; property TextColumn2Row3: INotificationContentText read TextFields[5]; property TextPrefixColumn1Row4: INotificationContentText read TextFields[6]; property TextColumn2Row4: INotificationContentText read TextFields[7]; property TextPrefixColumn1Row5: INotificationContentText read TextFields[8]; property TextColumn2Row5: INotificationContentText read TextFields[9]; end; /// <summary> /// A factory which creates tile content objects for all of the toast template types. /// </summary> TileContentFactory = public sealed class public /// <summary> /// Creates a tile content object for the TileSquareBlock template. /// </summary> /// <returns>A tile content object for the TileSquareBlock template.</returns> class method CreateTileSquareBlock: ITileSquareBlock; /// <summary> /// Creates a tile content object for the TileSquareImage template. /// </summary> /// <returns>A tile content object for the TileSquareImage template.</returns> class method CreateTileSquareImage: ITileSquareImage; /// <summary> /// Creates a tile content object for the TileSquarePeekImageAndText01 template. /// </summary> /// <returns>A tile content object for the TileSquarePeekImageAndText01 template.</returns> class method CreateTileSquarePeekImageAndText01: ITileSquarePeekImageAndText01; /// <summary> /// Creates a tile content object for the TileSquarePeekImageAndText02 template. /// </summary> /// <returns>A tile content object for the TileSquarePeekImageAndText02 template.</returns> class method CreateTileSquarePeekImageAndText02: ITileSquarePeekImageAndText02; /// <summary> /// Creates a tile content object for the TileSquarePeekImageAndText03 template. /// </summary> /// <returns>A tile content object for the TileSquarePeekImageAndText03 template.</returns> class method CreateTileSquarePeekImageAndText03: ITileSquarePeekImageAndText03; /// <summary> /// Creates a tile content object for the TileSquarePeekImageAndText04 template. /// </summary> /// <returns>A tile content object for the TileSquarePeekImageAndText04 template.</returns> class method CreateTileSquarePeekImageAndText04: ITileSquarePeekImageAndText04; /// <summary> /// Creates a tile content object for the TileSquareText01 template. /// </summary> /// <returns>A tile content object for the TileSquareText01 template.</returns> class method CreateTileSquareText01: ITileSquareText01; /// <summary> /// Creates a tile content object for the TileSquareText02 template. /// </summary> /// <returns>A tile content object for the TileSquareText02 template.</returns> class method CreateTileSquareText02: ITileSquareText02; /// <summary> /// Creates a tile content object for the TileSquareText03 template. /// </summary> /// <returns>A tile content object for the TileSquareText03 template.</returns> class method CreateTileSquareText03: ITileSquareText03; /// <summary> /// Creates a tile content object for the TileSquareText04 template. /// </summary> /// <returns>A tile content object for the TileSquareText04 template.</returns> class method CreateTileSquareText04: ITileSquareText04; /// <summary> /// Creates a tile content object for the TileWideBlockAndText01 template. /// </summary> /// <returns>A tile content object for the TileWideBlockAndText01 template.</returns> class method CreateTileWideBlockAndText01: ITileWideBlockAndText01; /// <summary> /// Creates a tile content object for the TileWideBlockAndText02 template. /// </summary> /// <returns>A tile content object for the TileWideBlockAndText02 template.</returns> class method CreateTileWideBlockAndText02: ITileWideBlockAndText02; /// <summary> /// Creates a tile content object for the TileWideImage template. /// </summary> /// <returns>A tile content object for the TileWideImage template.</returns> class method CreateTileWideImage: ITileWideImage; /// <summary> /// Creates a tile content object for the TileWideImageAndText01 template. /// </summary> /// <returns>A tile content object for the TileWideImageAndText01 template.</returns> class method CreateTileWideImageAndText01: ITileWideImageAndText01; /// <summary> /// Creates a tile content object for the TileWideImageAndText02 template. /// </summary> /// <returns>A tile content object for the TileWideImageAndText02 template.</returns> class method CreateTileWideImageAndText02: ITileWideImageAndText02; /// <summary> /// Creates a tile content object for the TileWideImageCollection template. /// </summary> /// <returns>A tile content object for the TileWideImageCollection template.</returns> class method CreateTileWideImageCollection: ITileWideImageCollection; /// <summary> /// Creates a tile content object for the TileWidePeekImage01 template. /// </summary> /// <returns>A tile content object for the TileWidePeekImage01 template.</returns> class method CreateTileWidePeekImage01: ITileWidePeekImage01; /// <summary> /// Creates a tile content object for the TileWidePeekImage02 template. /// </summary> /// <returns>A tile content object for the TileWidePeekImage02 template.</returns> class method CreateTileWidePeekImage02: ITileWidePeekImage02; /// <summary> /// Creates a tile content object for the TileWidePeekImage03 template. /// </summary> /// <returns>A tile content object for the TileWidePeekImage03 template.</returns> class method CreateTileWidePeekImage03: ITileWidePeekImage03; /// <summary> /// Creates a tile content object for the TileWidePeekImage04 template. /// </summary> /// <returns>A tile content object for the TileWidePeekImage04 template.</returns> class method CreateTileWidePeekImage04: ITileWidePeekImage04; /// <summary> /// Creates a tile content object for the TileWidePeekImage05 template. /// </summary> /// <returns>A tile content object for the TileWidePeekImage05 template.</returns> class method CreateTileWidePeekImage05: ITileWidePeekImage05; /// <summary> /// Creates a tile content object for the TileWidePeekImage06 template. /// </summary> /// <returns>A tile content object for the TileWidePeekImage06 template.</returns> class method CreateTileWidePeekImage06: ITileWidePeekImage06; /// <summary> /// Creates a tile content object for the TileWidePeekImageAndText01 template. /// </summary> /// <returns>A tile content object for the TileWidePeekImageAndText01 template.</returns> class method CreateTileWidePeekImageAndText01: ITileWidePeekImageAndText01; /// <summary> /// Creates a tile content object for the TileWidePeekImageAndText02 template. /// </summary> /// <returns>A tile content object for the TileWidePeekImageAndText02 template.</returns> class method CreateTileWidePeekImageAndText02: ITileWidePeekImageAndText02; /// <summary> /// Creates a tile content object for the TileWidePeekImageCollection01 template. /// </summary> /// <returns>A tile content object for the TileWidePeekImageCollection01 template.</returns> class method CreateTileWidePeekImageCollection01: ITileWidePeekImageCollection01; /// <summary> /// Creates a tile content object for the TileWidePeekImageCollection02 template. /// </summary> /// <returns>A tile content object for the TileWidePeekImageCollection02 template.</returns> class method CreateTileWidePeekImageCollection02: ITileWidePeekImageCollection02; /// <summary> /// Creates a tile content object for the TileWidePeekImageCollection03 template. /// </summary> /// <returns>A tile content object for the TileWidePeekImageCollection03 template.</returns> class method CreateTileWidePeekImageCollection03: ITileWidePeekImageCollection03; /// <summary> /// Creates a tile content object for the TileWidePeekImageCollection04 template. /// </summary> /// <returns>A tile content object for the TileWidePeekImageCollection04 template.</returns> class method CreateTileWidePeekImageCollection04: ITileWidePeekImageCollection04; /// <summary> /// Creates a tile content object for the TileWidePeekImageCollection05 template. /// </summary> /// <returns>A tile content object for the TileWidePeekImageCollection05 template.</returns> class method CreateTileWidePeekImageCollection05: ITileWidePeekImageCollection05; /// <summary> /// Creates a tile content object for the TileWidePeekImageCollection06 template. /// </summary> /// <returns>A tile content object for the TileWidePeekImageCollection06 template.</returns> class method CreateTileWidePeekImageCollection06: ITileWidePeekImageCollection06; /// <summary> /// Creates a tile content object for the TileWideSmallImageAndText01 template. /// </summary> /// <returns>A tile content object for the TileWideSmallImageAndText01 template.</returns> class method CreateTileWideSmallImageAndText01: ITileWideSmallImageAndText01; /// <summary> /// Creates a tile content object for the TileWideSmallImageAndText02 template. /// </summary> /// <returns>A tile content object for the TileWideSmallImageAndText02 template.</returns> class method CreateTileWideSmallImageAndText02: ITileWideSmallImageAndText02; /// <summary> /// Creates a tile content object for the TileWideSmallImageAndText03 template. /// </summary> /// <returns>A tile content object for the TileWideSmallImageAndText03 template.</returns> class method CreateTileWideSmallImageAndText03: ITileWideSmallImageAndText03; /// <summary> /// Creates a tile content object for the TileWideSmallImageAndText04 template. /// </summary> /// <returns>A tile content object for the TileWideSmallImageAndText04 template.</returns> class method CreateTileWideSmallImageAndText04: ITileWideSmallImageAndText04; /// <summary> /// Creates a tile content object for the TileWideText01 template. /// </summary> /// <returns>A tile content object for the TileWideText01 template.</returns> class method CreateTileWideText01: ITileWideText01; /// <summary> /// Creates a tile content object for the TileWideText02 template. /// </summary> /// <returns>A tile content object for the TileWideText02 template.</returns> class method CreateTileWideText02: ITileWideText02; /// <summary> /// Creates a tile content object for the TileWideText03 template. /// </summary> /// <returns>A tile content object for the TileWideText03 template.</returns> class method CreateTileWideText03: ITileWideText03; /// <summary> /// Creates a tile content object for the TileWideText04 template. /// </summary> /// <returns>A tile content object for the TileWideText04 template.</returns> class method CreateTileWideText04: ITileWideText04; /// <summary> /// Creates a tile content object for the TileWideText05 template. /// </summary> /// <returns>A tile content object for the TileWideText05 template.</returns> class method CreateTileWideText05: ITileWideText05; /// <summary> /// Creates a tile content object for the TileWideText06 template. /// </summary> /// <returns>A tile content object for the TileWideText06 template.</returns> class method CreateTileWideText06: ITileWideText06; /// <summary> /// Creates a tile content object for the TileWideText07 template. /// </summary> /// <returns>A tile content object for the TileWideText07 template.</returns> class method CreateTileWideText07: ITileWideText07; /// <summary> /// Creates a tile content object for the TileWideText08 template. /// </summary> /// <returns>A tile content object for the TileWideText08 template.</returns> class method CreateTileWideText08: ITileWideText08; /// <summary> /// Creates a tile content object for the TileWideText09 template. /// </summary> /// <returns>A tile content object for the TileWideText09 template.</returns> class method CreateTileWideText09: ITileWideText09; /// <summary> /// Creates a tile content object for the TileWideText10 template. /// </summary> /// <returns>A tile content object for the TileWideText10 template.</returns> class method CreateTileWideText10: ITileWideText10; /// <summary> /// Creates a tile content object for the TileWideText11 template. /// </summary> /// <returns>A tile content object for the TileWideText11 template.</returns> class method CreateTileWideText11: ITileWideText11; end; implementation constructor TileNotificationBase(templateName: System.String; imageCount: System.Int32; textCount: System.Int32); begin inherited constructor(templateName, imageCount, textCount); end; method TileNotificationBase.set_Branding(value: TileBranding); begin if not &Enum.IsDefined(typeOf(TileBranding), value) then begin raise new ArgumentOutOfRangeException('value') end; m_Branding := value end; method TileNotificationBase.CreateNotification: TileNotification; begin var xmlDoc: XmlDocument := new XmlDocument(); xmlDoc.LoadXml(GetContent()); exit new TileNotification(xmlDoc) end; constructor TileSquareBase(templateName: System.String; imageCount: System.Int32; textCount: System.Int32); begin inherited constructor(templateName, imageCount, textCount); end; method TileSquareBase.GetContent: System.String; begin var builder: StringBuilder := new StringBuilder(String.Empty); builder.AppendFormat('<tile><visual version=''{0}''', Util.NOTIFICATION_CONTENT_VERSION); if not String.IsNullOrWhiteSpace(Lang) then begin builder.AppendFormat(' lang=''{0}''', Util.HttpEncode(Lang)) end; if Branding <> TileBranding.Logo then begin builder.AppendFormat(' branding=''{0}''', Branding.ToString().ToLowerInvariant()) end; if not String.IsNullOrWhiteSpace(BaseUri) then begin builder.AppendFormat(' baseUri=''{0}''', Util.HttpEncode(BaseUri)) end; builder.Append('>'); builder.Append(SerializeBinding(Lang, BaseUri, Branding)); builder.Append('</visual></tile>'); exit builder.ToString() end; method TileSquareBase.SerializeBinding(globalLang: System.String; globalBaseUri: System.String; globalBranding: TileBranding): System.String; begin var bindingNode: StringBuilder := new StringBuilder(String.Empty); bindingNode.AppendFormat('<binding template=''{0}''', TemplateName); if (not String.IsNullOrWhiteSpace(Lang)) and (not Lang.Equals(globalLang)) then begin bindingNode.AppendFormat(' lang=''{0}''', Util.HttpEncode(Lang)); globalLang := Lang end; if (Branding <> TileBranding.Logo) and (Branding <> globalBranding) then begin bindingNode.AppendFormat(' branding=''{0}''', Branding.ToString().ToLowerInvariant()) end; if (not String.IsNullOrWhiteSpace(BaseUri)) and (not BaseUri.Equals(globalBaseUri)) then begin bindingNode.AppendFormat(' baseUri=''{0}''', Util.HttpEncode(BaseUri)); globalBaseUri := BaseUri end; bindingNode.AppendFormat('>{0}</binding>', SerializeProperties(globalLang, globalBaseUri)); exit bindingNode.ToString() end; constructor TileWideBase(templateName: System.String; imageCount: System.Int32; textCount: System.Int32); begin inherited constructor(templateName, imageCount, textCount); end; method TileWideBase.GetContent: System.String; begin if (RequireSquareContent) and (SquareContent = nil) then begin raise new NotificationContentValidationException('Square tile content should be included with each wide tile. ' + 'If this behavior is undesired, use the RequireSquareContent property.') end; var visualNode: StringBuilder := new StringBuilder(String.Empty); visualNode.AppendFormat('<visual version=''{0}''', Util.NOTIFICATION_CONTENT_VERSION); if not String.IsNullOrWhiteSpace(Lang) then begin visualNode.AppendFormat(' lang=''{0}''', Util.HttpEncode(Lang)) end; if Branding <> TileBranding.Logo then begin visualNode.AppendFormat(' branding=''{0}''', Branding.ToString().ToLowerInvariant()) end; if not String.IsNullOrWhiteSpace(BaseUri) then begin visualNode.AppendFormat(' baseUri=''{0}''', Util.HttpEncode(BaseUri)) end; visualNode.Append('>'); var builder: StringBuilder := new StringBuilder(String.Empty); builder.AppendFormat('<tile>{0}<binding template=''{1}''>{2}</binding>', visualNode, TemplateName, SerializeProperties(Lang, BaseUri)); if SquareContent <> nil then begin var squareBase: ISquareTileInternal := ISquareTileInternal(SquareContent); if squareBase = nil then begin raise new NotificationContentValidationException('The provided square tile content class is unsupported.') end; builder.Append(squareBase.SerializeBinding(Lang, BaseUri, Branding)) end; builder.Append('</visual></tile>'); exit builder.ToString() end; constructor TileSquareBlock; begin inherited constructor('TileSquareBlock', 0, 2); end; constructor TileSquareImage; begin inherited constructor('TileSquareImage', 1, 0); end; constructor TileSquarePeekImageAndText01; begin inherited constructor('TileSquarePeekImageAndText01', 1, 4); end; constructor TileSquarePeekImageAndText02; begin inherited constructor('TileSquarePeekImageAndText02', 1, 2); end; constructor TileSquarePeekImageAndText03; begin inherited constructor('TileSquarePeekImageAndText03', 1, 4); end; constructor TileSquarePeekImageAndText04; begin inherited constructor('TileSquarePeekImageAndText04', 1, 1); end; constructor TileSquareText01; begin inherited constructor('TileSquareText01', 0, 4); end; constructor TileSquareText02; begin inherited constructor('TileSquareText02', 0, 2); end; constructor TileSquareText03; begin inherited constructor('TileSquareText03', 0, 4); end; constructor TileSquareText04; begin inherited constructor('TileSquareText04', 0, 1); end; constructor TileWideBlockAndText01; begin inherited constructor('TileWideBlockAndText01', 0, 6); end; constructor TileWideBlockAndText02; begin inherited constructor('TileWideBlockAndText02', 0, 6); end; constructor TileWideImage; begin inherited constructor('TileWideImage', 1, 0); end; constructor TileWideImageAndText01; begin inherited constructor('TileWideImageAndText01', 1, 1); end; constructor TileWideImageAndText02; begin inherited constructor('TileWideImageAndText02', 1, 2); end; constructor TileWideImageCollection; begin inherited constructor('TileWideImageCollection', 5, 0); end; constructor TileWidePeekImage01; begin inherited constructor('TileWidePeekImage01', 1, 2); end; constructor TileWidePeekImage02; begin inherited constructor('TileWidePeekImage02', 1, 5); end; constructor TileWidePeekImage03; begin inherited constructor('TileWidePeekImage03', 1, 1); end; constructor TileWidePeekImage04; begin inherited constructor('TileWidePeekImage04', 1, 1); end; constructor TileWidePeekImage05; begin inherited constructor('TileWidePeekImage05', 2, 2); end; constructor TileWidePeekImage06; begin inherited constructor('TileWidePeekImage06', 2, 1); end; constructor TileWidePeekImageAndText01; begin inherited constructor('TileWidePeekImageAndText01', 1, 1); end; constructor TileWidePeekImageAndText02; begin inherited constructor('TileWidePeekImageAndText02', 1, 5); end; constructor TileWidePeekImageCollection01; begin inherited constructor('TileWidePeekImageCollection01', 5, 2); end; constructor TileWidePeekImageCollection02; begin inherited constructor('TileWidePeekImageCollection02', 5, 5); end; constructor TileWidePeekImageCollection03; begin inherited constructor('TileWidePeekImageCollection03', 5, 1); end; constructor TileWidePeekImageCollection04; begin inherited constructor('TileWidePeekImageCollection04', 5, 1); end; constructor TileWidePeekImageCollection05; begin inherited constructor('TileWidePeekImageCollection05', 6, 2); end; constructor TileWidePeekImageCollection06; begin inherited constructor('TileWidePeekImageCollection06', 6, 1); end; constructor TileWideSmallImageAndText01; begin inherited constructor('TileWideSmallImageAndText01', 1, 1); end; constructor TileWideSmallImageAndText02; begin inherited constructor('TileWideSmallImageAndText02', 1, 5); end; constructor TileWideSmallImageAndText03; begin inherited constructor('TileWideSmallImageAndText03', 1, 1); end; constructor TileWideSmallImageAndText04; begin inherited constructor('TileWideSmallImageAndText04', 1, 2); end; constructor TileWideText01; begin inherited constructor('TileWideText01', 0, 5); end; constructor TileWideText02; begin inherited constructor('TileWideText02', 0, 9); end; constructor TileWideText03; begin inherited constructor('TileWideText03', 0, 1); end; constructor TileWideText04; begin inherited constructor('TileWideText04', 0, 1); end; constructor TileWideText05; begin inherited constructor('TileWideText05', 0, 5); end; constructor TileWideText06; begin inherited constructor('TileWideText06', 0, 10); end; constructor TileWideText07; begin inherited constructor('TileWideText07', 0, 9); end; constructor TileWideText08; begin inherited constructor('TileWideText08', 0, 10); end; constructor TileWideText09; begin inherited constructor('TileWideText09', 0, 2); end; constructor TileWideText10; begin inherited constructor('TileWideText10', 0, 9); end; constructor TileWideText11; begin inherited constructor('TileWideText11', 0, 10); end; class method TileContentFactory.CreateTileSquareBlock: ITileSquareBlock; begin exit new TileSquareBlock() end; class method TileContentFactory.CreateTileSquareImage: ITileSquareImage; begin exit new TileSquareImage() end; class method TileContentFactory.CreateTileSquarePeekImageAndText01: ITileSquarePeekImageAndText01; begin exit new TileSquarePeekImageAndText01() end; class method TileContentFactory.CreateTileSquarePeekImageAndText02: ITileSquarePeekImageAndText02; begin exit new TileSquarePeekImageAndText02() end; class method TileContentFactory.CreateTileSquarePeekImageAndText03: ITileSquarePeekImageAndText03; begin exit new TileSquarePeekImageAndText03() end; class method TileContentFactory.CreateTileSquarePeekImageAndText04: ITileSquarePeekImageAndText04; begin exit new TileSquarePeekImageAndText04() end; class method TileContentFactory.CreateTileSquareText01: ITileSquareText01; begin exit new TileSquareText01() end; class method TileContentFactory.CreateTileSquareText02: ITileSquareText02; begin exit new TileSquareText02() end; class method TileContentFactory.CreateTileSquareText03: ITileSquareText03; begin exit new TileSquareText03() end; class method TileContentFactory.CreateTileSquareText04: ITileSquareText04; begin exit new TileSquareText04() end; class method TileContentFactory.CreateTileWideBlockAndText01: ITileWideBlockAndText01; begin exit new TileWideBlockAndText01() end; class method TileContentFactory.CreateTileWideBlockAndText02: ITileWideBlockAndText02; begin exit new TileWideBlockAndText02() end; class method TileContentFactory.CreateTileWideImage: ITileWideImage; begin exit new TileWideImage() end; class method TileContentFactory.CreateTileWideImageAndText01: ITileWideImageAndText01; begin exit new TileWideImageAndText01() end; class method TileContentFactory.CreateTileWideImageAndText02: ITileWideImageAndText02; begin exit new TileWideImageAndText02() end; class method TileContentFactory.CreateTileWideImageCollection: ITileWideImageCollection; begin exit new TileWideImageCollection() end; class method TileContentFactory.CreateTileWidePeekImage01: ITileWidePeekImage01; begin exit new TileWidePeekImage01() end; class method TileContentFactory.CreateTileWidePeekImage02: ITileWidePeekImage02; begin exit new TileWidePeekImage02() end; class method TileContentFactory.CreateTileWidePeekImage03: ITileWidePeekImage03; begin exit new TileWidePeekImage03() end; class method TileContentFactory.CreateTileWidePeekImage04: ITileWidePeekImage04; begin exit new TileWidePeekImage04() end; class method TileContentFactory.CreateTileWidePeekImage05: ITileWidePeekImage05; begin exit new TileWidePeekImage05() end; class method TileContentFactory.CreateTileWidePeekImage06: ITileWidePeekImage06; begin exit new TileWidePeekImage06() end; class method TileContentFactory.CreateTileWidePeekImageAndText01: ITileWidePeekImageAndText01; begin exit new TileWidePeekImageAndText01() end; class method TileContentFactory.CreateTileWidePeekImageAndText02: ITileWidePeekImageAndText02; begin exit new TileWidePeekImageAndText02() end; class method TileContentFactory.CreateTileWidePeekImageCollection01: ITileWidePeekImageCollection01; begin exit new TileWidePeekImageCollection01() end; class method TileContentFactory.CreateTileWidePeekImageCollection02: ITileWidePeekImageCollection02; begin exit new TileWidePeekImageCollection02() end; class method TileContentFactory.CreateTileWidePeekImageCollection03: ITileWidePeekImageCollection03; begin exit new TileWidePeekImageCollection03() end; class method TileContentFactory.CreateTileWidePeekImageCollection04: ITileWidePeekImageCollection04; begin exit new TileWidePeekImageCollection04() end; class method TileContentFactory.CreateTileWidePeekImageCollection05: ITileWidePeekImageCollection05; begin exit new TileWidePeekImageCollection05() end; class method TileContentFactory.CreateTileWidePeekImageCollection06: ITileWidePeekImageCollection06; begin exit new TileWidePeekImageCollection06() end; class method TileContentFactory.CreateTileWideSmallImageAndText01: ITileWideSmallImageAndText01; begin exit new TileWideSmallImageAndText01() end; class method TileContentFactory.CreateTileWideSmallImageAndText02: ITileWideSmallImageAndText02; begin exit new TileWideSmallImageAndText02() end; class method TileContentFactory.CreateTileWideSmallImageAndText03: ITileWideSmallImageAndText03; begin exit new TileWideSmallImageAndText03() end; class method TileContentFactory.CreateTileWideSmallImageAndText04: ITileWideSmallImageAndText04; begin exit new TileWideSmallImageAndText04() end; class method TileContentFactory.CreateTileWideText01: ITileWideText01; begin exit new TileWideText01() end; class method TileContentFactory.CreateTileWideText02: ITileWideText02; begin exit new TileWideText02() end; class method TileContentFactory.CreateTileWideText03: ITileWideText03; begin exit new TileWideText03() end; class method TileContentFactory.CreateTileWideText04: ITileWideText04; begin exit new TileWideText04() end; class method TileContentFactory.CreateTileWideText05: ITileWideText05; begin exit new TileWideText05() end; class method TileContentFactory.CreateTileWideText06: ITileWideText06; begin exit new TileWideText06() end; class method TileContentFactory.CreateTileWideText07: ITileWideText07; begin exit new TileWideText07() end; class method TileContentFactory.CreateTileWideText08: ITileWideText08; begin exit new TileWideText08() end; class method TileContentFactory.CreateTileWideText09: ITileWideText09; begin exit new TileWideText09() end; class method TileContentFactory.CreateTileWideText10: ITileWideText10; begin exit new TileWideText10() end; class method TileContentFactory.CreateTileWideText11: ITileWideText11; begin exit new TileWideText11() end; end.
{$Revision$ } program Arrays_Stat_vs_Dyno; procedure PointerOfArray(var Arr: array of Char); overload; begin write(' var Arr: @Arr and @Arr[Low(Arr)] is '); if @Arr = @Arr[Low(Arr)] then writeln('equal') else writeln('different'); end; procedure CompareStatArray1stElement; var Arr: array [0..15] of Char; begin write('Stat Arr: @Arr and @Arr[Low(Arr)] is '); if @Arr = @Arr[Low(Arr)] then writeln('equal') else writeln('different'); PointerOfArray(Arr); end; procedure CompareDynoArray1stElement; var Arr: array of Char; begin SetLength(Arr, 16); write('Dyno Arr: @Arr and @Arr[Low(Arr)] is '); if @Arr = @Arr[Low(Arr)] then writeln('equal') else writeln('different'); PointerOfArray(Arr); end; function PointerOfArray(var Arr: array of Byte): Pointer; overload; begin Result := @Arr; end; procedure CheckPointerOfStatArray; var Arr: array[0..15] of Byte; begin write('Stat Arr: PointerOfArray(var Arr) and @Arr is '); if PointerOfArray(Arr) = @Arr then writeln('equal') else writeln('different'); end; procedure CheckPointerOfDynoArray; var Arr: array of Byte; begin SetLength(Arr, 16); write('Dyno Arr: PointerOfArray(var Arr) and @Arr is '); if PointerOfArray(Arr) = @Arr then writeln('equal') else writeln('different'); end; procedure CheckPointerOfStatArray1stElement; var Arr: array[0..15] of Byte; begin write('Stat Arr: PointerOfArray(var Arr) and @Arr[Low(Arr)] is '); if PointerOfArray(Arr) = @Arr[Low(Arr)] then writeln('equal') else writeln('different'); end; procedure CheckPointerOfDynoArray1stElement; var Arr: array of Byte; begin SetLength(Arr, 16); write('Dyno Arr: PointerOfArray(var Arr) and @Arr[Low(Arr)] is '); if PointerOfArray(Arr) = @Arr[Low(Arr)] then writeln('equal') else writeln('different'); end; procedure ArrayParameter(A: array of Byte); begin writeln(High(A)); end; procedure CheckStatArrayParameter; var Arr: array[1..10] of Byte; begin write('ArrayParameter(A: Stat Array): High(A) = '); ArrayParameter(Arr); end; procedure CheckDynoArrayParameter; var Arr: array of Byte; begin SetLength(Arr, 10); write('ArrayParameter(A: Dyno Array): High(A) = '); ArrayParameter(Arr); end; procedure PrintArray(var A: array of Integer); var I: Integer; begin write('High(A) = ', High(A), ': '); for I in A do write(I, ' '); writeln; end; procedure SliceArray; var Arr: array [5..14] of Integer; I: Integer; begin for I:=Low(Arr) to High(Arr) do Arr[I] := I; PrintArray(Arr[5..10]); PrintArray(Arr[7..14]); end; begin CompareStatArray1stElement; CompareDynoArray1stElement; writeln; CheckPointerOfStatArray; CheckPointerOfDynoArray; writeln; CheckPointerOfStatArray1stElement; CheckPointerOfDynoArray1stElement; writeln; CheckStatArrayParameter; CheckDynoArrayParameter; writeln; SliceArray; end.
unit Level_Utils; interface uses Level, misc_utils, MultiSelection, SysUtils, Math; Const Any_Layer=-5000; {Complex level tranformations} Procedure TranslateSector(L:TLevel;sc:Integer;x,z:double); Procedure TranslateWall(L:TLevel;sc,wl:Integer;x,z:double); Procedure TranslateVertex(L:TLevel;sc,vx:Integer;x,z:double); Procedure TranslateObject(L:TLevel;ob:Integer;x,z:double); Procedure TranslateSectorSelection(L:TLevel;sel:TMultiSelection;x,z:Double); Procedure TranslateWallSelection(L:TLevel;sel:TMultiSelection;x,z:Double); Procedure TranslateVertexSelection(L:TLevel;sel:TMultiSelection;x,z:Double); Procedure TranslateObjectSelection(L:TLevel;sel:TMultiSelection;dx,dz:Double); Procedure DeleteSector(L:TLevel;sc:Integer); Procedure DeleteVertex(L:TLevel;sc,vx:Integer); Procedure DeleteWall(L:TLevel;sc,wl:Integer); Procedure DeleteOB(L:TLevel;ob:Integer); Procedure ClearMarks(L:TLevel); function MakeAdjoin(L:Tlevel; sc, wl : Integer) : Integer; function UnAdjoin(L:Tlevel; sc, wl : Integer) : Integer; Function SplitWall(l:TLevel; sc, wl : Integer):Integer; Function GetWLLen(L:TLevel;sc, wl:integer):Double; function GetWLfromV1(l:TLevel;sector, V1 : Integer) : Integer; function GetWLfromV2(l:TLevel;sector, V2 : Integer) : Integer; Function CreatePolygonSector(l:TLevel;x,z,radius:Double;sides,likeSC,likeWL:Integer):Integer; Procedure CreatePolygonGap(l:TLevel;sc:Integer;x,z,radius:Double;sides,likeSC,likeWL:Integer); Procedure ExtrudeWall(L:TLevel;sc,wl:Integer;ExtrudeBy:Double); function GetNearestWL(L:TLevel; Layer:Integer; X, Z : Double; VAR ASector : Integer; VAR AWall : Integer) : Boolean; function GetNearestSC(L:TLevel; Layer:Integer; X, Z : Double; VAR ASector : Integer) : Boolean; function GetNextNearestSC(L:TLevel; Layer:Integer; X, Z : Double; VAR ASector : Integer) : Boolean; function GetNearestVX(L:TLevel; Layer:Integer; X, Z : Double; VAR ASector : Integer; VAR AVertex : Integer) : Boolean; function GetNearestOB(L:TLevel; Layer:Integer; X, Z : Double; VAR AObject : Integer) : Boolean; function GetNextNearestVX(L:TLevel; Layer:Integer; X, Z : Double; VAR ASector : Integer; VAR AVertex : Integer) : Boolean; function GetObjectSC(L:TLevel;obnum : Integer; VAR ASector : Integer) : Boolean; Procedure ApplyFixUp(L:TLevel;const Name:String); implementation uses Files, FileOperations, Windows; Procedure ClearMarks(L:TLevel); var i,j:integer; begin With L do For i:=0 to sectors.count-1 do with sectors[i] do for j:=0 to Vertices.count-1 do vertices[j].mark:=0; end; Procedure TranslateSectorSelection(L:TLevel;sel:TMultiSelection;x,z:Double); var i,j,m : Integer; TheSector : TSector; TheSector2: TSector; TheVertex : TVertex; TheWall : TWall; TheWall2 : TWall; TheObject : TOB; begin ClearMarks(l); With L do begin {include the multiselection} for m := 0 to Sel.Count - 1 do With Sectors[Sel.GetSector(m)] do for i:=0 to vertices.count-1 do vertices[i].Mark:=1; {include the vertices of the adjoins} for m := 0 to Sel.Count - 1 do With Sectors[sel.GetSector(m)] do for i := 0 to Walls.Count - 1 do begin TheWall := Walls[i]; if TheWall.Adjoin <> -1 then begin TheSector2 := Sectors[TheWall.Adjoin]; TheWall2 := TheSector2.Walls[TheWall.Mirror]; TheVertex := TheSector2.Vertices[TheWall2.V1]; TheVertex.Mark := 1; TheVertex := TheSector2.Vertices[TheWall2.V2]; TheVertex.Mark := 1; end; if TheWall.DAdjoin <> -1 then begin TheSector2 := Sectors[TheWall.DAdjoin]; TheWall2 := TheSector2.Walls[TheWall.DMirror]; TheVertex := TheSector2.Vertices[TheWall2.V1]; TheVertex.Mark := 1; TheVertex := TheSector2.Vertices[TheWall2.V2]; TheVertex.Mark := 1; end; end; {include the vertices of the adjoins of the selection} {process the marked VXs} for i := 0 to Sectors.Count - 1 do With Sectors[i] do for j := 0 to Vertices.Count - 1 do begin TheVertex:=Vertices[j]; if TheVertex.Mark=1 then begin TheVertex.X:=TheVertex.X+X; TheVertex.Z:=TheVertex.Z+Z; end; end; end; end; Procedure TranslateWallSelection(L:TLevel;sel:TMultiSelection;x,z:Double); var m,i,j:Integer; TheWall, TheWall2:TWall; TheSector2:TSector; TheVertex:TVertex; begin ClearMarks(L); {include the multiselection and its mirrors} for m := 0 to Sel.Count - 1 do With L.Sectors[Sel.GetSector(m)] do begin TheWall := Walls[Sel.GetWall(m)]; Vertices[TheWall.V1].Mark:=1; Vertices[TheWall.V2].Mark:=1; if TheWall.Adjoin <> -1 then begin TheSector2:=l.Sectors[TheWall.Adjoin]; TheWall2 := TheSector2.Walls[TheWall.Mirror]; TheSector2.Vertices[TheWall2.V1].Mark:=1; TheSector2.Vertices[TheWall2.V2].Mark:=1; end; if TheWall.DAdjoin <> -1 then begin TheSector2:=l.Sectors[TheWall.DAdjoin]; TheWall2 := TheSector2.Walls[TheWall.DMirror]; TheSector2.Vertices[TheWall2.V1].Mark:=1; TheSector2.Vertices[TheWall2.V2].Mark:=1; end; end; {process the marked VXs} for i := 0 to l.Sectors.Count - 1 do With l.Sectors[i] do begin for j := 0 to Vertices.Count - 1 do begin TheVertex := Vertices[j]; if TheVertex.Mark = 1 then begin TheVertex.X := TheVertex.X + x; TheVertex.Z := TheVertex.Z + z; end; end; end; end; Procedure TranslateVertexSelection(L:TLevel;sel:TMultiSelection;x,z:Double); var m:Integer; TheVertex:TVertex; begin ClearMarks(l); for m := 0 to Sel.Count - 1 do With l.Sectors[sel.GetSector(m)] do begin TheVertex := Vertices[Sel.GetVertex(m)]; TheVertex.X := TheVertex.X + x; TheVertex.Z := TheVertex.Z + z; end; end; Procedure TranslateObjectSelection(L:TLevel;sel:TMultiSelection;dx,dz:Double); var m:Integer; begin for m := 0 to Sel.Count - 1 do With l.Objects[Sel.GetObject(m)] do begin X:=X+dx; Z:=Z+dz; end; end; Procedure DeleteSector(L:TLevel;sc:Integer); var i,j,k : Integer; TheSector : TSector; TheWall : TWall; TheObject : TOB; Procedure AdjustSCRef(Var oldSC:Integer); begin if oldSC>sc then Dec(OldSC) else if oldSC=sc then OldSC:=-1; end; begin {Update all the adjoins > to the sector} {Delete the adjoins = to the sector} for i := 0 to l.Sectors.Count - 1 do if i <> sc then With l.Sectors[i] do begin AdjustSCRef(VAdjoin); AdjustScRef(FloorSlope.Sector); AdjustScRef(CeilingSlope.Sector); for j := 0 to Walls.Count - 1 do begin TheWall := Walls[j]; AdjustSCRef(TheWall.Adjoin); if TheWall.Adjoin = -1 then TheWall.Mirror := -1; AdjustSCRef(TheWall.DAdjoin); if TheWall.DAdjoin = -1 then TheWall.DMirror := -1; end; {walls} end; {sectors} {Correct corresponding objects references} for i := 0 to l.Objects.Count - 1 do AdjustScRef(l.Objects[i].Sector); {Delete the entry in MAP_SEC} L.Sectors[sc].Free; l.Sectors.Delete(sc); end; Procedure DeleteVertex(L:TLevel;sc,vx:Integer); var TheWall,TheWall2:TWall; nDelWall,nWall,nWall2:Integer; i,j:Integer; Procedure AdjustWLRef(Var oldSC,oldWl:Integer); begin if oldSC<>sc then exit; if oldWL>nDelWall then Dec(oldWL) else if oldWL=nDelWall then begin OldWL:=-1; OldSC:=-1; end; end; begin With l.Sectors[sc] do begin TheWall:=nil; nWall:=-1; TheWall2:=nil; nWall2:=-1; {Find two walls this that meet at this vertex} For i:=0 to Walls.Count-1 do {Look for wall that starts at this vertex} if Walls[i].V1=vx then begin nWall:=i; TheWall:=Walls[i]; break; end; For i:=0 to Walls.Count-1 do {Look for wall that ends at this vertex} if Walls[i].V2=vx then begin nWall2:=i; TheWall2:=Walls[i]; break; end; nDelWall:=nWall; {Mark the wall that starts at this vertex for deletion, unless no wall does. Then mark wall that ends at this vertex for deletion, if any} if (TheWall<>nil) and (TheWall2<>nil) then TheWall2.V2:=TheWall.V2 else if TheWall=nil then nDelWall:=nWall2; {Adjusting vertex references} For i:= 0 to Walls.Count-1 do With Walls[i] do begin if V1>=vx then Dec(V1); if V2>=vx then Dec(V2); end; {Adjusting Wall references} if nDelWall<>-1 then 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; {Deleting walls and vertices} Vertices.Delete(vx); if nDelWall<>-1 then Walls.Delete(nDelWall); end; {With} if l.Sectors[sc].Vertices.Count=0 then DeleteSector(l,sc); {if it was the last vertex} end; Procedure DeleteWall(L:TLevel;sc,wl:Integer); begin DeleteVertex(L,sc,l.Sectors[sc].Walls[wl].V1); end; Procedure DeleteOB(L:TLevel;ob:Integer); begin l.Objects[ob].Free; l.Objects.Delete(ob); end; function MakeAdjoin(L:Tlevel; sc, wl : Integer) : Integer; var s,w : Integer; TheSector1 : TSector; TheSector2 : TSector; TheWall1 : TWall; TheWall2 : TWall; LVertex1 : TVertex; RVertex1 : TVertex; LVertex2 : TVertex; RVertex2 : TVertex; pSec1,PSec2,pWl1,PWl2:^Integer; Procedure ArrangeDAdjoin(wall:TWall); {arranges adjoins so that Adjoin is a higher sector, DAdjoin - lower} Var Sec1,Sec2:TSector; Adj,mir:Integer; begin If (Wall.Adjoin<0) or (Wall.Adjoin>=l.Sectors.count) then begin PanMessage(mt_Warning,Format('Incorrect adjoin: wall id: %x',[Wall.HexID])); exit; end; If (Wall.DAdjoin<0) or (Wall.DAdjoin>=l.Sectors.count) then begin PanMessage(mt_Warning,Format('Incorrect second adjoin: wall id: %x',[Wall.HexID])); exit; end; Sec1:=l.Sectors[Wall.Adjoin]; Sec2:=l.Sectors[Wall.Dadjoin]; if Sec1.Floor_Y<Sec2.Floor_Y then {exchange adjoins} begin adj:=Wall.Adjoin; mir:=Wall.Mirror; Wall.Adjoin:=Wall.DAdjoin; Wall.Mirror:=Wall.DAdjoin; Wall.Dadjoin:=adj; Wall.DMirror:=mir; end; end; begin Result := 0; TheSector1 := l.Sectors[sc]; TheWall1 := TheSector1.Walls[wl]; if (TheWall1.Adjoin<>-1) and (TheWall1.Dadjoin<>-1) then exit; LVertex1 := TheSector1.Vertices[TheWall1.V1]; RVertex1 := TheSector1.Vertices[TheWall1.V2]; for s := 0 to l.Sectors.Count - 1 do begin TheSector2 := l.Sectors[s]; for w := 0 to TheSector2.Walls.Count - 1 do begin TheWall2 := TheSector2.Walls[w]; With TheWall2 do if ((Adjoin=sc) and (Mirror=wl)) or ((DAdjoin=sc) and (DMirror=wl)) or ((Adjoin<>-1) and (DAdjoin<>-1)) then continue; LVertex2 := TheSector2.Vertices[TheWall2.V1]; RVertex2 := TheSector2.Vertices[TheWall2.V2]; {if found do the adjoin and prepare to break out of both loops} if ((LVertex1.X = RVertex2.X) and (LVertex1.Z = RVertex2.Z)) and ((RVertex1.X = LVertex2.X) and (RVertex1.Z = LVertex2.Z)) then begin if TheWall1.Adjoin=-1 then begin PSec1:=@TheWall1.Adjoin; PWl1:=@TheWall1.Mirror end else if TheWall1.DAdjoin=-1 then begin PSec1:=@TheWall1.DAdjoin; PWl1:=@TheWall1.DMirror end else break; if TheWall2.Adjoin=-1 then begin PSec2:=@TheWall2.Adjoin; PWl2:=@TheWall2.Mirror end else if TheWall2.DAdjoin=-1 then begin PSec2:=@TheWall2.DAdjoin; PWl2:=@TheWall2.DMirror end; PSec2^ := sc; PWl2^ := wl; pSec1^ := s; pWl1^ := w; if (TheWall2.Adjoin<>-1) and (TheWall2.Dadjoin<>-1) then ArrangeDAdjoin(TheWall2); Inc(Result); end; end; end; if (TheWall1.Adjoin<>-1) and (TheWall1.Dadjoin<>-1) then ArrangeDAdjoin(TheWall1); end; function UnAdjoin(L:Tlevel; sc, wl : Integer) : Integer; var TheWall : TWall; TheWall2 : TWall; TheSector2: TSector; BadAdjoin:Boolean; Function BadRef(ref:Integer;Max:Integer):Boolean; begin result:=(ref<0) or (ref>=Max); end; begin Result := 0; TheWall:=l.Sectors[sc].Walls[wl]; BadAdjoin:=false; Repeat if TheWall.Adjoin=-1 then break else if BadRef(TheWall.Adjoin,l.Sectors.Count) then begin BadAdjoin:=true; break; end; TheSector2:=l.Sectors[TheWall.Adjoin]; if BadRef(TheWall.Mirror, TheSector2.walls.count) then begin badAdjoin:=true; break; end; TheWall2:=TheSector2.Walls[TheWall.Mirror]; TheWall.Adjoin:=-1; TheWall.Mirror:=-1; if (TheWall2.Adjoin=sc) and (TheWall2.Mirror=wl) then begin TheWall2.Adjoin:=-1; TheWall2.Mirror:=-1; end else if (TheWall2.DAdjoin=sc) and (TheWall2.DMirror=wl) then begin TheWall2.DAdjoin:=-1; TheWall2.DMirror:=-1; end; Inc(Result); Until true; {Dummy cycle, just for break; to work} if badAdjoin then PanMessage(mt_Warning,Format('Bad adjoin: SC %d WL %d',[sc,wl])); BadAdjoin:=false; Repeat if TheWall.DAdjoin=-1 then break else if BadRef(TheWall.DAdjoin,l.Sectors.Count) then begin BadAdjoin:=true; break; end; TheSector2:=l.Sectors[TheWall.DAdjoin]; if BadRef(TheWall.DMirror, TheSector2.walls.count) then begin badAdjoin:=true; break; end; TheWall2:=TheSector2.Walls[TheWall.DMirror]; TheWall.DAdjoin:=-1; TheWall.DMirror:=-1; if (TheWall2.Adjoin=sc) and (TheWall2.Mirror=wl) then begin TheWall2.Adjoin:=-1; TheWall2.Mirror:=-1; end else if (TheWall2.DAdjoin=sc) and (TheWall2.DMirror=wl) then begin TheWall2.DAdjoin:=-1; TheWall2.DMirror:=-1; end; Inc(result); Until true; {Dummy cycle, just for "break" to work} if badAdjoin then PanMessage(mt_Warning,Format('Bad second adjoin: SC %d WL %d',[sc,wl])); end; Function GetWLLen(L:TLevel;sc, wl:integer):Double; Var TheWall:TWall; vx1,vx2:TVertex; begin With l.Sectors[sc] do begin TheWall:=Walls[wl]; vx1:=Vertices[TheWall.V1]; vx2:=Vertices[TheWall.V2]; Result:=sqrt(sqr(vx1.X - vx2.X)+sqr(vx1.Z - vx2.Z)); end; end; Function SplitWall(l:TLevel; sc, wl : Integer):Integer; {return the number of a new wall} var w : Integer; TheSector : TSector; TheSector2 : TSector; TheWall : TWall; TheWall2 : TWall; NEWWall : TWall; NEWVertex : TVertex; LVertex : TVertex; RVertex : TVertex; newvxpos : Integer; walllen : Real; begin Result:=-1; TheSector := l.Sectors[sc]; TheWall := TheSector.Walls[wl]; walllen := GetWLLen(l, sc, wl); LVertex := TheSector.Vertices[TheWall.V1]; RVertex := TheSector.Vertices[TheWall.V2]; NEWVertex := L.NewVertex; NEWVertex.Mark := 0; NEWVertex.X := (LVertex.X + RVertex.X ) / 2; NEWVertex.Z := (LVertex.Z + RVertex.Z ) / 2; NEWWall := L.NewWall; NewWall.Assign(TheWall); {preserve texture horiz alignment} TheWall.Mid.Offsx := RoundTo2Dec(TheWall.Mid.Offsx + walllen / 2); TheWall.Top.OffsX := RoundTo2Dec(TheWall.Top.OffsX + walllen / 2); TheWall.Bot.OffsX := RoundTo2Dec(TheWall.Bot.OffsX + walllen / 2); newvxpos := TheWall.V1 + 1; NEWWall.V1 := TheWall.V1; NEWWall.V2 := newvxpos; {Adjusting references in the current sector} for w := 0 to TheSector.Walls.Count - 1 do begin TheWall2 := TheSector.Walls[w]; if TheWall2.V1 >= newvxpos then Inc(TheWall2.V1); if TheWall2.V2 >= newvxpos then Inc(TheWall2.V2); end; TheSector.Vertices.Insert(newvxpos, NEWVertex); {TheSector.Walls.Insert(wl, NEWWall);} Result:=TheSector.Walls.Add(NEWWall); TheWall.V1 := newvxpos; {update the mirrors of the adjoins for the complete sector (easier)} { for w := 0 to TheSector.Walls.Count - 1 do begin TheWall := TheSector.Walls[w]; if TheWall.Adjoin <> -1 then begin TheSector2 := l.Sectors[TheWall.Adjoin]; TheWall2 := TheSector2.Walls[TheWall.Mirror]; TheWall2.Mirror := w; end; if TheWall.DAdjoin <> -1 then begin TheSector2 := l.Sectors[TheWall.DAdjoin]; TheWall2 := TheSector2.Walls[TheWall.DMirror]; TheWall2.DMirror := w; end; end;} end; function GetWLfromV1(l:TLevel;sector, V1 : Integer) : Integer; var TheWall : TWall; w : Integer; TheSector : TSector; begin Result := -1; TheSector := l.Sectors[sector]; for w := 0 to TheSector.Walls.Count - 1 do begin TheWall := TheSector.Walls[w]; if TheWall.V1 = V1 then begin Result := w; break; end; end; end; function GetWLfromV2(l:TLevel;sector, V2 : Integer) : Integer; var TheWall : TWall; w : Integer; TheSector : TSector; begin Result := -1; TheSector := l.Sectors[sector]; for w := 0 to TheSector.Walls.Count - 1 do begin TheWall := TheSector.Walls[w]; if TheWall.V2 = V2 then begin Result := w; break; end; end; end; Function GeneratePolygon(x,z,radius:Double;sides:Integer):TVertices; var TheVertex:TVertex; alpha,delta:double; i:Integer; begin Result:=TVertices.Create; if sides=4 then alpha := Pi/4 else Alpha:=0; delta := 2 * Pi / Sides; for i := 0 to Sides - 1 do begin TheVertex := TVertex.Create; TheVertex.X := RoundTo2Dec(X + Radius * cos(alpha)); TheVertex.Z := RoundTo2Dec(Z + Radius * sin(alpha)); alpha := alpha + delta; Result.Add(TheVertex); end; end; Function CreatePolygonSector(l:TLevel;x,z,radius:Double;sides,likeSC,likeWL:Integer):Integer; var i:Integer; TheSector:TSector; Wall:TWall; RefWall:TWall; nWalls:Integer; vxs:Tvertices; begin TheSector:=l.NewSector; Result:=l.Sectors.Add(TheSector); RefWall:=nil; if LikeSC<>-1 then begin TheSector.Assign(l.Sectors[likeSC]); RefWall:=l.Sectors[LikeSC].Walls[LikeWL]; end; vxs:=GeneratePolygon(x,z,radius,sides); nWalls:=vxs.Count; for i:=0 to nWalls-1 do begin TheSector.Vertices.Add(vxs[i]); Wall:=l.NewWall; if RefWall<>nil then Wall.Assign(RefWall); if i=nwalls-1 then Wall.V1:=0 else Wall.V1:=i+1; Wall.V2:=i; TheSector.Walls.Add(Wall); end; vxs.Free; end; Procedure CreatePolygonGap(l:TLevel;sc:Integer;x,z,radius:Double;sides,likeSC,likeWL:Integer); var vxs:TVertices; i:Integer; TheSector:TSector; Wall:TWall; RefWall:TWall; nNewWalls,NOldWalls:Integer; nOldVXs:Integer; begin vxs:=GeneratePolygon(x,z,radius,sides); RefWall:=nil; if LikeSC<>-1 then RefWall:=l.Sectors[LikeSC].Walls[LikeWL]; TheSector:=l.Sectors[sc]; nOldWalls:=TheSector.Walls.Count; nOldVXs:=TheSector.Vertices.Count; nNewWalls:=vxs.Count; for i:=0 to nNewWalls-1 do begin TheSector.Vertices.Add(vxs[i]); Wall:=L.NewWall; if RefWall<>nil then Wall.Assign(RefWall); Wall.V1:=nOldVXs+i; if i=nNewWalls-1 then Wall.V2:=nOldVXs else Wall.V2:=nOldVXs+i+1; TheSector.Walls.Add(Wall); end; vxs.Free; end; Procedure TranslateSector(L:TLevel;sc:Integer;x,z:double); var sel:TMultiSelection; begin sel:=TMultiSelection.Create; Sel.AddSector(sc); TranslateSectorSelection(L,sel,x,z); Sel.Free; end; Procedure TranslateWall(L:TLevel;sc,wl:Integer;x,z:double); var sel:TMultiSelection; begin sel:=TMultiSelection.Create; Sel.AddWall(sc,wl); TranslateWallSelection(L,sel,x,z); Sel.Free; end; Procedure TranslateVertex(L:TLevel;sc,vx:Integer;x,z:double); var sel:TMultiSelection; begin sel:=TMultiSelection.Create; Sel.AddVertex(sc,vx); TranslateVertexSelection(L,sel,x,z); Sel.Free; end; Procedure TranslateObject(L:TLevel;ob:Integer;x,z:double); var sel:TMultiSelection; begin sel:=TMultiSelection.Create; Sel.AddObject(ob); TranslateObjectSelection(L,sel,x,z); Sel.Free; end; Procedure ExtrudeWall(L:TLevel;sc,wl:Integer;ExtrudeBy:Double); var w : Integer; TheSector : TSector; TheSector2 : TSector; TheWall : TWall; TheWall2 : TWall; TheVertex2 : TVertex; LVertex, RVertex : TVertex; deltax, deltaz : Double; NewSector : Integer; begin TheSector:=L.Sectors[sc]; TheWall:=TheSector.Walls[wl]; { prepare the coordinates of the new vertices } LVertex := TheSector.Vertices[TheWall.V1]; RVertex := TheSector.Vertices[TheWall.V2]; deltax := LVertex.X - RVertex.x; deltaz := LVertex.z - RVertex.z; { Create and fill the new sector } TheSector2 := L.NewSector; TheSector2.Assign(TheSector); TheSector2.Flags:=TheSector2.Flags and (Not SECFLAG1_DOOR); Newsector:=L.Sectors.Add(TheSector2); {VX 0} TheVertex2 := l.NewVertex; TheVertex2.X := RVertex.X; TheVertex2.Z := RVertex.Z; TheSector2.Vertices.Add(TheVertex2); {VX 1} TheVertex2 := l.NewVertex; TheVertex2.X := LVertex.X; TheVertex2.Z := LVertex.Z; TheSector2.Vertices.Add(TheVertex2); {VX 2} TheVertex2 := l.NewVertex; TheVertex2.X := LVertex.X + ExtrudeBy * deltaz; TheVertex2.Z := LVertex.Z - ExtrudeBy * deltax; TheSector2.Vertices.Add(TheVertex2); {VX 3} TheVertex2 := l.NewVertex; TheVertex2.X := RVertex.X + ExtrudeBy * deltaz; TheVertex2.Z := RVertex.Z - ExtrudeBy * deltax; TheSector2.Vertices.Add(TheVertex2); for w := 0 to 3 do begin TheWall2 := l.NewWall; TheWall2.Assign(TheWall); CASE w OF 0 : begin TheWall2.V1 := 0; TheWall2.V2 := 1; end; 1 : begin TheWall2.V1 := 1; TheWall2.V2 := 2; end; 2 : begin TheWall2.V1 := 2; TheWall2.V2 := 3; end; 3 : begin TheWall2.V1 := 3; TheWall2.V2 := 0; end; END; IF w = 0 then begin TheWall2.Adjoin := sc; TheWall2.Mirror := wl; With TheWall do if Adjoin=-1 then begin Adjoin:= newsector; Mirror:=0; end else if DAdjoin=-1 then begin DAdjoin:= newsector; DMirror:=0; end; end; TheSector2.Walls.Add(TheWall2); end; end; function GetNearestWL(L:TLevel; Layer:Integer; X, Z : Double; VAR ASector : Integer; VAR AWall : Integer) : Boolean; var TheSector : TSector; TheWall : TWall; LVertex, RVertex : TVertex; w, itw : Integer; x1, z1, x2, z2, dd : Double; dmin, cal : Double; xi, zi : Double; Sector : Integer; begin dmin := 9999999.0; itw := -1; With L do if GetNearestSC(L,Layer,X, Z, sector) then begin TheSector := Sectors[sector]; for w := 0 to TheSector.Walls.Count - 1 do begin TheWall := TheSector.Walls[w]; LVertex := TheSector.Vertices[TheWall.V1]; RVertex := TheSector.Vertices[TheWall.V2]; x1 := LVertex.X; z1 := LVertex.Z; x2 := RVertex.X; z2 := RVertex.Z; if z1 <> z2 then { if not HORIZONTAL } begin if x1 = x2 then { if VERTICAL} begin xi := x1; end else begin dd := (z1 - z2) / (x1 - x2); xi := (z + dd * x1 - z1) / dd; end; {if VERTICAL} if (z >= real_min(z1, z2)) and (z <= real_max(z1, z2)) then { if intersection on wall } begin cal := abs(xi - x); if cal <= dmin then begin dmin := cal; itw := w; end; end; end { if not HORIZONTAL } else { if HORIZONTAL } begin zi := z1; if (x >= real_min(x1, x2)) and (x <= real_max(x1, x2)) then begin cal := abs(zi - z); if cal <= dmin then begin dmin := cal; itw := w; end; end; end; { if HORIZONTAL } end; ASector := Sector; AWall := itw; GetNearestWL := TRUE end else GetNearestWL := FALSE; end; function GetNearestSC(L:TLevel; Layer:Integer; X, Z : Double; VAR ASector : Integer) : Boolean; var NewSc:Integer; begin NewSC:=-1; Result:=GetNextNearestSC(L,Layer,X,Z,NewSC); if Result then ASector:=NewSC; end; function GetNextNearestSC(L:TLevel; Layer:Integer; X, Z : Double; VAR ASector : Integer) : Boolean; var TheSector : TSector; TheSector2 : TSector; TheWall : TWall; LVertex, RVertex : TVertex; s, w, its, itw : Integer; x1, z1, x2, z2, dd, a1, b1, a2, b2 : Double; dmin, cal : Double; xx, xi, zi : Double; ox, oz, deltax, deltaz, dx, dz, gx, gz : Double; dist_d, dist_g : Double; begin dmin := 999999.0; its := -1; With L do for s := 0 to Sectors.Count - 1 do begin TheSector := Sectors[s]; if (Layer=Any_Layer) or (TheSector.Layer = LAYER) and (s<>ASector) then begin for w := 0 to TheSector.Walls.Count - 1 do begin TheWall := TheSector.Walls[w]; LVertex := TheSector.Vertices[TheWall.V1]; RVertex := TheSector.Vertices[TheWall.V2]; x1 := LVertex.X; z1 := LVertex.Z; x2 := RVertex.X; z2 := RVertex.Z; if z1 <> z2 then { if not HORIZONTAL } begin if x1 = x2 then { if VERTICAL} begin xi := x1; end else begin dd := (z1 - z2) / (x1 - x2); xi := (z + dd * x1 - z1) / dd; end; {if VERTICAL} if (z >= real_min(z1, z2)) and (z <= real_max(z1, z2)) then { if intersection on wall } begin cal := abs(xi - x); { a test on the orientation of the wall } ox := (x1 + x2) / 2; oz := (z1 + z2) / 2; deltax := x1 - x2; deltaz := z1 - z2; dx := ox - deltaz; dz := oz + deltax; gx := ox + deltaz; gz := oz - deltax; dist_d := (dx - x) * (dx - x) + (dz - z) * (dz - z); dist_g := (gx - x) * (gx - x) + (gz - z) * (gz - z); { must be <= to give adjoins a chance ! } if cal <= dmin then begin if dist_d > dist_g then begin if TheWall.Adjoin <> -1 then begin if TheWall.Adjoin<>ASector then begin its := TheWall.Adjoin; { adjoin could be on wrong layer! } TheSector2 := Sectors[its]; if Layer<>Any_Layer then if TheSector2.layer <> LAYER then its := -1; dmin := cal; end {If Adjoin<>Asector sector} end else begin its := -1; dmin := cal; end; end else begin its := s; dmin := cal; end; end; end; { if intersection on wall } end; { if not HORIZONTAL } end; { for WALLS } end; { if LAYER } end; { for SECTORS } if its <> -1 then begin ASector := its; GetNextNearestSC := TRUE; end else begin GetNextNearestSC := FALSE; end; end; function GetNearestVX(L:TLevel; Layer:Integer; X, Z : Double; VAR ASector : Integer; VAR AVertex : Integer) : Boolean; var TheSector : TSector; TheVertex : TVertex; s, v, its, itv : Integer; cal, dmin : Double; begin dmin := 99999; its := -1; With L do for s := 0 to Sectors.Count - 1 do begin TheSector := Sectors[s]; if (Layer=Any_Layer) or (TheSector.Layer = LAYER) then begin for v := 0 to TheSector.Vertices.Count - 1 do begin TheVertex := TheSector.Vertices[v]; cal := (TheVertex.X - X) * (TheVertex.X - X) + (TheVertex.Z - Z) * (TheVertex.Z - Z); if cal < dmin then begin dmin := cal; its := s; itv := v; end; end; end; end; if its <> -1 then begin ASector := its; AVertex := itv; GetNearestVX := TRUE; end else GetNearestVX := FALSE; end; function GetNearestOB(L:TLevel; Layer:Integer; X, Z : Double; VAR AObject : Integer) : Boolean; var TheObject : TOB; TheSector : TSector; TheLayer : Integer; o, ito : Integer; cal, dmin : Double; begin dmin := 99999; ito := -1; With L do for o := 0 to Objects.Count - 1 do begin TheObject := Objects[o]; {if not DifficultyOk(TheObject) then continue;} if TheObject.Sector <> -1 then begin TheSector := Sectors[TheObject.Sector]; TheLayer := TheSector.Layer; end else TheLayer := 9999; if (Layer=Any_Layer) or (TheLayer = LAYER) or (TheLayer = 9999) then begin cal := (TheObject.X - X) * (TheObject.X - X) + (TheObject.Z - Z) * (TheObject.Z - Z); if cal < dmin then begin dmin := cal; ito := o; end; end; end; if ito <> -1 then begin AObject := ito; GetNearestOB := TRUE; end else GetNearestOB := FALSE; end; function GetNextNearestVX(L:TLevel; Layer:Integer; X, Z : Double; VAR ASector : Integer; VAR AVertex : Integer) : Boolean; var TheSector : TSector; TheVertex : TVertex; s, v, its, itv : Integer; cal, dmin : Double; begin dmin := 99999; its := -1; With L do for s := 0 to Sectors.Count - 1 do begin TheSector := Sectors[s]; if (Layer=Any_Layer) or (TheSector.Layer = LAYER) then begin for v := 0 to TheSector.Vertices.Count - 1 do begin TheVertex := TheSector.Vertices[v]; cal := (TheVertex.X - X) * (TheVertex.X - X) + (TheVertex.Z - Z) * (TheVertex.Z - Z); if cal < dmin then begin if (s <> ASector) or (v <> AVertex) then dmin := cal; its := s; itv := v; end; end; end; end; if its<>-1 then begin Asector:=its; Avertex:=itv; Result:=true; end else Result:=false; end; function GetObjectSC(L:TLevel;obnum: Integer; VAR ASector : Integer) : Boolean; var sc : Integer; TheObject : TOB; TheSector : TSector; aLayer:Integer; begin TheObject := L.Objects[obnum]; Result := FALSE; Sc:=-1; For aLayer:=l.MinLayer to L.MaxLayer do if GetNearestSC(L,aLayer,TheObject.X, TheObject.Z, sc) then begin TheSector := l.Sectors[sc]; if (TheObject.Y >= TheSector.Floor_Y) and (TheObject.Y <= TheSector.Ceiling_Y) then begin ASector := sc; Result:=true; Break; end; end; end; Procedure ApplyFixUp(L:TLevel;const Name:String); var t:TTextFile; s,w1,w2:String; p:Integer; TheWall:TWall; TheSector:TSector; Procedure ReadFmt(const Fmt:String;args:array of pointer); begin t.Readln(s); SScanf(s,fmt,args); end; Procedure LoadWall; Var ID,N:Longint; begin ReadFmt('SECTOR_TAG: %x',[@ID]); N:=L.GetSectorByID(ID); if N=-1 then exit; TheSector:=l.Sectors[N]; ReadFmt('WALL_TAG: %x',[@ID]); N:=TheSector.GetWallByID(ID); if N=-1 then begin PanMessage(mt_Warning,Format('Couldn''t find sector with ID %x',[ID])); exit; end; TheWall:=TheSector.Walls[n]; if N=-1 then begin PanMessage(mt_Warning,Format('Couldn''t find wall with ID %x',[ID])); exit; end; With TheWall do begin ReadFmt('UPPER_TEXTURE: %s %f %f',[@TOP.Name,@TOP.OffsX,@TOP.OffsY]); ReadFmt('MIDDLE_TEXTURE: %s %f %f',[@MID.Name,@MID.OffsX,@MID.OffsY]); ReadFmt('LOWER_TEXTURE: %s %f %f',[@BOT.Name,@BOT.OffsX,@BOT.OffsY]); ReadFmt('OVERLAY_TEXTURE: %s %f %f',[@Overlay.Name,@Overlay.OffsX,@Overlay.OffsY]); if Overlay.Name='-' then Overlay.Name:=''; ReadFmt('FLAG_1: %x',[@flags]); end; end; Procedure LoadSector; Var ID,N:Longint; begin ReadFmt('TAG: %x',[@ID]); N:=L.GetSectorByID(ID); if N=-1 then begin PanMessage(mt_Warning,Format('Couldn''t find sector with ID %x',[ID])); exit; end; TheSector:=l.Sectors[n]; With TheSector do begin ReadFmt('LIGHT: %b',[@Ambient]); ReadFmt('FLAG_1: %x',[@Flags]); ReadFmt('FLAG_2: %x',[@ID]); ReadFmt('FLAG_3: %x',[@ID]); ReadFmt('CEILING: %f %s %f %f %f', [@Ceiling_Y,@Ceiling_Texture.Name,@Ceiling_Texture.OffsX, @Ceiling_Texture.OffsY,@Ceiling_extra]); ReadFmt('OVERLAY: %s %f %f',[@C_Overlay_texture.Name,@C_Overlay_Texture.OffsX, @C_Overlay_Texture.OffsY,@C_OverLay_Extra]); if C_Overlay_Texture.Name='-' then C_Overlay_Texture.Name:=''; ReadFmt('FLOORS: %d',[@ID]); ReadFmt('FLOOR: %f %s %f %f %f', [@Floor_Y,@Floor_Texture.Name,@Floor_Texture.OffsX, @Floor_Texture.OffsY,@Floor_extra]); ReadFmt('OVERLAY: %s %f %f',[@F_OverLay_texture.Name,@F_OverLay_Texture.OffsX, @F_OverLay_Texture.OffsY,@F_OverLay_Extra]); if F_Overlay_Texture.Name='-' then F_Overlay_Texture.Name:=''; if F_Overlay_Texture.Name='-' then F_Overlay_Texture.Name:=''; With FloorSlope do ReadFmt('FLOOR SLOPE: %x %x %f',[@Sector,@Wall,@angle]); With CeilingSlope do ReadFmt('CEILING SLOPE: %x %x %f',[@Sector,@Wall,@angle]); ReadFmt('FRICTION: %f',[@friction]); ReadFmt('GRAVITY: %f',[@gravity]); ReadFmt('ELASTICITY: %f',[@Elasticity]); With Velocity do ReadFmt('VELOCITY: %f %f %f',[@dx,@dy,@dz]); ReadFmt('STEP SOUND: %s',[@Floor_Sound]); end; end; var OldCurSor:HCursor; begin {ApplyFixUp} OldCursor:=SetCursor(LoadCursor(0, IDC_WAIT)); T:=TTextFile.CreateRead(OpenFileRead(Name,0)); Try While not t.Eof do begin t.Readln(s); p:=GetWord(s,1,w1); p:=GetWord(s,p,w2); if w1<>'FIXUP:' then continue; if w2='WALL' then LoadWall else if w2='SECTOR' then LoadSector else if w2='DONE' then break; end; Finally T.FClose; SetCursor(OldCursor); end; end; Function IsInSector(Sc:TSector;ptx,ptz:double):boolean; function GetAngle(x,z:Double;vx1,vx2:TVertex):Double; {calculates angle formed by the X,Z and vertices of the wall} var a2,b2,c2:Double; {square of triangle sides} d:Double; begin a2:=Sqr(vx1.x-x)+sqr(vx1.z-z); b2:=Sqr(vx2.x-x)+sqr(vx2.z-z); c2:=Sqr(vx2.x-vx1.x)+sqr(vx2.z-vx1.z); d:=(a2-c2+b2)/(2*sqrt(b2)); Result:=ArcCos(d/sqrt(a2)); end; var i:Integer; ang:Double; begin {IsInSector} ang:=0; for i:=0 to Sc.Walls.Count-1 do With Sc.Walls[i] do begin ang:=ang+GetAngle(ptx,ptz,Sc.Vertices[V1],Sc.Vertices[V2]); end; Result:=RoundTo2Dec(ang)<>0; end; end.
unit mtTestWebSockets; interface uses TestFramework, IdHTTPWebsocketClient, IdServerWebsocketContext, IdWebsocketServer, IdContext, IdCustomHTTPServer; type TTextCallback = reference to procedure(aText: string); TTestWebSockets = class(TTestCase) private class var IndyHTTPWebsocketServer1: TIdWebsocketServer; class var IndyHTTPWebsocketClient1: TIdHTTPWebsocketClient; protected FLastWSMsg: string; FLastSocketIOMsg: string; procedure HandleHTTPServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure WebsocketTextMessage(const aData: string); procedure HandleWebsocketTextMessage(const AContext: TIdServerWSContext; const aText: string); public procedure SetUp; override; procedure TearDown; override; published procedure CreateObjects; procedure StartServer; procedure TestPlainHttp; procedure TestWebsocketMsg; procedure TestSocketIOMsg; procedure TestSocketIOCallback; procedure TestSocketIOError; procedure DestroyObjects; end; TBooleanFunction = reference to function: Boolean; function MaxWait(aProc: TBooleanFunction; aMaxWait_msec: Integer): Boolean; implementation uses Windows, Forms, DateUtils, SysUtils, Classes, IdSocketIOHandling, superobject, IdIOHandlerWebsocket; function MaxWait(aProc: TBooleanFunction; aMaxWait_msec: Integer): Boolean; var tStart: TDateTime; begin tStart := Now; Result := aProc; while not Result and (MilliSecondsBetween(Now, tStart) <= aMaxWait_msec) do begin Sleep(10); if GetCurrentThreadId = MainThreadID then CheckSynchronize(10); Result := aProc; end; end; { TTestWebSockets } procedure TTestWebSockets.SetUp; begin inherited; end; procedure TTestWebSockets.TearDown; begin inherited; end; procedure TTestWebSockets.CreateObjects; begin IndyHTTPWebsocketServer1 := TIdWebsocketServer.Create(nil); IndyHTTPWebsocketServer1.DefaultPort := 8099; IndyHTTPWebsocketServer1.KeepAlive := True; //IndyHTTPWebsocketServer1.DisableNagle := True; //SendClientAccessPolicyXml = captAllowAll //SendCrossOriginHeader = True IndyHTTPWebsocketClient1 := TIdHTTPWebsocketClient.Create(nil); IndyHTTPWebsocketClient1.Host := 'localhost'; IndyHTTPWebsocketClient1.Port := 8099; IndyHTTPWebsocketClient1.SocketIOCompatible := True; end; procedure TTestWebSockets.DestroyObjects; begin IndyHTTPWebsocketClient1.Free; IndyHTTPWebsocketServer1.Free; end; procedure TTestWebSockets.HandleHTTPServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var sfile: string; begin if ARequestInfo.Document = '/index.html' then AResponseInfo.ContentText := 'dummy index.html' else begin sfile := ExtractFilePath(Application.ExeName) + ARequestInfo.Document; if FileExists(sfile) then AResponseInfo.ContentStream := TFileStream.Create(sfile, fmOpenRead); end; end; procedure TTestWebSockets.StartServer; begin IndyHTTPWebsocketServer1.Active := True; end; procedure TTestWebSockets.TestPlainHttp; var strm: TMemoryStream; s: string; client: TIdHTTPWebsocketClient; begin client := TIdHTTPWebsocketClient.Create(nil); try client.Host := 'localhost'; client.Port := 8099; client.SocketIOCompatible := False; //plain http now IndyHTTPWebsocketServer1.OnCommandGet := HandleHTTPServerCommandGet; IndyHTTPWebsocketServer1.OnCommandOther := HandleHTTPServerCommandGet; strm := TMemoryStream.Create; try client.Get('http://localhost:8099/index.html', strm); with TStreamReader.Create(strm) do begin strm.Position := 0; s := ReadToEnd; Free; end; CheckEquals('dummy index.html', s); finally strm.Free; end; finally client.Free; end; end; procedure TTestWebSockets.TestSocketIOCallback; var received: string; begin //* client to server */ received := ''; IndyHTTPWebsocketServer1.SocketIO.OnEvent('TEST_EVENT', procedure(const ASocket: ISocketIOContext; const aArgument: TSuperArray; const aCallbackObj: TSocketIOCallbackObj) begin received := aArgument.ToJson; end); if not IndyHTTPWebsocketClient1.Connected then begin IndyHTTPWebsocketClient1.Connect; IndyHTTPWebsocketClient1.UpgradeToWebsocket; end; IndyHTTPWebsocketClient1.SocketIO.Emit('TEST_EVENT', SO('test event'), nil); MaxWait( function: Boolean begin Result := received <> ''; end, 10 * 1000); received := StringReplace(received, #13#10, '', [rfReplaceAll]); CheckEqualsString('["test event"]', received); //* server to client */ received := ''; IndyHTTPWebsocketClient1.SocketIO.OnEvent('TEST_EVENT', procedure(const ASocket: ISocketIOContext; const aArgument: TSuperArray; const aCallbackObj: TSocketIOCallbackObj) begin received := aArgument.ToJson; end); IndyHTTPWebsocketServer1.SocketIO.EmitEventToAll('TEST_EVENT', SO('test event'), nil); MaxWait( function: Boolean begin Result := received <> ''; end, 10 * 1000); received := StringReplace(received, #13#10, '', [rfReplaceAll]); CheckEqualsString('["test event"]', received); end; procedure TTestWebSockets.TestSocketIOError; begin //disconnect: mag geen AV's daarna geven! IndyHTTPWebsocketClient1.Disconnect(False); IndyHTTPWebsocketClient1.Connect; IndyHTTPWebsocketClient1.UpgradeToWebsocket; //* client to server */ FLastSocketIOMsg := ''; IndyHTTPWebsocketServer1.SocketIO.OnSocketIOMsg := procedure(const ASocket: ISocketIOContext; const aText: string; const aCallback: TSocketIOCallbackObj) begin Abort; end; IndyHTTPWebsocketClient1.SocketIO.Send('test message', procedure(const ASocket: ISocketIOContext; const aJSON: ISuperObject; const aCallback: TSocketIOCallbackObj) begin FLastSocketIOMsg := aJSON.AsString; end); MaxWait( function: Boolean begin Result := FLastSocketIOMsg <> ''; end, 10 * 1000); CheckEquals('[{"Error":{"Message":"Operation aborted","Type":"EAbort"}}]', FLastSocketIOMsg); FLastSocketIOMsg := ''; IndyHTTPWebsocketClient1.SocketIO.Send('test message', procedure(const ASocket: ISocketIOContext; const aJSON: ISuperObject; const aCallback: TSocketIOCallbackObj) begin Assert(False, 'should go to error handling callback'); FLastSocketIOMsg := 'error'; end, procedure(const ASocket: ISocketIOContext; const aErrorClass, aErrorMessage: string) begin FLastSocketIOMsg := aErrorMessage; end); MaxWait( function: Boolean begin Result := FLastSocketIOMsg <> ''; end, 10 * 1000); CheckEquals('Operation aborted', FLastSocketIOMsg); end; procedure TTestWebSockets.TestSocketIOMsg; begin //disconnect: mag geen AV's daarna geven! IndyHTTPWebsocketClient1.Disconnect(True); IndyHTTPWebsocketClient1.ResetChannel; IndyHTTPWebsocketClient1.SocketIOCompatible := True; IndyHTTPWebsocketClient1.Connect; IndyHTTPWebsocketClient1.UpgradeToWebsocket; //* client to server */ FLastSocketIOMsg := ''; IndyHTTPWebsocketServer1.SocketIO.OnSocketIOMsg := procedure(const ASocket: ISocketIOContext; const aText: string; const aCallback: TSocketIOCallbackObj) begin FLastSocketIOMsg := aText; end; IndyHTTPWebsocketClient1.SocketIO.Send('test message'); MaxWait( function: Boolean begin Result := FLastSocketIOMsg <> ''; end, 10 * 1000); CheckEquals('test message', FLastSocketIOMsg); //* server to client */ FLastSocketIOMsg := ''; IndyHTTPWebsocketClient1.SocketIO.OnSocketIOMsg := procedure(const ASocket: ISocketIOContext; const aText: string; const aCallback: TSocketIOCallbackObj) begin FLastSocketIOMsg := aText; end; if IndyHTTPWebsocketServer1.SocketIO.SendToAll('test message') = 0 then Check(False, 'nothing send'); MaxWait( function: Boolean begin Result := FLastSocketIOMsg <> ''; end, 10 * 1000); CheckEquals('test message', FLastSocketIOMsg); //disconnect: mag geen AV's daarna geven! IndyHTTPWebsocketClient1.Disconnect(False); IndyHTTPWebsocketClient1.Connect; IndyHTTPWebsocketClient1.UpgradeToWebsocket; IndyHTTPWebsocketClient1.SocketIO.Send('test message'); end; procedure TTestWebSockets.TestWebsocketMsg; var client: TIdHTTPWebsocketClient; begin client := TIdHTTPWebsocketClient.Create(nil); try client.Host := 'localhost'; client.Port := 8099; client.SocketIOCompatible := False; client.OnTextData := WebsocketTextMessage; IndyHTTPWebsocketServer1.OnMessageText := HandleWebsocketTextMessage; //client.Connect; client.UpgradeToWebsocket; client.IOHandler.Write('websocket client to server'); MaxWait( function: Boolean begin Result := FLastWSMsg <> ''; end, 10 * 1000); CheckEquals('websocket server to client', FLastWSMsg); finally client.Free; end; end; procedure TTestWebSockets.HandleWebsocketTextMessage( const AContext: TIdServerWSContext; const aText: string); begin if aText = 'websocket client to server' then AContext.IOHandler.Write('websocket server to client'); end; procedure TTestWebSockets.WebsocketTextMessage(const aData: string); begin FLastWSMsg := aData; end; end.
unit uPageObject; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, ExtCtrls, StdCtrls, uGlobal; type TPageObject = class protected Panel: TPanel; Border: TImageArray; Position: Integer; Checkbox: TImage; ContainerWidth: Integer; procedure CheckboxClick(Sender: TObject); procedure PanelResize(Sender: TObject); function GetHeight: Integer; function GetBottom: Integer; function GetTop: Integer; procedure SetTop(k: Integer); public property Top: Integer read GetTop write SetTop; property Bottom: Integer read GetBottom; property Height: Integer read GetHeight; constructor Create(WC: TWinControl; Pos, _ContainerWidth: Integer); destructor Destroy; override; end; implementation destructor TPageObject.Destroy; begin if Assigned(Panel) then FreeAndNil(Panel); end; procedure TPageObject.PanelResize(Sender: TObject); begin Checkbox.Top := (Panel.Height - Checkbox.Height) div 2; end; procedure TPageObject.CheckboxClick(Sender: TObject); begin with (Sender as TImage) do begin case Tag of 0: Tag := 1; 1: Tag := 0; end; Picture.LoadFromFile('./src/icons/checkbox_' + Tag.ToString + '.png'); end; end; function TPageObject.GetHeight: Integer; begin Result := Panel.Height; end; procedure TPageObject.SetTop(k: Integer); begin Panel.BorderSpacing.Top := k; end; function TPageObject.GetTop: Integer; begin Result := Panel.BorderSpacing.Top; end; function TPageObject.GetBottom: Integer; begin Result := GetTop + Panel.Height; end; constructor TPageObject.Create(WC: TWinControl; Pos, _ContainerWidth: Integer); begin Position := Pos; ContainerWidth := _ContainerWidth; Panel := TPanel.Create(Nil); with Panel do begin Parent := WC; AnchorToParent(TControl(Panel), [akLeft, akTop, akRight]); BorderSpacing.Left := 16; BorderSpacing.Top := Pos; BorderSpacing.Right := 16; BorderStyle := bsNone; BevelOuter := bvNone; BevelInner := bvNone; Height := 100; Color := $00FFFFFF; OnResize := @PanelResize; end; // Checkbox Checkbox := TImage.Create(Nil); with Checkbox do begin Parent := Panel; Width := 16; Height := 16; Top := (Parent.Height - Height) div 2; Left := 16; Picture.LoadFromFile('./src/icons/checkbox_0.png'); Cursor := crHandpoint; Tag := 0; OnClick := @CheckboxClick; end; // Border SetLength(Border, 8); case Random(3) of 0: Border := CardBorder(Panel, 'b'); 1: Border := CardBorder(Panel, 'g'); 2: Border := CardBorder(Panel, 'p'); end; end; end.
unit ComparatorFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Spin, InflatablesList_HTML_ElementFinder, InflatablesList_Manager; type TfrmComparatorFrame = class(TFrame) pnlMain: TPanel; leString: TLabeledEdit; lblVarIndex: TLabel; seVarIndex: TSpinEdit; cbCaseSensitive: TCheckBox; cbAllowPartial: TCheckBox; bvlStrSeparator: TBevel; lblOperator: TLabel; cmbOperator: TComboBox; cbNegate: TCheckBox; cbNestedText: TCheckBox; procedure leStringChange(Sender: TObject); procedure seVarIndexChange(Sender: TObject); procedure cbCaseSensitiveClick(Sender: TObject); procedure cbAllowPartialClick(Sender: TObject); procedure cmbOperatorChange(Sender: TObject); procedure cbNegateClick(Sender: TObject); procedure cbNestedTextClick(Sender: TObject); private fInitializing: Boolean; fILManager: TILManager; fComparator: TILFinderBaseClass; protected procedure PropagateChange; procedure FramePrepare; procedure FrameClear; procedure FrameSave; procedure FrameLoad; public OnChange: TNotifyEvent; procedure Initialize(ILManager: TILManager); procedure Finalize; procedure Save; procedure Load; procedure SetComparator(Comparator: TILFinderBaseClass; ProcessChange: Boolean); end; implementation {$R *.dfm} procedure TfrmComparatorFrame.PropagateChange; begin If Assigned(OnChange) then OnChange(Self); end; //------------------------------------------------------------------------------ procedure TfrmComparatorFrame.FramePrepare; begin leString.Visible := fComparator is TILTextComparator; lblVarIndex.Visible := fComparator is TILTextComparator; seVarIndex.Visible := fComparator is TILTextComparator; cbCaseSensitive.Visible := fComparator is TILTextComparator; cbAllowPartial.Visible := fComparator is TILTextComparator; bvlStrSeparator.Visible := (fComparator is TILTextComparator) and not fComparator.IsLeading; lblOperator.Visible := (fComparator is TILComparatorBase) and not fComparator.IsLeading; cmbOperator.Visible := (fComparator is TILComparatorBase) and not fComparator.IsLeading; cbNegate.Visible := (fComparator is TILComparatorBase) and not fComparator.IsLeading; cbNestedText.Visible := fComparator is TILElementComparator; end; //------------------------------------------------------------------------------ procedure TfrmComparatorFrame.FrameClear; begin leString.Text := ''; seVarIndex.Value := 0; cbCaseSensitive.Checked := False; cbAllowPartial.Checked := False; cmbOperator.ItemIndex := 0; cbNegate.Checked := False; cbNestedText.Checked := False; end; //------------------------------------------------------------------------------ procedure TfrmComparatorFrame.FrameSave; begin If Assigned(fComparator) then begin If not(fComparator is TILElementComparator) then begin If fComparator is TILTextComparator then begin TILTextComparator(fComparator).Str := leString.Text; TILTextComparator(fComparator).VariableIndex := seVarIndex.Value - 1; TILTextComparator(fComparator).CaseSensitive := cbCaseSensitive.Checked; TILTextComparator(fComparator).AllowPartial := cbAllowPartial.Checked; end; If fComparator is TILComparatorBase then begin TILComparatorBase(fComparator).Operator := TILSearchOperator(cmbOperator.ItemIndex); TILComparatorBase(fComparator).Negate := cbNegate.Checked; end; end else TILElementComparator(fComparator).NestedText := cbNestedText.Checked; end; end; //------------------------------------------------------------------------------ procedure TfrmComparatorFrame.FrameLoad; begin If Assigned(fComparator) then begin FramePrepare; fInitializing := True; try If not(fComparator is TILElementComparator) then begin If fComparator is TILTextComparator then begin leString.Text := TILTextComparator(fComparator).Str; seVarIndex.Value := TILTextComparator(fComparator).VariableIndex + 1; cbCaseSensitive.Checked := TILTextComparator(fComparator).CaseSensitive; cbAllowPartial.Checked := TILTextComparator(fComparator).AllowPartial; end; If fComparator is TILComparatorBase then begin cmbOperator.ItemIndex := Ord(TILComparatorBase(fComparator).Operator); cbNegate.Checked := TILComparatorBase(fComparator).Negate; end; end else cbNestedText.Checked := TILElementComparator(fComparator).NestedText; finally fInitializing := False; end; end; end; //============================================================================== procedure TfrmComparatorFrame.Initialize(ILManager: TILManager); var i: TILSearchOperator; begin fILManager := ILManager; // fill combobox cmbOperator.Items.BeginUpdate; try cmbOperator.Clear; For i := Low(TILSearchOperator) to High(TILSearchOperator) do cmbOperator.Items.Add(IL_SearchOperatorAsStr(i)); finally cmbOperator.Items.EndUpdate; end; If cmbOperator.Items.Count > 0 then cmbOperator.ItemIndex := 0; end; //------------------------------------------------------------------------------ procedure TfrmComparatorFrame.Finalize; begin // nothing to o here end; //------------------------------------------------------------------------------ procedure TfrmComparatorFrame.Save; begin FrameSave; end; //------------------------------------------------------------------------------ procedure TfrmComparatorFrame.Load; begin If Assigned(fComparator) then FrameLoad else FrameClear; end; //------------------------------------------------------------------------------ procedure TfrmComparatorFrame.SetComparator(Comparator: TILFinderBaseClass; ProcessChange: Boolean); var Reassigned: Boolean; begin Reassigned := fComparator = Comparator; If ProcessChange then begin If Assigned(fComparator) and not Reassigned then FrameSave; If Assigned(Comparator) then begin fComparator := Comparator; If not Reassigned then FrameLoad; end else begin fComparator := nil; FrameClear; end; Visible := Assigned(fComparator); Enabled := Assigned(fComparator); end else fComparator := Comparator; end; //============================================================================== procedure TfrmComparatorFrame.leStringChange(Sender: TObject); begin If (fComparator is TILTextComparator) and not fInitializing then begin TILTextComparator(fComparator).Str := leString.Text; PropagateChange; end; end; //------------------------------------------------------------------------------ procedure TfrmComparatorFrame.seVarIndexChange(Sender: TObject); begin If (fComparator is TILTextComparator) and not fInitializing then begin TILTextComparator(fComparator).VariableIndex := seVarIndex.Value - 1; PropagateChange; end; end; //------------------------------------------------------------------------------ procedure TfrmComparatorFrame.cbCaseSensitiveClick(Sender: TObject); begin If (fComparator is TILTextComparator) and not fInitializing then begin TILTextComparator(fComparator).CaseSensitive := cbCaseSensitive.Checked; PropagateChange; end; end; //------------------------------------------------------------------------------ procedure TfrmComparatorFrame.cbAllowPartialClick(Sender: TObject); begin If (fComparator is TILTextComparator) and not fInitializing then begin TILTextComparator(fComparator).AllowPartial := cbAllowPartial.Checked; PropagateChange; end; end; //------------------------------------------------------------------------------ procedure TfrmComparatorFrame.cmbOperatorChange(Sender: TObject); begin If (fComparator is TILComparatorBase) and not fInitializing then begin TILComparatorBase(fComparator).Operator := TILSearchOperator(cmbOperator.ItemIndex); PropagateChange; end; end; //------------------------------------------------------------------------------ procedure TfrmComparatorFrame.cbNegateClick(Sender: TObject); begin If (fComparator is TILComparatorBase) and not fInitializing then begin TILComparatorBase(fComparator).Negate := cbNegate.Checked; PropagateChange; end; end; //------------------------------------------------------------------------------ procedure TfrmComparatorFrame.cbNestedTextClick(Sender: TObject); begin If (fComparator is TILElementComparator) and not fInitializing then begin TILElementComparator(fComparator).NestedText := cbNestedText.Checked; PropagateChange; end; end; end.