text
stringlengths
14
6.51M
unit FreeOTFEExplorerfrmPropertiesDlg_Multiple; interface uses Classes, ComCtrls, Controls, Dialogs, ExtCtrls, Forms, FreeOTFEExplorerfrmPropertiesDlg_Base, Graphics, Messages, StdCtrls, SysUtils, Variants, Windows; type TfrmPropertiesDialog_Multiple = class (TfrmPropertiesDialog) procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); PRIVATE { Private declarations } PUBLIC MultipleItems: TStringList; ParentDir: WideString; end; implementation {$R *.dfm} uses SDFilesystem_FAT, SDUGeneral, SDUGraphics, SDUi18n; procedure TfrmPropertiesDialog_Multiple.FormCreate(Sender: TObject); begin inherited; MultipleItems := TStringList.Create(); end; procedure TfrmPropertiesDialog_Multiple.FormDestroy(Sender: TObject); begin MultipleItems.Free(); inherited; end; procedure TfrmPropertiesDialog_Multiple.FormShow(Sender: TObject); var totalSize: ULONGLONG; totalDirCnt: Integer; totalFileCnt: Integer; tmpIcon: TIcon; tmpSize: ULONGLONG; tmpDirCnt: Integer; tmpFileCnt: Integer; i: Integer; allOK: Boolean; filenamesOnlyCommaText: String; begin inherited; for i := 0 to (MultipleItems.Count - 1) do begin if (filenamesOnlyCommaText <> '') then begin filenamesOnlyCommaText := filenamesOnlyCommaText + ', '; end; filenamesOnlyCommaText := filenamesOnlyCommaText + ExtractFilename(MultipleItems[i]); end; self.Caption := SDUParamSubstitute(_('%1 Properties'), [filenamesOnlyCommaText]); totalSize := 0; totalDirCnt := 0; totalFileCnt := 0; for i := 0 to (MultipleItems.Count - 1) do begin allOK := Filesystem.ItemSize(MultipleItems[i], tmpSize, tmpDirCnt, tmpFileCnt); if not (allOK) then begin break; end else begin totalSize := totalSize + tmpSize; totalDirCnt := totalDirCnt + tmpDirCnt; totalFileCnt := totalFileCnt + tmpFileCnt; end; end; // Change borders on "filename"; user can *never* edit it, so make it look // more like a label edFilename.BevelOuter := bvNone; edFilename.BevelInner := bvNone; edFilename.BorderStyle := bsNone; edFilename.Text := SDUParamSubstitute(_('%1 Files, %2 Folders'), [totalFileCnt, totalDirCnt]); edFileType.Caption := _('Multiple types'); edLocation.Caption := SDUParamSubstitute(_('All in %1'), [ParentDir]); edSize.Caption := SDUParamSubstitute(_('%1 (%2 bytes)'), [SDUFormatAsBytesUnits(totalSize, 2), SDUIntToStrThousands(totalSize)]); tmpIcon := TIcon.Create(); try if SDULoadDLLIcon(DLL_SHELL32, False, DLL_SHELL32_MULTIPLE_FILES, tmpIcon) then begin imgFileType.Picture.Assign(tmpIcon); end; finally tmpIcon.Free(); end; end; end.
unit TipoProduto; interface type TTipoProduto = class private FCodigo: string; FDescricao: string; public property Codigo: string read FCodigo write FCodigo; property Descricao: string read FDescricao write FDescricao; constructor Create; overload; constructor Create(Codigo: string); overload; constructor Create(Codigo, Descricao: string); overload; end; implementation { TTipoProduto } constructor TTipoProduto.Create; begin end; constructor TTipoProduto.Create(Codigo: string); begin Self.Codigo := Codigo; end; constructor TTipoProduto.Create(Codigo, Descricao: string); begin Self.Codigo := Codigo; Self.Descricao := Descricao; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.StdCtrls, FMX.Controls.Presentation; type TForm1 = class(TForm) FormImageLabel: TLabel; FormImage: TImage; ResourceImageLabel: TLabel; ResourceImage: TImage; LanguageButton: TButton; procedure FormCreate(Sender: TObject); procedure LanguageButtonClick(Sender: TObject); private procedure UpdateValues; end; var Form1: TForm1; implementation {$R *.fmx} uses NtResource, NtResourceString, FMX.NtImageTranslator, FMX.NtLanguageDlg, FMX.NtTranslator; procedure TForm1.UpdateValues; var stream: TStream; begin stream := NtResources.GetResource('Image1'); try ResourceImage.Bitmap.LoadFromStream(stream); finally stream.Free; end; end; procedure TForm1.FormCreate(Sender: TObject); resourcestring SEnglish = 'English'; SFinnish = 'Finnish'; SGerman = 'German'; SFrench = 'French'; SJapanese = 'Japanese'; begin // Add language names so they can be localized // Attach a flag image to each name so the language dialog can show the flag with language name NtResources.Add('English', 'English', SEnglish, 'en').AddImage('en'); NtResources.Add('Finnish', 'suomi', SFinnish, 'fi').AddImage('fi'); NtResources.Add('German', 'Deutsch', SGerman, 'de').AddImage('de'); NtResources.Add('French', 'français', SFrench, 'fr').AddImage('fr'); NtResources.Add('Japanese', '日本語', SJapanese, 'ja').AddImage('ja'); _T(Self); UpdateValues; end; procedure TForm1.LanguageButtonClick(Sender: TObject); begin TNtLanguageDialog.Select( procedure begin UpdateValues; end); end; end.
unit uBrowserEmbedDraw; interface uses Winapi.Windows, Vcl.Graphics, Vcl.OleCtrls, MSHTML, ExplorerTypes, uConstants, uMemory, uBitmapUtils; type _HTML_PAINT_XFORM = packed record eM11: Single; eM12: Single; eM21: Single; eM22: Single; eDx: Single; eDy: Single; end; P_HTML_PAINT_DRAW_INFO = ^_HTML_PAINT_DRAW_INFO; _HTML_PAINT_DRAW_INFO = packed record rcViewport: tagRECT; hrgnUpdate: Pointer; xform: _HTML_PAINT_XFORM; end; PtagRECT = ^tagRECT; _HTML_PAINTER_INFO = packed record lFlags: Integer; lZOrder: Integer; iidDrawObject: TGUID; rcExpand: tagRECT; end; tagSIZE = packed record cx: Integer; cy: Integer; end; IHTMLPaintSite = interface(IUnknown) ['{3050F6A7-98B5-11CF-BB82-00AA00BDCE0B}'] function InvalidatePainterInfo: HResult; stdcall; function InvalidateRect(prcInvalid: PtagRECT): HResult; stdcall; function InvalidateRegion(var rgnInvalid: Pointer): HResult; stdcall; function GetDrawInfo(lFlags: Integer; out pDrawInfo: _HTML_PAINT_DRAW_INFO): HResult; stdcall; function TransformGlobalToLocal(ptGlobal: tagPOINT; out pptLocal: tagPOINT): HResult; stdcall; function TransformLocalToGlobal(ptLocal: tagPOINT; out pptGlobal: tagPOINT): HResult; stdcall; function GetHitTestCookie(out plCookie: Integer): HResult; stdcall; end; IHTMLPainter = interface(IUnknown) ['{3050F6A6-98B5-11CF-BB82-00AA00BDCE0B}'] function Draw(rcBounds: tagRECT; rcUpdate: tagRECT; lDrawFlags: Integer; hdc: hdc; pvDrawObject: Pointer): HResult; stdcall; function onresize(size: tagSIZE): HResult; stdcall; function GetPainterInfo(out pInfo: _HTML_PAINTER_INFO): HResult; stdcall; function HitTestPoint(pt: tagPOINT; out pbHit: Integer; out plPartID: Integer): HResult; stdcall; end; TElementBehavior = class(TInterfacedObject, IElementBehavior, IHTMLPainter) private FPaintSite: IHTMLPaintSite; FExplorer: TCustomExplorerForm; public constructor Create(Explorer: TCustomExplorerForm); { IElementBehavior } function Init(const pBehaviorSite: IElementBehaviorSite): HResult; stdcall; function Notify(lEvent: Integer; var pVar: OleVariant): HResult; stdcall; function Detach: HResult; stdcall; { IHTMLPainter } function Draw(rcBounds: tagRECT; rcUpdate: tagRECT; lDrawFlags: Integer; hdc: hdc; pvDrawObject: Pointer): HResult; stdcall; function onresize(size: tagSIZE): HResult; stdcall; function GetPainterInfo(out pInfo: _HTML_PAINTER_INFO): HResult; stdcall; function HitTestPoint(pt: tagPOINT; out pbHit: Integer; out plPartID: Integer): HResult; stdcall; end; TElementBehaviorFactory = class(TInterfacedObject, IElementBehaviorFactory) private FElemBehavior: IElementBehavior; public constructor Create(Owner: TCustomExplorerForm); destructor Destroy; override; function FindBehavior(const bstrBehavior: WideString; const bstrBehaviorUrl: WideString; const pSite: IElementBehaviorSite; out ppBehavior: IElementBehavior): HResult; stdcall; end; implementation { TElementBehaviorFactory } constructor TElementBehaviorFactory.Create(Owner: TCustomExplorerForm); begin FElemBehavior := TElementBehavior.Create(Owner); end; destructor TElementBehaviorFactory.Destroy; begin FElemBehavior := nil; inherited; end; function TElementBehaviorFactory.FindBehavior(const bstrBehavior, bstrBehaviorUrl: WideString; const pSite: IElementBehaviorSite; out ppBehavior: IElementBehavior): HResult; begin ppBehavior := FElemBehavior; Result := S_OK; end; { TElementBehavior } function TElementBehavior.Draw(rcBounds, rcUpdate: tagRECT; lDrawFlags: Integer; hdc: hdc; pvDrawObject: Pointer): HResult; var G: TGraphic; W, H: Integer; B, Bitmap, SB: TBitmap; begin { Draw embed object } Bitmap := TBitmap.Create; try FExplorer.GetCurrentImage(MapImageWidth, MapImageHeight, G); try if G <> nil then begin Bitmap.PixelFormat := pf24Bit; W := rcBounds.Right - rcBounds.Left; H := rcBounds.Bottom - rcBounds.Top; Bitmap.SetSize(W, H); FillColorEx(Bitmap, clWhite); if G is TIcon then Bitmap.Canvas.Draw(W div 2 - G.Width div 2, H div 2 - G.Height div 2, G); if G is TBitmap then begin B := TBitmap(G); if B.PixelFormat = pf24Bit then begin SB := TBitmap.Create; try KeepProportions(B, W - 4, H - 4); G := B; DrawShadowToImage(SB, B); DrawImageEx32To24(Bitmap, SB, W div 2 - SB.Width div 2, H div 2 - SB.Height div 2); finally F(SB); end; end; if B.PixelFormat = pf32Bit then DrawImageEx32To24(Bitmap, B, W div 2 - B.Width div 2, H div 2 - B.Height div 2); end; with rcBounds do BitBlt(hdc, Left, Top, W, H, Bitmap.Canvas.Handle, 0, 0, SRCCOPY); end; finally F(G); end; finally F(Bitmap); end; Result := S_OK; end; function TElementBehavior.GetPainterInfo(out pInfo: _HTML_PAINTER_INFO): HResult; {const HTMLPAINTER_OPAQUE = $00000001; HTMLPAINT_ZORDER_WINDOW_TOP = $00000008; } begin with pInfo do begin lFlags := HTMLPAINTER_OPAQUE; lZOrder := HTMLPAINT_ZORDER_REPLACE_ALL; FillChar(rcExpand, SizeOf(TRect), 0); end; Result := S_OK; end; function TElementBehavior.HitTestPoint(pt: tagPOINT; out pbHit, plPartID: Integer): HResult; begin { Dummy } Result := E_NOTIMPL; end; function TElementBehavior.onresize(size: tagSIZE): HResult; begin Result := S_OK; end; constructor TElementBehavior.Create(Explorer: TCustomExplorerForm); begin FExplorer := Explorer; end; function TElementBehavior.Detach: HResult; begin if Assigned(FPaintSite) then FPaintSite.InvalidateRect(nil); Result := S_OK; end; function TElementBehavior.Init( const pBehaviorSite: IElementBehaviorSite): HResult; begin Result := pBehaviorSite.QueryInterface(IHTMLPaintSite, FPaintSite); if Assigned(FPaintSite) then FPaintSite.InvalidateRect(nil); end; function TElementBehavior.Notify(lEvent: Integer; var pVar: OleVariant): HResult; begin Result := E_NOTIMPL; end; end.
unit uClassDBConnection; interface uses Data.SqlExpr, Data.DBXFirebird, uClassWorkIni; type TBaseDBConnection = class private sqlConn : TSQLConnection; FConnected: boolean; FConnection: TSQLConnection; procedure SetConnected(const Value: boolean); constructor Create; procedure SetConnection(const Value: TSQLConnection); public destructor Destroy; property Connected : boolean read FConnected write SetConnected; class function getInstance : TBaseDBConnection; property Connection : TSQLConnection read FConnection write SetConnection; end; implementation uses System.SysUtils; Var FInstance : TBaseDBConnection; { TBaseDBConnection } constructor TBaseDBConnection.Create; var ini : TBaseWorkIni; begin sqlConn := TSQLConnection.Create(nil); ini := TBaseWorkIni.create; with sqlConn do begin ConnectionName := 'FBConnection'; DriverName := 'Firebird'; LibraryName := 'dbxfb.dll'; GetDriverFunc := 'getSQLDriverINTERBASE'; VendorLib := 'fbclient.dll'; Params.Values['SQLDialect'] := '3'; Params.Values['Database'] := ini.path; Params.Values['User_Name'] := ini.username; Params.Values['Password'] := ini.password;; LoginPrompt := False; Connected := true; end; SetConnected(sqlConn.Connected); SetConnection(sqlConn); end; destructor TBaseDBConnection.Destroy; begin FreeAndNil(sqlConn); end; class function TBaseDBConnection.getInstance: TBaseDBConnection; begin if FInstance = Nil then FInstance := TBaseDBConnection.Create; result := FInstance; end; procedure TBaseDBConnection.SetConnected(const Value: boolean); begin FConnected := Value; end; procedure TBaseDBConnection.SetConnection(const Value: TSQLConnection); begin FConnection := Value; end; end.
unit Pospolite.View.HTML.Events; { +-------------------------+ | Package: Pospolite View | | Author: Matek0611 | | Email: matiowo@wp.pl | | Version: 1.0p | +-------------------------+ Comments: ... } {$mode objfpc}{$H+} {$modeswitch advancedrecords} interface uses Classes, SysUtils, variants, Controls, Pospolite.View.Basics, Pospolite.View.Threads; const // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button#return_value THTMLMouseButtonsSet = [mbLeft, mbMiddle, mbRight, mbExtra1, mbExtra2]; // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons#return_value THTMLMouseButtonsSetMulti: array[TMouseButton] of byte = (1, 2, 4, 8, 16); type { TPLHTMLEventProperties } TPLHTMLEventProperties = packed record public function button: Byte; public altKey: TPLBool; buttons: array[TMouseButton] of TPLBool; detail: Byte; // https://stackoverflow.com/questions/6480060/how-do-i-listen-for-triple-clicks-in-javascript // tbc ... shiftKey: TPLBool; end; function GetDefaultEventProperties(const AType: TPLString): TPLHTMLEventProperties; function ShiftStateToInt(const AShiftState: TShiftState): QWord; function IntToShiftState(const AShiftState: QWord): TShiftState; const PLHTMLEventPropertiesTemplate: TPLHTMLEventProperties = ( altKey: false; buttons: (false, false, false, false, false); detail: 0; shiftKey: false; ); type { TPLHTMLEvent } TPLHTMLEvent = packed record strict private FEvent: TPLAsyncProc; FProperties: TPLHTMLEventProperties; FTarget: TPLHTMLObject; FType: TPLString; FPrevent: TPLBool; public constructor Create(AEvent: TPLAsyncProc; ATarget: TPLHTMLObject; AType: TPLString; AProps: TPLHTMLEventProperties); class operator = (a, b: TPLHTMLEvent) r: TPLBool; procedure Call(const AArgs: array of const); procedure PreventDefault; procedure RestoreDefault; property Target: TPLHTMLObject read FTarget write FTarget; property &Type: TPLString read FType write FType; property Properties: TPLHTMLEventProperties read FProperties write FProperties; end; { TPLHTMLEventListener } TPLHTMLEventListener = packed record private FEvent: TPLHTMLEvent; public constructor Create(AEvent: TPLHTMLEvent); class operator = (a, b: TPLHTMLEventListener) r: TPLBool; procedure HandleEvent(AEvent: TPLHTMLEvent; const AArgs: array of const); end; TPLHTMLEventListeners = class(specialize TPLList<TPLHTMLEventListener>); { TPLHTMLEventListenerItem } TPLHTMLEventListenerItem = class private FList: TPLHTMLEventListeners; FTypeName: TPLString; public constructor Create(const ATypeName: TPLString); destructor Destroy; override; property TypeName: TPLString read FTypeName; property List: TPLHTMLEventListeners read FList; end; TPLFuncsOfClassEventListenerItem = specialize TPLFuncsOfClass<TPLHTMLEventListenerItem>; TPLHTMLEventListenerList = class(specialize TPLObjectList<TPLHTMLEventListenerItem>); { TPLHTMLEventTarget } TPLHTMLEventTarget = class private FListeners: TPLHTMLEventListenerList; FObject: TPLHTMLObject; function ComparatorForSearch(const AObject: TPLHTMLEventListenerItem; const ACriteria: Variant): TPLSign; function ComparatorForSort(a, b: TPLHTMLEventListenerItem): TPLSign; public constructor Create(AObject: TPLHTMLObject); destructor Destroy; override; procedure AddEventListener(const AType: TPLString; AListener: TPLHTMLEventListener); procedure RemoveEventListener(const AType: TPLString; AListener: TPLHTMLEventListener); procedure DispatchEvent(AEvent: TPLHTMLEvent; AArgs: array of const); procedure DispatchAllEventsFromListeners(const AType: TPLString; AArgs: array of const); function GetEventListeners(const ATypeName: TPLString): TPLHTMLEventListeners; property Listeners: TPLHTMLEventListenerList read FListeners; end; TPLHTMLEventManagerQueueItemParts = specialize TPLParameter<TPLString, TPLArrayOfConst>; TPLHTMLEventManagerQueueItem = specialize TPLParameter<TPLHTMLObject, TPLHTMLEventManagerQueueItemParts>; TPLHTMLEventManagerQueue = class(specialize TPLList<TPLHTMLEventManagerQueueItem>); { TPLHTMLEventManager } TPLHTMLEventManager = class sealed private FDocument: Pointer; FEnabled: TPLBool; FFocused: TPLBool; FFocusedElement: TPLHTMLObject; FTask: TPLAsyncTask; FQueue: TPLHTMLEventManagerQueue; procedure SetDocument(AValue: Pointer); procedure AsyncProc(const {%H-}AArguments: array of const); procedure SetFocusedElement(AValue: TPLHTMLObject); public constructor Create; destructor Destroy; override; procedure StartEvents; procedure StopEvents; procedure DoEvent(AObject: TPLHTMLObject; const AType: TPLString; const AParams: array of const); property Document: Pointer read FDocument write SetDocument; property Focused: TPLBool read FFocused write FFocused; property FocusedElement: TPLHTMLObject read FFocusedElement write SetFocusedElement; end; implementation uses Pospolite.View.HTML.Basics; function GetDefaultEventProperties(const AType: TPLString ): TPLHTMLEventProperties; begin Result := PLHTMLEventPropertiesTemplate; case AType of 'click': begin Result.detail := 1; Result.buttons[mbLeft] := true; end; 'dblclick': begin Result.detail := 2; Result.buttons[mbLeft] := true; end; 'tripleclick': begin Result.detail := 3; Result.buttons[mbLeft] := true; end; 'quadclick': begin Result.detail := 4; Result.buttons[mbLeft] := true; end; 'contextmenu': begin Result.detail := 1; Result.buttons[mbRight] := true; end; else begin // tmp Result.detail := 1; Result.buttons[mbLeft] := true; end; end; end; function ShiftStateToInt(const AShiftState: TShiftState): QWord; var s: TShiftStateEnum; begin Result := 0; for s in AShiftState do case s of ssShift: Result := Result or 1; ssAlt: Result := Result or (1 << 1); ssCtrl: Result := Result or (1 << 2); ssLeft: Result := Result or (1 << 3); ssRight: Result := Result or (1 << 4); ssMiddle: Result := Result or (1 << 5); ssDouble: Result := Result or (1 << 6); ssMeta: Result := Result or (1 << 7); ssSuper: Result := Result or (1 << 8); ssHyper: Result := Result or (1 << 9); ssAltGr: Result := Result or (1 << 10); ssCaps: Result := Result or (1 << 11); ssNum: Result := Result or (1 << 12); ssScroll: Result := Result or (1 << 13); ssTriple: Result := Result or (1 << 14); ssQuad: Result := Result or (1 << 15); ssExtra1: Result := Result or (1 << 16); ssExtra2: Result := Result or (1 << 17); end; end; function IntToShiftState(const AShiftState: QWord): TShiftState; var b: byte = 1; s: TShiftStateEnum; begin Result := []; for s in TShiftStateEnum do begin if (AShiftState and (1 << b)) <> 0 then Result += [s]; Inc(b); end; end; { TPLHTMLEventProperties } function TPLHTMLEventProperties.button: Byte; var m: TMouseButton; begin Result := 0; for m in THTMLMouseButtonsSet do if buttons[m] then Result += THTMLMouseButtonsSetMulti[m]; end; { TPLHTMLEvent } constructor TPLHTMLEvent.Create(AEvent: TPLAsyncProc; ATarget: TPLHTMLObject; AType: TPLString; AProps: TPLHTMLEventProperties); begin FEvent := AEvent; FTarget := ATarget; FType := AType; FPrevent := false; FProperties := AProps; end; class operator TPLHTMLEvent.=(a, b: TPLHTMLEvent) r: TPLBool; begin r := a.FEvent = b.FEvent; end; procedure TPLHTMLEvent.Call(const AArgs: array of const); begin if not FPrevent and Assigned(FEvent.AsPureProc) then FEvent.AsPureProc()(AArgs); end; procedure TPLHTMLEvent.PreventDefault; begin FPrevent := true; end; procedure TPLHTMLEvent.RestoreDefault; begin FPrevent := false; end; { TPLHTMLEventListener } constructor TPLHTMLEventListener.Create(AEvent: TPLHTMLEvent); begin FEvent := AEvent; end; class operator TPLHTMLEventListener.=(a, b: TPLHTMLEventListener) r: TPLBool; begin r := a.FEvent = b.FEvent; end; procedure TPLHTMLEventListener.HandleEvent(AEvent: TPLHTMLEvent; const AArgs: array of const); begin AEvent.Call(AArgs); end; { TPLHTMLEventListenerItem } constructor TPLHTMLEventListenerItem.Create(const ATypeName: TPLString); begin inherited Create; FTypeName := ATypeName; FList := TPLHTMLEventListeners.Create; end; destructor TPLHTMLEventListenerItem.Destroy; begin FList.Free; inherited Destroy; end; { TPLHTMLEventTarget } function TPLHTMLEventTarget.ComparatorForSearch( const AObject: TPLHTMLEventListenerItem; const ACriteria: Variant): TPLSign; var s: TPLString; begin s := VarToStr(ACriteria); if AObject.FTypeName < s then Result := -1 else if AObject.FTypeName > s then Result := 1 else Result := 0; end; function TPLHTMLEventTarget.ComparatorForSort(a, b: TPLHTMLEventListenerItem ): TPLSign; begin if a.FTypeName < b.FTypeName then Result := -1 else if a.FTypeName > b.FTypeName then Result := 1 else Result := 0; end; constructor TPLHTMLEventTarget.Create(AObject: TPLHTMLObject); begin FObject := AObject; FListeners := TPLHTMLEventListenerList.Create; end; destructor TPLHTMLEventTarget.Destroy; begin FListeners.Free; inherited Destroy; end; procedure TPLHTMLEventTarget.AddEventListener(const AType: TPLString; AListener: TPLHTMLEventListener); var id: SizeInt; found: TPLBool = true; begin id := TPLFuncsOfClassEventListenerItem.FastSearch(FListeners, AType, @ComparatorForSearch); if id < 0 then begin FListeners.Add(TPLHTMLEventListenerItem.Create(AType)); id := FListeners.Count - 1; found := false; end; FListeners[id].FList.Add(AListener); if not found then FListeners.Sort(@ComparatorForSort); end; procedure TPLHTMLEventTarget.RemoveEventListener(const AType: TPLString; AListener: TPLHTMLEventListener); var id: SizeInt; begin id := TPLFuncsOfClassEventListenerItem.FastSearch(FListeners, AType, @ComparatorForSearch); if id < 0 then exit; FListeners[id].FList.Remove(AListener); end; procedure TPLHTMLEventTarget.DispatchEvent(AEvent: TPLHTMLEvent; AArgs: array of const); begin AEvent.Call(AArgs); end; procedure TPLHTMLEventTarget.DispatchAllEventsFromListeners( const AType: TPLString; AArgs: array of const); var id, x: SizeInt; begin id := TPLFuncsOfClassEventListenerItem.FastSearch(FListeners, AType, @ComparatorForSearch); if id < 0 then exit; for x := 0 to FListeners[id].FList.Count-1 do FListeners[id].FList[x].FEvent.Call(AArgs); end; function TPLHTMLEventTarget.GetEventListeners(const ATypeName: TPLString ): TPLHTMLEventListeners; var id: SizeInt; begin id := TPLFuncsOfClassEventListenerItem.FastSearch(FListeners, ATypeName, @ComparatorForSearch); if id < 0 then Result := nil else Result := FListeners[id].FList; end; { TPLHTMLEventManager } procedure TPLHTMLEventManager.SetDocument(AValue: Pointer); begin if FDocument = AValue then exit; StopEvents; FDocument := AValue; end; procedure TPLHTMLEventManager.AsyncProc(const AArguments: array of const); begin while FEnabled do begin FTask.Sleep(1); // opt if not Assigned(FDocument) or not Assigned(FQueue) then break; if FQueue.Empty then continue; TPLHTMLEventTarget(FQueue.First.Key.GetElementTarget).DispatchAllEventsFromListeners(FQueue.First.Value.Key, FQueue.First.Value.Value); FQueue.Remove(FQueue.First); end; end; procedure TPLHTMLEventManager.SetFocusedElement(AValue: TPLHTMLObject); begin if FFocusedElement = AValue then exit; if Assigned(FFocusedElement) then TPLHTMLBasicObject(FFocusedElement).Focused := false; if Assigned(AValue) then TPLHTMLBasicObject(AValue).Focused := true; FFocusedElement := AValue; end; constructor TPLHTMLEventManager.Create; begin inherited Create; FQueue := TPLHTMLEventManagerQueue.Create; FTask := nil; FDocument := nil; FFocused := false; FFocusedElement := nil; end; destructor TPLHTMLEventManager.Destroy; begin StopEvents; FQueue.Free; inherited Destroy; end; procedure TPLHTMLEventManager.StartEvents; begin if not Assigned(FDocument) then exit; if Assigned(FTask) then FreeAndNil(FTask); FTask := TPLAsyncTask.Create(@AsyncProc); FTask.FreeIfDone := false; FTask.Name := 'Event Manager'; FTask.Async([]); end; procedure TPLHTMLEventManager.StopEvents; begin FEnabled := false; if Assigned(FTask) then begin FTask.Cancel; FreeAndNil(FTask); end; end; procedure TPLHTMLEventManager.DoEvent(AObject: TPLHTMLObject; const AType: TPLString; const AParams: array of const); var p: TPLArrayOfConst; i: SizeInt; begin SetLength(p, Length(AParams)); for i := Low(p) to High(p) do p[i] := AParams[i]; FQueue.Add(TPLHTMLEventManagerQueueItem.Create(AObject, TPLHTMLEventManagerQueueItemParts.Create(AType, p))); end; end.
unit Forms.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, AdvGlowButton, AdvMemo, Vcl.ExtCtrls, VCL.TMSFNCTypes, Modules.ServerContainer, AdvStyleIF, AdvAppStyler; type TFrmMain = class(TForm) mmInfo: TAdvMemo; btStart: TAdvGlowButton; btStop: TAdvGlowButton; btConfig: TAdvGlowButton; Image1: TImage; AdvFormStyler1: TAdvFormStyler; procedure btStartClick(ASender: TObject); procedure btStopClick(ASender: TObject); procedure FormCreate(ASender: TObject); procedure btConfigClick(Sender: TObject); strict private procedure UpdateGUI; procedure UpdateButtonStates; procedure ShowConfig; end; var FrmMain: TFrmMain; implementation {$R *.dfm} uses System.IOUtils, Modules.Configuration, Forms.Config; resourcestring SServerStopped = 'Server stopped'; SServerStartedAt = 'Server started at '; { TMainForm } procedure TFrmMain.btConfigClick(Sender: TObject); begin ShowConfig; end; procedure TFrmMain.btStartClick(ASender: TObject); begin ServerContainer.SparkleHttpSysDispatcher.Start; UpdateGUI; UpdateButtonStates; end; procedure TFrmMain.btStopClick(ASender: TObject); begin ServerContainer.SparkleHttpSysDispatcher.Stop; UpdateGUI; UpdateButtonStates; end; procedure TFrmMain.FormCreate(ASender: TObject); begin mmInfo.Lines.Clear; UpdateGUI; UpdateButtonStates; end; procedure TFrmMain.ShowConfig; var LFrm : TFrmConfig; begin LFrm := TFrmConfig.Create(nil); try LFrm.URI := Configuration.URI; LFrm.FolderName := Configuration.FolderName; if LFrm.ShowModal = mrOK then begin Configuration.URI := LFrm.URI; Configuration.FolderName := LFrm.FolderName; UpdateButtonStates; end; finally LFrm.Free; end; end; procedure TFrmMain.UpdateButtonStates; begin if ( Length( Configuration.URI ) = 0 ) OR (NOT TDirectory.Exists(Configuration.FolderName) ) then begin btStart.Enabled := False; btStop.Enabled := False; end else begin btStart.Enabled := not ServerContainer.SparkleHttpSysDispatcher.Active; btStop.Enabled := not btStart.Enabled; end; end; procedure TFrmMain.UpdateGUI; const cHttp = 'http://+'; cHttpLocalhost = 'http://localhost'; var LTime: String; begin LTime := DateTimeToStr( Now ); if ServerContainer.SparkleHttpSysDispatcher.Active then mmInfo.Lines.Add(LTime + ': ' + SServerStartedAt + StringReplace( ServerContainer.XDataServer.BaseUrl, cHttp, cHttpLocalhost, [rfIgnoreCase])) else mmInfo.Lines.Add(LTime + ': ' + SServerStopped); end; end.
{**************************************************************************************} { } { CCR Exif - Delphi class library for reading and writing image metadata } { Version 1.5.2 beta } { } { The contents of this file are subject to the Mozilla Public License Version 1.1 } { (the "License"); you may not use this file except in compliance with the License. } { You may obtain a copy of the License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an "AS IS" basis, WITHOUT } { WARRANTY OF ANY KIND, either express or implied. See the License for the specific } { language governing rights and limitations under the License. } { } { The Original Code is CCR.Exif.IPTC.pas. } { } { The Initial Developer of the Original Code is Chris Rolliston. Portions created by } { Chris Rolliston are Copyright (C) 2009-2012 Chris Rolliston. All Rights Reserved. } { } {**************************************************************************************} {$I CCR.Exif.inc} unit CCR.Exif.IPTC; { As saved, IPTC data is a flat list of tags ('datasets'), no more no less, which is reflected in the implementation of TIPTCData.LoadFromStream. However, as found in JPEG files, they are put in an Adobe data structure, itself put inside an APP13 segment. Note that by default, string tags are 'only' interpreted as having UTF-8 data if the encoding tag is set, with the UTF-8 marker as its data. If you don't load any tags before adding others, however, the default is to persist to UTF-8, writing said marker tag of course. To force interpreting loaded tags as UTF-8, set the AlwaysAssumeUTF8Encoding property of TIPTCData to True *before* calling LoadFromGraphic or LoadFromStream. } interface uses Types, SysUtils, Classes, {$IFDEF HasGenerics}Generics.Collections,{$ENDIF}{$IFDEF VCL}Jpeg,{$ENDIF} CCR.Exif.BaseUtils, CCR.Exif.TagIDs, CCR.Exif.TiffUtils; type EInvalidIPTCData = class(ECCRExifException); {$IFDEF HasGenerics} TIPTCRepeatablePair = TPair<string, string>; TIPTCRepeatablePairs = TArray<TIPTCRepeatablePair>; {$ELSE} TIPTCRepeatablePair = record Key, Value: string; end; TIPTCRepeatablePairs = array of TIPTCRepeatablePair; {$ENDIF} TIPTCStringArray = type Types.TStringDynArray; //using 'type' means the helper defined below will only apply to it {$IFDEF XE3+} TIPTCStringArrayHelper = record helper for TIPTCStringArray class function CreateFromStrings(const Strings: TStrings): TIPTCStringArray; static; function Join(const Separator: string): string; end; {$ENDIF} TIPTCData = class; TIPTCSection = class; TIPTCTagID = CCR.Exif.BaseUtils.TIPTCTagID; TIPTCTagIDs = set of TIPTCTagID; TIPTCTag = class //an instance represents a 'dataset' in IPTC jargon; instances need not be written in numerical order public type TChangeType = (ctID, ctData); private FData: Pointer; FDataSize: Integer; FID: TIPTCTagID; FSection: TIPTCSection; procedure SetDataSize(Value: Integer); procedure SetID(const Value: TIPTCTagID); function GetAsString: string; procedure SetAsString(const Value: string); function GetIndex: Integer; procedure SetIndex(NewIndex: Integer); public destructor Destroy; override; procedure Assign(Source: TIPTCTag); procedure Changed(AType: TChangeType = ctData); overload; //call this if Data is modified directly procedure Delete; procedure UpdateData(const Buffer); overload; inline; procedure UpdateData(NewDataSize: Integer; const Buffer); overload; procedure UpdateData(NewDataSize: Integer; Source: TStream); overload; { ReadString treats the data as string data, whatever the spec says. It respects TIPTCData.UTF8Encoded however. } function ReadString: string; { ReadUTF8String just assumes the tag data is UTF-8 text. } function ReadUTF8String: UTF8String; inline; procedure WriteString(const NewValue: RawByteString); overload; procedure WriteString(const NewValue: UnicodeString); overload; { AsString assumes the underlying data type is as per the spec (unlike the case of Exif tag headers, IPTC ones do not specify their data type). } property AsString: string read GetAsString write SetAsString; property Data: Pointer read FData; property DataSize: Integer read FDataSize write SetDataSize; property ID: TIPTCTagID read FID write SetID; //tag IDs need only be unique within sections 1, 7, 8 and 9 property Index: Integer read GetIndex write SetIndex; property Section: TIPTCSection read FSection; end; TIPTCSectionID = CCR.Exif.BaseUtils.TIPTCSectionID; {$Z1} //only TIPTCImageOrientation directly maps to the stored value TIPTCActionAdvised = (iaTagMissing, iaObjectKill, iaObjectReplace, iaObjectAppend, iaObjectReference); TIPTCImageOrientation = (ioTagMissing, ioLandscape = Ord('L'), ioPortrait = Ord('P'), ioSquare = Ord('S')); TIPTCPriority = (ipTagMissing, ipLowest, ipVeryLow, ipLow, ipNormal, ipNormalHigh, ipHigh, ipVeryHigh, ipHighest, ipUserDefined, ipReserved); TIPTCSection = class //an instance represents a 'record' in IPTC jargon public type TEnumerator = record strict private FIndex: Integer; FSource: TIPTCSection; function GetCurrent: TIPTCTag; public constructor Create(ASection: TIPTCSection); function MoveNext: Boolean; property Current: TIPTCTag read GetCurrent; end; private FDefinitelySorted: Boolean; FID: TIPTCSectionID; FModified: Boolean; FOwner: TIPTCData; FTags: TList; function GetTag(Index: Integer): TIPTCTag; function GetTagCount: Integer; public constructor Create(AOwner: TIPTCData; AID: TIPTCSectionID); destructor Destroy; override; function GetEnumerator: TEnumerator; function Add(ID: TIPTCTagID): TIPTCTag; //will try to insert in an appropriate place function Append(ID: TIPTCTagID): TIPTCTag; //will literally just append procedure Clear; procedure Delete(Index: Integer); function Find(ID: TIPTCTagID; out Tag: TIPTCTag): Boolean; function Insert(Index: Integer; ID: TIPTCTagID = 0): TIPTCTag; procedure Move(CurIndex, NewIndex: Integer); function Remove(TagID: TIPTCTagID): Integer; overload; inline; function Remove(TagIDs: TIPTCTagIDs): Integer; overload; procedure Sort; function TagExists(ID: TIPTCTagID; MinSize: Integer = 1): Boolean; function AddOrUpdate(TagID: TIPTCTagID; NewDataSize: LongInt; const Buffer): TIPTCTag; function GetDateValue(TagID: TIPTCTagID): TDateTimeTagValue; procedure SetDateValue(TagID: TIPTCTagID; const Value: TDateTimeTagValue); function GetDateTimeValue(DateTagID, TimeTagID: TIPTCTagID; AsUtc: Boolean = False): TDateTimeTagValue; procedure SetDateTimeValue(DateTagID, TimeTagID: TIPTCTagID; const Value: TDateTimeTagValue; AheadOfUtc: Boolean; UtcOffsetHrs, UtcOffsetMins: Byte); overload; {$IFDEF HasTTimeZone} procedure SetDateTimeValue(DateTagID, TimeTagID: TIPTCTagID; const Value: TDateTimeTagValue); overload; {$ENDIF} function GetPriorityValue(TagID: TIPTCTagID): TIPTCPriority; procedure SetPriorityValue(TagID: TIPTCTagID; Value: TIPTCPriority); function GetRepeatableValue(TagID: TIPTCTagID): TIPTCStringArray; overload; procedure GetRepeatableValue(TagID: TIPTCTagID; Dest: TStrings; ClearDestFirst: Boolean = True); overload; procedure SetRepeatableValue(TagID: TIPTCTagID; const Value: array of string); overload; procedure SetRepeatableValue(TagID: TIPTCTagID; Value: TStrings); overload; procedure GetRepeatablePairs(KeyID, ValueID: TIPTCTagID; Dest: TStrings; ClearDestFirst: Boolean = True); overload; procedure SetRepeatablePairs(KeyID, ValueID: TIPTCTagID; Pairs: TStrings); overload; function GetRepeatablePairs(KeyID, ValueID: TIPTCTagID): TIPTCRepeatablePairs; overload; procedure SetRepeatablePairs(KeyID, ValueID: TIPTCTagID; const Pairs: TIPTCRepeatablePairs); overload; function GetStringValue(TagID: TIPTCTagID): string; procedure SetStringValue(TagID: TIPTCTagID; const Value: string); function GetWordValue(TagID: TIPTCTagID): TWordTagValue; procedure SetWordValue(TagID: TIPTCTagID; const Value: TWordTagValue); property Count: Integer read GetTagCount; property ID: TIPTCSectionID read FID; property Modified: Boolean read FModified write FModified; property Owner: TIPTCData read FOwner; property Tags[Index: Integer]: TIPTCTag read GetTag; default; end; TIPTCData = class(TComponent, IStreamPersist, IStreamPersistEx, ITiffRewriteCallback) public type TEnumerator = record private FCurrentID: TIPTCSectionID; FDoneFirst: Boolean; FSource: TIPTCData; function GetCurrent: TIPTCSection; public constructor Create(ASource: TIPTCData); function MoveNext: Boolean; property Current: TIPTCSection read GetCurrent; end; strict private FAlwaysAssumeUTF8Encoding: Boolean; FDataToLazyLoad: IMetadataBlock; FLoadErrors: TMetadataLoadErrors; FSections: array[TIPTCSectionID] of TIPTCSection; FTiffRewriteCallback: TSimpleTiffRewriteCallbackImpl; FUTF8Encoded: Boolean; procedure GetGraphicSaveMethod(Stream: TStream; var Method: TGraphicSaveMethod); function GetModified: Boolean; function GetSection(ID: Integer): TIPTCSection; function GetSectionByID(ID: TIPTCSectionID): TIPTCSection; function GetUTF8Encoded: Boolean; procedure SetDataToLazyLoad(const Value: IMetadataBlock); procedure SetModified(Value: Boolean); procedure SetUTF8Encoded(Value: Boolean); function GetEnvelopeString(TagID: Integer): string; procedure SetEnvelopeString(TagID: Integer; const Value: string); function GetEnvelopeWord(TagID: Integer): TWordTagValue; procedure SetEnvelopeWord(TagID: Integer; const Value: TWordTagValue); function GetApplicationWord(TagID: Integer): TWordTagValue; procedure SetApplicationWord(TagID: Integer; const Value: TWordTagValue); function GetApplicationString(TagID: Integer): string; procedure SetApplicationString(TagID: Integer; const Value: string); function GetApplicationStrings(TagID: Integer): TIPTCStringArray; procedure SetApplicationStrings(TagID: Integer; const Value: TIPTCStringArray); function GetApplicationPairs(PackedTagIDs: Integer): TIPTCRepeatablePairs; procedure SetApplicationPairs(PackedTagIDs: Integer; const NewPairs: TIPTCRepeatablePairs); function GetUrgency: TIPTCPriority; procedure SetUrgency(Value: TIPTCPriority); function GetEnvelopePriority: TIPTCPriority; procedure SetEnvelopePriority(const Value: TIPTCPriority); function GetDate(PackedIndex: Integer): TDateTimeTagValue; procedure SetDate(PackedIndex: Integer; const Value: TDateTimeTagValue); function GetActionAdvised: TIPTCActionAdvised; procedure SetActionAdvised(Value: TIPTCActionAdvised); function GetDateTimeCreated: TDateTimeTagValue; function GetDateTimeSent: TDateTimeTagValue; {$IFDEF HasTTimeZone} procedure SetDateTimeCreatedProp(const Value: TDateTimeTagValue); procedure SetDateTimeSentProp(const Value: TDateTimeTagValue); {$ENDIF} function GetImageOrientation: TIPTCImageOrientation; procedure SetImageOrientation(Value: TIPTCImageOrientation); protected function CreateAdobeBlock: IAdobeResBlock; inline; procedure DefineProperties(Filer: TFiler); override; procedure DoSaveToJPEG(InStream, OutStream: TStream); procedure DoSaveToPSD(InStream, OutStream: TStream); procedure DoSaveToTIFF(InStream, OutStream: TStream); function GetEmpty: Boolean; procedure NeedLazyLoadedData; property TiffRewriteCallback: TSimpleTiffRewriteCallbackImpl read FTiffRewriteCallback implements ITiffRewriteCallback; public const UTF8Marker: array[1..3] of Byte = ($1B, $25, $47); public constructor Create(AOwner: TComponent = nil); override; class function CreateAsSubComponent(AOwner: TComponent): TIPTCData; //use a class function rather than a constructor to avoid compiler warning re C++ accessibility destructor Destroy; override; function GetEnumerator: TEnumerator; procedure AddFromStream(Stream: TStream); procedure Assign(Source: TPersistent); override; procedure Clear; procedure SetDateTimeCreated(const Value: TDateTimeTagValue; AheadOfUtc: Boolean; UtcOffsetHrs, UtcOffsetMins: Byte); overload; procedure SetDateTimeSent(const Value: TDateTimeTagValue; AheadOfUtc: Boolean; UtcOffsetHrs, UtcOffsetMins: Byte); overload; { Whether or not metadata was found, LoadFromGraphic returns True if the graphic format was recognised as one that *could* contain relevant metadata and False otherwise. } function LoadFromGraphic(Stream: TStream): Boolean; overload; function LoadFromGraphic(const Graphic: IStreamPersist): Boolean; overload; function LoadFromGraphic(const FileName: string): Boolean; overload; procedure LoadFromStream(Stream: TStream); { SaveToGraphic raises an exception if the target graphic either doesn't exist, or is neither a JPEG nor a PSD image. } procedure SaveToGraphic(const FileName: string); overload; procedure SaveToGraphic(const Graphic: IStreamPersist); overload; procedure SaveToStream(Stream: TStream); procedure SortTags; property LoadErrors: TMetadataLoadErrors read FLoadErrors write FLoadErrors; //!!!v. rarely set at present property Modified: Boolean read GetModified write SetModified; property EnvelopeSection: TIPTCSection index 1 read GetSection; property ApplicationSection: TIPTCSection index 2 read GetSection; property DataToLazyLoad: IMetadataBlock read FDataToLazyLoad write SetDataToLazyLoad; property FirstDescriptorSection: TIPTCSection index 7 read GetSection; property ObjectDataSection: TIPTCSection index 8 read GetSection; property SecondDescriptorSection: TIPTCSection index 9 read GetSection; property Sections[ID: TIPTCSectionID]: TIPTCSection read GetSectionByID; default; published property AlwaysAssumeUTF8Encoding: Boolean read FAlwaysAssumeUTF8Encoding write FAlwaysAssumeUTF8Encoding default False; property Empty: Boolean read GetEmpty; property UTF8Encoded: Boolean read GetUTF8Encoded write SetUTF8Encoded default True; { record 1 } property ModelVersion: TWordTagValue index itModelVersion read GetEnvelopeWord write SetEnvelopeWord stored False; property Destination: string index itDestination read GetEnvelopeString write SetEnvelopeString stored False; property FileFormat: TWordTagValue index itFileFormat read GetEnvelopeWord write SetEnvelopeWord stored False; //!!!make an enum property FileFormatVersion: TWordTagValue index itFileFormatVersion read GetEnvelopeWord write SetEnvelopeWord stored False; //!!!make an enum property ServiceIdentifier: string index itServiceIdentifier read GetEnvelopeString write SetEnvelopeString stored False; property EnvelopeNumberString: string index itEnvelopeNumber read GetEnvelopeString write SetEnvelopeString stored False; property ProductID: string index itProductID read GetEnvelopeString write SetEnvelopeString stored False; property EnvelopePriority: TIPTCPriority read GetEnvelopePriority write SetEnvelopePriority stored False; property DateSent: TDateTimeTagValue index isEnvelope or itDateSent shl 8 read GetDate write SetDate; property TimeSent: string index itTimeSent read GetEnvelopeString write SetEnvelopeString stored False; property DateTimeSent: TDateTimeTagValue read GetDateTimeSent {$IFDEF HasTTimeZone}write SetDateTimeSentProp{$ENDIF} stored False; property UNOCode: string index itUNO read GetEnvelopeString write SetEnvelopeString stored False; //should have a specific format property ARMIdentifier: TWordTagValue index itARMIdentifier read GetEnvelopeWord write SetEnvelopeWord stored False; //!!!make an enum property ARMVersion: TWordTagValue index itARMVersion read GetEnvelopeWord write SetEnvelopeWord stored False; //!!!make an enum { record 2 } property RecordVersion: TWordTagValue index itRecordVersion read GetApplicationWord write SetApplicationWord stored False; property ObjectTypeRef: string index itObjectTypeRef read GetApplicationString write SetApplicationString stored False; property ObjectAttributeRef: string index itObjectAttributeRef read GetApplicationString write SetApplicationString stored False; property ObjectName: string index itObjectName read GetApplicationString write SetApplicationString stored False; property EditStatus: string index itEditStatus read GetApplicationString write SetApplicationString stored False; property Urgency: TIPTCPriority read GetUrgency write SetUrgency stored False; property SubjectRefs: TIPTCStringArray index itSubjectRef read GetApplicationStrings write SetApplicationStrings stored False; property CategoryCode: string index itCategory read GetApplicationString write SetApplicationString stored False; //should be a 3 character code property SupplementaryCategories: TIPTCStringArray index itSupplementaryCategory read GetApplicationStrings write SetApplicationStrings stored False; property FixtureIdentifier: string index itFixtureIdentifier read GetApplicationString write SetApplicationString stored False; property Keywords: TIPTCStringArray index itKeyword read GetApplicationStrings write SetApplicationStrings stored False; procedure GetKeywords(Dest: TStrings); overload; procedure SetKeywords(NewWords: TStrings); overload; property ContentLocationCodes: TIPTCStringArray index itContentLocationCode read GetApplicationStrings write SetApplicationStrings stored False; property ContentLocationNames: TIPTCStringArray index itContentLocationName read GetApplicationStrings write SetApplicationStrings stored False; procedure GetContentLocationValues(Strings: TStrings; ClearDestFirst: Boolean = True); //Code=Name procedure SetContentLocationValues(Strings: TStrings); property ContentLocations: TIPTCRepeatablePairs index itContentLocationCode or itContentLocationName shl 8 read GetApplicationPairs write SetApplicationPairs; property ReleaseDate: TDateTimeTagValue index isApplication or itReleaseDate shl 8 read GetDate write SetDate stored False; property ExpirationDate: TDateTimeTagValue index isApplication or itExpirationDate shl 8 read GetDate write SetDate stored False; property SpecialInstructions: string index itSpecialInstructions read GetApplicationString write SetApplicationString stored False; property ActionAdvised: TIPTCActionAdvised read GetActionAdvised write SetActionAdvised stored False; property DateCreated: TDateTimeTagValue index isApplication or itDateCreated shl 8 read GetDate write SetDate stored False; property DateTimeCreated: TDateTimeTagValue read GetDateTimeCreated {$IFDEF HasTTimeZone}write SetDateTimeCreatedProp{$ENDIF} stored False; property DigitalCreationDate: TDateTimeTagValue index isApplication or itDigitalCreationDate shl 8 read GetDate write SetDate stored False; property OriginatingProgram: string index itOriginatingProgram read GetApplicationString write SetApplicationString stored False; property ProgramVersion: string index itProgramVersion read GetApplicationString write SetApplicationString stored False; property ObjectCycleCode: string index itObjectCycle read GetApplicationString write SetApplicationString stored False; //!!!enum property Bylines: TIPTCStringArray index itByline read GetApplicationStrings write SetApplicationStrings stored False; property BylineTitles: TIPTCStringArray index itBylineTitle read GetApplicationStrings write SetApplicationStrings stored False; procedure GetBylineValues(Strings: TStrings); inline; deprecated {$IFDEF DepCom}'Use GetBylineDetails instead'{$ENDIF}; procedure SetBylineValues(Strings: TStrings); inline; deprecated {$IFDEF DepCom}'Use SetBylineDetails instead'{$ENDIF}; procedure GetBylineDetails(Strings: TStrings; ClearDestFirst: Boolean = True); //Name=Title procedure SetBylineDetails(Strings: TStrings); property BylineDetails: TIPTCRepeatablePairs index itByline or itBylineTitle shl 8 read GetApplicationPairs write SetApplicationPairs; property City: string index itCity read GetApplicationString write SetApplicationString stored False; //!!!enum property SubLocation: string index itSubLocation read GetApplicationString write SetApplicationString stored False; //!!!enum property ProvinceOrState: string index itProvinceOrState read GetApplicationString write SetApplicationString stored False; //!!!enum property CountryCode: string index itCountryCode read GetApplicationString write SetApplicationString stored False; //!!!enum property CountryName: string index itCountryName read GetApplicationString write SetApplicationString stored False; //!!!enum property OriginalTransmissionRef: string index itOriginalTransmissionRef read GetApplicationString write SetApplicationString stored False; //!!!enum property Headline: string index itHeadline read GetApplicationString write SetApplicationString stored False; property Credit: string index itCredit read GetApplicationString write SetApplicationString stored False; property Source: string index itSource read GetApplicationString write SetApplicationString stored False; property CopyrightNotice: string index itCopyrightNotice read GetApplicationString write SetApplicationString stored False; property Contacts: TIPTCStringArray index itContact read GetApplicationStrings write SetApplicationStrings stored False; property CaptionOrAbstract: string index itCaptionOrAbstract read GetApplicationString write SetApplicationString stored False; property WritersOrEditors: TIPTCStringArray index itWriterOrEditor read GetApplicationStrings write SetApplicationStrings stored False; property ImageTypeCode: string index itImageType read GetApplicationString write SetApplicationString stored False; property ImageOrientation: TIPTCImageOrientation read GetImageOrientation write SetImageOrientation stored False; property LanguageIdentifier: string index itLanguageIdentifier read GetApplicationString write SetApplicationString stored False; property AudioTypeCode: string index itAudioType read GetApplicationString write SetApplicationString stored False; { Photoshop aliases } procedure GetPSCreatorValues(Strings: TStrings); inline;//Name=Title procedure SetPSCreatorValues(Strings: TStrings); inline; property PSDocumentTitle: string index itObjectName read GetApplicationString write SetApplicationString stored False; property PSCopyrightNotice: string index itCopyrightNotice read GetApplicationString write SetApplicationString stored False; property PSDescription: string index itCaptionOrAbstract read GetApplicationString write SetApplicationString stored False; property PSCreator: string index itByline read GetApplicationString write SetApplicationString stored False; property PSCreatorJobTitle: string index itBylineTitle read GetApplicationString write SetApplicationString stored False; end; implementation uses Contnrs, DateUtils, Math, {$IFDEF HasTTimeZone}TimeSpan,{$ENDIF} CCR.Exif.Consts, CCR.Exif.StreamHelper; const PriorityChars: array[TIPTCPriority] of AnsiChar = (#0, '8', '7', '6', '5', '4', '3', '2', '1', '9', '0'); type TIPTCTagDataType = (idString, idWord, idBinary); function FindProperDataType(Tag: TIPTCTag): TIPTCTagDataType; begin Result := idString; if Tag.Section <> nil then case Tag.Section.ID of isEnvelope: case Tag.ID of itModelVersion, itFileFormat, itFileFormatVersion, itARMIdentifier, itARMVersion: Result := idWord; end; isApplication: case Tag.ID of itRecordVersion: Result := idWord; end; end; end; { TIPTCStringArrayHelper } {$IF DECLARED(TIPTCStringArrayHelper)} class function TIPTCStringArrayHelper.CreateFromStrings(const Strings: TStrings): TIPTCStringArray; var I: Integer; begin SetLength(Result, Strings.Count); for I := Strings.Count - 1 downto 0 do Result[I] := Strings[I]; end; function TIPTCStringArrayHelper.Join(const Separator: string): string; var TotalLen: Integer; S: string; SeekPtr: PChar; begin TotalLen := High(Self) * Length(Separator); for S in Self do Inc(TotalLen, Length(S)); SetLength(Result, TotalLen); SeekPtr := Pointer(Result); for S in Self do begin MoveChars(Pointer(S)^, SeekPtr^, Length(S)); Inc(SeekPtr, Length(S) + Length(Separator)); end; end; {$IFEND} { TIPTCTag } destructor TIPTCTag.Destroy; begin if FSection <> nil then FSection.FTags.Extract(Self); ReallocMem(FData, 0); inherited; end; procedure TIPTCTag.Assign(Source: TIPTCTag); begin if Source = nil then SetDataSize(0) else begin FID := Source.ID; UpdateData(Source.DataSize, Source.Data^); end; end; procedure TIPTCTag.Changed(AType: TChangeType); begin if FSection = nil then Exit; FSection.Modified := True; if AType = ctID then FSection.FDefinitelySorted := False; end; procedure TIPTCTag.Delete; begin Free; end; function TIPTCTag.GetAsString: string; begin case FindProperDataType(Self) of idString: Result := ReadString; idBinary: Result := BinToHexStr(FData, FDataSize); else case DataSize of 1: Result := IntToStr(PByte(Data)^); 2: Result := IntToStr(Swap(PWord(Data)^)); 4: Result := IntToStr(SwapLongInt(PLongInt(Data)^)); else Result := ReadString; end; end; end; function TIPTCTag.GetIndex: Integer; begin if FSection = nil then Result := -1 else Result := FSection.FTags.IndexOf(Self); end; function TIPTCTag.ReadString: string; var Ansi: AnsiString; begin if (Section <> nil) and (Section.Owner <> nil) and Section.Owner.UTF8Encoded then begin Result := UTF8ToString(FData, FDataSize); Exit; end; SetString(Ansi, PAnsiChar(FData), FDataSize); Result := string(Ansi); end; function TIPTCTag.ReadUTF8String: UTF8String; begin SetString(Result, PAnsiChar(FData), FDataSize); end; procedure TIPTCTag.SetAsString(const Value: string); var WordVal: Integer; begin case FindProperDataType(Self) of idString: WriteString(Value); idBinary: begin SetDataSize(Length(Value) div 2); HexToBin(PChar(LowerCase(Value)), FData, FDataSize); end else {$RANGECHECKS ON} WordVal := StrToInt(Value); {$IFDEF RangeCheckingOff}{$RANGECHECKS OFF}{$ENDIF} WordVal := Swap(WordVal); UpdateData(2, WordVal); end; end; procedure TIPTCTag.SetDataSize(Value: Integer); begin if Value = FDataSize then Exit; ReallocMem(FData, Value); FDataSize := Value; Changed; end; procedure TIPTCTag.SetID(const Value: TIPTCTagID); begin if Value = FID then Exit; FID := Value; Changed(ctID); end; procedure TIPTCTag.SetIndex(NewIndex: Integer); begin if FSection <> nil then FSection.Move(Index, NewIndex); end; procedure TIPTCTag.UpdateData(const Buffer); begin UpdateData(DataSize, Buffer); end; procedure TIPTCTag.UpdateData(NewDataSize: Integer; const Buffer); begin ReallocMem(FData, NewDataSize); FDataSize := NewDataSize; Move(Buffer, FData^, NewDataSize); Changed; end; procedure TIPTCTag.UpdateData(NewDataSize: Integer; Source: TStream); begin ReallocMem(FData, NewDataSize); FDataSize := NewDataSize; Source.Read(FData^, NewDataSize); Changed; end; procedure TIPTCTag.WriteString(const NewValue: RawByteString); begin ReallocMem(FData, 0); FDataSize := Length(NewValue); if FDataSize <> 0 then begin ReallocMem(FData, FDataSize); Move(Pointer(NewValue)^, FData^, FDataSize); end; Changed; end; procedure TIPTCTag.WriteString(const NewValue: UnicodeString); begin if (Section <> nil) and (Section.Owner <> nil) and Section.Owner.UTF8Encoded then WriteString(UTF8Encode(NewValue)) else WriteString(AnsiString(NewValue)); end; { TIPTCSection.TEnumerator } constructor TIPTCSection.TEnumerator.Create(ASection: TIPTCSection); begin FIndex := -1; FSource := ASection; end; function TIPTCSection.TEnumerator.GetCurrent: TIPTCTag; begin Result := FSource[FIndex]; end; function TIPTCSection.TEnumerator.MoveNext: Boolean; begin Result := (Succ(FIndex) < FSource.Count); if Result then Inc(FIndex); end; { TIPTCSection } constructor TIPTCSection.Create(AOwner: TIPTCData; AID: TIPTCSectionID); begin inherited Create; FOwner := AOwner; FID := AID; FTags := TObjectList.Create(True); end; destructor TIPTCSection.Destroy; begin FTags.Free; inherited; end; function TIPTCSection.Add(ID: TIPTCTagID): TIPTCTag; var I: Integer; begin if ID = 0 then Result := Insert(Count) else begin for I := Count - 1 downto 0 do if ID > GetTag(I).ID then begin Result := Insert(I + 1, ID); Exit; end; Result := Insert(0, ID); end; end; function TIPTCSection.AddOrUpdate(TagID: TIPTCTagID; NewDataSize: Integer; const Buffer): TIPTCTag; begin if not Find(TagID, Result) then Result := Add(TagID); Result.UpdateData(NewDataSize, Buffer); end; function TIPTCSection.Append(ID: TIPTCTagID): TIPTCTag; begin Result := Insert(Count, ID); end; function TIPTCSection.Find(ID: TIPTCTagID; out Tag: TIPTCTag): Boolean; var I: Integer; begin Result := True; for I := 0 to FTags.Count - 1 do begin Tag := FTags[I]; if Tag.ID = ID then Exit; if FDefinitelySorted and (Tag.ID > ID) then Break; end; Tag := nil; Result := False; end; function TIPTCSection.GetDateValue(TagID: TIPTCTagID): TDateTimeTagValue; var Date: TDateTime; S: string; Year, Month, Day: Integer; begin S := GetStringValue(TagID); if TryStrToInt(Copy(S, 1, 4), Year) and TryStrToInt(Copy(S, 5, 2), Month) and TryStrToInt(Copy(S, 7, 2), Day) and TryEncodeDate(Year, Month, Day, Date) then Result := Date else Result := TDateTimeTagValue.CreateMissingOrInvalid; end; procedure TIPTCSection.SetDateValue(TagID: TIPTCTagID; const Value: TDateTimeTagValue); var Year, Month, Day: Word; begin if Value.MissingOrInvalid then begin Remove(TagID); Exit; end; DecodeDate(Value, Year, Month, Day); SetStringValue(TagID, Format('%.4d%.2d%.2d', [Year, Month, Day])); end; function TIPTCSection.GetDateTimeValue(DateTagID, TimeTagID: TIPTCTagID; AsUtc: Boolean): TDateTimeTagValue; var OffsetHrs, OffsetMins: Integer; I: Integer; S: string; TimePart: TDateTimeTagValue; Temp: TDateTime; begin TimePart := TDateTimeTagValue.CreateMissingOrInvalid; S := GetStringValue(TimeTagID); if (Length(S) = 11) and CharInSet(S[7], ['-', '+']) and TryStrToInt(Copy(S, 8, 2), OffsetHrs) and TryStrToInt(Copy(S, 10, 2), OffsetMins) then begin for I in [1, 2, 3, 4, 5, 6, 8, 9, 10, 11] do if not CharInSet(S[I], ['0'..'9']) then begin S := ''; Break; end; if (S <> '') then begin if not AsUtc then begin OffsetHrs := 0; OffsetMins := 0; end else if S[7] = '+' then //i.e., if the local time is ahead of GMT begin OffsetHrs := -OffsetHrs; OffsetMins := -OffsetMins; end; if TryEncodeTime(StrToInt(Copy(S, 1, 2)) + OffsetHrs, StrToInt(Copy(S, 3, 2)) + OffsetMins, StrToInt(Copy(S, 5, 2)), 0, Temp) then TimePart := Temp; end; end; Result := GetDateValue(DateTagID); if TimePart.MissingOrInvalid then Exit; if Result.MissingOrInvalid then Result := TimePart else Result := Result.Value + TimePart.Value; end; procedure TIPTCSection.SetDateTimeValue(DateTagID, TimeTagID: TIPTCTagID; const Value: TDateTimeTagValue; AheadOfUtc: Boolean; UtcOffsetHrs, UtcOffsetMins: Byte); const PlusOrMinus: array[Boolean] of string = ('-', '+'); var Year, Month, Day, Hour, Minute, Second, MilliSecond: Word; begin if Value.MissingOrInvalid then begin Remove([DateTagID, TimeTagID]); Exit; end; DecodeDateTime(Value, Year, Month, Day, Hour, Minute, Second, MilliSecond); SetStringValue(DateTagID, Format('%.4d%.2d%.2d', [Year, Month, Day])); SetStringValue(TimeTagID, Format('%.2d%.2d%.2d%s%.2d%.2d', [Hour, Minute, Second, PlusOrMinus[AheadOfUtc], UtcOffsetHrs, UtcOffsetMins])); end; {$IFDEF HasTTimeZone} procedure TIPTCSection.SetDateTimeValue(DateTagID, TimeTagID: TIPTCTagID; const Value: TDateTimeTagValue); var Offset: TTimeSpan; begin Offset := TTimeZone.Local.UtcOffset; SetDateTimeValue(DateTagID, TimeTagID, Value, Offset.Ticks >= 0, Abs(Offset.Hours), Abs(Offset.Minutes)); end; {$ENDIF} function TIPTCSection.GetEnumerator: TEnumerator; begin Result := TEnumerator.Create(Self); end; function TIPTCSection.GetStringValue(TagID: TIPTCTagID): string; var Tag: TIPTCTag; begin if Find(TagID, Tag) then Result := Tag.ReadString else Result := ''; end; function TIPTCSection.Remove(TagID: TIPTCTagID): Integer; begin Result := Remove([TagID]); end; function TIPTCSection.Remove(TagIDs: TIPTCTagIDs): Integer; var I: Integer; Tag: TIPTCTag; begin Result := -1; for I := Count - 1 downto 0 do begin Tag := Tags[I]; if Tag.ID in TagIDs then begin Delete(I); Result := I; end; end; end; procedure TIPTCSection.Clear; var I: Integer; begin for I := Count - 1 downto 0 do Delete(I); end; procedure TIPTCSection.Delete(Index: Integer); var Tag: TIPTCTag; begin Tag := FTags[Index]; Tag.FSection := nil; FTags.Delete(Index); FModified := True; if FTags.Count <= 1 then FDefinitelySorted := True; end; function TIPTCSection.GetPriorityValue(TagID: TIPTCTagID): TIPTCPriority; var Tag: TIPTCTag; begin if Find(TagID, Tag) and (Tag.DataSize = 1) then for Result := Low(TIPTCPriority) to High(TIPTCPriority) do if PriorityChars[Result] = PAnsiChar(Tag.Data)^ then Exit; Result := ipTagMissing; end; function TIPTCSection.GetRepeatableValue(TagID: TIPTCTagID): TIPTCStringArray; var Count: Integer; Tag: TIPTCTag; begin Count := 0; Result := nil; for Tag in Self do if Tag.ID = TagID then begin if Count = Length(Result) then SetLength(Result, Count + 8); Result[Count] := Tag.AsString; Inc(Count); end; if Count <> 0 then SetLength(Result, Count); end; procedure TIPTCSection.GetRepeatableValue(TagID: TIPTCTagID; Dest: TStrings; ClearDestFirst: Boolean); var Tag: TIPTCTag; begin Dest.BeginUpdate; try if ClearDestFirst then Dest.Clear; for Tag in Self do if Tag.ID = TagID then Dest.Add(Tag.AsString); finally Dest.EndUpdate; end; end; procedure TIPTCSection.GetRepeatablePairs(KeyID, ValueID: TIPTCTagID; Dest: TStrings; ClearDestFirst: Boolean = True); var Keys, Values: TIPTCStringArray; I: Integer; begin Dest.BeginUpdate; try if ClearDestFirst then Dest.Clear; Keys := GetRepeatableValue(KeyID); Values := GetRepeatableValue(ValueID); if Length(Values) > Length(Keys) then SetLength(Keys, Length(Values)) else SetLength(Values, Length(Keys)); for I := 0 to High(Keys) do Dest.Add(Keys[I] + Dest.NameValueSeparator + Values[I]); finally Dest.EndUpdate; end; end; function TIPTCSection.GetRepeatablePairs(KeyID, ValueID: TIPTCTagID): TIPTCRepeatablePairs; var Keys, Values: TIPTCStringArray; I: Integer; begin Keys := GetRepeatableValue(KeyID); Values := GetRepeatableValue(ValueID); if Length(Values) > Length(Keys) then SetLength(Keys, Length(Values)) else SetLength(Values, Length(Keys)); SetLength(Result, Length(Keys)); for I := 0 to High(Result) do begin Result[I].Key := Keys[I]; Result[I].Value := Values[I]; end; end; procedure TIPTCSection.SetPriorityValue(TagID: TIPTCTagID; Value: TIPTCPriority); begin if Value = ipTagMissing then Remove(TagID) else AddOrUpdate(TagID, 1, PriorityChars[Value]); end; procedure TIPTCSection.SetRepeatableValue(TagID: TIPTCTagID; const Value: array of string); var I, DestIndex: Integer; begin DestIndex := Remove(TagID); if DestIndex < 0 then begin DestIndex := 0; for I := Count - 1 downto 0 do if TagID > GetTag(I).ID then begin DestIndex := I + 1; Break; end; end; for I := 0 to High(Value) do begin Insert(DestIndex, TagID).AsString := Value[I]; Inc(DestIndex); end; end; procedure TIPTCSection.SetRepeatableValue(TagID: TIPTCTagID; Value: TStrings); var DynArray: TIPTCStringArray; I: Integer; begin SetLength(DynArray, Value.Count); for I := High(DynArray) downto 0 do DynArray[I] := Value[I]; SetRepeatableValue(TagID, DynArray); end; procedure TIPTCSection.SetRepeatablePairs(KeyID, ValueID: TIPTCTagID; Pairs: TStrings); var I, DestIndex: Integer; Key, Value: string; begin DestIndex := Remove([KeyID, ValueID]); if DestIndex < 0 then begin DestIndex := 0; for I := Count - 1 downto 0 do if KeyID > GetTag(I).ID then begin DestIndex := I + 1; Break; end; end; for I := 0 to Pairs.Count - 1 do begin Key := Pairs.Names[I]; Value := Pairs.ValueFromIndex[I]; if (Key <> '') or (Value <> '') then begin Insert(DestIndex, KeyID).AsString := Key; Inc(DestIndex); Insert(DestIndex, ValueID).AsString := Value; Inc(DestIndex); end; end; end; procedure TIPTCSection.SetRepeatablePairs(KeyID, ValueID: TIPTCTagID; const Pairs: TIPTCRepeatablePairs); var I, DestIndex: Integer; Pair: TIPTCRepeatablePair; begin DestIndex := Remove([KeyID, ValueID]); if DestIndex < 0 then begin DestIndex := 0; for I := Count - 1 downto 0 do if KeyID > GetTag(I).ID then begin DestIndex := I + 1; Break; end; end; for Pair in Pairs do if (Pair.Key <> '') or (Pair.Value <> '') then begin Insert(DestIndex, KeyID).AsString := Pair.Key; Inc(DestIndex); Insert(DestIndex, ValueID).AsString := Pair.Value; Inc(DestIndex); end; end; function TIPTCSection.GetTag(Index: Integer): TIPTCTag; begin Result := TIPTCTag(FTags[Index]); end; function TIPTCSection.GetTagCount: Integer; begin Result := FTags.Count; end; function TIPTCSection.GetWordValue(TagID: TIPTCTagID): TWordTagValue; var Tag: TIPTCTag; begin if Find(TagID, Tag) and (Tag.DataSize = 2) then Result := Swap(PWord(Tag.Data)^) else Result := TWordTagValue.CreateMissingOrInvalid; end; function TIPTCSection.Insert(Index: Integer; ID: TIPTCTagID = 0): TIPTCTag; begin if FDefinitelySorted and (Index < Count) and (ID > GetTag(Index).ID) then FDefinitelySorted := False; Result := TIPTCTag.Create; try Result.FID := ID; Result.FSection := Self; FTags.Insert(Index, Result); except Result.Free; raise; end; FModified := True; end; procedure TIPTCSection.Move(CurIndex, NewIndex: Integer); begin if CurIndex = NewIndex then Exit; FTags.Move(CurIndex, NewIndex); FModified := True; FDefinitelySorted := False; end; procedure TIPTCSection.SetStringValue(TagID: TIPTCTagID; const Value: string); var Tag: TIPTCTag; begin if Value = '' then begin Remove(TagID); Exit; end; if not Find(TagID, Tag) then Tag := Add(TagID); Tag.WriteString(Value); end; procedure TIPTCSection.SetWordValue(TagID: TIPTCTagID; const Value: TWordTagValue); var Data: Word; begin if Value.MissingOrInvalid then Remove(TagID) else begin Data := Swap(Value.Value); AddOrUpdate(TagID, 2, Data); end; end; function CompareIDs(Item1, Item2: TIPTCTag): Integer; begin Result := Item2.ID - Item1.ID; end; procedure TIPTCSection.Sort; begin if FDefinitelySorted then Exit; FTags.Sort(@CompareIDs); FModified := True; FDefinitelySorted := True; end; function TIPTCSection.TagExists(ID: TIPTCTagID; MinSize: Integer = 1): Boolean; var Tag: TIPTCTag; begin Result := Find(ID, Tag) and (Tag.DataSize >= MinSize); end; { TIPTCData.TEnumerator } constructor TIPTCData.TEnumerator.Create(ASource: TIPTCData); begin FCurrentID := Low(FCurrentID); FDoneFirst := False; FSource := ASource; end; function TIPTCData.TEnumerator.GetCurrent: TIPTCSection; begin Result := FSource.Sections[FCurrentID]; end; function TIPTCData.TEnumerator.MoveNext: Boolean; begin Result := (FCurrentID < High(FCurrentID)); if Result and FDoneFirst then Inc(FCurrentID) else FDoneFirst := True; end; { TIPTCData } constructor TIPTCData.Create(AOwner: TComponent); var ID: TIPTCSectionID; begin inherited Create(AOwner); for ID := Low(ID) to High(ID) do FSections[ID] := TIPTCSection.Create(Self, ID); FTiffRewriteCallback := TSimpleTiffRewriteCallbackImpl.Create(Self, ttIPTC); FUTF8Encoded := True; end; class function TIPTCData.CreateAsSubComponent(AOwner: TComponent): TIPTCData; begin Result := Create(AOwner); Result.Name := 'IPTCData'; Result.SetSubComponent(True); end; destructor TIPTCData.Destroy; var ID: TIPTCSectionID; begin for ID := Low(ID) to High(ID) do FSections[ID].Free; FTiffRewriteCallback.Free; inherited; end; procedure TIPTCData.AddFromStream(Stream: TStream); var Info: TIPTCTagInfo; NewTag: TIPTCTag; begin NeedLazyLoadedData; while TAdobeResBlock.TryReadIPTCHeader(Stream, Info) do begin NewTag := FSections[Info.SectionID].Append(Info.TagID); try NewTag.UpdateData(Info.DataSize, Stream); except NewTag.Free; raise; end; if (Info.SectionID = 1) and (Info.TagID = 90) and (Info.DataSize = SizeOf(UTF8Marker)) and CompareMem(NewTag.Data, @UTF8Marker, Info.DataSize) then FUTF8Encoded := True; end; end; procedure TIPTCData.Assign(Source: TPersistent); var SectID: TIPTCSectionID; Tag: TIPTCTag; begin if not (Source is TIPTCData) then begin if Source = nil then Clear else inherited; Exit; end; if TIPTCData(Source).DataToLazyLoad <> nil then DataToLazyLoad := TIPTCData(Source).DataToLazyLoad else for SectID := Low(SectID) to High(SectID) do begin FSections[SectID].Clear; for Tag in TIPTCData(Source).Sections[SectID] do FSections[SectID].Add(Tag.ID).UpdateData(Tag.DataSize, Tag.Data^); end; end; procedure TIPTCData.Clear; var ID: TIPTCSectionID; begin FLoadErrors := []; FDataToLazyLoad := nil; for ID := Low(ID) to High(ID) do FSections[ID].Clear; end; procedure TIPTCData.DefineProperties(Filer: TFiler); begin Filer.DefineBinaryProperty('Data', LoadFromStream, SaveToStream, not Empty); end; function TIPTCData.CreateAdobeBlock: IAdobeResBlock; begin Result := CCR.Exif.BaseUtils.CreateAdobeBlock(TAdobeResBlock.IPTCTypeID, Self); end; procedure TIPTCData.DoSaveToJPEG(InStream, OutStream: TStream); var Block: IAdobeResBlock; RewrittenSegment: IJPEGSegment; SavedIPTC: Boolean; Segment: IFoundJPEGSegment; StartPos: Int64; begin SavedIPTC := Empty; StartPos := InStream.Position; for Segment in JPEGHeader(InStream, [jmApp13]) do if Segment.IsAdobeApp13 then begin //IrfanView just wipes the original segment and replaces it with the new IPTC data, even if it contained non-IPTC blocks too. Eek! if StartPos <> Segment.Offset then begin InStream.Position := StartPos; OutStream.CopyFrom(InStream, Segment.Offset - StartPos); end; if SavedIPTC then RewrittenSegment := CreateAdobeApp13Segment else begin RewrittenSegment := CreateAdobeApp13Segment([CreateAdobeBlock]); SavedIPTC := True; end; for Block in Segment do if not Block.IsIPTCBlock then Block.SaveToStream(RewrittenSegment.Data); WriteJPEGSegment(OutStream, RewrittenSegment); StartPos := Segment.Offset + Segment.TotalSize; end; if not SavedIPTC then begin InStream.Position := StartPos; for Segment in JPEGHeader(InStream, AnyJPEGMarker - [jmJFIF, jmApp1]) do begin //insert immediately after any Exif or XMP segments if they exist, at the top of the file if they do not InStream.Position := StartPos; OutStream.CopyFrom(InStream, Segment.Offset - StartPos); WriteJPEGSegment(OutStream, CreateAdobeApp13Segment([CreateAdobeBlock])); StartPos := Segment.Offset; Break; end; end; InStream.Position := StartPos; OutStream.CopyFrom(InStream, InStream.Size - StartPos); end; procedure TIPTCData.DoSaveToPSD(InStream, OutStream: TStream); var Block: IAdobeResBlock; Info: TPSDInfo; NewBlocks: IInterfaceList; StartPos: Int64; begin StartPos := InStream.Position; NewBlocks := TInterfaceList.Create; if not Empty then NewBlocks.Add(CreateAdobeBlock); for Block in ParsePSDHeader(InStream, Info) do if not Block.IsIPTCBlock then NewBlocks.Add(Block); WritePSDHeader(OutStream, Info.Header); WritePSDResourceSection(OutStream, NewBlocks); InStream.Position := StartPos + Info.LayersSectionOffset; OutStream.CopyFrom(InStream, InStream.Size - InStream.Position); end; procedure TIPTCData.DoSaveToTIFF(InStream, OutStream: TStream); begin RewriteTiff(InStream, OutStream, Self); end; function TIPTCData.GetActionAdvised: TIPTCActionAdvised; var IntValue: Integer; begin if TryStrToInt(ApplicationSection.GetStringValue(itActionAdvised), IntValue) and (IntValue > 0) and (IntValue <= 99) then Result := TIPTCActionAdvised(IntValue) else Result := iaTagMissing; end; procedure TIPTCData.SetActionAdvised(Value: TIPTCActionAdvised); begin if Value = iaTagMissing then ApplicationSection.Remove(itActionAdvised) else ApplicationSection.SetStringValue(itActionAdvised, Format('%.2d', [Ord(Value)])); end; procedure TIPTCData.GetBylineDetails(Strings: TStrings; ClearDestFirst: Boolean = True); begin ApplicationSection.GetRepeatablePairs(itByline, itBylineTitle, Strings, ClearDestFirst); end; procedure TIPTCData.GetBylineValues(Strings: TStrings); begin GetBylineDetails(Strings); end; procedure TIPTCData.GetPSCreatorValues(Strings: TStrings); begin GetBylineDetails(Strings); end; procedure TIPTCData.GetContentLocationValues(Strings: TStrings; ClearDestFirst: Boolean = True); begin ApplicationSection.GetRepeatablePairs(itContentLocationCode, itContentLocationName, Strings, ClearDestFirst); end; function TIPTCData.GetDate(PackedIndex: Integer): TDateTimeTagValue; begin Result := Sections[Lo(PackedIndex)].GetDateValue(Hi(PackedIndex)); end; function TIPTCData.GetDateTimeCreated: TDateTimeTagValue; begin Result := Sections[isApplication].GetDateTimeValue(itDateCreated, itTimeCreated) end; function TIPTCData.GetDateTimeSent: TDateTimeTagValue; begin Result := Sections[isEnvelope].GetDateTimeValue(itDateSent, itTimeSent) end; procedure TIPTCData.SetDateTimeCreated(const Value: TDateTimeTagValue; AheadOfUtc: Boolean; UtcOffsetHrs, UtcOffsetMins: Byte); begin Sections[isApplication].SetDateTimeValue(itDateCreated, itTimeCreated, Value, AheadOfUtc, UtcOffsetHrs, UtcOffsetMins); end; procedure TIPTCData.SetDateTimeSent(const Value: TDateTimeTagValue; AheadOfUtc: Boolean; UtcOffsetHrs, UtcOffsetMins: Byte); begin Sections[isEnvelope].SetDateTimeValue(itDateSent, itTimeSent, Value, AheadOfUtc, UtcOffsetHrs, UtcOffsetMins); end; {$IFDEF HasTTimeZone} procedure TIPTCData.SetDateTimeCreatedProp(const Value: TDateTimeTagValue); begin Sections[isApplication].SetDateTimeValue(itDateCreated, itTimeCreated, Value); end; procedure TIPTCData.SetDateTimeSentProp(const Value: TDateTimeTagValue); begin Sections[isEnvelope].SetDateTimeValue(itDateSent, itTimeSent, Value); end; {$ENDIF} function TIPTCData.GetImageOrientation: TIPTCImageOrientation; var Tag: TIPTCTag; begin if not ApplicationSection.Find(itImageOrientation, Tag) or (Tag.DataSize <> 1) then Result := ioTagMissing else Result := TIPTCImageOrientation(UpCase(PAnsiChar(Tag.Data)^)); end; procedure TIPTCData.SetImageOrientation(Value: TIPTCImageOrientation); begin if Value = ioTagMissing then ApplicationSection.Remove(itImageOrientation) else ApplicationSection.AddOrUpdate(itImageOrientation, 1, Value); end; function TIPTCData.GetApplicationPairs(PackedTagIDs: Integer): TIPTCRepeatablePairs; begin Result := ApplicationSection.GetRepeatablePairs(Lo(PackedTagIDs), Hi(PackedTagIDs)); end; function TIPTCData.GetApplicationString(TagID: Integer): string; begin Result := ApplicationSection.GetStringValue(TagID) end; function TIPTCData.GetApplicationStrings(TagID: Integer): TIPTCStringArray; begin Result := ApplicationSection.GetRepeatableValue(TagID); end; function TIPTCData.GetEnvelopePriority: TIPTCPriority; begin Result := EnvelopeSection.GetPriorityValue(itEnvelopePriority); end; function TIPTCData.GetEnvelopeString(TagID: Integer): string; begin Result := EnvelopeSection.GetStringValue(TagID) end; function TIPTCData.GetApplicationWord(TagID: Integer): TWordTagValue; begin Result := ApplicationSection.GetWordValue(TagID); end; function TIPTCData.GetEnvelopeWord(TagID: Integer): TWordTagValue; begin Result := EnvelopeSection.GetWordValue(TagID); end; function TIPTCData.GetUrgency: TIPTCPriority; begin Result := ApplicationSection.GetPriorityValue(itUrgency); end; procedure TIPTCData.SetUrgency(Value: TIPTCPriority); begin ApplicationSection.SetPriorityValue(itUrgency, Value); end; function TIPTCData.GetEmpty: Boolean; var Section: TIPTCSection; begin Result := False; if DataToLazyLoad <> nil then Exit; for Section in FSections do if Section.Count <> 0 then Exit; Result := True; end; function TIPTCData.GetEnumerator: TEnumerator; begin NeedLazyLoadedData; Result := TEnumerator.Create(Self); end; procedure TIPTCData.GetKeyWords(Dest: TStrings); begin ApplicationSection.GetRepeatableValue(itKeyword, Dest); end; function TIPTCData.GetModified: Boolean; var ID: TIPTCSectionID; begin Result := True; if DataToLazyLoad = nil then for ID := Low(ID) to High(ID) do if FSections[ID].Modified then Exit; Result := False; end; function TIPTCData.GetSection(ID: Integer): TIPTCSection; begin NeedLazyLoadedData; Result := FSections[ID]; end; function TIPTCData.GetSectionByID(ID: TIPTCSectionID): TIPTCSection; begin NeedLazyLoadedData; Result := FSections[ID]; end; function TIPTCData.GetUTF8Encoded: Boolean; begin NeedLazyLoadedData; Result := FUTF8Encoded; end; function TIPTCData.LoadFromGraphic(Stream: TStream): Boolean; var AdobeBlock: IAdobeResBlock; Directory: IFoundTiffDirectory; Info: TPSDInfo; Segment: IFoundJPEGSegment; Tag: ITiffTag; begin Result := True; if HasJPEGHeader(Stream) then begin for Segment in JPEGHeader(Stream, [jmApp13]) do for AdobeBlock in Segment do if AdobeBlock.IsIPTCBlock then begin LoadFromStream(AdobeBlock.Data); Exit; end end else if HasPSDHeader(Stream) then begin for AdobeBlock in ParsePSDHeader(Stream, Info) do if AdobeBlock.IsIPTCBlock then begin LoadFromStream(AdobeBlock.Data); Exit; end; end else if HasTiffHeader(Stream) then begin for Directory in ParseTiff(Stream) do begin if Directory.FindTag(ttIPTC, Tag) then begin LoadFromStream(Tag.Data); Exit; end; Break; //only interested in the main IFD end; end else Result := False; Clear; end; function TIPTCData.LoadFromGraphic(const Graphic: IStreamPersist): Boolean; var Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try Graphic.SaveToStream(Stream); Stream.Position := 0; Result := LoadFromGraphic(Stream); finally Stream.Free; end; end; function TIPTCData.LoadFromGraphic(const FileName: string): Boolean; var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try Result := LoadFromGraphic(Stream) finally Stream.Free; end; end; procedure TIPTCData.LoadFromStream(Stream: TStream); var I: Integer; Section: TIPTCSection; begin Clear; FUTF8Encoded := AlwaysAssumeUTF8Encoding; AddFromStream(Stream); for Section in FSections do begin Section.Modified := False; Section.FDefinitelySorted := True; for I := 1 to Section.Count - 1 do if Section[I].ID < Section[I - 1].ID then begin Section.FDefinitelySorted := False; Break; end; end; end; procedure TIPTCData.NeedLazyLoadedData; var Item: IMetadataBlock; begin if FDataToLazyLoad = nil then Exit; Item := FDataToLazyLoad; FDataToLazyLoad := nil; //in case of an exception, nil this beforehand Item.Data.Seek(0, soFromBeginning); LoadFromStream(Item.Data); end; procedure TIPTCData.GetGraphicSaveMethod(Stream: TStream; var Method: TGraphicSaveMethod); begin if HasJPEGHeader(Stream) then Method := DoSaveToJPEG else if HasPSDHeader(Stream) then Method := DoSaveToPSD else if HasTiffHeader(Stream) then Method := DoSaveToTIFF end; procedure TIPTCData.SaveToGraphic(const FileName: string); begin DoSaveToGraphic(FileName, GetGraphicSaveMethod); end; procedure TIPTCData.SaveToGraphic(const Graphic: IStreamPersist); begin DoSaveToGraphic(Graphic, GetGraphicSaveMethod); end; procedure TIPTCData.SaveToStream(Stream: TStream); const BigDataSizeMarker: SmallInt = -4; var Section: TIPTCSection; Tag: TIPTCTag; begin if DataToLazyLoad <> nil then begin DataToLazyLoad.Data.SaveToStream(Stream); Exit; end; if UTF8Encoded then Sections[1].AddOrUpdate(90, SizeOf(UTF8Marker), UTF8Marker) else if Sections[1].Find(90, Tag) and (Tag.DataSize = SizeOf(UTF8Marker)) and CompareMem(Tag.Data, @UTF8Marker, SizeOf(UTF8Marker)) then Tag.Free; for Section in FSections do for Tag in Section do begin Stream.WriteBuffer(TAdobeResBlock.NewIPTCTagMarker, SizeOf(TAdobeResBlock.NewIPTCTagMarker)); Stream.WriteBuffer(Tag.Section.ID, SizeOf(TIPTCSectionID)); Stream.WriteBuffer(Tag.ID, SizeOf(TIPTCTagID)); if Tag.DataSize <= High(SmallInt) then Stream.WriteSmallInt(Tag.DataSize, BigEndian) else begin Stream.WriteSmallInt(BigDataSizeMarker, BigEndian); Stream.WriteLongInt(Tag.DataSize, BigEndian); end; if Tag.DataSize <> 0 then Stream.WriteBuffer(Tag.Data^, Tag.DataSize); end; end; procedure TIPTCData.SetDataToLazyLoad(const Value: IMetadataBlock); begin if Value = FDataToLazyLoad then Exit; Clear; FDataToLazyLoad := Value; end; procedure TIPTCData.SortTags; var SectID: TIPTCSectionID; begin NeedLazyLoadedData; for SectID := Low(SectID) to High(SectID) do FSections[SectID].Sort; end; procedure TIPTCData.SetBylineDetails(Strings: TStrings); begin ApplicationSection.SetRepeatablePairs(itByline, itBylineTitle, Strings); end; procedure TIPTCData.SetBylineValues(Strings: TStrings); begin SetBylineDetails(Strings); end; procedure TIPTCData.SetPSCreatorValues(Strings: TStrings); begin SetBylineDetails(Strings); end; procedure TIPTCData.SetContentLocationValues(Strings: TStrings); begin ApplicationSection.SetRepeatablePairs(itContentLocationCode, itContentLocationName, Strings); end; procedure TIPTCData.SetDate(PackedIndex: Integer; const Value: TDateTimeTagValue); begin FSections[Lo(PackedIndex)].SetDateValue(Hi(PackedIndex), Value) end; procedure TIPTCData.SetApplicationPairs(PackedTagIDs: Integer; const NewPairs: TIPTCRepeatablePairs); begin ApplicationSection.SetRepeatablePairs(Lo(PackedTagIDs), Hi(PackedTagIDs), NewPairs); end; procedure TIPTCData.SetApplicationString(TagID: Integer; const Value: string); begin ApplicationSection.SetStringValue(TagID, Value); end; procedure TIPTCData.SetApplicationStrings(TagID: Integer; const Value: TIPTCStringArray); begin ApplicationSection.SetRepeatableValue(TagID, Value); end; procedure TIPTCData.SetApplicationWord(TagID: Integer; const Value: TWordTagValue); begin ApplicationSection.SetWordValue(TagID, Value); end; procedure TIPTCData.SetEnvelopePriority(const Value: TIPTCPriority); begin EnvelopeSection.SetPriorityValue(itEnvelopePriority, Value); end; procedure TIPTCData.SetEnvelopeString(TagID: Integer; const Value: string); begin EnvelopeSection.SetStringValue(TagID, Value); end; procedure TIPTCData.SetEnvelopeWord(TagID: Integer; const Value: TWordTagValue); begin EnvelopeSection.SetWordValue(TagID, Value); end; procedure TIPTCData.SetKeywords(NewWords: TStrings); begin ApplicationSection.SetRepeatableValue(itKeyword, NewWords); end; procedure TIPTCData.SetModified(Value: Boolean); var ID: TIPTCSectionID; begin NeedLazyLoadedData; for ID := Low(ID) to High(ID) do FSections[ID].Modified := Value; end; procedure TIPTCData.SetUTF8Encoded(Value: Boolean); var I: Integer; SectID: TIPTCSectionID; Tag: TIPTCTag; Strings: array[TIPTCSectionID] of TIPTCStringArray; begin if Value = UTF8Encoded then Exit; for SectID := Low(SectID) to High(SectID) do begin SetLength(Strings[SectID], FSections[SectID].Count); for I := 0 to High(Strings[SectID]) do begin Tag := FSections[SectID].Tags[I]; if FindProperDataType(Tag) = idString then Strings[SectID][I] := Tag.ReadString; end; end; FUTF8Encoded := Value; for SectID := Low(SectID) to High(SectID) do for I := 0 to High(Strings[SectID]) do begin Tag := FSections[SectID].Tags[I]; if FindProperDataType(Tag) = idString then Tag.WriteString(Strings[SectID][I]); end; end; end.
unit uinfodll; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; PDLLVerInfo = ^TDLLVersionInfo; TDLLVersionInfo = record cbSize, // Size of the structure, in bytes. dwMajorVersion, // Major version of the DLL dwMinorVersion, // Minor version of the DLL dwBuildNumber, // Build number of the DLL dwPlatformID: DWord; // Identifies the platform for which the DLL was built end; var Form1: TForm1; DllGetVersion: function(dvi: PDLLVerInfo): PDLLVerInfo; stdcall; implementation {$R *.dfm} function GetDllVersion(DllName: string; var DLLVersionInfo: TDLLVersionInfo): Boolean; var hInstDll: THandle; p: pDLLVerInfo; begin Result := False; // Get a handle to the DLL module. // das Handle zum DLL Modul ermitteln. hInstDll := LoadLibrary(PChar(DllName)); if (hInstDll = 0) then Exit; // Return the address of the specified exported (DLL) function. // Adresse der Dll-Funktion ermitteln @DllGetVersion := GetProcAddress(hInstDll, 'DllGetVersion'); // If the handle is not valid, clean up an exit. // Wenn das Handle ungültig ist, wird die Funktion verlassen if (@DllGetVersion) = nil then begin FreeLibrary(hInstDll); Exit; end; new(p); try ZeroMemory(p, SizeOf(p^)); p^.cbSize := SizeOf(p^); // Call the DllGetVersion function // Die DllGetVersion() Funktion aufrufen DllGetVersion(p); DLLVersionInfo.dwMajorVersion := p^.dwMajorVersion; DLLVersionInfo.dwMinorVersion := p^.dwMinorVersion; @DllGetVersion := nil; Result := True; finally dispose(P); end; // Free the DLL module. // Dll wieder freigeben. FreeLibrary(hInstDll); end; // Example to get version info from comctl32.dll // Beispiel, um von comctl32 Versions/Informationen zu erhalten procedure TForm1.Button1Click(Sender: TObject); var DLLVersionInfo: TDLLVersionInfo; begin if not GetDllVersion('minhadll.dll', DLLVersionInfo) then begin DLLVersionInfo.dwMajorVersion := 4; DLLVersionInfo.dwMinorVersion := 0; end; with DLLVersionInfo do ShowMessage(Format('Version: %d.%d / Build: %d', [dwMajorVersion, dwMinorVersion, dwBuildNumber])) end; end.
unit uTurnFrame; 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.ImgList, Vcl.Buttons; type TfrTurn = class(TFrame) gb: TGroupBox; Label5: TLabel; Label6: TLabel; Label7: TLabel; cbStateIn: TComboBox; cbStateOut: TComboBox; cbEmergency: TCheckBox; edCardExit: TEdit; Label1: TLabel; cbReader: TComboBox; btnIn: TButton; ImageList1: TImageList; btnOut: TButton; btnCardExit: TSpeedButton; Timer1: TTimer; Label2: TLabel; Label3: TLabel; lEnterCount: TLabel; lExitCount: TLabel; Label4: TLabel; edCardEnter: TEdit; btnCardEnter: TSpeedButton; Timer2: TTimer; edLED1: TEdit; edLED2: TEdit; procedure edCardExitKeyPress(Sender: TObject; var Key: Char); procedure btnCardExitClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure btnInClick(Sender: TObject); procedure btnOutClick(Sender: TObject); procedure btnCardEnterClick(Sender: TObject); procedure Timer2Timer(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} uses uMain, uTurnDef; procedure TfrTurn.btnCardEnterClick(Sender: TObject); begin if length(edCardEnter.Text) > 5 then with Turnstiles.ByAddr(self.Tag) do EnterCardNum := edCardEnter.Text; end; procedure TfrTurn.btnCardExitClick(Sender: TObject); begin if length(edCardExit.Text) > 5 then with Turnstiles.ByAddr(self.Tag) do ExitCardNum := edCardExit.Text; end; procedure TfrTurn.btnInClick(Sender: TObject); begin with Turnstiles.ByAddr(self.Tag) do begin if EnterState <> 0 then begin EnterCount := EnterCount + 1; lEnterCount.Caption := IntToStr(EnterCount); if EnterState < $FFFF then EnterState := EnterState - 1; if EnterState = 0 then begin Timer1.Enabled := false; btnIn.Enabled := false; btnIn.ImageIndex := 0; end; end; end; end; procedure TfrTurn.btnOutClick(Sender: TObject); begin with Turnstiles.ByAddr(self.Tag) do begin if ExitState <> 0 then begin ExitCount := ExitCount + 1; lExitCount.Caption := IntToStr(ExitCount); if ExitState < $FFFF then ExitState := ExitState - 1; if ExitState = 0 then begin Timer2.Enabled := false; btnOut.Enabled := false; btnOut.ImageIndex := 0; end; end; end; end; procedure TfrTurn.edCardExitKeyPress(Sender: TObject; var Key: Char); begin if not(Key in ['0'..'9', 'A'..'F', 'a'..'f', #8]) then Key := #0; end; procedure TfrTurn.Timer1Timer(Sender: TObject); begin Timer1.Enabled := false; btnIn.ImageIndex := 0; btnIn.Enabled := false; with Turnstiles.ByAddr(self.Tag) do EnterState := EnterState - 1; end; procedure TfrTurn.Timer2Timer(Sender: TObject); begin Timer2.Enabled := false; btnOut.ImageIndex := 0; btnOut.Enabled := false; with Turnstiles.ByAddr(self.Tag) do ExitState := ExitState - 1; end; end.
{ NAME: Jordan Millett CLASS: Comp Sci 1 DATE: 12/12/2016 PURPOSE: To make a program that will: Get 3/5 numbers from the user Display the numbers Find the total(display) Done in procedures ABOVE AND BEYOND Find the average Find the biggest and smallest num } Program testscores; uses crt; Procedure getInt(ask:string; var num : integer); var numStr : string; code : integer; begin repeat write(ask); readln(numstr); val(numStr, num, code); if code <> 0 then begin writeln('Not an integer '); writeln('Press any key to continue'); readkey; clrscr; end; until (code = 0); end; procedure getnums(var num1,num2,num3,num4,num5:integer); begin getInt('Enter the first number: ',num1); getInt('Enter the second number: ',num2); getInt('Enter the third number: ',num3); getInt('Enter the fourth number: ',num4); getInt('Enter the fifth number: ',num5); clrscr; end; procedure addthem(var num1,num2,num3,num4,num5,total:integer); begin total:=num1+num2+num3+num4+num5; end; procedure display(var num1,num2,num3,num4,num5,total:integer); begin writeln(num1,' + ',num2,' + ',num3,' + ',num4,' + ',num5,' = ',total); end; var num1,num2,num3,num4,num5,total:integer; begin {main} getnums(num1,num2,num3,num4,num5); addthem(num1,num2,num3,num4,num5,total); display(num1,num2,num3,num4,num5,total); writeln('Press any key to end the program'); readkey; end. {main}
(* UDCBuff.PAS - Copyright (c) 1995-1996, Eminent Domain Software *) unit UDCBuff; {-UDC Memo Writer buffer manager for EDSSpell component} interface uses Classes, Controls, Graphics, SysUtils, Forms, StdCtrls, WinProcs, WinTypes, AbsBuff, MemoUtil, SpellGbl, UDC_mwps, UDC_Win; type TUDCBuf = class (TPCharBuffer) {UDC Memo Writer Buffer Manager} private { Private declarations } WeModified: Boolean; protected { Protected declarations } public { Public declarations } constructor Create (AParent: TControl); override; function IsModified: Boolean; override; {-returns TRUE if parent had been modified} procedure SetModified (NowModified: Boolean); override; {-sets parents modified flag} function GetYPos: integer; override; {-gets the current y location of the highlighted word (absolute screen)} procedure SetSelectedText; override; {-highlights the current word using BeginPos & EndPos} function GetNextWord: string; override; {-returns the next word in the buffer} procedure UpdateBuffer; override; {-updates the buffer from the parent component, if any} procedure ReplaceWord (WithWord: string); override; {-replaces the current word with the word provided} end; { TUDCBuf } implementation {UDC Memo Writer Buffer Manager} constructor TUDCBuf.Create (AParent: TControl); begin inherited Create (AParent); WeModified := FALSE; end; { TUDCBuf.Create } function TUDCBuf.IsModified: Boolean; {-returns TRUE if parent had been modified} begin Result := WeModified; end; { TUDCBuf.IsModified } procedure TUDCBuf.SetModified (NowModified: Boolean); {-sets parents modified flag} begin WeModified := NowModified; end; { TUDCBuf.SetModified } function TUDCBuf.GetYPos: integer; {-gets the current y location of the highlighted word (absolute screen)} begin Result := 0; end; { TUDCBuf.GetYPos } procedure TUDCBuf.SetSelectedText; {-highlights the current word using FBeginPos & FEndPos} begin with Parent as TUdcMWPStandard do SPSelectWord; end; { TUDCBuf.SetSelectedText } function TUDCBuf.GetNextWord: string; {-returns the next word in the buffer} var i: byte; begin with Parent as TUdcMWPStandard do begin Result := SPGetNextWord; AllNumbers := TRUE; i := 1; while (i <= Length (Result)) and AllNumbers do begin AllNumbers := AllNumbers and (Result[i] in NumberSet); Inc(i); end; { while } end; { if... } end; { TUDCBuf.GetNextWord } procedure TUDCBuf.UpdateBuffer; {-updates the buffer from the parent component, if any} begin {do nothing} end; { TUDCBuf.UpdateBuffer } procedure TUDCBuf.ReplaceWord (WithWord: string); {-replaces the current word with the word provided} begin with Parent as TUdcMWPStandard do SelText := WithWord; WeModified := TRUE; end; { TUDCBuf.ReplaceWord } end. { UDCBuff }
unit fmeSDUDiskPartitions; interface { layers used are: //delphi and 3rd party libs - layer 0 // LibreCrypt forms - layer 2 //main form - layer 3 } uses //delphi and 3rd party libs - layer 0 Classes, SysUtils, //sdu & LibreCrypt utils - layer 1 fmeSDUBlocks, SDUGeneral, SDUObjectManager, Vcl.Controls, Vcl.StdCtrls; type // Exceptions... ESDUPartitionsException = Exception; ESDUUnableToGetDriveLayout = ESDUPartitionsException; const NO_DISK = -1; NO_PARTITION = -1; resourcestring UNABLE_TO_GET_DISK_LAYOUT = 'Unable to get disk layout for disk: %1'; type TfmeSDUDiskPartitions = class (TfmeSDUBlocks) private FDiskNumber: Integer; FDriveLayoutInfo: TSDUDriveLayoutInformationEx; FDriveLayoutInfoValid: Boolean; FShowPartitionsWithPNZero: Boolean; // The index into this TStringList is the block number // The objects of the TStringList are the indexes into FDriveLayoutInfo's // "Partition" member FMapBlockToPartition: TStringList; objMgr: TSDUObjManager; // Strings are the device names for the drives, Objects are the ordinal // value of the drive letter driveDevices: TStringList; procedure SetDiskNumber(DiskNo: Integer); function GetPartitionInfo(idx: Integer): TPartitionInformationEx; function GetDriveLetter(idx: Integer): Char; function GetDriveLetterForPartition(DiskNo: Integer; PartitionNo: Integer): DriveLetterChar; procedure RefreshPartitions(); protected function GetDriveLayout(physicalDiskNo: Integer; var driveLayout: TSDUDriveLayoutInformationEx): Boolean; virtual; function IgnorePartition(partInfo: TPartitionInformationEx): Boolean; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; property PartitionInfo[idx: Integer]: TPartitionInformationEx Read GetPartitionInfo; property DriveLetter[idx: Integer]: Char Read GetDriveLetter; procedure Clear(); override; published // Show partitions with partition number zero // USE WITH CAUTION! Referencing the partitions with partition number zero // mean the entire drive! (Partition number zero) property ShowPartitionsWithPNZero: Boolean Read FShowPartitionsWithPNZero Write FShowPartitionsWithPNZero default False; // Set to NO_DISK for no disk display property DiskNumber: Integer Read FDiskNumber Write SetDiskNumber default NO_DISK; property DriveLayoutInformation: TSDUDriveLayoutInformationEx Read FDriveLayoutInfo; property DriveLayoutInformationValid: Boolean Read FDriveLayoutInfoValid; end; //procedure Register; implementation uses Math, Windows; {$R *.dfm} const ULL_ONEMEG: ULONGLONG = 1024 * 1024; //procedure Register; //begin // RegisterComponents('SDeanUtils', [TfmeSDUDiskPartitions]); //end; constructor TfmeSDUDiskPartitions.Create(AOwner: TComponent); begin inherited; FMapBlockToPartition := TStringList.Create(); FDiskNumber := NO_DISK; end; destructor TfmeSDUDiskPartitions.Destroy(); begin FMapBlockToPartition.Free(); if (objMgr <> nil) then begin objMgr.Free(); end; if (driveDevices <> nil) then begin driveDevices.Free(); end; inherited; end; procedure TfmeSDUDiskPartitions.Clear(); begin inherited; FMapBlockToPartition.Clear(); end; procedure TfmeSDUDiskPartitions.RefreshPartitions(); var i: Integer; blk: TBlock; idx: Integer; cnt: ULONGLONG; oneMeg: ULONGLONG; // Temp variables to prevent Delphi converting to (signed!) int64 or // (signed!) float during math operations // For the same reason, calculations are carried out step-by-step tmpA: ULONGLONG; tmpB: ULONGLONG; currPartition: TPartitionInformationEx; minPcnt: Double; totalPcnt: Double; driveLetter: DriveLetterChar; drive: String; prettyPartitionType: String; begin Self.Clear(); FDriveLayoutInfoValid := False; if (DiskNumber >= 0) then begin FDriveLayoutInfo.PartitionCount := 0; if not (GetDriveLayout(DiskNumber, FDriveLayoutInfo)) then begin // Call invalidate to ensure the display is refreshed Invalidate(); raise ESDUUnableToGetDriveLayout.Create(SDUParamSubstitute(UNABLE_TO_GET_DISK_LAYOUT, [DiskNumber])); end else begin FDriveLayoutInfoValid := True; oneMeg := 1024 * 1024; cnt := 0; for i := 0 to (FDriveLayoutInfo.PartitionCount - 1) do begin if IgnorePartition(FDriveLayoutInfo.PartitionEntry[i]) then begin // Extended partition, or similar continue; end; FMapBlockToPartition.AddObject(inttohex(FDriveLayoutInfo.PartitionEntry[i].StartingOffset, 16), TObject(i)); tmpA := (FDriveLayoutInfo.PartitionEntry[i].PartitionLength div oneMeg); cnt := cnt + tmpA; end; // Partitions within an extended partition reset their partition offset to // zero, so the above is actually storing the wrong offsets; otherwise we // *should* be doing this... // FMapBlockToPartition.Sort; // The percentages are the percentage of the whole disk, with a min // percentage of: minPcnt := 0; if (FMapBlockToPartition.Count > 0) then begin minPcnt := 100 / (FMapBlockToPartition.Count * 2); end; for i := 0 to (FMapBlockToPartition.Count - 1) do begin idx := Integer(FMapBlockToPartition.Objects[i]); currPartition := FDriveLayoutInfo.PartitionEntry[idx]; tmpA := (currPartition.PartitionLength div oneMeg); if (tmpA = 0) then begin tmpB := 0; end else begin tmpB := (cnt div tmpA); end; if (tmpB = 0) then begin blk.Percentage := 0; end else begin blk.Percentage := ((1 / tmpB) * 100); end; blk.Percentage := max(blk.Percentage, minPcnt); blk.Data := TObject(idx); drive := ' '; // Needs to be set to *something* or it won't be // displayed as a blank line if empty driveLetter := GetDriveLetterForPartition(DiskNumber, currPartition.PartitionNumber); if (driveLetter <> #0) then begin drive := driveLetter + ':'; end; if currPartition.PartitionStyle = PARTITION_STYLE_MBR then begin prettyPartitionType := SDUMbrPartitionType(currPartition.Mbr.PartitionType, False); end else begin if currPartition.PartitionStyle = PARTITION_STYLE_GPT then begin prettyPartitionType := SDUGptPartitionType(currPartition.gpt.PartitionType, False); end else begin //raw prettyPartitionType := 'RAW psartition'; end; end; blk.Caption := SDUFormatAsBytesUnits(currPartition.PartitionLength) + SDUCRLF + drive; blk.SubCaption := prettyPartitionType; //'Idx: '+inttostr(idx)+SDUCRLF+ //'PN: '+inttostr(currPartition.PartitionNumber)+SDUCRLF+ //'PT: 0x'+inttohex(currPartition.PartitionType, 2); Add(blk); end; // Rejig the percentages so they add up to 100% (could be more at this // point, due to the min percentage and much larger disks) totalPcnt := 0; for i := 0 to (Count - 1) do begin blk := Item[i]; totalPcnt := totalPcnt + blk.Percentage; Item[i] := blk; end; for i := 0 to (Count - 1) do begin blk := Item[i]; blk.Percentage := (blk.Percentage / totalPcnt) * 100; Item[i] := blk; end; end; end; end; procedure TfmeSDUDiskPartitions.SetDiskNumber(DiskNo: Integer); begin FDiskNumber := DiskNo; RefreshPartitions(); Invalidate(); end; function TfmeSDUDiskPartitions.GetPartitionInfo(idx: Integer): TPartitionInformationEx; var lstIdx: Integer; begin // Sanity check... Assert( ((idx >= low(FBlocks)) or (idx <= high(FBlocks))), 'GetPartitionInfo called with bad index: ' + IntToStr(idx) ); lstIdx := Integer(FMapBlockToPartition.Objects[idx]); Result := FDriveLayoutInfo.PartitionEntry[lstIdx]; end; // Returns #0 if drive letter can't be found function TfmeSDUDiskPartitions.GetDriveLetterForPartition(DiskNo: Integer; PartitionNo: Integer): DriveLetterChar; var partitionDevice: String; partitionUnderlying: String; driveLetter: Char; idx: Integer; tmpDeviceName: String; begin Result := #0; if (objMgr = nil) then begin objMgr := TSDUObjManager.Create(); end; // Get the underlying device name for each drive letter... if (driveDevices = nil) then begin driveDevices := TStringList.Create(); for driveLetter := 'A' to 'Z' do begin tmpDeviceName := objMgr.UnderlyingDeviceForDrive(driveLetter); if (tmpDeviceName <> '') then begin driveDevices.AddObject(tmpDeviceName, TObject(Ord(driveLetter))); end; end; end; // Get the partition device name for the disk/partition we're interested in... partitionDevice := SDUDeviceNameForPartition(DiskNo, PartitionNo); // Get the underlying device name for the disk/partition we're interested in... partitionUnderlying := objMgr.UnderlyingDeviceForName(partitionDevice); // Locate the drive letter for the underlying device name for the // disk/partition we're interested in... idx := driveDevices.IndexOf(partitionUnderlying); if (idx >= 0) then begin Result := Char(Integer(driveDevices.Objects[idx])); end; end; // Returns #0 if no partition selected/no drive letter assigned to partition function TfmeSDUDiskPartitions.GetDriveLetter(idx: Integer): Char; var partInfo: TPartitionInformationEx; begin Result := #0; if (idx >= 0) then begin partInfo := PartitionInfo[idx]; Result := GetDriveLetterForPartition(DiskNumber, partInfo.PartitionNumber); end; end; function TfmeSDUDiskPartitions.GetDriveLayout(physicalDiskNo: Integer; var driveLayout: TSDUDriveLayoutInformationEx): Boolean; begin Result := SDUGetDriveLayout(DiskNumber, FDriveLayoutInfo); end; function TfmeSDUDiskPartitions.IgnorePartition(partInfo: TPartitionInformationEx): Boolean; begin Result := ( // USE CAUTION! We don't want the user selecting a partition, and // ending up using the whole HDD (partition number zero) (not (ShowPartitionsWithPNZero) and (partInfo.PartitionNumber = 0)) or // Piddly partitions; extended partitions, etc (partInfo.PartitionLength < ULL_ONEMEG) or // $05/$0F = extended partition definition ((partInfo.PartitionStyle = PARTITION_STYLE_MBR) and (partInfo.mbr.PartitionType = $05) or (partInfo.mbr.PartitionType = $0F))); end; end.
(* Desciption: Find primes that is smaller than N Programmer: ... Date: dd/mm/yyyy Version: v1.0 *) (* Program name *) program HomeWork8; (* Unit's inclusion *) uses crt; (* Type's declaration *) type arrOfFiveHundInts = array [0..499] of integer; (* Variable's declration *) var primes : arrOfFiveHundInts; number : integer = 0; curIndex : integer = 0; (* Function's declaration *) function IsPrime(number : integer) : boolean; (* Local variables *) var result : boolean = false; tempNum : integer = 0; (* Funtion body *) begin if (number < 2) then begin result := false; end else begin result := true; for tempNum := 2 to (number div 2) do begin if ((number mod tempNum) = 0) then begin result := false; break; end; end; end; IsPrime := result; end; (* Procedure's declaration *) procedure InitArr(var arr : arrOfFiveHundInts); (* Local variables *) var curIndex : integer = 0; (* Funtion body *) begin for curIndex := 0 to (SizeOf(arr) div SizeOf(integer)) - 1 do begin arr[curIndex] := 0; end; end; procedure FindPrimes(number : integer; var primes : arrOfFiveHundInts); (* Local variables *) var curIndex : integer = 0; tempNum : integer = 0; (* Funtion body *) begin for tempNum := 2 to number - 1 do begin if (IsPrime(tempNum) = true) then begin primes[curIndex] := tempNum; curIndex := curIndex + 1; end; end; end; (* Main program *) begin write('Enter N: '); readln(number); InitArr(primes); FindPrimes(number, primes); curIndex := 0; while (curIndex < (SizeOf(primes) div SizeOf(integer))) do if (primes[curIndex] <> 0) then begin writeln(primes[curIndex], ' '); curIndex := curIndex + 1; end else begin break; end; end.
{Алгоритм сравнения файлов} Unit CompF; interface uses Enliner, Consts, MsgBox; procedure compareFiles(var en1: TEnliner; var en2: TEnliner); implementation { Можно использовать только такие команды для обращения к энлайнеру: [ en1.lineCount ] - Количество линий в энлайнере [ en1.lines[X]^ ] - Использовать линию целиком как обычную строку [ en1.getSym(линия, номер символа) ] -> Символ [ en1.getLineSize(линия) ] -> Длина указанной линии [ en1.getMark(линия, номер символа) ] -> Цвет маркера этого символа [ en1.setMark(линия, номер символа, цвет символа) ] ^ Окрашивает указанный символ указанным цветом Цвета: nomatchColor - Красное выделение defaultColor - Обычный цвет markingColor - Серое выделение } type sword = record wd: string[15]; startWordLine : integer; endWordLine : integer; startWordSymbol : integer; endWordSymbol : integer; end; wordArray = array[0..20] of sword; listLCS = array[0..20] of integer; LCS = array[0..20, 0..20] of integer; symbol = set of char; procedure fillArray(en: TEnliner; var txt: wordArray; var k: integer); var i, j, u, p: integer; punctuationMarks, letters: symbol; begin punctuationMarks := [' ', '.', ',', ':', ';', '-', '!', '?', chr(26), chr(13), chr(10)]; letters := ['a'..'z', 'A'..'Z', '0'..'9']; k := 0; u := 0; for i := 0 to en.lineCount - 1 do for j := 0 to en.getLineSize(i) - 1 do if (en.getSym(i, j) in letters) then begin Inc(u); txt[k].wd[u] := en.getSym(i, j); txt[k].wd[0] := char(u); if (u = 1) then begin txt[k].startWordLine := i; txt[k].startWordSymbol := j; end; if ((en.getSym(i, j + 1) in punctuationMarks) or (j = en.getLineSize(i) - 1)) then begin txt[k].endWordSymbol := j; Inc(k); u := 0; end; end; txt[k].wd := chr(26); end; function max(a, b: integer): integer; begin if (a >= b) then max := a; if (a < b) then max := b; end; procedure createArrayLCS(var firstText, secondText: wordArray; n, m: integer; var arrayLCS: LCS); var i, j: integer; begin for i := m downto 0 do for j := n downto 0 do if ((firstText[i].wd = chr(26)) or (secondText[j].wd = chr(26))) then arrayLCS[i, j] := 0 else if (firstText[i].wd = secondText[j].wd) then arrayLCS[i, j] := 1 + arrayLCS[i+1, j+1] else arrayLCS[i, j] := max(arrayLCS[i + 1, j], arrayLCS[i, j + 1]); end; procedure createListLCS(firstText, secondText: wordArray; n, m: integer; arrayLCS: LCS; var firstList, secondList: listLCS); var i, j, k: integer; begin i := 0; j := 0; for k := 0 to 20 do begin firstList [k] := 0; secondList[k] := 0; end; while ((i < m) and (j < n)) do if (firstText[i].wd = secondText[j].wd) then begin firstList [i] := 1; secondList[j] := 1; i := i + 1; j := j + 1; end else if (arrayLCS[i + 1, j] >= arrayLCS[i, j + 1]) then i := i + 1 else j := j + 1; end; procedure colorizeText(var en: TEnliner; text: wordArray; list: listLCS; n: integer); var i, j: integer; begin for i := 0 to n - 1 do if (list[i] = 0) then for j := text[i].startWordSymbol to text[i].endWordSymbol do en.setMark(text[i].startWordLine, j, nomatchColor); end; procedure compareFiles(var en1: TEnliner; var en2: TEnliner); var firstText, secondText: wordArray; firstList, secondList: listLCS; arrayLCS: LCS; n, m: integer; begin if (en1.lineCount = 0) or (en2.lineCount = 0) then Exit; n := 0; m := 0; fillArray(en1, firstText, m); fillArray(en2, secondText, n); createArrayLCS(firstText, secondText, n, m, arrayLCS); createListLCS (firstText, secondText, n, m, arrayLCS, firstList, secondList); colorizeText(en1, firstText, firstList, m); colorizeText(en2, secondText, secondList, n); end; begin {DO NOTHING} end.
unit DSA.List_Stack_Queue.QueueCompare; interface uses System.SysUtils, System.Classes, DSA.Interfaces.DataStructure, DSA.List_Stack_Queue.ArrayListQueue, DSA.List_Stack_Queue.LoopListQueue, DSA.List_Stack_Queue.LinkedListQueue; procedure Main; implementation function testTime(q: IQueue<Integer>; opCount: Integer): string; var startTime, endTime: Cardinal; i: Integer; begin Randomize; startTime := TThread.GetTickCount; for i := 0 to opCount - 1 do q.EnQueue(Random(Integer.MaxValue)); for i := 0 to opCount - 1 do q.DeQueue; endTime := TThread.GetTickCount; Result := FloatToStr((endTime - startTime) / 1000); end; type TArrayListQueue_int = TArrayListQueue<Integer>; TLoopListQueue_int = TLoopListQueue<Integer>; TLinkedListQueue_int = TLinkedListQueue<Integer>; procedure Main; var ArrayListQueue: TArrayListQueue_int; LoopListQueue: TLoopListQueue_int; LinkedListQueue: TLinkedListQueue_int; vTime: string; opCount: Integer; begin opCount := 10000000; ArrayListQueue := TArrayListQueue_int.Create(); vTime := testTime(ArrayListQueue, opCount); Writeln('ArrayListQueue, time: ' + vTime + ' s'); LoopListQueue := TLoopListQueue_int.Create(); vTime := testTime(LoopListQueue, opCount); Writeln('LoopListQueue, time: ' + vTime + ' s'); LinkedListQueue := TLinkedListQueue_int.Create(); vTime := testTime(LinkedListQueue, opCount); Writeln('LinkedlistQueue, time: ' + vTime + ' s'); end; end.
unit EditPositionFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, DBClient, StdCtrls, DBCtrls, Mask, RzEdit, RzDBEdit, RzButton, RzLabel, ExtCtrls, RzPanel,CommonLIB; type TfrmEditPosition = class(TForm) RzPanel1: TRzPanel; RzLabel1: TRzLabel; RzLabel3: TRzLabel; btnSave: TRzBitBtn; btnCancel: TRzBitBtn; RzDBEdit17: TRzDBEdit; RzDBEdit1: TRzDBEdit; DBCheckBox1: TDBCheckBox; cdsPosition: TClientDataSet; dsPosition: TDataSource; procedure btnCancelClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private FPositionCode: integer; FAppParameter: TDLLParameter; procedure SetPositionCode(const Value: integer); procedure SetAppParameter(const Value: TDLLParameter); { Private declarations } public { Public declarations } property PositionCode : integer read FPositionCode write SetPositionCode; property AppParameter : TDLLParameter read FAppParameter write SetAppParameter; end; var frmEditPosition: TfrmEditPosition; implementation uses CdeLIB, STDLIB; {$R *.dfm} { TfrmEditPosition } procedure TfrmEditPosition.SetAppParameter(const Value: TDLLParameter); begin FAppParameter := Value; end; procedure TfrmEditPosition.SetPositionCode(const Value: integer); begin FPositionCode := Value; cdsPosition.Data :=GetDataSet('select * from ICMTTPOS where POSCOD='+IntToStr(FPositionCode)); end; procedure TfrmEditPosition.btnCancelClick(Sender: TObject); begin Close; end; procedure TfrmEditPosition.btnSaveClick(Sender: TObject); var IsNew : boolean; begin if cdsPosition.State in [dsinsert] then begin IsNew := true; cdsPosition.FieldByName('POSCOD').AsInteger :=getCdeRun('SETTING','RUNNING','POSCOD','CDENM1'); cdsPosition.FieldByName('POSCDE').AsString :=FormatCurr('000',cdsPosition.FieldByName('POSCOD').AsInteger); if cdsPosition.FieldByName('POSACT').IsNull then cdsPosition.FieldByName('POSACT').AsString:='A'; setEntryUSRDT(cdsPosition,FAppParameter.UserID); setSystemCMP(cdsPosition,FAppParameter.Company,FAppParameter.Branch,FAppParameter.Department,FAppParameter.Section); end; if cdsPosition.State in [dsinsert,dsedit] then setModifyUSRDT(cdsPosition,FAppParameter.UserID); if cdsPosition.State in [dsedit,dsinsert] then cdsPosition.Post; if cdsPosition.ChangeCount>0 then begin UpdateDataset(cdsPosition,'select * from ICMTTPOS where POSCOD='+IntToStr(FPositionCode)) ; if IsNew then setCdeRun('SETTING','RUNNING','POSCOD','CDENM1'); end; FPositionCode:= cdsPosition.FieldByName('POSCOD').AsInteger; Close; end; procedure TfrmEditPosition.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=VK_ESCAPE then btnCancelClick(nil); if Key=VK_F11 then btnSaveClick(nil); end; end.
unit UFRCommon; interface uses {$IFnDEF FPC} Windows, {$ELSE} LCLIntf, LCLType, LMessages, DOM, XmlRead, {$ENDIF} SysUtils; procedure SaveXMLInit(var LogPath: string); procedure SaveXML(const LogPath, stLog: string; var LogNum: Integer); {$ifndef FPC} procedure AppProcessMessages(); deprecated; function IsThisWine: Boolean; procedure Sleep2(const msec: DWord); {$endif} function ReadFileToString(fn: string): string; procedure DeleteSpaces(var st: string); function GetDigit(const DigNum: Integer; const stDig: string; const DecYear: Boolean = True): Integer; function FlagPresented(const Mask: int64; const Flags: array of int64): Boolean; function AnsiTo866(const stAnsi: string): string; function CP866ToAnsi(const stAnsi: string): string; function BCDToDWord(const BCD: DWord): DWord; stdcall; assembler; function BCDToByte(const BCD: Byte): Byte; stdcall; assembler; function BCDToInt64(const BCD: int64): int64; stdcall; assembler; function GetBit(const bt, nBit: Byte): Boolean; stdcall; assembler; function SetBit(const bt, nBit: Byte): Byte; stdcall; assembler; procedure DWordToBcd(dw: DWord; BCDRes: Pointer; BCDResLen: DWord); procedure SwapBytes(const pBt: Pointer; Count: Integer); stdcall; assembler; implementation function BCDToDWord(const BCD: DWord): DWord; stdcall; assembler; asm PUSH EBX PUSH ECX PUSH EDX PUSH EDI PUSH ESI MOV ESI,BCD MOV EDI,ESI AND EDI,$0000000F //число единиц MOV ECX,8-1 //осталось еще семь шестнадцатеричных цифр (в DWORD их 8) MOV EBX,10 @@1: SHR ESI,4 MOV EAX,ESI AND EAX,$0000000F MUL EBX //здесь последовательно умножаем на 10, на 100, на 1000 и т.д. ADD EDI,EAX MOV EAX,EBX SHL EBX,3 //*8 SHL EAX,1 //*2 ADD EBX,EAX //ebx = ebx * 10 LOOP @@1 MOV EAX,EDI //результат в EAX POP ESI POP EDI POP EDX POP ECX POP EBX end; function BCDToByte(const BCD: Byte): Byte; stdcall; assembler; asm PUSH EBX XOR EAX,EAX MOV AL,Byte Ptr BCD MOV BL,AL AND BL,$0F AND AL,$F0 SHR EAX,3 LEA EAX,[EAX+4*EAX] ADD AL,BL //в al результат POP EBX end; function BCDToInt64(const BCD: int64): int64; stdcall; assembler; asm PUSH EBX PUSH ECX PUSH EDI PUSH ESI //Сначала обработаем старшее двойное слово MOV ESI,DWord Ptr BCD[4] MOV EDI,ESI AND EDI,$0000000F MOV ECX,8-1 MOV EBX,10 @@1: SHR ESI,4 MOV EAX,ESI AND EAX,$0000000F MUL EBX ADD EDI,EAX MOV EAX,EBX SHL EBX,3 //*8 SHL EAX,1 //*2 ADD EBX,EAX //ebx = ebx * 10 LOOP @@1 PUSH EDI //Сохраним результат в стеке //Теперь обработаем младшее двойное слово MOV ESI,DWord Ptr BCD MOV EDI,ESI AND EDI,$0000000F MOV ECX,8-1 MOV EBX,10 @@2: SHR ESI,4 MOV EAX,ESI AND EAX,$0000000F MUL EBX ADD EDI,EAX MOV EAX,EBX SHL EBX,3 //*8 SHL EAX,1 //*2 ADD EBX,EAX //ebx = ebx * 10 LOOP @@2 //Извлечем из стека //результат обработки старшего двойного слова, POP EAX MOV EBX,100000000 MUL EBX //умножим его на 100000000 //и сложим с результатом обработки младшего двойного слова ADD EAX,EDI ADC EDX,0 //Результат получается в регистрах EDX:EAX POP ESI POP EDI POP ECX POP EBX end; function GetBit(const bt, nBit: Byte): Boolean; stdcall; assembler; asm PUSH EBX //делаем в eax маску XOR EAX,EAX MOVZX EBX,nBit BTS EAX,EBX //взводим в al бит nBit POP EBX AND AL,bt end; function SetBit(const bt, nBit: Byte): Byte; stdcall; assembler; asm PUSH EBX //делаем в eax маску XOR EAX,EAX MOVZX EBX,nBit BTS EAX,EBX //взводим в al бит nBit MOV BL,bt OR BL,AL MOV AL,BL POP EBX end; //меняет местами заданное количество байтов //если, напр., на входе массив (1,2,3,4,5), то на выходе будет (5,4,3,2,1) procedure SwapBytes(const pBt: Pointer; Count: Integer); stdcall; assembler; asm PUSH EDI PUSH ESI PUSHFD MOV ESI,pBt MOV EDI,ESI ADD EDI,Count DEC EDI CLD @Swap: LODSB XCHG AL,[EDI] MOV [ESI-1],AL DEC EDI CMP EDI,ESI JA @Swap POPFD POP ESI POP EDI end; procedure DWordToBcd(dw: DWord; BCDRes: Pointer; BCDResLen: DWord); var i: DWord; //i :Integer; rst: Byte; a: array[0..9] of Byte; begin if BCDResLen > 10 then BCDResLen := 10; FillChar(a, 10, 0); i := 0; repeat rst := dw mod 10; dw := dw div 10; a[i] := rst; rst := dw mod 10; dw := dw div 10; a[i] := a[i] or (rst shl 4); Inc(i); until (dw = 0) or (i = BCDResLen); Dec(BCDResLen); for i := 0 to BCDResLen do pByte(DWord(BCDRes) + BCDResLen - i)^ := a[i]; end; {$ifndef FPC} procedure AppProcessMessages; var Msg: TagMsg; begin if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then begin TranslateMessage(Msg); DispatchMessage(Msg); end; end; function IsThisWine: Boolean; var H: DWord; begin H := GetModuleHandle('ntdll.dll'); Result := Assigned(GetProcAddress(H, 'wine_get_version')); end; procedure Sleep2(const msec: DWord); var freq, Count, count2, delta: int64; begin if (not QueryPerformanceFrequency(freq)) or (not QueryPerformanceCounter(Count)) then begin Sleep(msec); Exit; end; delta := msec * freq div 1000; count2 := Count + delta; while count2 > Count do QueryPerformanceCounter(Count); end; {$endif FPC} {Function Utf8ToWin(s :String) :String; Const Utf2WinTable :Array [0..65, 0..1] of String = ((#208#144,#192), (#208#145,#193), (#208#146,#194), (#208#147,#195), (#208#148,#196), (#208#149,#197), (#208#129,#168), (#208#150,#198), (#208#151,#199), (#208#152,#200), (#208#153,#201), (#208#154,#202), (#208#155,#203), (#208#156,#204), (#208#157,#205), (#208#158,#206), (#208#159,#207), (#208#160,#208), (#208#161,#209), (#208#162,#210), (#208#163,#211), (#208#164,#212), (#208#165,#213), (#208#166,#214), (#208#167,#215), (#208#168,#216), (#208#169,#217), (#208#170,#218), (#208#171,#219), (#208#172,#220), (#208#173,#221), (#208#174,#222), (#208#175,#223), (#208#176,#224), (#208#177,#225), (#208#178,#226), (#208#179,#227), (#208#180,#228), (#208#181,#229), (#209#145,#184), (#208#182,#230), (#208#183,#231), (#208#184,#232), (#208#185,#233), (#208#186,#234), (#208#187,#235), (#208#188,#236), (#208#189,#237), (#208#190,#238), (#208#191,#239), (#209#128,#240), (#209#129,#241), (#209#130,#242), (#209#131,#243), (#209#132,#244), (#209#133,#245), (#209#134,#246), (#209#135,#247), (#209#136,#248), (#209#137,#249), (#209#138,#250), (#209#139,#251), (#209#140,#252), (#209#141,#253), (#209#142,#254), (#209#143,#255) ); Var i :Integer; Begin Result:=s; For i:=0 to 65 do If Pos(Utf2WinTable[i,0],Result)<>0 then Result:=StringReplace(Result,Utf2WinTable[i,0],Utf2WinTable[i,1],[rfReplaceAll]); end;} function Utf8ToWin(s: string): string; var stU: WideString; l: Integer; begin SetLength(stU, Length(s)); Utf8ToUnicode(pWideChar(stU), Length(s), PChar(s), Length(s)); l := WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR, @stU[1], -1, nil, 0, nil, nil); SetLength(Result, l - 1); if l <> 0 then WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR, @stU[1], -1, @Result[1], l - 1, nil, nil); end; procedure SaveXMLInit(var LogPath: string); var FI: TSearchRec; begin if not DirectoryExists(LogPath) then try if not ForceDirectories(LogPath) then begin LogPath := ''; Exit; end; except LogPath := ''; Exit; end; if LogPath[Length(LogPath)] <> '\' then LogPath := LogPath + '\'; if FindFirst(LogPath + '*.log', faAnyFile, FI) = 0 then begin repeat DeleteFile(LogPath + FI.Name); until FindNext(FI) <> 0; FindClose(FI); end; end; procedure SaveXML(const LogPath, stLog: string; var LogNum: Integer); var fLog: TextFile; begin if LogPath = '' then Exit; Inc(LogNum); AssignFile(fLog, LogPath + IntToHex(LogNum, 5) + '.log'); Rewrite(fLog); if IOResult <> 0 then Exit; Write(fLog, stLog); CloseFile(fLog); end; function ReadFileToString(fn: string): string; var fXML: file; begin AssignFile(fXML, fn); Reset(fXML, 1); SetLength(Result, FileSize(fXML)); BlockRead(fXML, Result[1], Length(Result)); CloseFile(fXML); end; procedure DeleteSpaces(var st: string); begin while Pos(' ', st) <> 0 do Delete(st, Pos(' ', st), 1); end; //возвращает число из строки, содержащей несколько чисел, разделенных между собой какими-либо символами //числа будут только положительные, т.е. знак '-' принимается за разделитель function GetDigit(const DigNum: Integer; const stDig: string; const DecYear: Boolean = True): Integer; var i, Pos1, Pos2: Integer; begin i := 0; Result := -1; Pos1 := 1; for Pos2 := 1 to Length(stDig) do if not (stDig[Pos2] in ['0'..'9']) then begin Inc(i); if i = DigNum then Break; Pos1 := Pos2 + 1; end; if Pos1 = Pos2 then Exit; if Pos2 = Length(stDig) then Inc(Pos2); i := StrToInt(Copy(stDig, Pos1, Pos2 - Pos1)); if DecYear and (i > 2000) then Dec(i, 2000); Result := i; end; function FlagPresented(const Mask: int64; const Flags: array of int64): Boolean; var j: Integer; begin Result := False; for j := 0 to High(Flags) do if Mask and Flags[j] <> 0 then begin Result := True; Exit; end; end; function AnsiTo866(const stAnsi: string): string; var j: Integer; begin SetLength(Result, Length(stAnsi)); for j := 1 to Length(stAnsi) do case byte(stAnsi[j]) of $A8: {Ё} Result[j] := char($F0); $B8: {ё} Result[j] := char($F1); $AA: {Є} Result[j] := char($F2); $BA: {є} Result[j] := char($F3); $AF: {Ї} Result[j] := char($F4); $BF: {ї} Result[j] := char($F5); $A1: {Ў} Result[j] := char($F6); $A2: {ў} Result[j] := char($F7); $B9: {№} Result[j] := char($FC); $C0..$EF: {А-п} Result[j] := char(byte(stAnsi[j]) - $40); $F0..$FF: {р-я} Result[j] := char(byte(stAnsi[j]) - $10); else Result[j] := stAnsi[j]; end; end; function CP866ToAnsi(const stAnsi: string): string; var j: Integer; begin SetLength(Result, Length(stAnsi)); for j := 1 to Length(stAnsi) do case byte(stAnsi[j]) of $F0: {Ё} Result[j] := char($A8); $F1: {ё} Result[j] := char($B8); $F2: {Є} Result[j] := char($AA); $F3: {є} Result[j] := char($BA); $F4: {Ї} Result[j] := char($AF); $F5: {ї} Result[j] := char($BF); $F6: {Ў} Result[j] := char($A1); $F7: {ў} Result[j] := char($A2); $FC: {№} Result[j] := char($B9); $80..$AF: {А-п} Result[j] := char(byte(stAnsi[j]) + $40); $E0..$EF: {р-я} Result[j] := char(byte(stAnsi[j]) + $10); else Result[j] := stAnsi[j]; end; end; end.
unit uSerasaConsts; interface const // Constantes do Header HEADER_COD_TRANS = 'RE01'; HEADER_COD_TRANS_CONTRATADA = 'RX21'; HEADER_COD_RELEASE = 'VERSAO-01.09'; HEADER_CHR_ENCERRAMENTO = 'X'; HEADER_MEIO_ACESSO_STRING = '1'; TAM_NOME = 68; TAM_DATA = 8; TAM_MES_ANO = 6; TAM_REG_NADA_CONSTA = 42; TAM_REG00 = 193; //TAM_REG04 = 101; TAM_REG08 = 109; TAM_REG04 = TAM_REG08; TAM_REG10 = 19; TAM_REG05 = TAM_REG10; TAM_REG14 = 72; TAM_REG18 = 42; TAM_REG22 = 75; TAM_REG26 = 55; TAM_REG30 = 83; TAM_REG32 = 181; TAM_REG34 = 43; TAM_REG36 = 129; TAM_REG40 = 42; TAM_REG44 = 137; TAM_REG46 = 42; TAM_REG48 = 135; TAM_REG52 = 206; TAM_REG54 = 42; TAM_REG90 = 45; COD_FINALIZACAO = '99'; MSG_ERRO_TAMANHO_INVALIDO = 'Erro: Registro %S com tamanho inválido'; MSG_ERRO_RETORNO90 = 'Erro: "%S" Mensagem: "%S"'; MSG_ERRO_RETORNO_INVALIDO = 'Tipo de retorno inválido "%S"'; TXT_NAO_INFORMADO = 'Não Informado'; implementation end.
{ *********************************************************************** } { } { GUI Hangman } { Version 1.0 - First release of program } { Last Revised: 27nd of July 2004 } { Copyright (c) 2004 Chris Alley } { } { *********************************************************************** } unit UNewPlayer; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TNewPlayerDialog = class(TForm) FirstNameLabeledEdit: TLabeledEdit; LastNameLabeledEdit: TLabeledEdit; OKButton: TButton; Cancel: TButton; WelcomeLabel: TLabel; procedure FirstNameLabeledEditChange(Sender: TObject); procedure LastNameLabeledEditChange(Sender: TObject); procedure LastNameLabeledEditEnter(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} procedure TNewPlayerDialog.FirstNameLabeledEditChange(Sender: TObject); begin Self.LastNameLabeledEditChange(Self); end; procedure TNewPlayerDialog.LastNameLabeledEditChange(Sender: TObject); { Disables the New Player form's OK Button unless the strings in FirstNameLabeledEdit and LastNameLabeledEdit consist of only letters and are not empty. } var Count: integer; begin if (Self.FirstNameLabeledEdit.Text = '') or (Self.LastNameLabeledEdit.Text = '') then Self.OKButton.Enabled := False else begin Self.OKButton.Enabled := True; for Count := 1 to length(Self.FirstNameLabeledEdit.Text) do begin if not(Upcase(Self.FirstNameLabeledEdit.Text[Count]) in ['A'..'Z']) then Self.OKButton.Enabled := False; end; for Count := 1 to length(Self.LastNameLabeledEdit.Text) do begin if not(Upcase(Self.LastNameLabeledEdit.Text[Count]) in ['A'..'Z']) then Self.OKButton.Enabled := False; end; end; end; procedure TNewPlayerDialog.LastNameLabeledEditEnter(Sender: TObject); { Makes the OK button the default component for the form, after Enter is pushed on the last Edit box. } begin Self.OKButton.Default := True; end; end.
unit Classes.Dataset.Helpers; interface uses Data.DB , Spring , RDQuery ; type TFieldsValueReader = record private FQuery: TRDQuery; public function FieldAsStr(const AFieldName: string): string; function FieldAsNullableStr(const AFieldName: string): Nullable<String>; function FieldAsInt(const AFieldName: string): Integer; function FieldAsNullableInt(const AFieldName: string): TNullableInteger; function FieldAsFloat(const AFieldName: string): Double; function FieldAsDateTime(const AFieldName: string): TDateTime; function FieldAsNullableDateTime(const AFieldName: string): TNullableDateTime; property Query: TRDQuery read FQuery write FQuery; end; implementation {======================================================================================================================} function TFieldsValueReader.FieldAsStr(const AFieldName: string): string; {======================================================================================================================} begin Result := FQuery.FieldByName(AFieldName).AsString; end; {======================================================================================================================} function TFieldsValueReader.FieldAsNullableStr(const AFieldName: string): Nullable<String>; {======================================================================================================================} begin Result := nil; if (not FQuery.FieldByName(AFieldName).IsNull) then Result := FieldAsStr(AFieldName); end; {======================================================================================================================} function TFieldsValueReader.FieldAsInt(const AFieldName: string): Integer; {======================================================================================================================} begin Result := FQuery.FieldByName(AFieldName).AsInteger; end; {======================================================================================================================} function TFieldsValueReader.FieldAsNullableInt(const AFieldName: string): TNullableInteger; {======================================================================================================================} begin Result := nil; if (not FQuery.FieldByName(AFieldName).IsNull) then Result := FQuery.FieldByName(AFieldName).AsInteger; end; {======================================================================================================================} function TFieldsValueReader.FieldAsFloat(const AFieldName: string): Double; {======================================================================================================================} begin Result := FQuery.FieldByName(AFieldName).AsFloat; end; {======================================================================================================================} function TFieldsValueReader.FieldAsDateTime(const AFieldName: string): TDateTime; {======================================================================================================================} begin Result := FQuery.FieldByName(AFieldName).AsDateTime; end; {======================================================================================================================} function TFieldsValueReader.FieldAsNullableDateTime(const AFieldName: string): TNullableDateTime; {======================================================================================================================} begin Result := nil; if (not FQuery.FieldByName(AFieldName).IsNull) then Result := FQuery.FieldByName(AFieldName).AsDateTime; end; end.
unit Grijjy.FBSDK; { Cross platform abstraction for Facebook SDKs and libraries } interface uses Grijjy.FBSDK.Types, {$IF Defined(IOS)} Grijjy.FBSDK.iOS, {$ELSEIF Defined(ANDROID)} Grijjy.FBSDK.Android, {$ELSE} { Unsupported platform } {$ENDIF} System.Messaging, System.SysUtils; type TgoFacebook = class private procedure FacebookLoginResultMessageListener(const Sender: TObject; const M: TMessage); procedure FacebookGraphResultMessageListener(const Sender: TObject; const M: TMessage); private function GetAccessToken: String; public constructor Create; destructor Destroy; override; public procedure Login; procedure GetSelf; public property AccessToken: String read GetAccessToken; end; implementation uses Grijjy.Bson, Grijjy.Bson.IO, Grijjy.Social; { TgoFacebook } constructor TgoFacebook.Create; begin TMessageManager.DefaultManager.SubscribeToMessage(TFacebookLoginResultMessage, FacebookLoginResultMessageListener); TMessageManager.DefaultManager.SubscribeToMessage(TFacebookGraphResultMessage, FacebookGraphResultMessageListener); end; destructor TgoFacebook.Destroy; begin TMessageManager.DefaultManager.Unsubscribe(TFacebookLoginResultMessage, FacebookLoginResultMessageListener); TMessageManager.DefaultManager.Unsubscribe(TFacebookGraphResultMessage, FacebookGraphResultMessageListener); inherited; end; procedure TgoFacebook.FacebookLoginResultMessageListener(const Sender: TObject; const M: TMessage); var FacebookLoginResultMessage: TFacebookLoginResultMessage; SocialLogin: TgoSocialLogin; SocialLoginMessage: TgoSocialLoginMessage; begin FacebookLoginResultMessage := M as TFacebookLoginResultMessage; { social login message } SocialLogin.Result := FacebookLoginResultMessage.Value.Result; SocialLogin.Network := TgoSocialNetwork.Facebook; SocialLogin.Id := FacebookLoginResultMessage.Value.UserId; SocialLogin.AccessToken := FacebookLoginResultMessage.Value.Token; SocialLoginMessage := TgoSocialLoginMessage.Create(SocialLogin); TMessageManager.DefaultManager.SendMessage(Self, SocialLoginMessage); end; procedure TgoFacebook.FacebookGraphResultMessageListener(const Sender: TObject; const M: TMessage); var FacebookGraphResultMessage: TFacebookGraphResultMessage; begin FacebookGraphResultMessage := M as TFacebookGraphResultMessage; end; procedure TgoFacebook.Login; var SocialLogin: TgoSocialLogin; SocialLoginMessage: TgoSocialLoginMessage; begin {$IF Defined(IOS) or Defined(ANDROID)} if FacebookSDK.CurrentAccessToken = '' then FacebookSDK.LogInWithReadPermissions(['public_profile', 'user_friends', 'email']) else begin { social login message } SocialLogin.Result := True; SocialLogin.Network := TgoSocialNetwork.Facebook; SocialLogin.Id := FacebookSDK.CurrentUserId; SocialLogin.AccessToken := FacebookSDK.CurrentAccessToken; SocialLoginMessage := TgoSocialLoginMessage.Create(SocialLogin); TMessageManager.DefaultManager.SendMessage(Self, SocialLoginMessage); end; {$ELSE} { Facebook (currently) unsupported for this platform } SocialLogin.Result := False; SocialLogin.Network := TgoSocialNetwork.Facebook; SocialLogin.Username := ''; SocialLogin.Password := ''; SocialLoginMessage := TgoSocialLoginMessage.Create(SocialLogin); TMessageManager.DefaultManager.SendMessage(Self, SocialLoginMessage); {$ENDIF} end; function TgoFacebook.GetAccessToken: String; begin {$IF Defined(IOS) or Defined(ANDROID)} Result := FacebookSDK.CurrentAccessToken; {$ELSE} Result := ''; {$ENDIF} end; procedure TgoFacebook.GetSelf; begin {$IF Defined(IOS) or Defined(ANDROID)} FacebookSDK.GraphPath('me?fields=name,email'); {$ELSE} {$ENDIF} end; end.
unit MainForm; {$mode delphi} interface uses Classes, Interfaces, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons, StdCtrls, World, MyWorld; type TMainForm = class(TForm) PaintBox: TPaintBox; ButtonStart: TButton; ButtonStop: TButton; ButtonClose: TBitBtn; procedure ButtonStartClick(Sender: TObject); procedure ButtonStopClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PaintBoxPaint(Sender: TObject); procedure PaintBoxMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private world: TWorld; end; var FMain: TMainForm; implementation {$R *.lfm} procedure TMainForm.FormCreate; begin self.world := TMyWorld.Create; self.world.LinkPaintBox(self.PaintBox); self.ButtonStop.Enabled := false; end; procedure TMainForm.PaintBoxPaint; begin self.world.Paint; self.world.PaintEntities; with self.PaintBox.Canvas do begin Brush.Color := clBlack; Pen.Width := 1; FrameRect(ClipRect); end; end; procedure TMainForm.PaintBoxMouseUp; begin self.world.Click(X / self.PaintBox.Width, Y / self.PaintBox.Height); self.PaintBoxPaint(Sender); end; procedure TMainForm.ButtonStartClick; begin self.world.Start; self.ButtonStart.Enabled := false; self.ButtonStop.Enabled := true; end; procedure TMainForm.ButtonStopClick; begin self.world.Terminate; self.world := TMyWorld.Create; self.world.LinkPaintBox(self.PaintBox); self.ButtonStart.Enabled := true; self.ButtonStop.Enabled := false; end; end.
unit ibSHDesignIntf; interface uses SysUtils, Classes, Graphics, SHDesignIntf, ibSHDriverIntf; type { Common } IibSHDummy = interface(ISHDummy) ['{715D9CE4-9B25-4F5F-AFFE-835DD9D9AE47}'] end; IibSHComponent = interface(ISHComponent) ['{2155CAD7-4EB7-4DC6-9B8D-56F502DAFE31}'] end; IibSHDomain = interface; IibSHDDLGenerator = interface(ISHDDLGenerator) ['{3E3E1692-B175-4822-8FB2-E6E53E161F91}'] function GetTerminator: string; procedure SetTerminator(Value: string); function GetUseFakeValues: Boolean; procedure SetUseFakeValues(Value: Boolean); procedure SetBasedOnDomain(ADRVQuery: IibSHDRVQuery; ADomain: IibSHDomain; const ACaption: string); property Terminator: string read GetTerminator write SetTerminator; property UseFakeValues: Boolean read GetUseFakeValues write SetUseFakeValues; end; IibBTTemplates = interface ['{89CB07B7-9B1D-4CA0-94A0-C941FDF52E11}'] function GetCurrentTemplateFile:string; procedure SetCurrentTemplateFile(const FileName:string); property CurrentTemplateFile:string read GetCurrentTemplateFile write SetCurrentTemplateFile; end; IibSHSQLGenerator = interface ['{419BB04F-3A6D-4D5D-AD14-071EDCF55540}'] procedure SetAutoGenerateSQLsParams(AComponent: TSHComponent); procedure GenerateSQLs(AComponent: TSHComponent); end; IibSHDDLParser = interface(ISHDDLParser) ['{C180D55D-58EE-4F39-816F-796AC618CFD8}'] function GetSQLParserNotification: IibSHDRVSQLParserNotification; procedure SetSQLParserNotification(Value: IibSHDRVSQLParserNotification); property SQLParserNotification: IibSHDRVSQLParserNotification read GetSQLParserNotification write SetSQLParserNotification; end; IibSHDDLCompiler = interface(ISHDDLCompiler) ['{1C859878-AB4D-48B9-AD83-21600031CF45}'] end; IibSHServer = interface(ISHServer) ['{1A1FF139-B6AB-473E-8063-0E3608614D32}'] function GetDRVService: IibSHDRVService; function GetHost: string; procedure SetHost(Value: string); function GetAlias: string; procedure SetAlias(Value: string); function GetVersion: string; procedure SetVersion(Value: string); function SetLongMetadataNames: Boolean; procedure GetLongMetadataNames(Value: Boolean); function GetClientLibrary: string; procedure SetClientLibrary(Value: string); function GetProtocol: string; procedure SetProtocol(Value: string); function GetPort: string; procedure SetPort(Value: string); function GetSecurityDatabase: string; procedure SetSecurityDatabase(Value: string); function GetUserName: string; procedure SetUserName(Value: string); function GetPassword: string; procedure SetPassword(Value: string); function GetRole: string; procedure SetRole(Value: string); function GetLoginPrompt: Boolean; procedure SetLoginPrompt(Value: Boolean); function GetDescription: string; procedure SetDescription(Value: string); function GetDataRootDirectory: string; function DRVNormalize(const DriverIID: TGUID): TGUID; function PrepareDRVService: Boolean; //IB2007 function GetInstanceName:string; procedure SetInstanceName(const Value:string); property DRVService: IibSHDRVService read GetDRVService; property Host: string read GetHost write SetHost; property Alias: string read GetAlias write SetAlias; property Version: string read GetVersion write SetVersion; property LongMetadataNames: Boolean read SetLongMetadataNames write GetLongMetadataNames; property ClientLibrary: string read GetClientLibrary write SetClientLibrary; property Protocol: string read GetProtocol write SetProtocol; property Port: string read GetPort write SetPort; property SecurityDatabase: string read GetSecurityDatabase write SetSecurityDatabase; property UserName: string read GetUserName write SetUserName; property Password: string read GetPassword write SetPassword; property Role: string read GetRole write SetRole; property LoginPrompt: Boolean read GetLoginPrompt write SetLoginPrompt; property Description: string read GetDescription write SetDescription; property DataRootDirectory: string read GetDataRootDirectory; property InstanceName:string read GetInstanceName write SetInstanceName; end; IibSHDatabaseAliasOptions = interface; IibSHDatabase = interface(ISHDatabase) ['{EDFEA11D-6E23-4835-A350-3DFB5C55BBD9}'] function GetBTCLServer: IibSHServer; function GetDRVDatabase: IibSHDRVDatabase; function GetDRVQuery: IibSHDRVQuery; function GetServer: string; procedure SetServer(Value: string); function GetDatabase: string; procedure SetDatabase(Value: string); function GetAlias: string; procedure SetAlias(Value: string); function GetPageSize: string; procedure SetPageSize(Value: string); function GetCharset: string; procedure SetCharset(Value: string); function GetSQLDialect: Integer; procedure SetSQLDialect(Value: Integer); function GetCapitalizeNames: Boolean; procedure SetCapitalizeNames(Value: Boolean); function GetAdditionalConnectParams: TStrings; procedure SetAdditionalConnectParams(Value: TStrings); function GetUserName: string; procedure SetUserName(Value: string); function GetPassword: string; procedure SetPassword(Value: string); function GetRole: string; procedure SetRole(Value: string); function GetLoginPrompt: Boolean; procedure SetLoginPrompt(Value: Boolean); function GetDescription: string; procedure SetDescription(Value: string); function GetStillConnect: Boolean; procedure SetStillConnect(Value: Boolean); function GetDatabaseAliasOptions: IibSHDatabaseAliasOptions; function GetExistsPrecision: Boolean; function GetDBCharset: string; function GetWasLostconnect: Boolean; function GetDataRootDirectory: string; function GetExistsProcParamDomains: Boolean; procedure CreateDatabase; procedure DropDatabase; function ExistsInDatabase(const AClassIID: TGUID; const ACaption: string): Boolean; function ChangeNameList(const AClassIID: TGUID; const ACaption: string; Operation: TOperation): Boolean; property BTCLServer: IibSHServer read GetBTCLServer; property DRVDatabase: IibSHDRVDatabase read GetDRVDatabase; property DRVQuery: IibSHDRVQuery read GetDRVQuery; property Server: string read GetServer write SetServer; property Database: string read GetDatabase write SetDatabase; property Alias: string read GetAlias write SetAlias; property PageSize: string read GetPageSize write SetPageSize; property Charset: string read GetCharset write SetCharset; property SQLDialect: Integer read GetSQLDialect write SetSQLDialect; property CapitalizeNames: Boolean read GetCapitalizeNames write SetCapitalizeNames; property AdditionalConnectParams: TStrings read GetAdditionalConnectParams write SetAdditionalConnectParams; property UserName: string read GetUserName write SetUserName; property Password: string read GetPassword write SetPassword; property Role: string read GetRole write SetRole; property LoginPrompt: Boolean read GetLoginPrompt write SetLoginPrompt; property Description: string read GetDescription write SetDescription; property StillConnect: Boolean read GetStillConnect write SetStillConnect; property DatabaseAliasOptions: IibSHDatabaseAliasOptions read GetDatabaseAliasOptions; property ExistsPrecision: Boolean read GetExistsPrecision; property DBCharset: string read GetDBCharset; property WasLostConnect: Boolean read GetWasLostConnect; property DataRootDirectory: string read GetDataRootDirectory; property ExistsProcParamDomains:boolean read GetExistsProcParamDomains; end; IibBTDataBaseExt= interface ['{1461C2F1-42CA-4DFF-99C0-E9E92C509036}'] //Buzz procedure GetObjectsHaveComment(ClassObject:TGUID;Results:TStrings); end; IibSHCodeNormalizer = interface ['{B9814849-1E21-4E41-A1ED-190425A645D4}'] //функция принимает название объекта в виде, в котором оно хранится в системных таблицах БД //и преобразовывает к виду, в котором должен его написать пользователь в редакторе function SourceDDLToMetadataName(const AObjectName: string): string; //функция принимает название объекта в виде, в котором оно хранится в системных таблицах БД //и преобразовывает к виду, в котором должен его написать пользователь в редакторе //(и в котором оно хранится в исходных DDL текстах объектов) function MetadataNameToSourceDDL(const ADatabase: IibSHDatabase; const AObjectName: string): string; function MetadataNameToSourceDDLCase(const ADatabase: IibSHDatabase; const AObjectName: string): string; //функция принимает название объекта таким, как его написал пользователь //и приводит его к виду, в котором оно хранится в системных таблицах БД //бывшая InputValueToCaption function InputValueToMetadata(const ADatabase: IibSHDatabase; const AObjectName: string): string; function InputValueToMetadataCheck(const ADatabase: IibSHDatabase; var AObjectName: string): Boolean; //функция преобразует регистр ключевых слов, использующихся для //формирования DDL объектов function CaseSQLKeyword(const AKeywordsString: string): string; // проверка на наличие слова, как ключевого function IsKeyword(const ADatabase: IibSHDatabase; const AKeyword: string): Boolean; end; IibSHDBObjectFactory = interface(ISHComponentFactory) ['{F8EB73CA-878D-4675-889A-5F4633EF3FC8}'] // // Отложенное разрушение и создание нового компонента (Create/Recreate и Drop в IDE) // procedure SuspendedDestroyCreateComponent(OldComponent: TSHComponent; const NewOwnerIID, NewClassIID: TGUID; const NewCaption: string); end; { DBObjects } IibSHDBObject = interface(ISHDBComponent) ['{3983FDB0-20BA-4E66-836D-9AE55E827539}'] function GetBTCLDatabase: IibSHDatabase; function GetOwnerName: string; procedure SetOwnerName(Value: string); function GetParams: TStrings; function GetReturns: TStrings; function GetBodyText: TStrings; function GetBLR: TStrings; function GetFields: TStrings; function GetConstraints: TStrings; function GetIndices: TStrings; function GetTriggers: TStrings; function GetGrants: TStrings; function GetTRParams: TStrings; function GetDescriptionText: string; function GetDescriptionStatement(AsParam: Boolean): string; procedure SetDescription; procedure FormGrants; property BTCLDatabase: IibSHDatabase read GetBTCLDatabase; property OwnerName: string read GetOwnerName write SetOwnerName; property Params: TStrings read GetParams; property Returns: TStrings read GetReturns; property BodyText: TStrings read GetBodyText; property BLR: TStrings read GetBLR; property Fields: TStrings read GetFields; property Constraints: TStrings read GetConstraints; property Indices: TStrings read GetIndices; property Triggers: TStrings read GetTriggers; property Grants: TStrings read GetGrants; property TRParams: TStrings read GetTRParams; end; IibSHDomain = interface(IibSHDBObject) ['{EC361E00-8CA5-4652-8D82-F0C91CDE8E8F}'] function GetFieldTypeID: Integer; procedure SetFieldTypeID(Value: Integer); function GetSubTypeID: Integer; procedure SetSubTypeID(Value: Integer); function GetCharsetID: Integer; procedure SetCharsetID(Value: Integer); function GetCollateID: Integer; procedure SetCollateID(Value: Integer); function GetArrayDimID: Integer; procedure SetArrayDimID(Value: Integer); function GetDataType: string; procedure SetDataType(Value: string); function GetDataTypeExt: string; procedure SetDataTypeExt(Value: string); function GetDataTypeField: string; procedure SetDataTypeField(Value: string); function GetDataTypeFieldExt: string; procedure SetDataTypeFieldExt(Value: string); function GetLength: Integer; procedure SetLength(Value: Integer); function GetPrecision: Integer; procedure SetPrecision(Value: Integer); function GetScale: Integer; procedure SetScale(Value: Integer); function GetNotNull: Boolean; procedure SetNotNull(Value: Boolean); function GetNullType: string; procedure SetNullType(Value: string); function GetSubType: string; procedure SetSubType(Value: string); function GetSegmentSize: Integer; procedure SetSegmentSize(Value: Integer); function GetCharset: string; procedure SetCharset(Value: string); function GetCollate: string; procedure SetCollate(Value: string); function GetDefaultExpression: TStrings; procedure SetDefaultExpression(Value: TStrings); function GetCheckConstraint: TStrings; procedure SetCheckConstraint(Value: TStrings); function GetArrayDim: string; procedure SetArrayDim(Value: string); // For Fields function GetDomain: string; procedure SetDomain(Value: string); function GetTableName: string; procedure SetTableName(Value: string); function GetFieldDefault: TStrings; procedure SetFieldDefault(Value: TStrings); function GetFieldNotNull: Boolean; procedure SetFieldNotNull(Value: Boolean); function GetFieldNullType: string; procedure SetFieldNullType(Value: string); function GetFieldCollateID: Integer; procedure SetFieldCollateID(Value: Integer); function GetFieldCollate: string; procedure SetFieldCollate(Value: string); function GetComputedSource: TStrings; procedure SetComputedSource(Value: TStrings); // Other (for ibSHDDLGenerator) function GetUseCustomValues: Boolean; procedure SetUseCustomValues(Value: Boolean); function GetNameWasChanged: Boolean; procedure SetNameWasChanged(Value: Boolean); function GetDataTypeWasChanged: Boolean; procedure SetDataTypeWasChanged(Value: Boolean); function GetDefaultWasChanged: Boolean; procedure SetDefaultWasChanged(Value: Boolean); function GetCheckWasChanged: Boolean; procedure SetCheckWasChanged(Value: Boolean); function GetNullTypeWasChanged: Boolean; procedure SetNullTypeWasChanged(Value: Boolean); function GetCollateWasChanged: Boolean; procedure SetCollateWasChanged(Value: Boolean); property FieldTypeID: Integer read GetFieldTypeID write SetFieldTypeID; property SubTypeID: Integer read GetSubTypeID write SetSubTypeID; property CharsetID: Integer read GetCharsetID write SetCharsetID; property CollateID: Integer read GetCollateID write SetCollateID; property ArrayDimID: Integer read GetArrayDimID write SetArrayDimID; property DataType: string read GetDataType write SetDataType; property DataTypeExt: string read GetDataTypeExt write SetDataTypeExt; property DataTypeField: string read GetDataTypeField write SetDataTypeField; property DataTypeFieldExt: string read GetDataTypeFieldExt write SetDataTypeFieldExt; {decode domains :)} property Length: Integer read GetLength write SetLength; property Precision: Integer read GetPrecision write SetPrecision; property Scale: Integer read GetScale write SetScale; property NotNull: Boolean read GetNotNull write SetNotNull; property NullType: string read GetNullType write SetNullType; property SubType: string read GetSubType write SetSubType; property SegmentSize: Integer read GetSegmentSize write SetSegmentSize; property Charset: string read GetCharset write SetCharset; property Collate: string read GetCollate write SetCollate; property DefaultExpression: TStrings read GetDefaultExpression write SetDefaultExpression; property CheckConstraint: TStrings read GetCheckConstraint write SetCheckConstraint; property ArrayDim: string read GetArrayDim write SetArrayDim; // For Fields property Domain: string read GetDomain write SetDomain; property TableName: string read GetTableName write SetTableName; property FieldDefault: TStrings read GetFieldDefault write SetFieldDefault; property FieldNotNull: Boolean read GetFieldNotNull write SetFieldNotNull; property FieldNullType: string read GetFieldNullType write SetFieldNullType; property FieldCollateID: Integer read GetFieldCollateID write SetFieldCollateID; property FieldCollate: string read GetFieldCollate write SetFieldCollate; property ComputedSource: TStrings read GetComputedSource write SetComputedSource; // Other (for ibSHDDLGenerator) property UseCustomValues: Boolean read GetUseCustomValues write SetUseCustomValues; property NameWasChanged: Boolean read GetNameWasChanged write SetNameWasChanged; property DataTypeWasChanged: Boolean read GetDataTypeWasChanged write SetDataTypeWasChanged; property DefaultWasChanged: Boolean read GetDefaultWasChanged write SetDefaultWasChanged; property CheckWasChanged: Boolean read GetCheckWasChanged write SetCheckWasChanged; property NullTypeWasChanged: Boolean read GetNullTypeWasChanged write SetNullTypeWasChanged; property CollateWasChanged: Boolean read GetCollateWasChanged write SetCollateWasChanged; end; IibSHSystemDomain = interface(IibSHDomain) ['{5DCB98BF-E848-447A-A10E-92F1CE2DDD0E}'] end; IibSHSystemGeneratedDomain = interface(IibSHDomain) ['{7A01A180-215D-4479-B36C-52F5DE7861B2}'] end; IibSHField = interface(IibSHDomain) ['{F347B4BE-4902-4554-9FF5-0D635CD70724}'] end; IibSHConstraint = interface(IibSHDBObject) ['{903FA616-0C7A-4DE5-A4F9-720F21AA6547}'] function GetConstraintType: string; procedure SetConstraintType(Value: string); function GetTableName: string; procedure SetTableName(Value: string); function GetReferenceTable: string; procedure SetReferenceTable(Value: string); function GetReferenceFields: TStrings; procedure SetReferenceFields(Value: TStrings); function GetOnUpdateRule: string; procedure SetOnUpdateRule(Value: string); function GetOnDeleteRule: string; procedure SetOnDeleteRule(Value: string); function GetIndexName: string; procedure SetIndexName(Value: string); function GetIndexSorting: string; procedure SetIndexSorting(Value: string); function GetCheckSource: TStrings; procedure SetCheckSource(Value: TStrings); property ConstraintType: string read GetConstraintType write SetConstraintType; property TableName: string read GetTableName write SetTableName; property ReferenceTable: string read GetReferenceTable write SetReferenceTable; property ReferenceFields: TStrings read GetReferenceFields write SetReferenceFields; property OnUpdateRule: string read GetOnUpdateRule write SetOnUpdateRule; property OnDeleteRule: string read GetOnDeleteRule write SetOnDeleteRule; property IndexName: string read GetIndexName write SetIndexName; property IndexSorting: string read GetIndexSorting write SetIndexSorting; property CheckSource: TStrings read GetCheckSource write SetCheckSource; end; IibSHSystemGeneratedConstraint = interface(IibSHConstraint) ['{A07F035A-9471-48D7-9E13-2DD0EFAEBDA8}'] end; IibSHIndex = interface(IibSHDBObject) ['{C4C5A61B-A51E-4F80-A4DA-F7BCE4B4615F}'] function GetIndexTypeID: Integer; procedure SetIndexTypeID(Value: Integer); function GetSortingID: Integer; procedure SetSortingID(Value: Integer); function GetStatusID: Integer; procedure SetStatusID(Value: Integer); function GetIndexType: string; procedure SetIndexType(Value: string); function GetSorting: string; procedure SetSorting(Value: string); function GetTableName: string; procedure SetTableName(Value: string); function GetExpression: TStrings; procedure SetExpression(Value: TStrings); function GetStatus: string; procedure SetStatus(Value: string); function GetStatistics: string; procedure SetStatistics(Value: string); procedure RecountStatistics; procedure SetIsConstraintIndex(const Value:boolean); function GetIsConstraintIndex:boolean; property IndexTypeID: Integer read GetIndexTypeID write SetIndexTypeID; property SortingID: Integer read GetSortingID write SetSortingID; property StatusID: Integer read GetStatusID write SetStatusID; property IndexType: string read GetIndexType write SetIndexType; property Sorting: string read GetSorting write SetSorting; property TableName: string read GetTableName write SetTableName; property Expression: TStrings read GetExpression write SetExpression; property Status: string read GetStatus write SetStatus; property Statistics: string read GetStatistics write SetStatistics; property IsConstraintIndex:boolean read GetIsConstraintIndex write SetIsConstraintIndex; end; IibSHTrigger = interface; IibSHTable = interface(IibSHDBObject) ['{E811EC57-F0EC-45AB-8BFA-58028E875FCA}'] function GetDecodeDomains: Boolean; procedure SetDecodeDomains(Value: Boolean); function GetWithoutComputed: Boolean; procedure SetWithoutComputed(Value: Boolean); function GetRecordCountFrmt: string; function GetChangeCountFrmt: string; function GetExternalFile: string; procedure SetExternalFile(const Value: string); function GetField(Index: Integer): IibSHField; function GetConstraint(Index: Integer): IibSHConstraint; function GetIndex(Index: Integer): IibSHIndex; function GetTrigger(Index: Integer): IibSHTrigger; procedure SetRecordCount; procedure SetChangeCount; property DecodeDomains: Boolean read GetDecodeDomains write SetDecodeDomains; property WithoutComputed: Boolean read GetWithoutComputed write SetWithoutComputed; property RecordCountFrmt: string read GetRecordCountFrmt; property ChangeCountFrmt: string read GetChangeCountFrmt; property ExternalFile : string read GetExternalFile; end; IibSHSystemTable = interface(IibSHTable) ['{5F94ACEF-37BD-48B2-B762-1FBA420F1184}'] end; IibSHSystemTableTmp = interface(IibSHTable) ['{9F487B77-EABA-4D51-AEF6-53EDC4C5D33F}'] end; IibSHView = interface(IibSHDBObject) ['{B577D723-A56C-41D5-B00C-CCF0309EA763}'] function GetField(Index: Integer): IibSHField; function GetTrigger(Index: Integer): IibSHTrigger; function GetRecordCountFrmt: string; procedure SetRecordCount; property RecordCountFrmt: string read GetRecordCountFrmt; end; IibSHProcParam = interface(IibSHDomain) ['{67C3D531-0C2A-4475-BFC9-B6CD7E3C18D2}'] end; IibSHProcedure = interface(IibSHDBObject) ['{2769981B-AB6D-4F38-87AC-7C414166C212}'] function GetCanExecute: Boolean; function GetParamsExt: TStrings; function GetReturnsExt: TStrings; function GetHeaderDDL: TStrings; function GetParam(Index: Integer): IibSHProcParam; function GetReturn(Index: Integer): IibSHProcParam; procedure Execute; property CanExecute: Boolean read GetCanExecute; property ParamsExt: TStrings read GetParamsExt; property ReturnsExt: TStrings read GetReturnsExt; property HeaderDDL: TStrings read GetHeaderDDL; end; IibSHTrigger = interface(IibSHDBObject) ['{CA484F4C-1E7D-4909-8808-C795F20769E7}'] function GetTableName: string; procedure SetTableName(Value: string); function GetStatus: string; procedure SetStatus(Value: string); function GetTypePrefix: string; procedure SetTypePrefix(Value: string); function GetTypeSuffix: string; procedure SetTypeSuffix(Value: string); function GetPosition: Integer; procedure SetPosition(Value: Integer); property TableName: string read GetTableName write SetTableName; property Status: string read GetStatus write SetStatus; property TypePrefix: string read GetTypePrefix write SetTypePrefix; property TypeSuffix: string read GetTypeSuffix write SetTypeSuffix; property Position: Integer read GetPosition write SetPosition; end; IibSHSystemGeneratedTrigger = interface(IibSHTrigger) ['{7527B15D-14C5-422B-9356-18CD3AB48291}'] end; IibSHGenerator = interface(IibSHDBObject) ['{541922B1-AE56-4C07-AF09-A477875C29CB}'] function GetShowSetClause: Boolean; procedure SetShowSetClause(Value: Boolean); function GetValue: Integer; procedure SetValue(Value: Integer); property ShowSetClause: Boolean read GetShowSetClause write SetShowSetClause; property Value: Integer read GetValue write SetValue; end; IibSHException = interface(IibSHDBObject) ['{F66EAE2B-24BD-4FDE-996B-8A2AC3F14D9D}'] function GetText: string; procedure SetText(Value: string); function GetNumber: Integer; procedure SetNumber(Value: Integer); property Text: string read GetText write SetText; property Number: Integer read GetNumber write SetNumber; end; IibSHFuncParam = interface(IibSHDomain) ['{D433EFA2-38AB-44CD-A57D-836FADBC86A4}'] end; IibSHFunction = interface(IibSHDBObject) ['{EFF0E79D-6D87-491F-8594-F0D706BBE819}'] function GetEntryPoint: string; procedure SetEntryPoint(Value: string); function GetModuleName: string; procedure SetModuleName(Value: string); function GetReturnsArgument: Integer; procedure SetReturnsArgument(Value: Integer); function GetParam(Index: Integer): IibSHFuncParam; property EntryPoint: string read GetEntryPoint write SetEntryPoint; property ModuleName: string read GetModuleName write SetModuleName; property ReturnsArgument: Integer read GetReturnsArgument write SetReturnsArgument; end; IibSHFilter = interface(IibSHDBObject) ['{0A2D14C5-E4A9-4990-892B-ECA8E2D27C3A}'] function GetInputType: Integer; procedure SetInputType(Value: Integer); function GetOutputType: Integer; procedure SetOutputType(Value: Integer); function GetEntryPoint: string; procedure SetEntryPoint(Value: string); function GetModuleName: string; procedure SetModuleName(Value: string); property InputType: Integer read GetInputType write SetInputType; property OutputType: Integer read GetOutputType write SetOutputType; property EntryPoint: string read GetEntryPoint write SetEntryPoint; property ModuleName: string read GetModuleName write SetModuleName; end; IibSHRole = interface(IibSHDBObject) ['{600ABCE2-E93A-459F-A7AB-E8F081C9D6BE}'] end; IibSHShadow = interface(IibSHDBObject) ['{DF446552-BA17-4C01-A267-F1FD846078DD}'] function GetShadowMode: string; procedure SetShadowMode(Value: string); function GetShadowType: string; procedure SetShadowType(Value: string); function GetFileName: string; procedure SetFileName(Value: string); function GetSecondaryFiles: string; procedure SetSecondaryFiles(Value: string); property ShadowMode: string read GetShadowMode write SetShadowMode; property ShadowType: string read GetShadowType write SetShadowType; property FileName: string read GetFileName write SetFileName; property SecondaryFiles: string read GetSecondaryFiles write SetSecondaryFiles; end; { Tools } IibSHTool = interface(IibSHComponent) ['{CEF3550A-CF00-458B-A163-A6B9EBB68073}'] function GetBTCLServer: IibSHServer; function GetBTCLDatabase: IibSHDatabase; property BTCLServer: IibSHServer read GetBTCLServer; property BTCLDatabase: IibSHDatabase read GetBTCLDatabase; end; IibSHStatistics = interface ['{09520F3B-32D2-4D4B-BA26-E79745B08B4F}'] function GetDatabase: IibSHDatabase; procedure SetDatabase(const Value: IibSHDatabase); function GetDRVStatistics: IibSHDRVStatistics; function GetDRVTimeStatistics: IibSHDRVExecTimeStatistics; procedure SetDRVTimeStatistics(const Value: IibSHDRVExecTimeStatistics); function TableStatisticsStr(AIncludeSystemTables: Boolean): string; function ExecuteTimeStatisticsStr: string; procedure StartCollection; procedure CalculateStatistics; property Database: IibSHDatabase read GetDatabase write SetDatabase; property DRVStatistics: IibSHDRVStatistics read GetDRVStatistics; property DRVTimeStatistics: IibSHDRVExecTimeStatistics read GetDRVTimeStatistics write SetDRVTimeStatistics; end; IibSHSQLEditor = interface(IibSHTool) ['{FF095100-C03B-4637-9C44-41E9EC1BEA47}'] function GetAutoCommit: Boolean; procedure SetAutoCommit(Value: Boolean); function GetExecuteSelected: Boolean; procedure SetExecuteSelected(Value: Boolean); function GetRetrievePlan: Boolean; procedure SetRetrievePlan(Value: Boolean); function GetRetrieveStatistics: Boolean; procedure SetRetrieveStatistics(Value: Boolean); function GetAfterExecute: string; procedure SetAfterExecute(Value: string); function GetRecordCountFrmt: string; function GetResultType: string; procedure SetResultType(Value: string); function GetThreadResults: Boolean; procedure SetThreadResults(Value: Boolean); function GetIsolationLevel: string; procedure SetIsolationLevel(Value: string); function GetTransactionParams: TStrings; procedure SetTransactionParams(Value: TStrings); procedure SetRecordCount; property AutoCommit: Boolean read GetAutoCommit write SetAutoCommit; property ExecuteSelected: Boolean read GetExecuteSelected write SetExecuteSelected; property RetrievePlan: Boolean read GetRetrievePlan write SetRetrievePlan; property RetrieveStatistics: Boolean read GetRetrieveStatistics write SetRetrieveStatistics; property AfterExecute: string read GetAfterExecute write SetAfterExecute; property RecordCountFrmt: string read GetRecordCountFrmt; property ResultType: string read GetResultType write SetResultType; property ThreadResults: Boolean read GetThreadResults write SetThreadResults; property IsolationLevel: string read GetIsolationLevel write SetIsolationLevel; property TransactionParams: TStrings read GetTransactionParams write SetTransactionParams; end; IibSHInputParameters = interface ['{288F8014-162D-4D1B-93CA-4566F5A3B88A}'] function GetParams: IibSHDRVParams; function InputParameters(AParams: IibSHDRVParams): Boolean; property Params: IibSHDRVParams read GetParams; end; IibSHData = interface ['{D58CB2AF-BAF6-4C73-9FA9-7B4813A8C141}'] function GetTransaction: IibSHDRVTransaction; function GetDataset: IibSHDRVDataset; function GetErrorText: string; function GetReadOnly: Boolean; procedure SetReadOnly(const Value: Boolean); function Prepare: Boolean; function Open: Boolean; procedure FetchAll; procedure Close; procedure Commit; procedure Rollback; property Transaction: IibSHDRVTransaction read GetTransaction; property Dataset: IibSHDRVDataset read GetDataset; property ErrorText: string read GetErrorText; property ReadOnly: Boolean read GetReadOnly write SetReadOnly; end; { Psewdo DBObject } IibSHQuery = interface(IibSHDBObject) ['{24551BC4-99C7-4077-A489-F56348BA742E}'] function GetData: IibSHData; procedure SetData(Value: IibSHData); function GetField(Index: Integer): IibSHField; property Data: IibSHData read GetData write SetData; end; IibSHDMLHistory = interface(IibSHTool) ['{5D78199A-267F-4125-AE59-3EF341A2D2F0}'] function GetActive: Boolean; procedure SetActive(const Value: Boolean); function GetHistoryFileName: string; function GetMaxCount: Integer; procedure SetMaxCount(const Value: Integer); function GetSelect: Boolean; procedure SetSelect(const Value: Boolean); function GetInsert: Boolean; procedure SetInsert(const Value: Boolean); function GetUpdate: Boolean; procedure SetUpdate(const Value: Boolean); function GetDelete: Boolean; procedure SetDelete(const Value: Boolean); function GetExecute: Boolean; procedure SetExecute(const Value: Boolean); function GetCrash: Boolean; procedure SetCrash(const Value: Boolean); function Count: Integer; procedure Clear; function Statement(Index: Integer): string; function Item(Index: Integer): string; function Statistics(Index: Integer): string; function AddStatement(AStatement: string; AStatistics: IibSHStatistics): Integer; procedure DeleteStatement(AStatementNo: Integer); procedure LoadFromFile; procedure SaveToFile; property Active: Boolean read GetActive write SetActive; property MaxCount: Integer read GetMaxCount write SetMaxCount; property Select: Boolean read GetSelect write SetSelect; property Insert: Boolean read GetInsert write SetInsert; property Update: Boolean read GetUpdate write SetUpdate; property Delete: Boolean read GetDelete write SetDelete; property Execute: Boolean read GetExecute write SetExecute; property Crash: Boolean read GetCrash write SetCrash; end; IibSHDDLHistory = interface(IibSHTool) ['{10C78888-44DB-4117-B123-052199CE07FD}'] function GetActive: Boolean; procedure SetActive(const Value: Boolean); function GetHistoryFileName: string; function Count: Integer; procedure Clear; function Statement(Index: Integer): string; function Item(Index: Integer): string; function AddStatement(AStatement: string): Integer; procedure CommitNewStatements; procedure RollbackNewStatements; procedure LoadFromFile; procedure SaveToFile; property Active: Boolean read GetActive write SetActive; end; IibSHSQLPerformance = interface(IibSHTool) ['{5BA6C2E7-63B3-4A59-A03E-767E053A993C}'] end; IibSHSQLPlan = interface(IibSHTool) ['{291E635D-A239-4B77-A90C-6DE99B081D53}'] end; IibSHSQLPlayer = interface(IibSHTool) ['{CEDED95A-F963-4F3E-A99B-B96E0B418474}'] function GetServer: string; procedure SetServer(Value: string); function GetMode: string; procedure SetMode(Value: string); function GetAutoDDL: Boolean; procedure SetAutoDDL(Value: Boolean); function GetAbortOnError: Boolean; procedure SetAbortOnError(Value: Boolean); function GetAfterError: string; procedure SetAfterError(Value: string); function GetDefaultSQLDialect: Integer; procedure SetDefaultSQLDialect(Value: Integer); function GetSignScript: Boolean; procedure SetSignScript(Value: Boolean); property Server: string read GetServer write SetServer; property Mode: string read GetMode write SetMode; property AutoDDL: Boolean read GetAutoDDL write SetAutoDDL; property AbortOnError: Boolean read GetAbortOnError write SetAbortOnError; property AfterError: string read GetAfterError write SetAfterError; property DefaultSQLDialect: Integer read GetDefaultSQLDialect write SetDefaultSQLDialect; property SignScript: Boolean read GetSignScript write SetSignScript; end; IibSHDMLExporterFactory = interface(ISHComponentFactory) ['{E82413B4-5CEB-4890-9DEF-E081778AFAD8}'] // // Свойства для инициализации аналогичных свойств компонента // function GetData: IibSHData; procedure SetData(Value: IibSHData); function GetMode: string; procedure SetMode(Value: string); function GetTablesForDumping: TStrings; procedure SetTablesForDumping(Value: TStrings); procedure SuspendedDestroyComponent(AComponent: TSHComponent); property Data: IibSHData read GetData write SetData; property Mode: string read GetMode write SetMode; property TablesForDumping: TStrings read GetTablesForDumping write SetTablesForDumping; end; IibSHDMLExporter = interface(IibSHTool) ['{ACD94134-D1A5-427E-AC7F-BEE935C34071}'] function GetData: IibSHData; procedure SetData(Value: IibSHData); function GetMode: string; procedure SetMode(Value: string); function GetTablesForDumping: TStrings; procedure SetTablesForDumping(Value: TStrings); function GetActive: Boolean; procedure SetActive(Value: Boolean); function GetOutput: string; procedure SetOutput(Value: string); function GetStatementType: string; procedure SetStatementType(Value: string); function GetHeader: Boolean; procedure SetHeader(Value: Boolean); function GetPassword: Boolean; procedure SetPassword(Value: Boolean); function GetCommitAfter: Integer; procedure SetCommitAfter(Value: Integer); function GetCommitEachTable: Boolean; procedure SetCommitEachTable(Value: Boolean); function GetDateFormat: string; procedure SetDateFormat(Value: string); function GetTimeFormat: string; procedure SetTimeFormat(Value: string); function GetUseDateTimeANSIPrefix: Boolean; procedure SetUseDateTimeANSIPrefix(Value: Boolean); function GetNonPrintChar2Space: Boolean; procedure SetNonPrintChar2Space(Value: Boolean); function GetUseExecuteBlock:boolean; procedure SetUseExecuteBlock(Value:boolean); property Data: IibSHData read GetData write SetData; property Mode: string read GetMode write SetMode; property TablesForDumping: TStrings read GetTablesForDumping write SetTablesForDumping; property Active: Boolean read GetActive write SetActive; property Output: string read GetOutput write SetOutput; property StatementType: string read GetStatementType write SetStatementType; property Header: Boolean read GetHeader write SetHeader; property Password: Boolean read GetPassword write SetPassword; property CommitAfter: Integer read GetCommitAfter write SetCommitAfter; property CommitEachTable: Boolean read GetCommitEachTable write SetCommitEachTable; property DateFormat: string read GetDateFormat write SetDateFormat; property TimeFormat: string read GetTimeFormat write SetTimeFormat; property UseDateTimeANSIPrefix: Boolean read GetUseDateTimeANSIPrefix write SetUseDateTimeANSIPrefix; property NonPrintChar2Space: Boolean read GetNonPrintChar2Space write SetNonPrintChar2Space; property UseExecuteBlock:boolean read GetUseExecuteBlock write SetUseExecuteBlock; end; TibSHSQLMonitorEvent = procedure(ApplicationName, OperationName, ObjectName, LongTime, ShortTime, SQLText: string) of object; IibSHSQLMonitor = interface(IibSHTool) ['{05A40F9C-68C8-4037-9C83-B8335013E23F}'] function GetActive: Boolean; procedure SetActive(Value: Boolean); function GetPrepare: Boolean; procedure SetPrepare(Value: Boolean); function GetExecute: Boolean; procedure SetExecute(Value: Boolean); function GetFetch: Boolean; procedure SetFetch(Value: Boolean); function GetConnect: Boolean; procedure SetConnect(Value: Boolean); function GetTransact: Boolean; procedure SetTransact(Value: Boolean); function GetService: Boolean; procedure SetService(Value: Boolean); function GetStmt: Boolean; procedure SetStmt(Value: Boolean); function GetError: Boolean; procedure SetError(Value: Boolean); function GetBlob: Boolean; procedure SetBlob(Value: Boolean); function GetMisc: Boolean; procedure SetMisc(Value: Boolean); function GetFilter: TStrings; procedure SetFilter(Value: TStrings); function GetOnEvent: TibSHSQLMonitorEvent; procedure SetOnEvent(Value: TibSHSQLMonitorEvent); property Active: Boolean read GetActive write SetActive; property Prepare: Boolean read GetPrepare write SetPrepare; property Execute: Boolean read GetExecute write SetExecute; property Fetch: Boolean read GetFetch write SetFetch; property Connect: Boolean read GetConnect write SetConnect; property Transact: Boolean read GetTransact write SetTransact; property Service: Boolean read GetService write SetService; property Stmt: Boolean read GetStmt write SetStmt; property Error: Boolean read GetError write SetError; property Blob: Boolean read GetBlob write SetBlob; property Misc: Boolean read GetMisc write SetMisc; property Filter: TStrings read GetFilter write SetFilter; property OnEvent: TibSHSQLMonitorEvent read GetOnEvent write SetOnEvent; end; IibSHFIBMonitor = interface(IibSHSQLMonitor) ['{C6C66A3A-B515-4893-B1B1-AB3811567DC9}'] end; IibSHIBXMonitor = interface(IibSHSQLMonitor) ['{73EBB6C1-3BEA-464C-ABC2-1FD362F602B2}'] end; IibSHDDLGrantor = interface(IibSHTool) ['{C86278F9-A4DB-402A-8B6A-B342A39346D3}'] function GetPrivilegesFor: string; procedure SetPrivilegesFor(Value: string); function GetGrantsOn: string; procedure SetGrantsOn(Value: string); function GetDisplay: string; procedure SetDisplay(Value: string); function GetShowSystemTables: Boolean; procedure SetShowSystemTables(Value: Boolean); function GetIncludeFields: Boolean; procedure SetIncludeFields(Value: Boolean); function GetUnionUsers: TStrings; function GetAbsentUsers: TStrings; procedure ExtractGrants(const AClassIID: TGUID; const ACaption: string); function GetGrantSelectIndex(const ACaption: string): Integer; function GetGrantUpdateIndex(const ACaption: string): Integer; function GetGrantDeleteIndex(const ACaption: string): Integer; function GetGrantInsertIndex(const ACaption: string): Integer; function GetGrantReferenceIndex(const ACaption: string): Integer; function GetGrantExecuteIndex(const ACaption: string): Integer; function IsGranted(const ACaption: string): Boolean; function GrantTable(const AClassIID: TGUID; const Privilege, OnObject, ToObject: string; WGO: Boolean): Boolean; function GrantTableField(const AClassIID: TGUID; const Privilege, OnField, OnObject, ToObject: string; WGO: Boolean): Boolean; function GrantProcedure(const AClassIID: TGUID; const OnObject, ToObject: string; WGO: Boolean): Boolean; function RevokeTable(const AClassIID: TGUID; const Privilege, OnObject, FromObject: string; WGO: Boolean): Boolean; function RevokeTableField(const AClassIID: TGUID; const Privilege, OnField, OnObject, FromObject: string; WGO: Boolean): Boolean; function RevokeProcedure(const AClassIID: TGUID; const OnObject, FromObject: string; WGO: Boolean): Boolean; property PrivilegesFor: string read GetPrivilegesFor write SetPrivilegesFor; property GrantsOn: string read GetGrantsOn write SetGrantsOn; property Display: string read GetDisplay write SetDisplay; property ShowSystemTables: Boolean read GetShowSystemTables write SetShowSystemTables; property IncludeFields: Boolean read GetIncludeFields write SetIncludeFields; end; IibSHGrant = interface ['{8EC9F4D2-6BE1-4FC8-B5C0-951D07759925}'] end; IibSHGrantWGO = interface ['{810472C3-93B7-42D3-9182-278C30FD608C}'] end; IibSHUser = interface ['{25F094D4-53CE-481A-A2DF-35D4BD56CA23}'] function GetUserName: string; procedure SetUserName(Value: string); function GetPassword: string; procedure SetPassword(Value: string); function GetFirstName: string; procedure SetFirstName(Value: string); function GetMiddleName: string; procedure SetMiddleName(Value: string); function GetLastName: string; procedure SetLastName(Value: string); property UserName: string read GetUserName write SetUserName; property Password: string read GetPassword write SetPassword; property FirstName: string read GetFirstName write SetFirstName; property MiddleName: string read GetMiddleName write SetMiddleName; property LastName: string read GetLastName write SetLastName; end; IibSHUserManager = interface(IibSHTool) ['{F04A5F0F-BA09-496A-B6F4-CAE6A77496FB}'] procedure DisplayUsers; function GetUserCount: Integer; function GetUserName(AIndex: Integer): string; function GetFirstName(AIndex: Integer): string; function GetMiddleName(AIndex: Integer): string; function GetLastName(AIndex: Integer): string; function GetConnectCount(const UserName: string): Integer; function AddUser(const UserName, Password, FirstName, MiddleName, LastName: string): Boolean; function ModifyUser(const UserName, Password, FirstName, MiddleName, LastName: string): Boolean; function DeleteUser(const UserName: string): Boolean; end; IibSHLookIn = interface ['{53D67FF9-2FE4-4B17-8992-45079D7C5026}'] function GetDomains: Boolean; procedure SetDomains(Value: Boolean); function GetTables: Boolean; procedure SetTables(Value: Boolean); function GetConstraints: Boolean; procedure SetConstraints(Value: Boolean); function GetIndices: Boolean; procedure SetIndices(Value: Boolean); function GetViews: Boolean; procedure SetViews(Value: Boolean); function GetProcedures: Boolean; procedure SetProcedures(Value: Boolean); function GetTriggers: Boolean; procedure SetTriggers(Value: Boolean); function GetGenerators: Boolean; procedure SetGenerators(Value: Boolean); function GetExceptions: Boolean; procedure SetExceptions(Value: Boolean); function GetFunctions: Boolean; procedure SetFunctions(Value: Boolean); function GetFilters: Boolean; procedure SetFilters(Value: Boolean); function GetRoles: Boolean; procedure SetRoles(Value: Boolean); property Domains: Boolean read GetDomains write SetDomains; property Tables: Boolean read GetTables write SetTables; property Constraints: Boolean read GetConstraints write SetConstraints; property Indices: Boolean read GetIndices write SetIndices; property Views: Boolean read GetViews write SetViews; property Procedures: Boolean read GetProcedures write SetProcedures; property Triggers: Boolean read GetTriggers write SetTriggers; property Generators: Boolean read GetGenerators write SetGenerators; property Exceptions: Boolean read GetExceptions write SetExceptions; property Functions: Boolean read GetFunctions write SetFunctions; property Filters: Boolean read GetFilters write SetFilters; property Roles: Boolean read GetRoles write SetRoles; end; IibSHDDLCommentator = interface(IibSHTool) ['{600FAFBF-C868-43E2-8029-FE7BB56498B6}'] function GetMode: string; procedure SetMode(Value: string); function GetGoNext: Boolean; procedure SetGoNext(Value: Boolean); property Mode: string read GetMode write SetMode; property GoNext: Boolean read GetGoNext write SetGoNext; end; IibSHDDLDocumentor = interface(IibSHTool) ['{143A5606-8C20-4A25-AD60-3B40BCDFEFBC}'] end; IibSHDDLFinder = interface(IibSHTool) ['{F742FE83-424E-4ACC-9C29-2A03561C4A85}'] function GetActive: Boolean; procedure SetActive(Value: Boolean); function GetFindString: string; procedure SetFindString(Value: string); function GetCaseSensitive: Boolean; procedure SetCaseSensitive(Value: Boolean); function GetWholeWordsOnly: Boolean; procedure SetWholeWordsOnly(Value: Boolean); function GetRegularExpression: Boolean; procedure SetRegularExpression(Value: Boolean); function GetLookIn: IibSHLookIn; function Find(const ASource: string): Boolean; function FindIn(const AClassIID: TGUID; const ACaption: string): Boolean; function LastSource: string; property Active: Boolean read GetActive write SetActive; property FindString: string read GetFindString write SetFindString; property CaseSensitive: Boolean read GetCaseSensitive write SetCaseSensitive; property WholeWordsOnly: Boolean read GetWholeWordsOnly write SetWholeWordsOnly; property RegularExpression: Boolean read GetRegularExpression write SetRegularExpression; property LookIn: IibSHLookIn read GetLookIn; end; IibSHDDLExtractor = interface(IibSHTool) ['{69B6954D-56BE-471F-880C-9A303C59BB1C}'] function GetActive: Boolean; procedure SetActive(Value: Boolean); function GetMode: string; procedure SetMode(Value: string); function GetHeader: string; procedure SetHeader(Value: string); function GetPassword: Boolean; procedure SetPassword(Value: Boolean); function GetGeneratorValues: Boolean; procedure SetGeneratorValues(Value: Boolean); function GetComputedSeparately: Boolean; procedure SetComputedSeparately(Value: Boolean); function GetDecodeDomains: Boolean; procedure SetDecodeDomains(Value: Boolean); function GetDescriptions: Boolean; procedure SetDescriptions(Value: Boolean); function GetGrants: Boolean; procedure SetGrants(Value: Boolean); function GetOwnerName: Boolean; procedure SetOwnerName(Value: Boolean); function GetTerminator: string; procedure SetTerminator(Value: string); function GetFinalCommit: Boolean; procedure SetFinalCommit(Value: Boolean); function GetOnTextNotify: TSHOnTextNotify; procedure SetOnTextNotify(Value: TSHOnTextNotify); procedure Prepare; procedure DisplayScriptHeader; procedure DisplayScriptFooter; procedure DisplayDialect; procedure DisplayNames; procedure DisplayDatabase; procedure DisplayConnect; procedure DisplayTerminatorStart; procedure DisplayTerminatorEnd; procedure DisplayCommitWork; // Flag: Procedure Headers(0) procedure DisplayDBObject(const AClassIID: TGUID; const ACaption: string; Flag: Integer = -1); procedure DisplayGrants; function GetComputedList: TStrings; function GetPrimaryList: TStrings; function GetUniqueList: TStrings; function GetForeignList: TStrings; function GetCheckList: TStrings; function GetIndexList: TStrings; function GetTriggerList: TStrings; function GetDescriptionList: TStrings; function GetGrantList: TStrings; property Active: Boolean read GetActive write SetActive; property Mode: string read GetMode write SetMode; property Header: string read GetHeader write SetHeader; property Password: Boolean read GetPassword write SetPassword; property GeneratorValues: Boolean read GetGeneratorValues write SetGeneratorValues; property ComputedSeparately: Boolean read GetComputedSeparately write SetComputedSeparately; property DecodeDomains: Boolean read GetDecodeDomains write SetDecodeDomains; property Descriptions: Boolean read GetDescriptions write SetDescriptions; property Grants: Boolean read GetGrants write SetGrants; property OwnerName: Boolean read GetOwnerName write SetOwnerName; property Terminator: string read GetTerminator write SetTerminator; property FinalCommit: Boolean read GetFinalCommit write SetFinalCommit; property OnTextNotify: TSHOnTextNotify read GetOnTextNotify write SetOnTextNotify; end; IibSHTXTLoader = interface(IibSHTool) ['{F85E41EE-5F60-4526-9626-B742335363D5}'] function GetActive: Boolean; procedure SetActive(Value: Boolean); function GetFileName: string; procedure SetFileName(Value: string); function GetInsertSQL: TStrings; function GetErrorText: string; function GetDelimiter: string; procedure SetDelimiter(Value: string); function GetTrimValues: Boolean; procedure SetTrimValues(Value: Boolean); function GetTrimLengths: Boolean; procedure SetTrimLengths(Value: Boolean); function GetAbortOnError: Boolean; procedure SetAbortOnError(Value: Boolean); function GetCommitEachLine: Boolean; procedure SetCommitEachLine(Value: Boolean); function GetColumnCheckOnly: Integer; procedure SetColumnCheckOnly(Value: Integer); function GetVerbose: Boolean; procedure SetVerbose(Value: Boolean); function GetOnTextNotify: TSHOnTextNotify; procedure SetOnTextNotify(Value: TSHOnTextNotify); function GetStringCount: Integer; function GetCurLineNumber: Integer; function Execute: Boolean; function InTransaction: Boolean; procedure Commit; procedure Rollback; property Active: Boolean read GetActive write SetActive; property FileName: string read GetFileName write SetFileName; property InsertSQL: TStrings read GetInsertSQL; property ErrorText: string read GetErrorText; property Delimiter: string read GetDelimiter write SetDelimiter; property TrimValues: Boolean read GetTrimValues write SetTrimValues; property TrimLengths: Boolean read GetTrimLengths write SetTrimLengths; property AbortOnError: Boolean read GetAbortOnError write SetAbortOnError; property CommitEachLine: Boolean read GetCommitEachLine write SetCommitEachLine; property ColumnCheckOnly: Integer read GetColumnCheckOnly write SetColumnCheckOnly; property Verbose: Boolean read GetVerbose write SetVerbose; property OnTextNotify: TSHOnTextNotify read GetOnTextNotify write SetOnTextNotify; end; IibSHBlobEditor = interface(IibSHTool) ['{BABD6B0C-0B13-4B95-BF0D-347378DAF95C}'] end; IibSHReportManager = interface(IibSHTool) ['{843AADA5-B58F-45E2-B273-C081617CABCC}'] end; IibSHDataGenerator = interface(IibSHTool) ['{165B0809-52A1-450F-B3F8-9A4692FE6A1F}'] end; IibSHDBComparer = interface(IibSHTool) ['{E776498E-2CB1-4D3D-858F-96DA53B5B3C2}'] end; IibSHSecondaryFiles = interface(IibSHTool) ['{6E318C61-6AA4-4986-91A6-C001CC654605}'] end; IibSHCVSExchanger = interface(IibSHTool) ['{9235C797-D904-4441-A5AF-7C1D3BC00BB6}'] end; IibSHDBDesigner = interface(IibSHTool) ['{19EDD484-65CB-4BE1-8032-B57DD73C0C26}'] end; { Services } IibSHService = interface(IibSHTool) ['{72065280-AF55-4AF7-8131-83522224A36D}'] function GetDRVService: IibSHDRVService; function GetDatabaseName: string; procedure SetDatabaseName(Value: string); function GetErrorText: string; procedure SetErrorText(Value: string); function GetOnTextNotify: TSHOnTextNotify; procedure SetOnTextNotify(Value: TSHOnTextNotify); function Execute: Boolean; property DRVService: IibSHDRVService read GetDRVService; property DatabaseName: string read GetDatabaseName write SetDatabaseName; property ErrorText: string read GetErrorText write SetErrorText; property OnTextNotify: TSHOnTextNotify read GetOnTextNotify write SetOnTextNotify; end; IibSHServerProps = interface(IibSHService) ['{AF50436C-FBA5-41DA-9DFC-8188D0BAE4A5}'] end; IibSHServerLog = interface(IibSHService) ['{CACE0E68-401C-4D73-BCC4-1D655641807C}'] end; IibSHServerConfig = interface(IibSHService) ['{5322517F-A114-4CD3-A643-A3841F0147B7}'] end; IibSHServerLicense = interface(IibSHService) ['{FCEDDD13-B1A0-4781-8620-2C5FE17411A7}'] end; IibSHDatabaseShutdown = interface(IibSHService) ['{2E8A3AA4-9871-43E0-99EE-53EF7A33BD0A}'] end; IibSHDatabaseOnline = interface(IibSHService) ['{4E8122EA-4F3F-43B3-9DFF-6C5EB9CF5F48}'] end; IibSHBackupRestoreService = interface(IibSHService) ['{79A37CE0-EB23-4AF7-B45E-A51E73AA6C1A}'] function GetSourceFileList: TStrings; function GetDestinationFileList: TStrings; property SourceFileList: TStrings read GetSourceFileList; property DestinationFileList: TStrings read GetDestinationFileList; end; IibSHDatabaseBackup = interface(IibSHService) ['{B4B3A02A-D464-44BD-B04B-88B29C5D43F5}'] end; IibSHDatabaseRestore = interface(IibSHService) ['{68A91EFA-A07C-494D-96CA-DEF67D975D65}'] end; IibSHDatabaseStatistics = interface(IibSHService) ['{86645FA0-2737-4535-A58B-A7423BD6CF16}'] end; IibSHDatabaseValidation = interface(IibSHService) ['{B3824F7D-FA57-42C1-BBA5-42125E241DB4}'] end; IibSHDatabaseSweep = interface(IibSHService) ['{909AB7EA-2C47-4FF4-BF6A-2EDA95C05A89}'] end; IibSHDatabaseMend = interface(IibSHService) ['{6DF8DEB0-4F66-4AB2-841B-4173A8543A1D}'] end; IibSHTransactionRecovery = interface(IibSHService) ['{BAC20386-E0C1-4CED-B271-B4873E18BC37}'] end; IibSHDatabaseProps = interface(IibSHService) ['{8E238E00-5498-4DA3-9F1D-40DE7FF87475}'] end; { Options } IibSHOptions = interface(ISHComponentOptions) ['{0EBB91E9-C010-420C-A0DA-8B2F2FF8E32C}'] end; IfbSHOptions = interface(ISHComponentOptions) ['{11D79503-51A7-4E14-9FB7-BC081CC34A1C}'] end; IibSHServerOptions = interface(ISHComponentOptions) ['{7554712C-3010-40E2-90A2-1EF55F50693A}'] function GetHost: string; procedure SetHost(Value: string); function GetVersion: string; procedure SetVersion(Value: string); function GetClientLibrary: string; procedure SetClientLibrary(Value: string); function GetProtocol: string; procedure SetProtocol(Value: string); function GetPort: string; procedure SetPort(Value: string); function GetSecurityDatabase: string; procedure SetSecurityDatabase(Value: string); function GetUserName: string; procedure SetUserName(Value: string); function GetPassword: string; procedure SetPassword(Value: string); function GetRole: string; procedure SetRole(Value: string); function GetLoginPrompt: Boolean; procedure SetLoginPrompt(Value: Boolean); function GetSaveResultFilterIndex: Integer; procedure SetSaveResultFilterIndex(Value: Integer); property Host: string read GetHost write SetHost; property Version: string read GetVersion write SetVersion; property ClientLibrary: string read GetClientLibrary write SetClientLibrary; property Protocol: string read GetProtocol write SetProtocol; property Port: string read GetPort write SetPort; property SecurityDatabase: string read GetSecurityDatabase write SetSecurityDatabase; property UserName: string read GetUserName write SetUserName; property Password: string read GetPassword write SetPassword; property Role: string read GetRole write SetRole; property LoginPrompt: Boolean read GetLoginPrompt write SetLoginPrompt; //Invisible //DataForm property SaveResultFilterIndex: Integer read GetSaveResultFilterIndex write SetSaveResultFilterIndex; end; IfbSHServerOptions = interface ['{E8FAA97F-F3A8-44D9-BAA1-3A9B8D0D1652}'] end; IibSHDatabaseOptions = interface(ISHComponentOptions) ['{B59C248C-7DC2-4FF0-9BA0-2C2DD216A564}'] function GetCharset: string; procedure SetCharset(Value: string); function GetCapitalizeNames: Boolean; procedure SetCapitalizeNames(Value: Boolean); property Charset: string read GetCharset write SetCharset; property CapitalizeNames: Boolean read GetCapitalizeNames write SetCapitalizeNames; end; IfbSHDatabaseOptions = interface ['{02A2F059-8913-44D0-9520-4DCAE1833071}'] end; // ---------------------------------------------------------------------------- IibSHDDLOptions = interface ['{44676723-368A-4FE2-9CA0-D2CC4321F4AA}'] function GetAutoCommit: Boolean; procedure SetAutoCommit(Value: Boolean); function GetStartDomainForm: string; procedure SetStartDomainForm(Value: string); function GetStartTableForm: string; procedure SetStartTableForm(Value: string); function GetStartIndexForm: string; procedure SetStartIndexForm(Value: string); function GetStartViewForm: string; procedure SetStartViewForm(Value: string); function GetStartProcedureForm: string; procedure SetStartProcedureForm(Value: string); function GetStartTriggerForm: string; procedure SetStartTriggerForm(Value: string); function GetStartGeneratorForm: string; procedure SetStartGeneratorForm(Value: string); function GetStartExceptionForm: string; procedure SetStartExceptionForm(Value: string); function GetStartFunctionForm: string; procedure SetStartFunctionForm(Value: string); function GetStartFilterForm: string; procedure SetStartFilterForm(Value: string); function GetStartRoleForm: string; procedure SetStartRoleForm(Value: string); property AutoCommit: Boolean read GetAutoCommit write SetAutoCommit; property StartDomainForm: string read GetStartDomainForm write SetStartDomainForm; property StartTableForm: string read GetStartTableForm write SetStartTableForm; property StartIndexForm: string read GetStartIndexForm write SetStartIndexForm; property StartViewForm: string read GetStartViewForm write SetStartViewForm; property StartProcedureForm: string read GetStartProcedureForm write SetStartProcedureForm; property StartTriggerForm: string read GetStartTriggerForm write SetStartTriggerForm; property StartGeneratorForm: string read GetStartGeneratorForm write SetStartGeneratorForm; property StartExceptionForm: string read GetStartExceptionForm write SetStartExceptionForm; property StartFunctionForm: string read GetStartFunctionForm write SetStartFunctionForm; property StartFilterForm: string read GetStartFilterForm write SetStartFilterForm; property StartRoleForm: string read GetStartRoleForm write SetStartRoleForm; end; IibSHDMLOptions = interface ['{BE067240-AE3A-4EE3-BB83-F4178C74688D}'] function GetAutoCommit: Boolean; procedure SetAutoCommit(Value: Boolean); function GetShowDB_KEY: Boolean; procedure SetShowDB_KEY(Value: Boolean); function GetUseDB_KEY: Boolean; procedure SetUseDB_KEY(Value: Boolean); function GetConfirmEndTransaction: string; procedure SetConfirmEndTransaction(Value: string); function GetDefaultTransactionAction: string; procedure SetDefaultTransactionAction(Value: string); function GetIsolationLevel: string; procedure SetIsolationLevel(Value: string); function GetTransactionParams: TStrings; procedure SetTransactionParams(Value: TStrings); property AutoCommit: Boolean read GetAutoCommit write SetAutoCommit; property ShowDB_KEY: Boolean read GetShowDB_KEY write SetShowDB_KEY; property UseDB_KEY: Boolean read GetUseDB_KEY write SetUseDB_KEY; property ConfirmEndTransaction: string read GetConfirmEndTransaction write SetConfirmEndTransaction; property DefaultTransactionAction: string read GetDefaultTransactionAction write SetDefaultTransactionAction; property IsolationLevel: string read GetIsolationLevel write SetIsolationLevel; property TransactionParams: TStrings read GetTransactionParams write SetTransactionParams; end; IibSHNavigatorOptions = interface ['{2CB5DCEE-E7B0-4F43-ADA7-E99444066966}'] function GetFavoriteObjectNames: TStrings; procedure SetFavoriteObjectNames(Value: TStrings); function GetFavoriteObjectColor: TColor; procedure SetFavoriteObjectColor(Value: TColor); function GetShowDomains: Boolean; procedure SetShowDomains(Value: Boolean); function GetShowTables: Boolean; procedure SetShowTables(Value: Boolean); function GetShowViews: Boolean; procedure SetShowViews(Value: Boolean); function GetShowProcedures: Boolean; procedure SetShowProcedures(Value: Boolean); function GetShowTriggers: Boolean; procedure SetShowTriggers(Value: Boolean); function GetShowGenerators: Boolean; procedure SetShowGenerators(Value: Boolean); function GetShowExceptions: Boolean; procedure SetShowExceptions(Value: Boolean); function GetShowFunctions: Boolean; procedure SetShowFunctions(Value: Boolean); function GetShowFilters: Boolean; procedure SetShowFilters(Value: Boolean); function GetShowRoles: Boolean; procedure SetShowRoles(Value: Boolean); function GetShowIndices: Boolean; procedure SetShowIndices(Value: Boolean); property FavoriteObjectNames: TStrings read GetFavoriteObjectNames write SetFavoriteObjectNames; property FavoriteObjectColor: TColor read GetFavoriteObjectColor write SetFavoriteObjectColor; property ShowDomains: Boolean read GetShowDomains write SetShowDomains; property ShowTables: Boolean read GetShowTables write SetShowTables; property ShowViews: Boolean read GetShowViews write SetShowViews; property ShowProcedures: Boolean read GetShowProcedures write SetShowProcedures; property ShowTriggers: Boolean read GetShowTriggers write SetShowTriggers; property ShowGenerators: Boolean read GetShowGenerators write SetShowGenerators; property ShowExceptions: Boolean read GetShowExceptions write SetShowExceptions; property ShowFunctions: Boolean read GetShowFunctions write SetShowFunctions; property ShowFilters: Boolean read GetShowFilters write SetShowFilters; property ShowRoles: Boolean read GetShowRoles write SetShowRoles; property ShowIndices: Boolean read GetShowIndices write SetShowIndices; end; IibSHDatabaseAliasOptions = interface ['{EBE8842E-19C1-4C41-B9FF-2A93B7823129}'] function GetDDL: IibSHDDLOptions; function GetDML: IibSHDMLOptions; function GetNavigator: IibSHNavigatorOptions; property DDL: IibSHDDLOptions read GetDDL; property DML: IibSHDMLOptions read GetDML; property Navigator: IibSHNavigatorOptions read GetNavigator; end; IibSHDatabaseAliasOptionsInt = interface ['{929467CA-A5B2-45EF-8C10-9272DE2960D6}'] function GetFilterList: TStrings; procedure SetFilterList(Value: TStrings); function GetFilterIndex: Integer; procedure SetFilterIndex(Value: Integer); function GetDMLHistoryActive: Boolean; procedure SetDMLHistoryActive(const Value: Boolean); function GetDMLHistoryMaxCount: Integer; procedure SetDMLHistoryMaxCount(const Value: Integer); function GetDMLHistorySelect: Boolean; procedure SetDMLHistorySelect(const Value: Boolean); function GetDMLHistoryInsert: Boolean; procedure SetDMLHistoryInsert(const Value: Boolean); function GetDMLHistoryUpdate: Boolean; procedure SetDMLHistoryUpdate(const Value: Boolean); function GetDMLHistoryDelete: Boolean; procedure SetDMLHistoryDelete(const Value: Boolean); function GetDMLHistoryExecute: Boolean; procedure SetDMLHistoryExecute(const Value: Boolean); function GetDMLHistoryCrash: Boolean; procedure SetDMLHistoryCrash(const Value: Boolean); function GetDDLHistoryActive: Boolean; procedure SetDDLHistoryActive(const Value: Boolean); //For Database Alias Filter property FilterList: TStrings read GetFilterList write SetFilterList; property FilterIndex: Integer read GetFilterIndex write SetFilterIndex; //For DML History property DMLHistoryActive: Boolean read GetDMLHistoryActive write SetDMLHistoryActive; property DMLHistoryMaxCount: Integer read GetDMLHistoryMaxCount write SetDMLHistoryMaxCount; property DMLHistorySelect: Boolean read GetDMLHistorySelect write SetDMLHistorySelect; property DMLHistoryInsert: Boolean read GetDMLHistoryInsert write SetDMLHistoryInsert; property DMLHistoryUpdate: Boolean read GetDMLHistoryUpdate write SetDMLHistoryUpdate; property DMLHistoryDelete: Boolean read GetDMLHistoryDelete write SetDMLHistoryDelete; property DMLHistoryExecute: Boolean read GetDMLHistoryExecute write SetDMLHistoryExecute; property DMLHistoryCrash: Boolean read GetDMLHistoryCrash write SetDMLHistoryCrash; //For DDL History property DDLHistoryActive: Boolean read GetDDLHistoryActive write SetDDLHistoryActive; end; // ---------------------------------------------------------------------------- {Editor} IibSHKeywordsList = interface ['{F3C2E68C-D9CA-461E-A11A-7CA9342E7D9A}'] function GetFunctionList: TStrings; function GetDataTypeList: TStrings; function GetKeywordList: TStrings; function GetAllKeywordList: TStrings; property FunctionList: TStrings read GetFunctionList; property DataTypeList: TStrings read GetDataTypeList; property KeywordList: TStrings read GetKeywordList; property AllKeywordList: TStrings read GetAllKeywordList; end; IibSHEditorRegistrator = interface ['{92F3E712-E2FC-4567-8055-0918B185813A}'] procedure AfterChangeServerVersion(Sender: TObject); procedure RegisterEditor(AEditor: TComponent; AServer, ADatabase: IInterface); function GetKeywordsManager(AServer: IInterface): IInterface; function GetObjectNameManager(AServer, ADatabase: IInterface): IInterface; end; IibSHAutoComplete = interface ['{863802AC-7F9A-4455-A32C-F851C87B10AB}'] end; IibSHAutoReplace = interface ['{01F48236-59F6-4E9B-A6E5-92731F28E57D}'] end; IibCustomStrings = interface ['{3F7CDD61-27E8-4EA6-B6FA-93726E5FDFEE}'] end; (* IibSHSQLInfo = interface ['{71A0DEF6-C7C7-45D8-B1C8-9F3FB0671470}'] function GetSQL: TStrings; function GetBTCLDatabase: IibSHDatabase; function GetResultType: string; function GetTransaction: IibSHDRVTransaction; function GetDataset: IibSHDRVDataset; procedure SetDataset(Value: IibSHDRVDataset); property SQL: TStrings read GetSQL; property BTCLDatabase: IibSHDatabase read GetBTCLDatabase; property ResultType: string read GetResultType; property Transaction: IibSHDRVTransaction read GetTransaction; property Dataset: IibSHDRVDataset read GetDataset write SetDataset; end; *) IibSHDDLInfo = interface ['{65A0BEA3-7541-40B2-AC5C-BDE75B41E2F4}'] function GetDDL: TStrings; function GetBTCLDatabase: IibSHDatabase; function GetState: TSHDBComponentState; property DDL: TStrings read GetDDL; property BTCLDatabase: IibSHDatabase read GetBTCLDatabase; property State: TSHDBComponentState read GetState; end; TibSHDependenceType = (dtUsedBy, dtUses); IibSHDependencies = interface ['{74B5799D-25DD-4E99-82BA-CC795C59E166}'] procedure Execute(AType: TibSHDependenceType; const BTCLDatabase: IibSHDatabase; const AClassIID: TGUID; const ACaption: string; AOwnerCaption: string = ''); function GetObjectNames(const AClassIID: TGUID; AOwnerCaption: string = ''): TStrings; function IsEmpty: Boolean; end; IibSHPSQLDebugger = interface ['{C09789E6-ECED-4619-AB84-0C9F6FE5ACA9}'] function GetDebugComponent: TSHComponent; function GetDRVTransaction: IibSHDRVTransaction; function GetParentDebugger: IibSHPSQLDebugger; procedure Debug(AParentDebugger: IibSHPSQLDebugger; AClassIID: TGUID; ACaption: string); property DebugComponent: TSHComponent read GetDebugComponent; property DRVTransaction: IibSHDRVTransaction read GetDRVTransaction; property ParentDebugger: IibSHPSQLDebugger read GetParentDebugger; end; // ComponentForm Interfaces IibSHDDLForm = interface(ISHComponentForm) ['{0827E71A-4092-413D-B492-E7635EEFF74A}'] function GetDDLText: TStrings; procedure SetDDLText(Value: TStrings); function GetOnAfterRun: TNotifyEvent; procedure SetOnAfterRun(Value: TNotifyEvent); function GetOnAfterCommit: TNotifyEvent; procedure SetOnAfterCommit(Value: TNotifyEvent); function GetOnAfterRollback: TNotifyEvent; procedure SetOnAfterRollback(Value: TNotifyEvent); procedure PrepareControls; procedure ShowDDLText; property DDLText: TStrings read GetDDLText write SetDDLText; property OnAfterRun: TNotifyEvent read GetOnAfterRun write SetOnAfterRun; property OnAfterCommit: TNotifyEvent read GetOnAfterCommit write SetOnAfterCommit; property OnAfterRollback: TNotifyEvent read GetOnAfterRollback write SetOnAfterRollback; end; IibSHTableForm = interface(ISHComponentForm) ['{1CF92A26-33A4-47FE-A4C5-60DA5A8C7576}'] function GetDBComponent: TSHComponent; property DBComponent: TSHComponent read GetDBComponent; end; IibSHFieldOrderForm = interface(ISHComponentForm) ['{BC7DD945-4E9B-4B3C-8EF5-816B775FE7DF}'] function GetCanMoveUp: Boolean; function GetCanMoveDown: Boolean; procedure MoveUp; procedure MoveDown; property CanMoveUp: Boolean read GetCanMoveUp; property CanMoveDown: Boolean read GetCanMoveDown; end; IibSHDDLFinderForm = interface(ISHComponentForm) ['{69F2CDED-F120-4487-A8A8-E1A6BDEA4ACD}'] function GetCanShowNextResult: Boolean; function GetCanShowPrevResult: Boolean; procedure ShowNextResult; procedure ShowPrevResult; property CanShowNextResult: Boolean read GetCanShowNextResult; property CanShowPrevResult: Boolean read GetCanShowPrevResult; end; IibSHDDLGrantorForm = interface(ISHComponentForm) ['{5F480382-A026-4AEC-BA0F-DE23E684A78A}'] procedure RefreshPrivilegesForTree; procedure RefreshGrantsOnTree; end; IibSHSQLEditorForm = interface(ISHComponentForm) ['{5A59E816-B8DB-469A-AB3D-6A74B5CE97C7}'] function GetSQLText: string; procedure ShowPlan; procedure ShowTransactionCommited; procedure ShowTransactionRolledBack; procedure ShowStatistics; procedure ClearMessages; procedure InsertStatement(AText: string); procedure LoadLastContext; function GetCanPreviousQuery: Boolean; function GetCanNextQuery: Boolean; function GetCanPrepare: Boolean; function GetCanEndTransaction: Boolean; procedure PreviousQuery; procedure NextQuery; procedure RunAndFetchAll; procedure Prepare; property SQLText: string read GetSQLText; end; TibSHImageFormat = (imUnknown, imBitmap, imJPEG, imWMF, imEMF, imICO); IibSHDataCustomForm = interface(ISHComponentForm) ['{0E32EE91-9EF0-4EA3-A424-B245234F3609}'] function GetImageStreamFormat(AStream: TStream): TibSHImageFormat; function GetCanFilter: Boolean; function GetFiltered: Boolean; procedure SetFiltered(Value: Boolean); function GetAutoCommit: Boolean; procedure AddToResultEdit(AText: string; DoClear: Boolean = True); procedure SetDBGridOptions(ADBGrid: TComponent); property CanFilter: Boolean read GetCanFilter; property Filtered: Boolean read GetFiltered write SetFiltered; property AutoCommit: Boolean read GetAutoCommit; end; IibSHDataVCLForm = interface(ISHComponentForm) ['{7A2E7DD3-8B3B-46C7-AB4B-C870C68E20F0}'] function GetAutoAdjustNodeHeight: Boolean; procedure SetAutoAdjustNodeHeight(Value: Boolean); function GetCanSelectNextField: Boolean; function GetCanSelectPreviousField: Boolean; procedure SelectNextField; procedure SelectPreviouField; property AutoAdjustNodeHeight: Boolean read GetAutoAdjustNodeHeight write SetAutoAdjustNodeHeight; property CanSelectNextField: Boolean read GetCanSelectNextField; property CanSelectPreviousField: Boolean read GetCanSelectPreviousField; end; IibSHSQLPlayerForm = interface(ISHComponentForm) ['{D822F7E6-A064-432C-84D3-D9D9BE40FDCB}'] function GetCanRunCurrent: Boolean; function GetCanRunFromCurrent: Boolean; function GetCanRunFromFile: Boolean; function GetRegionVisible: Boolean; function ChangeNotification: Boolean; procedure CheckAll; procedure UnCheckAll; procedure InsertScript(AText: string); procedure RunCurrent; procedure RunFromCurrent; procedure RunFromFile; property CanRunCurrent: Boolean read GetCanRunCurrent; property CanRunFromCurrent: Boolean read GetCanRunFromCurrent; property CanRunFromFile: Boolean read GetCanRunFromFile; property RegionVisible: Boolean read GetRegionVisible; end; IibSHSQLMonitorForm = interface(ISHComponentForm) ['{8FED1B58-444C-4D2D-AE86-5736A09777E9}'] function CanJumpToApplication: Boolean; procedure JumpToApplication; end; IibSHStatisticsForm = interface(ISHComponentForm) ['{04B710E0-23BA-41BA-97D0-80CD938F8C8F}'] end; IibSHDMLHistoryForm = interface(ISHComponentForm) ['{A313ACC8-CFCF-4BFF-9801-555CBE0073C5}'] function GetRegionVisible: Boolean; procedure FillEditor; procedure ChangeNotification(AOldItem: Integer; Operation: TOperation); function GetCanSendToSQLEditor: Boolean; procedure SendToSQLEditor; property RegionVisible: Boolean read GetRegionVisible; end; IibSHDDLHistoryForm = interface(ISHComponentForm) ['{F3792938-57F4-46EC-B611-7BB622738EDB}'] function GetRegionVisible: Boolean; procedure FillEditor; procedure ChangeNotification; function GetCanSendToSQLPlayer: Boolean; procedure SendToSQLPlayer; function GetCanSendToSQLEditor: Boolean; procedure SendToSQLEditor; property RegionVisible: Boolean read GetRegionVisible; end; IibSHDMLExporterForm = interface(ISHComponentForm) ['{131962AA-B737-4693-852D-F9D0B717C72C}'] function GetCanMoveDown: Boolean; function GetCanMoveUp: Boolean; procedure UpdateTree; procedure CheckAll; procedure UnCheckAll; procedure MoveDown; procedure MoveUp; property CanMoveDown: Boolean read GetCanMoveDown; property CanMoveUp: Boolean read GetCanMoveUp; end; IibSHPSQLDebuggerForm = interface(ISHComponentForm) ['{49780B97-45EA-4FB0-88C9-847F0D9BE52E}'] function GetCanAddWatch: Boolean; function GetCanReset: Boolean; function GetCanRunToCursor: Boolean; function GetCanSetParameters: Boolean; function GetCanSkipStatement: Boolean; function GetCanStepOver: Boolean; function GetCanToggleBreakpoint: Boolean; function GetCanTraceInto: Boolean; function GetCanModifyVarValues: Boolean; function ChangeNotification: Boolean; procedure AddWatch; procedure Reset; procedure RunToCursor; procedure SetParameters; procedure SkipStatement; procedure StepOver; procedure ToggleBreakpoint; procedure ModifyVarValues; procedure TraceInto; property CanAddWatch: Boolean read GetCanAddWatch; property CanReset: Boolean read GetCanReset; property CanRunToCursor: Boolean read GetCanRunToCursor; property CanSetParameters: Boolean read GetCanSetParameters; property CanSkipStatement: Boolean read GetCanSkipStatement; property CanStepOver: Boolean read GetCanStepOver; property CanToggleBreakpoint: Boolean read GetCanToggleBreakpoint; property CanTraceInto: Boolean read GetCanTraceInto; end; implementation end.
unit Definitions; interface const {Comparison types} coEqual = 0; coGreaterThan = 1; coLessThan = 2; coGreaterThanOrEqual = 3; coLessThanOrEqual = 4; coNotEqual = 5; coBlank = 6; coNotBlank = 7; coContains = 8; coStartsWith = 9; coBetween = 10; coMatchesPartialOrFirstItemBlank = 11; coMatchesOrFirstItemBlank = 12; coDoesNotStartWith = 13; {Display Formats} DecimalDisplay = ',0.00'; DecimalEditDisplay = '0.00'; DecimalDisplay_BlankZero = ',0.00;,0.00;'''; DecimalEditDisplay_BlankZero = '0.00;"-"0.00;'''; NoDecimalDisplay_BlankZero = ',0.;,"-"0.;'''; NoDecimalDisplay = '0.'; DollarDecimalDisplay = '"$",0.'; DollarDecimalDisplay_BlankZero = '"$",0.;"$-",0.;'''; TimeFormat = 'hh:mm ampm'; DateFormat = 'm/d/yyyy'; {Ini file sections} sct_Components ='COMPONENTS'; emEdit = 'M'; emInsert = 'A'; emBrowse = 'V'; emDelete = 'D'; type TLocateOptionTypes = (loPartialKey, loChangeIndex, loSameEndingRange); TLocateOptions = set of TLocateOptionTypes; TTableOpenOptionTypes = (toExclusive, toReadOnly, toOpenAsIs, toNoReopen); TTableOpenOptions = set of TTableOpenOptionTypes; TInsertRecordOptionTypes = (irSuppressInitializeFields, irSuppressPost); TInsertRecordOptions = set of TInsertRecordOptionTypes; var GlblCurrentCommaDelimitedField : Integer; implementation initialization GlblCurrentCommaDelimitedField := 0; end.
unit AI.ListNode; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DeepStar.Utils, DeepStar.UString; type TListNode = class public Val: integer; Next: TListNode; constructor Create(x: integer); constructor Create(arr: TArr_int); destructor Destroy; override; function FindNdoe(v: integer): TListNode; function ToString: UString; reintroduce; procedure CLearAndFree; end; implementation { TListNode } constructor TListNode.Create(x: integer); begin Val := x; Next := nil; end; constructor TListNode.Create(arr: TArr_int); var cur: TListNode; i: integer; begin Assert(arr <> nil); Self.Val := arr[0]; cur := self; for i := 1 to High(arr) do begin cur.Next := TListNode.Create(arr[i]); cur := cur.Next; end; end; procedure TListNode.CLearAndFree; var cur, del: TListNode; begin cur := Self; while cur.Next <> nil do begin del := cur.Next; cur.Next := del.Next; FreeAndNil(del); end; Self.Free; end; destructor TListNode.Destroy; begin inherited Destroy; end; function TListNode.FindNdoe(v: integer): TListNode; var cur: TListNode; begin if Self = nil then exit(nil); if self.Val = v then Exit(self); cur := self.Next; while cur <> nil do begin if cur.Val = v then Break; cur := cur.Next; end; Result := cur; end; function TListNode.ToString: UString; var sb: TStringBuilder; cur: TListNode; begin Assert(Self <> nil); sb := TStringBuilder.Create; cur := Self; while cur <> nil do begin sb.Append(cur.Val.ToString); if cur.Next <> nil then sb.Append(' -> ') else sb.Append(' -> NULL'); cur := cur.Next; end; Result := UString(sb.ToString); sb.Free; end; end.
unit TextEditorFooter; interface uses SysUtils,Windows,Classes,CompileErrorManager,ComCtrls; type TEditMode=(emInsert,emOverwrite); IEditStateListener=interface(IInterfaceComponentReference) ['{D5CCEF7F-6E6C-4D92-831A-D69C6A9C1D58}'] procedure EditStateChanged; end; ITextEditor=interface ['{773F843B-7CAF-4BE9-9764-FB50607CD227}'] procedure RegisterEditStateListener(Listener:IEditStateListener); procedure UnregisterEditStateListener(Listener:IEditStateListener); function GetCaretPos:TPoint; property CaretPos:TPoint read GetCaretPos; function GetEditMode:TEditMode; property EditMode:TEditMode read GetEditMode; function GetModified:Boolean; property Modified:Boolean read GetModified; end; TTextEditorFooter=class(TCustomStatusBar,IEditStateListener) private FTextEditor: ITextEditor; procedure SetTextEditor(const Value: ITextEditor); protected procedure Notification(AComponent:TComponent;Operation:TOperation);override; procedure EditStateChanged; function GetComponent:TComponent; public constructor Create(AOwner:TComponent);override; destructor Destroy;override; published property TextEditor:ITextEditor read FTextEditor write SetTextEditor; end; implementation { TTextEditorFooter } constructor TTextEditorFooter.Create(AOwner: TCOmponent); begin inherited; with Panels do begin with Add do begin Alignment:=taCenter; Width:=85; end; with Add do begin Width:=70; end; with Add do begin Width:=70; end; with Add do begin Alignment:=taCenter; Width:=40; end; with Add do begin Alignment:=taCenter; Width:=40; end; Add; end; end; destructor TTextEditorFooter.Destroy; begin TextEditor:=nil; inherited; end; procedure TTextEditorFooter.EditStateChanged; const T1:array[False..True] of string=('','Modified'); T2:array[emInsert..emOverwrite] of string=('Insert','Overwrite'); T3:array[False..True] of string=('NUM',''); T4:array[False..True] of string=('CAPS',''); var a:Integer; begin if Assigned(FTextEditor) then begin with FTextEditor.CaretPos do Panels[0].Text:=IntToStr(X+1)+' : '+IntToStr(Y+1); Panels[1].Text:=T1[FTextEditor.Modified]; Panels[2].Text:=T2[FTextEditor.EditMode]; Panels[3].Text:=T3[GetKeyState(VK_NUMLOCK) and $1=0]; Panels[4].Text:=T4[GetKeyState(VK_CAPITAL) and $1=0]; end else for a:=0 to Panels.Count-1 do Panels[a].Text:=''; end; function TTextEditorFooter.GetComponent: TComponent; begin Result:=Self; end; procedure TTextEditorFooter.Notification(AComponent: TComponent; Operation: TOperation); begin if Assigned(FTextEditor) and Supports(FTextEditor,IInterfaceComponentReference) and ((FTextEditor as IInterfaceComponentReference).GetComponent=AComponent) then begin FTextEditor:=nil; EditStateChanged; end; inherited; end; procedure TTextEditorFooter.SetTextEditor(const Value: ITextEditor); begin if Assigned(FTextEditor) then FTextEditor.UnregisterEditStateListener(Self); FTextEditor := Value; if Assigned(FTextEditor) then begin FTextEditor.RegisterEditStateListener(Self); if Supports(FTextEditor,IInterfaceComponentReference) then (FTextEditor as IInterfaceComponentReference).GetComponent.FreeNotification(Self); end; EditStateChanged; end; end.
unit SDPartitionImage; interface uses Classes, SDUGeneral, SyncObjs, SysUtils, Windows; const DEFAULT_SECTOR_SIZE = 512; type EPartitionError = class (Exception); EPartitionNotMounted = class (EPartitionError); {$M+}// Required to get rid of compiler warning "W1055 PUBLISHED caused RTTI ($M+) to be added to type '%s'" TSDPartitionImage = class protected FMounted: Boolean; FSectorSize: Integer; FReadOnly: Boolean; FSerializeCS: TCriticalSection; // Protect by serializing read/write // operations in multithreaded operations procedure SetMounted(newMounted: Boolean); procedure AssertMounted(); function DoMount(): Boolean; virtual; procedure DoDismount(); virtual; function GetSize(): ULONGLONG; virtual; abstract; public constructor Create(); virtual; destructor Destroy(); override; function ReadSector(sectorID: uint64; sector: TStream; maxSize: Integer = -1): Boolean; virtual; function WriteSector(sectorID: uint64; sector: TStream; maxSize: Integer = -1): Boolean; virtual; function ReadConsecutiveSectors(startSectorID: uint64; sectors: TStream; maxSize: Integer = -1): Boolean; virtual; abstract; function WriteConsecutiveSectors(startSectorID: uint64; sectors: TStream; maxSize: Integer = -1): Boolean; virtual; abstract; function CopySector(srcSectorID: uint64; destSectorID: uint64): Boolean; published property Mounted: Boolean Read FMounted Write SetMounted; property ReadOnly: Boolean Read FReadOnly Write FReadOnly; property Size: ULONGLONG Read GetSize; property SectorSize: Integer Read FSectorSize Write FSectorSize; end; implementation uses SDUClasses; constructor TSDPartitionImage.Create(); begin inherited; FMounted := False; FSectorSize := DEFAULT_SECTOR_SIZE; FSerializeCS := TCriticalSection.Create(); end; destructor TSDPartitionImage.Destroy(); begin Mounted := False; FSerializeCS.Free(); inherited; end; function TSDPartitionImage.DoMount(): Boolean; begin FSerializeCS := TCriticalSection.Create(); Result := True; end; procedure TSDPartitionImage.DoDismount(); begin FSerializeCS.Free(); end; procedure TSDPartitionImage.SetMounted(newMounted: Boolean); begin inherited; if (newMounted <> Mounted) then begin if newMounted then begin FMounted := DoMount(); end else begin DoDismount(); FMounted := False; end; end; end; procedure TSDPartitionImage.AssertMounted(); begin inherited; if not (Mounted) then begin raise EPartitionNotMounted.Create('Partition not mounted'); end; end; function TSDPartitionImage.ReadSector(sectorID: uint64; sector: TStream; maxSize: Integer = -1): Boolean; begin Result := ReadConsecutiveSectors(sectorID, sector, maxSize); end; function TSDPartitionImage.WriteSector(sectorID: uint64; sector: TStream; maxSize: Integer = -1): Boolean; begin Result := WriteConsecutiveSectors(sectorID, sector, maxSize); end; function TSDPartitionImage.CopySector(srcSectorID: uint64; destSectorID: uint64): Boolean; var tmpSector: TSDUMemoryStream; begin Result := False; tmpSector := TSDUMemoryStream.Create(); try tmpSector.Position := 0; if ReadSector(srcSectorID, tmpSector) then begin tmpSector.Position := 0; Result := WriteSector(srcSectorID, tmpSector); end; finally tmpSector.Free(); end; end; end.
unit DynamicInspector; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, TypInfo, Dialogs, StdCtrls, dcgen, dcsystem, dcdsgnstuff, dcdsgnutil, dcedit, oinspect, CustomInspector, LrDynamicProperties; type TDynamicProperty = class(TCustomProperty) private FComponent: TPersistent; FItem: TLrDynamicPropertyItem; protected procedure SetItem(const Value: TLrDynamicPropertyItem); public function GetAttributes: TPropertyAttributes; override; function GetName: string; override; function GetValue: string; override; procedure Edit; override; procedure SetValue(const Value: string); override; property Component: TPersistent read FComponent write FComponent; property Item: TLrDynamicPropertyItem read FItem write SetItem; end; // TNewDynamicProperty = class(TCustomProperty) private FComponent: TPersistent; FInspector: TCustomInspector; FProperties: TLrDynamicProperties; public function GetAttributes: TPropertyAttributes; override; function GetName: string; override; function GetValue: string; override; procedure Edit; override; procedure SetValue(const Value: string); override; property Component: TPersistent read FComponent write FComponent; property Properties: TLrDynamicProperties read FProperties write FProperties; property Inspector: TCustomInspector read FInspector write FInspector; end; // TScriptEventProperty = class(TDynamicProperty) public class procedure SetCodeDesigner(inDesigner: TCodeDesigner); protected function GetCodeDesigner: TCodeDesigner; procedure RenameMethod(const inOldName, inNewName: string); procedure SetMethod(const inName: string); public procedure Edit; override; procedure SetValue(const Value: string); override; end; // TDynamicPropertyInspector = class(TCustomInspector) private FCollectionName: string; protected function CreateProperty(inType: TLrDynamicPropertyType): TDynamicProperty; function GetProperties(inComponent: TPersistent): TLrDynamicProperties; procedure AddNewProp(inComponent: TPersistent; inProperties: TLrDynamicProperties; Proc: TGetPropEditProc); procedure AddProps(inComponent: TPersistent; inProperties: TLrDynamicProperties; Proc: TGetPropEditProc); procedure GetAllPropertyEditors(Components: TComponentList; Filter: TTypeKinds; Designer: TFormDesigner; Proc: TGetPropEditProc); override; public constructor Create(inOwner: TComponent); override; published property BorderStyle; property CollectionName: string read FCollectionName write FCollectionName; end; implementation { TDynamicProperty } procedure TDynamicProperty.SetItem(const Value: TLrDynamicPropertyItem); begin FItem := Value; end; function TDynamicProperty.GetName: string; begin Result := Item.Name; end; function TDynamicProperty.GetValue: string; begin Result := Item.Value; end; procedure TDynamicProperty.SetValue(const Value: string); begin Item.Value := Value; end; function TDynamicProperty.GetAttributes: TPropertyAttributes; begin Result := inherited GetAttributes; end; procedure TDynamicProperty.Edit; begin // end; { TNewDynamicProperty } function TNewDynamicProperty.GetAttributes: TPropertyAttributes; begin Result := inherited GetAttributes; Include(Result, paDialog); end; function TNewDynamicProperty.GetName: string; begin Result := '(new property)'; end; function TNewDynamicProperty.GetValue: string; begin Result := '(use dialog)'; end; procedure TNewDynamicProperty.SetValue(const Value: string); begin //FNewEventName := Value; end; procedure TNewDynamicProperty.Edit; begin { with TAddJsEventForm.Create(nil) do try if ShowModal = mrOk then if Events.FindEvent(EventEdit.Text) = nil then begin Events.AddEvent.EventName := EventEdit.Text; Inspector.Rescan; end; finally Free; end; } end; { TScriptEventProperty } var CodeDesigner: TCodeDesigner; class procedure TScriptEventProperty.SetCodeDesigner(inDesigner: TCodeDesigner); begin CodeDesigner := inDesigner; end; function TScriptEventProperty.GetCodeDesigner: TCodeDesigner; begin Result := CodeDesigner; end; procedure TScriptEventProperty.SetValue(const Value: string); begin if (GetValue <> '') and (Value <> '') then RenameMethod(GetValue, Value) else if (Value <> '') then SetMethod(Value); inherited; end; procedure TScriptEventProperty.SetMethod(const inName: string); begin if CodeDesigner <> nil then with CodeDesigner do if MethodExists(inName) then ShowMethod(inName) else CreateMethod(inName, nil); end; procedure TScriptEventProperty.RenameMethod(const inOldName, inNewName: string); begin if CodeDesigner <> nil then with CodeDesigner do if MethodExists(inOldName) then begin RenameMethod(inOldName, inNewName); ShowMethod(inNewName); end else CreateMethod(inNewName, nil); end; procedure TScriptEventProperty.Edit; var n: string; begin n := GetValue; if n = '' then n := Component.GetNamePath + Copy(GetName, 3, MAXINT); SetValue(n); end; { TDynamicPropertyInspector } constructor TDynamicPropertyInspector.Create(inOwner: TComponent); begin inherited; Align := alClient; end; function TDynamicPropertyInspector.GetProperties( inComponent: TPersistent): TLrDynamicProperties; var ppi: PPropInfo; obj: TObject; begin Result := nil; if CollectionName = '' then ppi := nil else ppi := GetPropInfo(inComponent, CollectionName); if ppi <> nil then begin obj := GetObjectProp(inComponent, ppi); if (obj <> nil) and (obj is TLrDynamicProperties) then Result := TLrDynamicProperties(obj) end; end; function TDynamicPropertyInspector.CreateProperty( inType: TLrDynamicPropertyType): TDynamicProperty; const cPropClasses: array[ptString..ptEvent] of TClass = ( TDynamicProperty, TScriptEventProperty ); begin Result := TDynamicProperty(cPropClasses[inType].Create); end; procedure TDynamicPropertyInspector.AddProps(inComponent: TPersistent; inProperties: TLrDynamicProperties; Proc: TGetPropEditProc); var i: Integer; prop: TDynamicProperty; begin for i := 0 to Pred(inProperties.Count) do begin prop := CreateProperty(inProperties[i].PropertyType); prop.Component := inComponent; prop.Item := inProperties[i]; PropList.Add(prop); Proc(prop); end; end; procedure TDynamicPropertyInspector.AddNewProp(inComponent: TPersistent; inProperties: TLrDynamicProperties; Proc: TGetPropEditProc); var newprop: TNewDynamicProperty; begin newprop := TNewDynamicProperty.Create; newprop.Component := inComponent; newprop.Properties := inProperties; newprop.Inspector := Self; PropList.Add(newprop); Proc(newprop); end; procedure TDynamicPropertyInspector.GetAllPropertyEditors( Components: TComponentList; Filter: TTypeKinds; Designer: TFormDesigner; Proc: TGetPropEditProc); var c: TPersistent; p: TLrDynamicProperties; begin PropList.Clear; if Components.Count > 0 then begin c := Components[0]; p := GetProperties(c); if (p <> nil) then begin AddProps(c, p, Proc); if p.Extendable then AddNewProp(c, p, Proc); end; end; end; end.
// Copyright (c) 2009, ConTEXT Project Ltd // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. unit uCommonClass; interface {$I ConTEXT.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, ImgList, uCommon, SynEditTypes, uSafeRegistry; type TFileData = class private fIconIndex :integer; fIsDirectory :boolean; fFileName :string; procedure SetFileName(Value:string); public constructor Create(AFileName:string); virtual; property FileName :string read fFileName write SetFileName; property IconIndex :integer read fIconIndex; property IsDirectory :boolean read fIsDirectory; end; TBookmark = class Index :integer; X :integer; Y :integer; function GetFormattedString:string; end; TBookmarkList = class private FItems :TList; function GetItem(Index: integer): TBookmark; function GetCount: integer; public constructor Create; destructor Destroy; override; procedure Add(Index,X,Y:integer); procedure Clear; function SaveToFormattedList:TStringList; property Count :integer read GetCount; property Items[Index:integer] :TBookmark read GetItem; default; end; TFindTextResult = class private fFileName: string; fPosition: TBufferCoord; fLine: string; fLen: integer; fFormattedLine: string; fOriginalLine: string; public constructor Create(FileName, Line: string; Position: TBufferCoord; Len: integer); property FileName: string read fFileName; property Line: string read fLine; property FormattedLine: string read fFormattedLine write fFormattedLine; property OriginalLine: string read fOriginalLine write fOriginalLine; property Position: TBufferCoord read fPosition; property Len: integer read fLen; end; TFindTextResultList = class(TList) private fSharedItems: boolean; function Get(Index: integer): TFindTextResult; procedure Put(Index: integer; const Value: TFindTextResult); public procedure Clear; override; property SharedItems: boolean read fSharedItems write fSharedItems; property Items[Index: integer]: TFindTextResult read Get write Put; default; end; TEditorOptions = class private public end; implementation uses fMain; //////////////////////////////////////////////////////////////////////////////////////////// // TFileData //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ constructor TFileData.Create(AFileName:string); begin FileName:=AFileName; fIsDirectory:=(FileGetAttr(FileName) and faDirectory)>0; end; //------------------------------------------------------------------------------------------ procedure TFileData.SetFileName(Value:string); begin if (fFileName<>Value) then begin fFileName:=Value; fIconIndex:=fmMain.FileIconPool.GetIconIndex(FileName); end; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // TBookmark //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ function TBookmark.GetFormattedString: string; begin result:=Format('(%d:%d,%d);',[Index,X,Y]); end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // TBookmark //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ constructor TBookmarkList.Create; begin FItems:=TList.Create; end; //------------------------------------------------------------------------------------------ destructor TBookmarkList.Destroy; begin Clear; FItems.Free; inherited; end; //------------------------------------------------------------------------------------------ function TBookmarkList.GetCount: integer; begin result:=FItems.Count; end; //------------------------------------------------------------------------------------------ function TBookmarkList.GetItem(Index: integer): TBookmark; begin if (Index>=0) and (Index<Count) then result:=FItems[Index] else result:=nil; end; //------------------------------------------------------------------------------------------ procedure TBookmarkList.Add(Index, X, Y: integer); var bm :TBookmark; begin bm:=TBookmark.Create; bm.Index:=Index; bm.X:=X; bm.Y:=Y; FItems.Add(bm); end; //------------------------------------------------------------------------------------------ procedure TBookmarkList.Clear; var i :integer; begin for i:=0 to Count-1 do Items[i].Free; FItems.Clear; end; //------------------------------------------------------------------------------------------ function TBookmarkList.SaveToFormattedList:TStringList; var str :TStringList; i :integer; bm :TBookmark; begin str:=TStringList.Create; str.Add('BookmarkCount='+IntToStr(Count)); for i:=0 to Count-1 do begin bm:=Items[i]; str.Add(Format('Bookmark%dIndex=%d',[i,bm.Index])); str.Add(Format('Bookmark%dX=%d',[i,bm.X])); str.Add(Format('Bookmark%dY=%d',[i,bm.Y])); end; result:=str; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // TFindTextResult //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ constructor TFindTextResult.Create(FileName, Line: string; Position: TBufferCoord; Len: integer); begin fFileName:=FileName; fPosition:=Position; fLine:=Line; fLen:=Len; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // TFindTextResultList //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ procedure TFindTextResultList.Clear; var i: integer; begin if not fSharedItems then for i:=0 to Count-1 do Items[i].Free; inherited; end; //------------------------------------------------------------------------------------------ function TFindTextResultList.Get(Index: integer): TFindTextResult; begin result:=inherited Get(Index); end; //------------------------------------------------------------------------------------------ procedure TFindTextResultList.Put(Index: integer; const Value: TFindTextResult); begin inherited Put(Index, Value); end; //------------------------------------------------------------------------------------------ end.
unit kiwi.s3.client; interface uses System.SysUtils, System.DateUtils, System.StrUtils, System.Types, System.UITypes, System.Classes, System.NetEncoding, System.Net.URLClient, System.Hash, idhttp, Data.Cloud.CloudAPI, Data.Cloud.AmazonAPI, Xml.XMLIntf, Xml.XMLDoc, kiwi.s3.interfaces; type tkiwiS3Client = class(tinterfacedobject, ikiwiS3Client) private { private declarations } fconnIdhttp: tidhttp; fstraccountName: string; fstraccountKey: string; fstrBucket: string; fstrRegion: string; fbooAccelerate: boolean; { functions } function buildHeaders(pbooAccelerate: boolean): tstringList; { functions componente tamazonstorageservice } function isoDateTimenoSeparators: string; function buildStringToSignHeaders(Headers: TStringList): string; function buildQueryParameterString(const QueryPrefix: string; QueryParameters: TStringList; DoSort: Boolean = False; ForURL: Boolean = True): string; function buildStringToSign(const HTTPVerb, Region: string; Headers, QueryParameters: TStringList; const QueryPrefix, URL: string): string; function getAuthorization(const accountName, accountKey, stringToSign, dateISO, region, serviceName, signedStrHeaders: string): string; function parseResponseError(pstrResponse, pstrResultString: string): string; procedure sortHeaders(const Headers: TStringList); procedure urlEncodeQueryParams(const ForURL: Boolean; var ParamName, ParamValue: string); public { public declarations } constructor Create(accountName, accountKey, region, bucket: string; accelerate: boolean = false); destructor Destroy; override; class function new(accountName, accountKey, region, bucket: string; accelerate: boolean = false): ikiwiS3Client; property AccountName: string read fstraccountName write fstraccountName; property AccountKey: string read fstraccountKey write fstraccountKey; property Bucket: string read fstrBucket write fstrBucket; property Region: string read fstrRegion write fstrRegion; property Accelerate: boolean read fbooAccelerate write fbooAccelerate; function get(const pstrObjectName: string; var pstrmResult: tmemorystream; var pstrError: string): boolean; function upload(const pstrObjectName: string; var pstrmMemoryFile: tmemorystream; var pstrError: string; pslmetaData: tstrings = nil): boolean; function delete(const pstrObjectName: string; var pstrError: string): boolean; function properties(pstrObjectName: string; var pstrsProperties, pstrsMetadata: tstringlist): boolean; end; var kiwiS3Client: tkiwiS3Client; implementation function CaseSensitiveHyphenCompare(List: TStringList; Index1, Index2: Integer): Integer; begin if List <> nil then //case sensitive stringSort is needed to sort with hyphen (-) precedence Result := string.Compare(List.Strings[Index1], List.Strings[Index2], [coStringSort]) else Result := 0; end; { TAmazonS3 } function tkiwiS3Client.buildQueryParameterString(const QueryPrefix: string; QueryParameters: TStringList; DoSort, ForURL: Boolean): string; var Count: Integer; I: Integer; lastParam, nextParam: string; QueryStartChar, QuerySepChar, QueryKeyValueSepChar: Char; CurrValue: string; CommaVal: string; begin try //if there aren't any parameters, just return the prefix if not Assigned(QueryParameters) or (QueryParameters.Count = 0) then Exit(QueryPrefix); if ForURL then begin //If the query parameter string is beign created for a URL, then //we use the default characters for building the strings, as will be required in a URL QueryStartChar := '?'; QuerySepChar := '&'; QueryKeyValueSepChar := '='; end else begin //otherwise, use the charaters as they need to appear in the signed string QueryStartChar := '?'; QuerySepChar := '&'; QueryKeyValueSepChar := '='; end; {if DoSort and not QueryParameters.Sorted then SortQueryParameters(QueryParameters, ForURL);} Count := QueryParameters.Count; lastParam := QueryParameters.Names[0]; CurrValue := Trim(QueryParameters.ValueFromIndex[0]); //URL Encode the firs set of params urlEncodeQueryParams(ForURL, lastParam, CurrValue); //there is at least one parameter, so add the query prefix, and then the first parameter //provided it is a valid non-empty string name Result := QueryPrefix; if CurrValue <> EmptyStr then Result := Result + Format('%s%s%s%s', [QueryStartChar, lastParam, QueryKeyValueSepChar, CurrValue]) else Result := Result + Format('%s%s', [QueryStartChar, lastParam]); //in the URL, the comma character must be escaped. In the StringToSign, it shouldn't be. //this may need to be pulled out into a function which can be overridden by individual Cloud services. if ForURL then CommaVal := '%2c' else CommaVal := ','; //add the remaining query parameters, if any for I := 1 to Count - 1 do begin nextParam := Trim(QueryParameters.Names[I]); CurrValue := QueryParameters.ValueFromIndex[I]; urlEncodeQueryParams(ForURL, nextParam, CurrValue); //match on key name only if the key names are not empty string. //if there is a key with no value, it should be formatted as in the else block if (lastParam <> EmptyStr) and (AnsiCompareText(lastParam, nextParam) = 0) then Result := Result + CommaVal + CurrValue else begin if (not ForURL) or (nextParam <> EmptyStr) then begin if CurrValue <> EmptyStr then Result := Result + Format('%s%s%s%s', [QuerySepChar, nextParam, QueryKeyValueSepChar, CurrValue]) else Result := Result + Format('%s%s', [QuerySepChar, nextParam]); end; lastParam := nextParam; end; end; except raise; end; end; function tkiwiS3Client.buildStringToSign(const HTTPVerb, Region: string; Headers, QueryParameters: TStringList; const QueryPrefix, URL: string): string; var CanRequest, Scope, LdateISO, Ldate, Lregion : string; URLrec : TURI; LParams: TStringList; VPParam : TNameValuePair; begin //URLrec := nil; LParams := nil; try try //Build the first part of the string to sign, including HTTPMethod CanRequest := HTTPVerb+ #10; //find and encode the requests resource URLrec := TURI.Create(URL); //CanonicalURI URL encoded CanRequest := CanRequest + TNetEncoding.URL.EncodePath(URLrec.Path, [Ord('"'), Ord(''''), Ord(':'), Ord(';'), Ord('<'), Ord('='), Ord('>'), Ord('@'), Ord('['), Ord(']'), Ord('^'), Ord('`'), Ord('{'), Ord('}'), Ord('|'), Ord('/'), Ord('\'), Ord('?'), Ord('#'), Ord('&'), Ord('!'), Ord('$'), Ord('('), Ord(')'), Ord(',')]) + #10; //CanonicalQueryString encoded if not URLrec.Query.IsEmpty then begin if Length(URLrec.Params) = 1 then CanRequest := CanRequest + URLrec.Query + #10 else begin LParams := TStringList.Create; for VPParam in URLrec.Params do LParams.Append(VPParam.Name+'='+VPParam.Value); CanRequest := CanRequest + buildQueryParameterString('', LParams,true,false).Substring(1) + #10 end; end else CanRequest := CanRequest + #10; //add sorted headers and header names in series for signedheader part CanRequest := CanRequest + buildStringToSignHeaders(Headers) + #10; CanRequest := CanRequest + Headers.Values['x-amz-content-sha256']; LdateISO := Headers.Values['x-amz-date']; Ldate := Leftstr(LdateISO,8); Lregion := Region; Scope := Ldate + '/'+Lregion+ '/s3' + '/aws4_request'; Result := 'AWS4-HMAC-SHA256' + #10 + LdateISO + #10 + Scope + #10 + TCloudSHA256Authentication.GetHashSHA256Hex(CanRequest); except raise; end; finally if LParams <> nil then freeandnil(LParams); //if URLrec <> nil then //freeandnil(URLrec); end; end; function tkiwiS3Client.buildStringToSignHeaders(Headers: TStringList): string; var RequiredHeadersInstanceOwner: Boolean; RequiredHeaders: TStringList; I, ReqCount: Integer; Aux: string; lastParam, nextParam, ConHeadPrefix: string; begin RequiredHeaders := nil; try try //AWS always has required headers RequiredHeaders := TStringList.create; RequiredHeaders.Add('host'); RequiredHeaders.Add('x-amz-content-sha256'); RequiredHeaders.Add('x-amz-date'); Assert(RequiredHeaders <> nil); Assert(Headers <> nil); //if (Headers = nil) then // Headers.AddStrings(RequiredHeaders); //AWS4 - content-type must be included in string to sign if found in headers if Headers.IndexOfName('content-type') > -1 then //Headers.Find('content-type',Index) then RequiredHeaders.Add('content-type'); if Headers.IndexOfName('content-md5') > -1 then RequiredHeaders.Add('content-md5'); RequiredHeaders.Sorted := True; RequiredHeaders.Duplicates := TDuplicates.dupIgnore; ConHeadPrefix := 'x-amz-';{AnsiLowerCase(GetCanonicalizedHeaderPrefix);} for I := 0 to Headers.Count - 1 do begin Aux := AnsiLowerCase(Headers.Names[I]); if AnsiStartsStr(ConHeadPrefix, Aux) then RequiredHeaders.Add(Aux); end; RequiredHeaders.Sorted := False; //custom sorting sortHeaders(RequiredHeaders); ReqCount := RequiredHeaders.Count; //AWS4 get value pairs (ordered + lowercase) if (Headers <> nil) then begin for I := 0 to ReqCount - 1 do begin Aux := AnsiLowerCase(RequiredHeaders[I]); if Headers.IndexOfName(Aux) < 0 then raise Exception.Create('Missing Required Header: '+RequiredHeaders[I]); nextParam := Aux; if lastParam = EmptyStr then begin lastParam := nextParam; Result := Result + Format('%s:%s', [nextParam, Headers.Values[lastParam]]); end else begin lastParam := nextParam; Result := Result + Format(#10'%s:%s', [nextParam, Headers.Values[lastParam]]); end; end; if lastParam <> EmptyStr then Result := Result + #10''; end; // string of header names Result := Result + #10''; for I := 0 to ReqCount - 1 do begin Result := Result + Format('%s;', [RequiredHeaders[I]]); end; SetLength(Result,Length(Result)-1); except raise; end; finally if RequiredHeaders <> nil then freeandnil(RequiredHeaders); end; end; function tkiwiS3Client.buildHeaders(pbooAccelerate: boolean): tstringlist; begin result := TStringList.Create; result.CaseSensitive := false; result.Duplicates := TDuplicates.dupIgnore; if pbooAccelerate then result.Values['host'] := fstrBucket + '.s3-accelerate.amazonaws.com' else result.Values['host'] := fstrBucket + '.s3.amazonaws.com'; result.Values['x-amz-content-sha256'] := 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'; // empty string result.Values['x-amz-date'] := isoDateTimenoSeparators; result.Values['x-amz-acl'] := 'private'; end; constructor tkiwiS3Client.Create(accountName, accountKey, region, bucket: string; accelerate: boolean = false); begin fstraccountName := accountName; fstraccountKey := accountKey; fstrBucket := bucket; fstrRegion := region; fbooAccelerate := accelerate; fconnIdhttp := tidhttp.Create(nil); fconnIdhttp.ProtocolVersion := pv1_1; fconnIdhttp.Request.ContentType := 'application/octet-stream'; fconnIdhttp.Request.BasicAuthentication := False; end; function tkiwiS3Client.delete(const pstrObjectName: string; var pstrError: string): boolean; var l_str_meta_name : string; l_str_url_file : string; l_str_queryprefix : string; l_str_string_sign : string; l_str_authorization : string; l_str_signed_headers: string; l_int_count : integer; l_sl_headers : TStringList; l_content_stream : TBytesStream; begin result := false; l_sl_headers := nil; l_content_stream := nil; try try { create headers } l_sl_headers := buildHeaders(false); { authorization } l_str_url_file := 'http://'+l_sl_headers.Values['host']+ '/' + pstrObjectName.trim; l_str_queryprefix := '/'+ fstrBucket + '/' + pstrObjectName.trim; l_str_string_sign := buildStringToSign('DELETE', fstrRegion, l_sl_headers, nil, l_str_queryprefix, l_str_url_file); for l_int_count := 0 to l_sl_headers.Count - 1 do if AnsiStartsText('x-amz-', l_sl_headers.names[l_int_count]) or (l_sl_headers.names[l_int_count] = 'host') then l_str_signed_headers := l_str_signed_headers + l_sl_headers.names[l_int_count] + ';'; l_str_signed_headers := copy(l_str_signed_headers,0, length(l_str_signed_headers)-1); l_str_authorization := getAuthorization(fstraccountName, fstraccountKey, l_str_string_sign, formatdatetime('yyyyMMdd', TTimeZone.Local.ToUniversalTime(Now)), fstrRegion, 's3', l_str_signed_headers); { delete } fconnIdhttp.Request.CustomHeaders.Clear; fconnIdhttp.Request.BasicAuthentication := False; fconnIdhttp.Request.CustomHeaders.Values['Authorization'] := l_str_authorization; for l_int_count := 0 to l_sl_headers.Count -1 do fconnIdhttp.Request.CustomHeaders.values[l_sl_headers.Names[l_int_count]] := l_sl_headers.ValueFromIndex[l_int_count]; try fconnIdhttp.delete(l_str_url_file, l_content_stream); except end; if fconnIdhttp.Response = nil then exit; if not(fconnIdhttp.Response.ResponseCode in [100, 200]) then pstrError := fconnIdhttp.Response.ResponseText else result := true; except on e: exception do begin if pstrError.Trim <> '' then pstrError := pstrError + ', '+ e.message else pstrError := e.message; end; end; finally if l_sl_headers <> nil then freeandnil(l_sl_headers); end; end; destructor tkiwiS3Client.Destroy; begin if fconnIdhttp <> nil then freeandnil(fconnIdhttp); inherited; end; function tkiwiS3Client.get(const pstrObjectName: string; var pstrmResult: tmemorystream; var pstrError: string): boolean; var lslHeaders: tstringList; lintCount: integer; lstrUrlFile: string; lstrQueryPrefix: string; lstrSignedHeaders: string; lstrAuthorization: string; lstrStringSign: string; lconnIdhttp: tidhttp; begin result := false; lslHeaders := nil; try try if pstrmResult = nil then exit; { create headers } lslHeaders := buildHeaders(false); { authorization } lstrUrlFile := 'http://'+lslHeaders.Values['host']+ '/' + pstrObjectName.trim; lstrQueryPrefix := '/'+ fstrBucket + '/' + pstrObjectName.trim; lstrStringSign := buildStringToSign('GET', fstrRegion, lslHeaders, nil, lstrQueryPrefix, lstrUrlFile); for lintCount := 0 to lslHeaders.Count - 1 do if AnsiStartsText('x-amz-', lslHeaders.names[lintCount]) or (lslHeaders.names[lintCount] = 'host') then lstrSignedHeaders := lstrSignedHeaders + lslHeaders.names[lintCount] + ';'; lstrSignedHeaders := copy(lstrSignedHeaders,0, length(lstrSignedHeaders)-1); lstrAuthorization := getAuthorization(fstraccountName, fstraccountKey, lstrStringSign, formatdatetime('yyyyMMdd', TTimeZone.Local.ToUniversalTime(Now)), fstrRegion, 's3', lstrSignedHeaders); { get } lconnIdhttp := tidhttp.Create(nil); lconnIdhttp.ProtocolVersion := pv1_1; lconnIdhttp.Request.ContentType := 'application/octet-stream'; lconnIdhttp.Request.BasicAuthentication := False; lconnIdhttp.Request.CustomHeaders.Clear; lconnIdhttp.Request.BasicAuthentication := False; lconnIdhttp.Request.CustomHeaders.Values['Authorization'] := lstrAuthorization; for lintCount := 0 to lslHeaders.Count -1 do lconnIdhttp.Request.CustomHeaders.values[lslHeaders.Names[lintCount]] := lslHeaders.ValueFromIndex[lintCount]; try lconnIdhttp.get(lstrUrlFile, pstrmResult, [404]); except end; if lconnIdhttp.Response = nil then exit; if not(lconnIdhttp.Response.ResponseCode in [100, 200]) then pstrError := lconnIdhttp.Response.ResponseText else result := true; except on e: exception do begin if pstrError.Trim <> '' then pstrError := pstrError + ', '+ e.message else pstrError := e.message; end; end; finally if lslHeaders <> nil then freeandnil(lslHeaders); if lconnIdhttp <> nil then freeandnil(lconnIdhttp); end; end; function tkiwiS3Client.properties(pstrObjectName: string; var pstrsProperties, pstrsMetadata: tstringlist): boolean; var lstrMetaName: string; lstrUrlFile: string; lstrQueryPrefix: string; lstrStringSign: string; lstrAuthorization: string; lstrSignedHeaders: string; lstrHeaderName: string; lintCount: integer; lslHeaders: tstringList; begin result := false; lslHeaders := nil; try try { create headers } lslHeaders := buildHeaders(false); { authorization } lstrUrlFile := 'http://'+lslHeaders.Values['host']+ '/' + pstrObjectName.trim; lstrQueryPrefix := '/'+ fstrBucket + '/' + pstrObjectName.trim; lstrStringSign := buildStringToSign('HEAD', fstrRegion, lslHeaders, nil, lstrQueryPrefix, lstrUrlFile); for lintCount := 0 to lslHeaders.Count - 1 do if AnsiStartsText('x-amz-', lslHeaders.names[lintCount]) or (lslHeaders.names[lintCount] = 'host') then lstrSignedHeaders := lstrSignedHeaders + lslHeaders.names[lintCount] + ';'; lstrSignedHeaders := copy(lstrSignedHeaders,0, length(lstrSignedHeaders)-1); lstrAuthorization := getAuthorization(fstraccountName, fstraccountKey, lstrStringSign, formatdatetime('yyyyMMdd', TTimeZone.Local.ToUniversalTime(Now)), fstrRegion, 's3', lstrSignedHeaders); { head } fconnIdhttp.Request.CustomHeaders.Clear; fconnIdhttp.Request.BasicAuthentication := False; fconnIdhttp.Request.CustomHeaders.Values['Authorization'] := lstrAuthorization; for lintCount := 0 to lslHeaders.Count -1 do fconnIdhttp.Request.CustomHeaders.values[lslHeaders.Names[lintCount]] := lslHeaders.ValueFromIndex[lintCount]; try fconnIdhttp.head(lstrUrlFile); except end; if (fconnIdhttp.Response <> nil) and (fconnIdhttp.Response.ResponseCode = 200) then begin result := true; if pstrsProperties = nil then pstrsProperties := tstringlist.create; pstrsProperties.CaseSensitive := false; pstrsProperties.Duplicates := TDuplicates.dupIgnore; if pstrsMetadata = nil then pstrsMetadata := tstringlist.create; pstrsMetadata.CaseSensitive := false; pstrsMetadata.Duplicates := TDuplicates.dupIgnore; for lintCount := 0 to fconnIdhttp.Response.RawHeaders.Count - 1 do begin lstrHeaderName := fconnIdhttp.Response.RawHeaders.Names[lintCount]; if AnsiStartsText('x-amz-meta-', lstrHeaderName ) then begin //strip the "x-amz-meta-" prefix from the name of the header, //to get the original metadata header name, as entered by the user. pstrsMetadata.Values[lstrHeaderName.Substring(11)] := fconnIdhttp.Response.RawHeaders.Values[lstrHeaderName]; end else pstrsProperties.Values[lstrHeaderName ] := fconnIdhttp.Response.RawHeaders.Values[lstrHeaderName]; end; end; except end; finally if lslHeaders <> nil then freeandnil(lslHeaders); end; end; function tkiwiS3Client.getAuthorization(const accountName, accountKey, stringToSign, dateISO, region, serviceName, signedStrHeaders: string): string; function SignString(const Signkey: TBytes; const StringToSign: string): TBytes; begin Result := THashSHA2.GetHMACAsBytes(StringToSign, Signkey); end; function GetSignatureKey(const accountkey, datestamp, region, serviceName: string): TBytes; begin Result := SignString(TEncoding.Default.GetBytes('AWS4'+AccountKey), datestamp); //'20130524' Result := SignString(Result, region); Result := SignString(Result, serviceName); Result := SignString(Result, 'aws4_request'); end; var l_byte_signing_key: TBytes; l_str_Credentials: string; l_str_signedheaders: string; l_str_signature: string; begin try l_byte_signing_key := GetSignatureKey(accountKey, dateISO, region, serviceName); l_str_Credentials := 'Credential='+accountName + '/'+ dateISO + '/'+region+ '/' + serviceName + '/aws4_request'+','; l_str_signedheaders := 'SignedHeaders='+signedStrHeaders + ','; l_str_signature := 'Signature='+THash.DigestAsString(SignString(l_byte_signing_key, stringToSign)); Result := 'AWS4-HMAC-SHA256 '+ l_str_Credentials + l_str_signedheaders + l_str_signature; except raise; end; end; function tkiwiS3Client.isoDateTimenoSeparators: string; begin Result := DateToISO8601(TTimeZone.Local.ToUniversalTime(Now),True); Result := StringReplace(Result,'-','',[rfReplaceAll]); Result := StringReplace(Result,'+','',[rfReplaceAll]); Result := StringReplace(Result,':','',[rfReplaceAll]); Result := LeftStr(Result,Pos('.',Result)-1)+'Z'; end; class function tkiwiS3Client.new(accountName, accountKey, region, bucket: string; accelerate: boolean): ikiwiS3Client; begin result := self.create(accountName, accountKey, region, bucket, accelerate); end; function tkiwiS3Client.parseResponseError(pstrResponse, pstrResultString: string): string; var xmlDoc: IXMLDocument; Aux, ErrorNode, MessageNode: IXMLNode; ErrorCode, ErrorMsg: string; begin //If the ResponseInfo instance exists (to be populated) and the passed in string is Error XML, then //continue, otherwise exit doing nothing. if (pstrResultString = EmptyStr) then Exit; if (AnsiPos('<Error', pstrResultString) > 0) then begin xmlDoc := TXMLDocument.Create(nil); try xmlDoc.LoadFromXML(pstrResultString); except //Response content isn't XML Exit; end; //Amazon has different formats for returning errors as XML ErrorNode := xmlDoc.DocumentElement; if (ErrorNode <> nil) and (ErrorNode.HasChildNodes) then begin MessageNode := ErrorNode.ChildNodes.FindNode('Message'); if (MessageNode <> nil) then ErrorMsg := MessageNode.Text; if ErrorMsg <> EmptyStr then begin //Populate the error code Aux := ErrorNode.ChildNodes.FindNode('Code'); if (Aux <> nil) then ErrorCode := Aux.Text; result := Format('%s - %s (%s)', [pstrResponse, ErrorMsg, ErrorCode]); end; end; end end; procedure tkiwiS3Client.sortHeaders(const Headers: TStringList); begin if (Headers <> nil) then begin Headers.CustomSort(CaseSensitiveHyphenCompare); end; end; function tkiwiS3Client.upload(const pstrObjectName: string; var pstrmMemoryFile: tmemorystream; var pstrError: string; pslmetaData: tstrings = nil): boolean; var lstrMetaName: string; lstrUrlFile: string; lstrQueryPrefix: string; lstrStringSign: string; lstrAuthorization: string; lstrSignedHeaders: string; lstrResultMessage: string; lintCount: integer; lslHeaders: tstringList; lContentStream: tbytesStream; begin result := false; lslHeaders := nil; lContentStream := nil; try try if pstrmMemoryFile = nil then exit; { load file } lContentStream := TBytesStream.Create; pstrmMemoryFile.Position := 0; lContentStream.LoadFromstream(pstrmMemoryFile); { create headers } lslHeaders := buildHeaders(fbooAccelerate); lslHeaders.Values['x-amz-content-sha256'] := TCloudSHA256Authentication.GetStreamToHashSHA256Hex(lContentStream); lslHeaders.Values['content-length'] := lContentStream.Size.tostring; if pSlMetaData <> nil then for lintCount := 0 to pSlMetaData.Count - 1 do begin lstrMetaName := pSlMetaData.Names[lintCount]; if not AnsiStartsText('x-amz-meta-', lstrMetaName) then lstrMetaName := 'x-amz-meta-' + lstrMetaName; lslHeaders.Values[lstrMetaName] := pSlMetaData.ValueFromIndex[lintCount]; end; { authorization } lstrUrlFile := 'http://'+lslHeaders.Values['host']+ '/' + pstrObjectName.trim; lstrQueryPrefix := '/'+ fstrBucket + '/' + pstrObjectName.trim; lstrStringSign := buildStringToSign('PUT', fstrRegion, lslHeaders, nil, lstrQueryPrefix, lstrUrlFile); for lintCount := 0 to lslHeaders.Count - 1 do if AnsiStartsText('x-amz-', lslHeaders.names[lintCount]) or (lslHeaders.names[lintCount] = 'host') then lstrSignedHeaders := lstrSignedHeaders + lslHeaders.names[lintCount] + ';'; lstrSignedHeaders := copy(lstrSignedHeaders,0, length(lstrSignedHeaders)-1); lstrAuthorization := getAuthorization(fstraccountName, fstraccountKey, lstrStringSign, formatdatetime('yyyyMMdd', TTimeZone.Local.ToUniversalTime(Now)), fstrRegion, 's3', lstrSignedHeaders); { put } fconnIdhttp.Request.CustomHeaders.Clear; fconnIdhttp.Request.BasicAuthentication := False; fconnIdhttp.Request.CustomHeaders.Values['Authorization'] := lstrAuthorization; for lintCount := 0 to lslHeaders.Count -1 do fconnIdhttp.Request.CustomHeaders.values[lslHeaders.Names[lintCount]] := lslHeaders.ValueFromIndex[lintCount]; try lContentStream.position := 0; lstrResultMessage := fconnIdhttp.put(lstrUrlFile, lContentStream); except end; if fconnIdhttp.Response = nil then exit; if not(fconnIdhttp.Response.ResponseCode in [100, 200]) then begin pstrError := parseResponseError(fconnIdhttp.Response.ResponseText,lstrResultMessage); if pstrError.trim = '' then pstrError := fconnIdhttp.Response.ResponseText; end else result := true; except on e: exception do begin if pstrError.Trim <> '' then pstrError := pstrError + ', '+ e.message else pstrError := e.message; if lstrResultMessage.Trim <> '' then pstrError := pstrError + ', '+ lstrResultMessage; end; end; finally if lslHeaders <> nil then freeandnil(lslHeaders); if lContentStream <> nil then freeandnil(lContentStream); end; end; procedure tkiwiS3Client.urlEncodeQueryParams(const ForURL: Boolean; var ParamName, ParamValue: string); begin ParamName := URLEncode(ParamName, ['=']); ParamValue := URLEncode(ParamValue, ['=']); end; end.
unit UResponsavelVO; interface uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO, UPessoasVO, UCondominioVO; type [TEntity] [TTable('Responsavel')] TResponsavelVO = class(TGenericVO) private FidResponsavel : Integer; FidCondominio : Integer; FidPessoa : Integer; FOcupacao : String; FdtEntrada : TDateTime; FdtSaida : TDateTime; FRespReceita : String; Fnome : String; public PessoaVO : TPessoasVO; CondominioVO : TCondominioVO; [TId('idResponsavel')] [TGeneratedValue(sAuto)] property idResponsavel : Integer read FidResponsavel write FidResponsavel; [TColumn('nome','Pessoa',250,[ldGrid], True, 'Pessoa', 'idPessoa', 'idPessoa')] property Nome: string read FNome write FNome; [TColumn('idCondominio','Condominio',0,[ldLookup,ldComboBox], False)] property idCondominio: integer read FidCondominio write FidCondominio; [TColumn('idPessoa','Pessoa',0,[ldLookup,ldComboBox], False)] property idPessoa: integer read FidPessoa write FidPessoa; [TColumn('Ocupacao','Ocupação',180,[ldGrid,ldLookup,ldComboBox], False)] property Ocupacao: string read FOcupacao write FOcupacao; [TColumn('dtEntrada','Data Entrada',20,[ldGrid, ldLookup,ldComboBox], False)] property dtEntrada: TDateTime read FdtEntrada write FdtEntrada; [TColumn('dtSaida','Data Saida',0,[ ldLookup,ldComboBox], False)] property dtSaida: TDateTime read FdtSaida write FdtSaida; [TColumn('RespReceita','Receita',10,[ldGrid,ldLookup,ldComboBox], False)] property RespReceita: String read FRespReceita write FRespReceita; procedure ValidarCamposObrigatorios; end; implementation { TContadorVO } procedure TResponsavelVO.ValidarCamposObrigatorios; begin if (Self.FidPessoa = 0) then begin raise Exception.Create('O campo Pessoa é obrigatório!'); end; if (Self.dtEntrada= 0) then begin raise Exception.Create('O campo Data Entrada é obrigatório!'); end; end; end.
unit uCodigoControl; interface Uses SysUtils, Math; type TCodigoControl = class private public numeroAutorizacion: string; numeroFactura : string; nitCliente : string; fechaTransaccion : string; montoTransaccion : string; llaveDosificacion : string; function f_invertir(s:string):string; function f_base64(s:string):string; function f_verhoeff(s:string):string; function f_allegedRC4(cadena,llave:string):string; function f_sumatoria(s, dv:string):string; function f_codigoControlPuro():string; function f_codigoControlImpresion(codigoControlPuro:string):string; constructor create(AnumeroAutorizacion, AnumeroFactura, AnitCliente, AfechaTransaccion, AmontoTransaccion, AllaveDosificacion: string); end; const mul : array[0..9,0..9] of integer = ((0,1,2,3,4,5,6,7,8,9),(1,2,3,4,0,6,7,8,9,5),(2,3,4,0,1,7,8,9,5,6),(3,4,0,1,2,8,9,5,6,7),(4,0,1,2,3,9,5,6,7,8),(5,9,8,7,6,0,4,3,2,1),(6,5,9,8,7,1,0,4,3,2),(7,6,5,9,8,2,1,0,4,3),(8,7,6,5,9,3,2,1,0,4),(9,8,7,6,5,4,3,2,1,0)); per : array[0..7,0..9] of integer = ((0,1,2,3,4,5,6,7,8,9),(1,5,7,6,2,8,3,0,9,4),(5,8,0,3,7,9,6,1,4,2),(8,9,1,6,0,4,3,5,2,7),(9,4,5,3,1,2,6,8,7,0),(4,2,8,6,5,7,3,9,0,1),(2,7,9,3,8,0,6,4,1,5),(7,0,4,6,9,1,3,2,5,8)); dig : array[0..9] of integer = (0,4,3,2,1,5,6,7,8,9); base64: array[0..63] of string = ('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','+','/'); implementation constructor TCodigoControl.create(AnumeroAutorizacion, AnumeroFactura, AnitCliente, AfechaTransaccion, AmontoTransaccion, AllaveDosificacion: string); begin numeroAutorizacion := AnumeroAutorizacion; numeroFactura := AnumeroFactura; nitCliente := AnitCliente; fechaTransaccion := AfechaTransaccion; montoTransaccion := AmontoTransaccion; llaveDosificacion := AllaveDosificacion; end; function TCodigoControl.f_codigoControlImpresion(codigoControlPuro:string):string; var i:integer; codigoControl: string; begin i := 1; while i < length(codigoControlPuro) do begin codigoControl := codigoControl + copy(codigoControlPuro,i,2)+'-'; i := i + 2; end; result := copy(codigoControl,1,(length(codigoControl)-1)); end; function TcodigoControl.f_codigoControlPuro():string; var suma : Int64 ; i,j: integer; digitoVerhoeff, suma5:string; dig5 :array[0..4] of integer; cadena:array[0..4] of string; cadenaConcatenada, llaveCifrado: string; sumatoria, base64_ : string; codigoControl : string; numeroFactura_v, nitCliente_v, fechaTransaccion_v, montotransaccion_v: string; begin numeroFactura_v := numeroFactura + f_verhoeff(numeroFactura); numeroFactura_v := numeroFactura_v + f_verhoeff(numeroFactura_v); nitCliente_v := nitCliente + f_verhoeff(nitCliente); nitCliente_v := nitCliente_v + f_verhoeff(nitCliente_v); fechaTransaccion_v := fechaTransaccion + f_verhoeff(fechaTransaccion); fechaTransaccion_v := fechaTransaccion_v + f_verhoeff(fechaTransaccion_v); montotransaccion_v := montoTransaccion + f_verhoeff(montoTransaccion); montotransaccion_v := montotransaccion_v + f_verhoeff(montotransaccion_v); suma := strtoint(numeroFactura_v)+StrToInt64(nitCliente_v)+strtoint(fechaTransaccion_v)+strtoint(montotransaccion_v); suma5 := inttostr(suma); for i:= 1 to 5 do begin suma5 := suma5 + f_verhoeff(suma5); end; for i:= length(suma5) downto (length(suma5)-4) do digitoVerhoeff := digitoVerhoeff + copy(suma5,i,1); j:= 0; for i:= 5 downto 1 do begin dig5[j]:= strtoint(copy(digitoVerhoeff,i,1))+1; j := j + 1; end; j := 1; for i:= 0 to 4 do begin cadena[i]:=copy(llaveDosificacion,j,dig5[i]); j:= j + dig5[i]; end; cadenaConcatenada := numeroAutorizacion+cadena[0]+numeroFactura_v+cadena[1]+nitCliente_v+cadena[2]+fechaTransaccion_v+cadena[3]+montoTransaccion_v+cadena[4]; llaveCifrado := llaveDosificacion + f_invertir(digitoverhoeff); sumatoria := f_sumatoria(f_allegedRC4(CadenaConcatenada,llaveCifrado), digitoVerhoeff); base64_:= f_base64(sumatoria); codigoControl := f_allegedRC4(base64_,llaveCifrado); result := codigoControl; end; function TCodigoControl.f_invertir(s:string):string; var i:byte; begin for i := (length(s)) downto 1 do begin result := result + copy(s,i,1); end; end; function TCodigoControl.f_base64(s:string):string; var resto:integer; cociente, numero: integer; cadena:string; begin numero := strtoint(s); cociente := 1; cadena := ''; while(cociente > 0)do begin cociente := trunc(numero/64); resto := numero mod 64; cadena := base64[resto]+cadena; numero := cociente; end; result := cadena; end; function TCodigoControl.f_verhoeff(s:string):string; var i, check:integer; a,b,c:integer; r:integer; largo:integer; invertido:string; begin invertido := f_invertir(s); check := 0; largo := length(s)-1; for i := 0 to largo do begin a := (i+1) mod 8; b := strtoint(invertido[i+1]); c := per[a,b]; check := mul[check,c]; end; r := dig[check]; result := inttostr(r); end; function TCodigoControl.f_allegedRC4(cadena, llave: string):string; var estado:array[0..255] of integer; i, x, y, index1, index2, nmen, intercambiar, est: integer; mensajeCifrado:string; ascii : integer; begin x := 0; y := 0; index1:= 0; index2:= 0; mensajeCifrado:= ''; for i := 0 to 255 do estado[i] := i; for i := 0 to 255 do begin ascii := ord(llave[index1+1]); index2 := (ascii + estado[i] + index2) mod 256; intercambiar := estado[i]; estado[i] := estado[index2]; estado[index2] := intercambiar; index1 := (index1 + 1) mod length(llave); end; for i:= 0 to (length(cadena) - 1) do begin x := (x+1) mod 256; y := (estado[x]+y) mod 256; intercambiar := estado[x]; estado[x] := estado[y]; estado[y] := intercambiar; ascii := ord(cadena[i+1]); est := estado[(estado[x]+estado[y]) mod 256]; nmen := ascii xor est; mensajeCifrado := mensajeCifrado + inttohex(nmen,2); end; result := mensajeCifrado; end; function TcodigoControl.f_sumatoria(s, dv: string):string; var j, sumTotal, res: integer; sumPar: array[0..4] of integer; digitoVerhoeff : string; begin j := 0; sumTotal := 0; digitoVerhoeff := ''; digitoVerhoeff := f_invertir(dv); sumPar[0] := 0; sumPar[1] := 0; sumPar[2] := 0; sumPar[3] := 0; sumPar[4] := 0; while j <= (length(s)) do begin if (j+1)<=length(s) then sumPar[0] := sumPar[0]+ ord(s[j+1]); if (j+2)<=length(s) then sumPar[1] := sumPar[1]+ ord(s[j+2]); if (j+3)<=length(s) then sumPar[2] := sumPar[2]+ ord(s[j+3]); if (j+4)<=length(s) then sumPar[3] := sumPar[3]+ ord(s[j+4]); if (j+5)<=length(s) then sumPar[4] := sumPar[4]+ ord(s[j+5]); j := j + 5; if (j) > (length(s)) then break; end; sumTotal := sumPar[0] + sumPar[1] + sumPar[2] + sumPar[3] + sumPar[4]; res := 0; for j:= 0 to 4 do res := trunc((sumTotal * sumPar[j]) / (strtoint((digitoVerhoeff[j+1]))+1)) + res; result := inttostr(res); end; end.
{----------------------------------------------------------------------------- Unit Name: frmPythonII Author: Kiriakos Vlahos Date: 20-Jan-2005 Purpose: Python Interactive Interperter using Python for Delphi and Synedit Features: Syntax Highlighting Brace Highlighting Command History - Alt-UP : previous command - Alt-Down : next command - Esc : clear command Code Completion Call Tips History: -----------------------------------------------------------------------------} unit frmPythonII; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs , Menus, PythonEngine, SyncObjs, SynHighlighterPython, SynEditHighlighter, SynEdit, SynEditKeyCmds, SynCompletionProposal, JvComponent, JvDockControlForm, frmIDEDockWin, ExtCtrls, TBX, TBXThemes, PythonGUIInputOutput, JvComponentBase, SynUnicode, TB2Item, ActnList; const WM_APPENDTEXT = WM_USER + 1020; type TPythonIIForm = class(TIDEDockWindow) SynEdit: TSynEdit; PythonEngine: TPythonEngine; PythonIO: TPythonInputOutput; SynCodeCompletion: TSynCompletionProposal; DebugIDE: TPythonModule; SynParamCompletion: TSynCompletionProposal; InterpreterPopUp: TTBXPopupMenu; InterpreterActionList: TActionList; actCleanUpNameSpace: TAction; actCleanUpSysModules: TAction; TBXItem1: TTBXItem; TBXItem2: TTBXItem; TBXSeparatorItem1: TTBXSeparatorItem; TBXItem3: TTBXItem; actCopyHistory: TAction; TBXSeparatorItem2: TTBXSeparatorItem; TBXItem4: TTBXItem; procedure testResultAddError(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); procedure testResultAddFailure(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); procedure testResultAddSuccess(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); procedure testResultStopTestExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); procedure testResultStartTestExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); procedure MaskFPUExceptionsExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); procedure UnMaskFPUExceptionsExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); procedure Get8087CWExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); procedure SynEditReplaceText(Sender: TObject; const ASearch, AReplace: WideString; Line, Column: Integer; var Action: TSynReplaceAction); procedure SynEditPaintTransient(Sender: TObject; Canvas: TCanvas; TransientType: TTransientType); procedure FormCreate(Sender: TObject); procedure SynEditProcessCommand(Sender: TObject; var Command: TSynEditorCommand; var AChar: WideChar; Data: Pointer); procedure SynEditProcessUserCommand(Sender: TObject; var Command: TSynEditorCommand; var AChar: WideChar; Data: Pointer); procedure SynCodeCompletionExecute(Kind: SynCompletionType; Sender: TObject; var CurrentInput: WideString; var x, y: Integer; var CanExecute: Boolean); function FormHelp(Command: Word; Data: Integer; var CallHelp: Boolean): Boolean; procedure InputBoxExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); procedure FormActivate(Sender: TObject); procedure StatusWriteExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); procedure MessageWriteExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); procedure FormDestroy(Sender: TObject); procedure SynParamCompletionExecute(Kind: SynCompletionType; Sender: TObject; var CurrentInput: WideString; var x, y: Integer; var CanExecute: Boolean); procedure SynEditCommandProcessed(Sender: TObject; var Command: TSynEditorCommand; var AChar: WideChar; Data: Pointer); procedure actCleanUpNameSpaceExecute(Sender: TObject); procedure InterpreterPopUpPopup(Sender: TObject); procedure actCleanUpSysModulesExecute(Sender: TObject); procedure actCopyHistoryExecute(Sender: TObject); procedure SynEditDblClick(Sender: TObject); private { Private declarations } fCommandHistory : TWideStringList; fCommandHistorySize : integer; fCommandHistoryPointer : integer; fShowOutput : Boolean; FCriticalSection : TCriticalSection; fOutputStream : TMemoryStream; fCloseBracketChar: WideChar; procedure GetBlockBoundary(LineN: integer; var StartLineN, EndLineN: integer; var IsCode: Boolean); function GetPromptPrefix(line: string): string; procedure SetCommandHistorySize(const Value: integer); protected procedure PythonIOSendData(Sender: TObject; const Data: WideString); procedure PythonIOReceiveData(Sender: TObject; var Data: WideString); procedure TBMThemeChange(var Message: TMessage); message TBM_THEMECHANGE; procedure WMAPPENDTEXT(var Message: TMessage); message WM_APPENDTEXT; public { Public declarations } II : Variant; // wrapping sys and code modules Debugger, LineCache, BuiltIns : Variant; PS1, PS2 : WideString; PythonHelpFile : string; function OutputSupressor : IInterface; procedure AppendText(S: WideString); procedure AppendToPrompt(Buffer : array of WideString); function IsEmpty : Boolean; function CanFind: boolean; function CanFindNext: boolean; function CanReplace: boolean; procedure ExecFind; procedure ExecFindNext; procedure ExecFindPrev; procedure ExecReplace; procedure RegisterHistoryCommands; property ShowOutput : boolean read fShowOutput write fShowOutput; property CommandHistorySize : integer read fCommandHistorySize write SetCommandHistorySize; end; var PythonIIForm: TPythonIIForm; implementation Uses SynEditTypes, Math, frmPyIDEMain, dmCommands, VarPyth, Registry, frmMessages, uCommonFunctions, JclStrings, frmVariables, StringResources, dlgConfirmReplace, frmUnitTests, JvDockGlobals, SynRegExpr; {$R *.dfm} { Class TSuppressOuptput modelled after JVCL.WaitCursor} type TSuppressOutput = class(TInterfacedObject, IInterface) private fPythonIIForm : TPythonIIForm; OldShowOutput : Boolean; public constructor Create(PythonIIForm : TPythonIIForm); destructor Destroy; override; end; constructor TSuppressOutput.Create(PythonIIForm : TPythonIIForm); begin inherited Create; fPythonIIForm := PythonIIForm; if Assigned(fPythonIIForm) then begin OldShowOutput := PythonIIForm.ShowOutput; PythonIIForm.ShowOutput := False; end; end; destructor TSuppressOutput.Destroy; begin if Assigned(fPythonIIForm) then fPythonIIForm.ShowOutput := OldShowOutput; inherited Destroy; end; { PythonIIForm } function TPythonIIForm.OutputSupressor: IInterface; begin Result := TSuppressOutput.Create(Self); end; procedure TPythonIIForm.SynEditPaintTransient(Sender: TObject; Canvas: TCanvas; TransientType: TTransientType); begin if (not Assigned(SynEdit.Highlighter)) then Exit; CommandsDataModule.PaintMatchingBrackets(Canvas, SynEdit, TransientType); end; procedure TPythonIIForm.PythonIOReceiveData(Sender: TObject; var Data: WideString); Var S : string; begin S := Data; if not InputQuery('PyScripter - Input requested', 'Input:', S) then with GetPythonEngine do PyErr_SetString(PyExc_KeyboardInterrupt^, 'Operation cancelled') else Data := S + #10; end; procedure TPythonIIForm.PythonIOSendData(Sender: TObject; const Data: WideString); Var WS : WideString; begin if fShowOutput then begin fCriticalSection.Acquire; try fOutputStream.Write(Data[1], Length (Data) * 2); //fOutputStream.Write(WideLineBreak[1], Length (WideLineBreak) * 2); RawOutput if GetCurrentThreadId = MainThreadId then begin SetLength(WS, fOutputStream.Size div 2); fOutputStream.Position := 0; fOutputStream.Read(WS[1], Length(WS)*2); AppendText(WS); fOutputStream.Size := 0; end else begin PostMessage(Handle, WM_APPENDTEXT, 0, 0); end; finally fCriticalSection.Release; end; end; end; procedure TPythonIIForm.actCleanUpNameSpaceExecute(Sender: TObject); begin CommandsDataModule.PyIDEOptions.CleanupMainDict := (Sender as TAction).Checked; end; procedure TPythonIIForm.actCleanUpSysModulesExecute(Sender: TObject); begin CommandsDataModule.PyIDEOptions.CleanupSysModules := (Sender as TAction).Checked; end; procedure TPythonIIForm.actCopyHistoryExecute(Sender: TObject); begin SetClipboardText(fCommandHistory.Text); end; procedure TPythonIIForm.AppendText(S: WideString); begin SynEdit.ExecuteCommand(ecEditorBottom, ' ', nil); SynEdit.SelText := S; SynEdit.ExecuteCommand(ecEditorBottom, ' ', nil); SynEdit.EnsureCursorPosVisible; end; procedure TPythonIIForm.AppendToPrompt(Buffer: array of WideString); Var LineCount, i : integer; Line : WideString; begin LineCount := SynEdit.Lines.Count; Line := SynEdit.Lines[LineCount-1]; SynEdit.BeginUpdate; try if Line <> PS1 then begin if Line <> '' then AppendText(WideLineBreak); AppendText(PS1); end; for i := Low(Buffer) to High(Buffer) - 1 do AppendText(Buffer[i] + WideLineBreak + PS2); if Length(Buffer) > 0 then AppendText(Buffer[High(Buffer)]); finally SynEdit.EndUpdate; end; end; procedure TPythonIIForm.FormCreate(Sender: TObject); function IsPythonVersionParam(const AParam : String; out AVersion : String) : Boolean; begin Result := (Length(AParam) = 9) and SameText(Copy(AParam, 1, 7), '-PYTHON') and (AParam[8] in ['0'..'9']) and (AParam[9] in ['0'..'9']); if Result then AVersion := AParam[8] + '.' + AParam[9]; end; function IndexOfKnownVersion(const AVersion : String) : Integer; var i : Integer; begin Result := -1; for i := High(PYTHON_KNOWN_VERSIONS) downto Low(PYTHON_KNOWN_VERSIONS) do if PYTHON_KNOWN_VERSIONS[i].RegVersion = AVersion then begin Result := i; Break; end; end; Var S : string; Registry : TRegistry; i : integer; idx : Integer; versionIdx : Integer; expectedVersion : string; RegKey : string; expectedVersionIdx : Integer; begin inherited; SynEdit.ControlStyle := SynEdit.ControlStyle + [csOpaque]; SynEdit.Highlighter := TSynPythonInterpreterSyn.Create(Self); SynEdit.Highlighter.Assign(CommandsDataModule.SynPythonSyn); SynEdit.Assign(CommandsDataModule.InterpreterEditorOptions); RegisterHistoryCommands; // IO PythonIO.OnSendUniData := PythonIOSendData; PythonIO.OnReceiveUniData := PythonIOReceiveData; PythonIO.UnicodeIO := True; PythonIO.RawOutput := True; // Load Python DLL // first find an optional parameter specifying the expected Python version in the form of -PYTHONXY expectedVersion := ''; expectedVersionIdx := -1; for i := 1 to ParamCount do begin if IsPythonVersionParam(ParamStr(i), expectedVersion) then begin idx := IndexOfKnownVersion(expectedVersion); if idx >= COMPILED_FOR_PYTHON_VERSION_INDEX then expectedVersionIdx := idx; if expectedVersionIdx = -1 then if idx = -1 then MessageDlg(Format('PyScripter can''t use command line parameter %s because it doesn''t know this version of Python.', [ParamStr(i)]), mtWarning, [mbOK], 0) else MessageDlg(Format('PyScripter can''t use command line parameter %s because it was compiled for Python %s or later.', [ParamStr(i), PYTHON_KNOWN_VERSIONS[COMPILED_FOR_PYTHON_VERSION_INDEX].RegVersion]), mtWarning, [mbOK], 0); Break; end; end; // disable feature that will try to use the last version of Python because we provide our // own behaviour. Note that this feature would not load the latest version if the python dll // matching the compiled version of P4D was found. PythonEngine.UseLastKnownVersion := False; if expectedVersionIdx > -1 then begin // if we found a parameter requiring a specific version of Python, // then we must immediatly fail if P4D did not find the expected dll. versionIdx := expectedVersionIdx; PythonEngine.FatalMsgDlg := True; PythonEngine.FatalAbort := True; end else begin // otherwise, let's start searching a valid python dll from the latest known version versionIdx := High(PYTHON_KNOWN_VERSIONS); PythonEngine.FatalMsgDlg := False; PythonEngine.FatalAbort := False; end; // try to find an acceptable version of Python, starting from either the specified version, // or the latest know version, but stop when we reach the version targeted on compilation. for i := versionIdx downto COMPILED_FOR_PYTHON_VERSION_INDEX do begin PythonEngine.DllName := PYTHON_KNOWN_VERSIONS[i].DllName; PythonEngine.APIVersion := PYTHON_KNOWN_VERSIONS[i].APIVersion; PythonEngine.RegVersion := PYTHON_KNOWN_VERSIONS[i].RegVersion; if i = COMPILED_FOR_PYTHON_VERSION_INDEX then begin // last chance, so raise an error if it goes wrong PythonEngine.FatalMsgDlg := True; PythonEngine.FatalAbort := True; end; PythonEngine.LoadDll; if PythonEngine.IsHandleValid then // we found a valid version Break; end; fShowOutput := True; // For handling output from Python threads FCriticalSection := TCriticalSection.Create; fOutputStream := TMemoryStream.Create; // For recalling old commands in Interactive Window; fCommandHistory := TWideStringList.Create(); fCommandHistorySize := 20; fCommandHistoryPointer := 0; // Get Python vars and print banner S := Format('*** Python %s on %s. ***'+sLineBreak, [SysModule.version, SysModule.platform]); AppendText(S); PS1 := SysModule.ps1; PS2 := SysModule.ps2; II := VarPythonEval('_II'); PythonEngine.ExecString('del _II'); Debugger := II.debugger; LineCache := Import('linecache'); BuiltIns := VarPythonEval('__builtins__'); AppendText(PS1); // Python Help File Registry := TRegistry.Create(KEY_READ); try Registry.RootKey := HKEY_LOCAL_MACHINE; // False because we do not want to create it if it doesn't exist RegKey := '\SOFTWARE\Python\PythonCore\'+SysModule.winver+ '\Help\Main Python Documentation'; if Registry.OpenKey(RegKey, False) then PythonHelpFile := Registry.ReadString('') else begin // try Current User Registry.RootKey := HKEY_CURRENT_USER; if Registry.OpenKey(RegKey, False) then PythonHelpFile := Registry.ReadString('') end; finally Registry.Free; end; end; procedure TPythonIIForm.FormDestroy(Sender: TObject); begin fCommandHistory.Free; FCriticalSection.Free; fOutputStream.Free; inherited; end; procedure TPythonIIForm.GetBlockBoundary(LineN: integer; var StartLineN, EndLineN: integer; var IsCode: Boolean); {----------------------------------------------------------------------------- GetBlockBoundary takes a line number, and will return the start and and line numbers of the block, and a flag indicating if the block is a Python code block. If the line specified has a Python prompt, then the lines are parsed and forwards, and the IsCode is true. If the line does not start with a prompt, the block is searched forward and backward until a prompt _is_ found, and all lines in between without prompts are returned, and the IsCode is false. -----------------------------------------------------------------------------} Var Line, Prefix : string; MaxLineNo : integer; begin Line := SynEdit.Lines[LineN]; MaxLineNo := SynEdit.Lines.Count - 1; Prefix := GetPromptPrefix(line); if Prefix = '' then begin IsCode := False; StartLineN := LineN; while StartLineN > 0 do begin if GetPromptPrefix(SynEdit.Lines[StartLineN-1]) <> '' then break; Dec(StartLineN); end; EndLineN := LineN; while EndLineN < MaxLineNo do begin if GetPromptPrefix(SynEdit.Lines[EndLineN+1]) <> '' then break; Inc(EndLineN); end; end else begin IsCode := True; StartLineN := LineN; while (StartLineN > 0) and (Prefix <> PS1) do begin Prefix := GetPromptPrefix(SynEdit.Lines[StartLineN-1]); if Prefix = '' then break; Dec(StartLineN); end; EndLineN := LineN; while EndLineN < MaxLineNo do begin Prefix := GetPromptPrefix(SynEdit.Lines[EndLineN+1]); if (Prefix = PS1) or (Prefix = '') then break; Inc(EndLineN); end; end; end; function TPythonIIForm.GetPromptPrefix(line: string): string; begin if Copy(line, 1, Length(PS1)) = PS1 then Result := PS1 else if Copy(line, 1, Length(PS2)) = PS2 then Result := PS2 else Result := ''; end; procedure TPythonIIForm.SynEditProcessCommand(Sender: TObject; var Command: TSynEditorCommand; var AChar: WideChar; Data: Pointer); Var LineN, StartLineN, EndLineN, i, Len, Position : integer; NeedIndent : boolean; IsCode : Boolean; Line, CurLine, Source, Indent : WideString; EncodedSource : string; Buffer : array of WideString; P : PPyObject; V : Variant; begin case Command of ecLineBreak : begin Command := ecNone; // do not processed it further if SynParamCompletion.Form.Visible then SynParamCompletion.CancelCompletion; LineN := SynEdit.CaretY - 1; // Caret is 1 based GetBlockBoundary(LineN, StartLineN, EndLineN, IsCode); // If we are in a code-block, but it isnt at the end of the buffer // then copy it to the end ready for editing and subsequent execution if not IsCode then begin SetLength(Buffer, 0); AppendToPrompt(Buffer); end else begin SetLength(Buffer, EndLineN-StartLineN + 1); Source := ''; for i := StartLineN to EndLineN do begin Line := SynEdit.Lines[i]; Len := Length(GetPromptPrefix(Line)); Buffer[i-StartLineN] := Copy(Line, Len+1, MaxInt); Source := Source + Buffer[i-StartLineN] + WideLF; end; Delete(Source, Length(Source), 1); // If we are in a code-block, but it isnt at the end of the buffer // then copy it to the end ready for editing and subsequent execution if EndLineN <> SynEdit.Lines.Count - 1 then AppendToPrompt(Buffer) else if Trim(Source) = '' then begin AppendText(WideLineBreak); AppendText(PS1); end else begin SynEdit.ExecuteCommand(ecEditorBottom, ' ', nil); AppendText(WideLineBreak); //remove trailing tabs for i := Length(Source) downto 1 do if Source[i] = #9 then Delete(Source, i, 1) else break; if CommandsDataModule.PyIDEOptions.UTF8inInterpreter then EncodedSource := UTF8BOMString + Utf8Encode(Source) else EncodedSource := Source; // Workaround due to PREFER_UNICODE flag to make sure // no conversion to Unicode and back will take place with GetPythonEngine do begin P := PyString_FromString(PChar(EncodedSource)); V := VarPythonCreate(P); Py_XDECREF(P); end; if II.runsource(V, '<interactive input>') then NeedIndent := True else begin // The source code has been executed // If the last line isnt empty, append a newline SetLength(Buffer, 0); AppendToPrompt(Buffer); NeedIndent := False; // Add the command executed to History FCommandHistory.Add(Source); SetCommandHistorySize(fCommandHistorySize); fCommandHistoryPointer := fCommandHistory.Count; VariablesWindow.UpdateWindow; end; if NeedIndent then begin // Now attempt to correct indentation CurLine := Copy(SynEdit.Lines[lineN], Length(PS2)+1, MaxInt); //!! Position := 1; Indent := ''; while (Length(CurLine)>=Position) and (CurLine[Position] in [WideChar(#09), WideChar(#32)]) do begin Indent := Indent + CurLine[Position]; Inc(Position); end; if CommandsDataModule.IsBlockOpener(CurLine) then Indent := Indent + #9 else if CommandsDataModule.IsBlockCloser(CurLine) then Delete(Indent, Length(Indent), 1); // use ReplaceSel to ensure it goes at the cursor rather than end of buffer. SynEdit.SelText := PS2 + Indent; end; end; end; SynEdit.EnsureCursorPosVisible; end; ecDeleteLastChar : begin Line := SynEdit.Lines[SynEdit.CaretY - 1]; if ((Pos(PS1, Line) = 1) and (SynEdit.CaretX <= Length(PS1)+1)) or ((Pos(PS2, Line) = 1) and (SynEdit.CaretX <= Length(PS2)+1)) then Command := ecNone; // do not processed it further end; ecLineStart : begin Line := SynEdit.Lines[SynEdit.CaretY - 1]; if Pos(PS1, Line) = 1 then begin Command := ecNone; // do not processed it further SynEdit.CaretX := Length(PS1) + 1; end else if Pos(PS2, Line) = 1 then begin Command := ecNone; // do not processed it further SynEdit.CaretX := Length(PS2) + 1; end; end; ecChar, ecDeleteChar, ecDeleteWord, ecDeleteLastWord, ecCut, ecPaste: begin Line := SynEdit.Lines[SynEdit.CaretY - 1]; if ((Pos(PS1, Line) = 1) and (SynEdit.CaretX <= Length(PS1))) or ((Pos(PS2, Line) = 1) and (SynEdit.CaretX <= Length(PS2))) then Command := ecNone; // do not processed it further end; end; end; procedure TPythonIIForm.SynEditCommandProcessed(Sender: TObject; var Command: TSynEditorCommand; var AChar: WideChar; Data: Pointer); const OpenBrackets : WideString = '([{'; CloseBrackets : WideString = ')]}'; Var OpenBracketPos : integer; Line: WideString; begin if (Command = ecChar) and CommandsDataModule.PyIDEOptions.AutoCompleteBrackets then with SynEdit do begin if aChar = fCloseBracketChar then begin Line := LineText; if InsertMode and (CaretX <= Length(Line)) and (Line[CaretX] = fCloseBracketChar) then ExecuteCommand(ecDeleteChar, WideChar(#0), nil); fCloseBracketChar := #0; end else begin fCloseBracketChar := #0; OpenBracketPos := Pos(aChar, OpenBrackets); if (OpenBracketPos > 0) and (CaretX > Length(LineText)) then begin SelText := CloseBrackets[OpenBracketPos]; CaretX := CaretX - 1; fCloseBracketChar := CloseBrackets[OpenBracketPos]; end; end; end; end; procedure TPythonIIForm.SynEditDblClick(Sender: TObject); var RegExpr : TRegExpr; ErrLineNo : integer; FileName : string; begin RegExpr := TRegExpr.Create; try RegExpr.Expression := STracebackFilePosExpr; if RegExpr.Exec(Synedit.LineText) then begin ErrLineNo := StrToIntDef(RegExpr.Match[3], 0); FileName := GetLongFileName(ExpandFileName(RegExpr.Match[1])); PyIDEMainForm.ShowFilePosition(FileName, ErrLineNo, 1); end; finally RegExpr.Free; end; end; procedure TPythonIIForm.SynEditProcessUserCommand(Sender: TObject; var Command: TSynEditorCommand; var AChar: WideChar; Data: Pointer); Var LineN, StartLineN, EndLineN, i: integer; IsCode: Boolean; Source : WideString; Buffer : array of WideString; SL : TWideStringList; begin if Command = ecCodeCompletion then begin if SynCodeCompletion.Form.Visible then SynCodeCompletion.CancelCompletion; //SynCodeCompletion.DefaultType := ctCode; SynCodeCompletion.ActivateCompletion; Command := ecNone; end else if Command = ecParamCompletion then begin if SynParamCompletion.Form.Visible then SynParamCompletion.CancelCompletion; //SynCodeCompletion.DefaultType := ctParams; SynParamCompletion.ActivateCompletion; Command := ecNone; end; // The following does not work. compiler bug??? // if Command in [ecRecallCommandPrev, ecRecallCommandNext, ecRecallCommandEsc] then begin if (Command = ecRecallCommandPrev) or (Command = ecRecallCommandNext) or (Command = ecRecallCommandEsc) then begin SynCodeCompletion.CancelCompletion; SynParamCompletion.CancelCompletion; LineN := SynEdit.CaretY -1; GetBlockBoundary(LineN, StartLineN, EndLineN, IsCode); // if we have code at the end remove code block if IsCode and (EndLineN = SynEdit.Lines.Count - 1) then begin SynEdit.BeginUpdate; try for i := EndLineN downto StartLineN do SynEdit.Lines.Delete(i); finally SynEdit.EndUpdate; end; end; //Append new prompt if needed SetLength(Buffer, 0); AppendToPrompt(Buffer); SynEdit.ExecuteCommand(ecEditorBottom, ' ', nil); SynEdit.EnsureCursorPosVisible; end else Exit; // We get here if Command is one or our defined commands Source := ''; if fCommandHistory.Count = 0 then Exit; if Command = ecRecallCommandPrev then fCommandHistoryPointer := Max (fCommandHistoryPointer - 1, -1) else if Command = ecRecallCommandNext then fCommandHistoryPointer := Min (fCommandHistoryPointer + 1, fCommandHistory.Count) else if Command = ecRecallCommandEsc then fCommandHistoryPointer := fCommandHistory.Count; if (fCommandHistoryPointer >= 0) and (fCommandHistoryPointer < fCommandHistory.Count) then Source := fCommandHistory[fCommandHistoryPointer]; if Source <> '' then begin SL := TWideStringList.Create; try SL.Text := Source; SetLength(Buffer, SL.Count); for i := 0 to SL.Count - 1 do Buffer[i] := SL[i]; AppendToPrompt(Buffer); SynEdit.ExecuteCommand(ecEditorBottom, ' ', nil); SynEdit.EnsureCursorPosVisible; finally SL.Free; end; end; Command := ecNone; // do not processed it further end; procedure TPythonIIForm.SetCommandHistorySize(const Value: integer); Var i : integer; begin fCommandHistorySize := Value; if FCommandHistory.Count > Value then begin for i := 1 to FCommandHistory.Count - Value do FCommandHistory.Delete(0); end; end; procedure TPythonIIForm.SynCodeCompletionExecute(Kind: SynCompletionType; Sender: TObject; var CurrentInput: WideString; var x, y: Integer; var CanExecute: Boolean); {----------------------------------------------------------------------------- Based on code from Syendit Demo -----------------------------------------------------------------------------} var locline, lookup: String; TmpX, Index, ImageIndex, i, TmpLocation : Integer; FoundMatch : Boolean; DisplayText, InsertText, S : string; InspectModule, ItemsDict, ItemKeys, ItemValue, StringModule, LookupObj : Variant; begin with TSynCompletionProposal(Sender).Editor do begin locLine := LineText; //go back from the cursor and find the first open paren TmpX := CaretX; if TmpX > length(locLine) then TmpX := length(locLine) else dec(TmpX); TmpLocation := 0; lookup := GetWordAtPos(LocLine, TmpX, IdentChars+['.'], True, False, True); Index := CharLastPos(lookup, '.'); InspectModule := Import('inspect'); StringModule := Import('string'); if Index > 0 then begin lookup := Copy(lookup, 1, Index-1); DisplayText := ''; try //Evaluate the lookup expression and get the hint text fShowOutput := False; // Do not show Traceback for errors LookupObj := II.evalcode(lookup); ItemsDict := BuiltinModule.dict(InspectModule.getmembers(LookupObj)); except ItemsDict := BuiltinModule.dict(); end; fShowOutput := True; end else begin // globals and builtins (could add keywords as well) ItemsDict := BuiltInModule.dict(); ItemsDict.update(VarPythonEval('vars()')); ItemsDict.update(BuiltinModule.__dict__); end; ItemKeys := ItemsDict.keys(); ItemKeys.sort(); DisplayText := ''; for i := 0 to len(ItemKeys) - 1 do begin S := ItemKeys.GetItem(i); ItemValue := ItemsDict.GetItem(S); if InspectModule.ismodule(ItemValue) then ImageIndex := 16 else if InspectModule.isfunction(ItemValue) or InspectModule.isbuiltin(ItemValue) then ImageIndex := 17 else if InspectModule.ismethod(ItemValue) or InspectModule.ismethoddescriptor(ItemValue) then ImageIndex := 14 else if InspectModule.isclass(ItemValue) then ImageIndex := 13 else begin if Index > 0 then ImageIndex := 1 else ImageIndex := 0; end; DisplayText := DisplayText + Format('\Image{%d}\hspace{2}%s', [ImageIndex, S]); if i < len(ItemKeys) - 1 then DisplayText := DisplayText + #10; end; InsertText := StringModule.join(ItemKeys, ''#10); FoundMatch := DisplayText <> ''; end; CanExecute := FoundMatch; if CanExecute then begin TSynCompletionProposal(Sender).Form.CurrentIndex := TmpLocation; TSynCompletionProposal(Sender).ItemList.Text := DisplayText; TSynCompletionProposal(Sender).InsertList.Text := InsertText; end else begin TSynCompletionProposal(Sender).ItemList.Clear; TSynCompletionProposal(Sender).InsertList.Clear; end; end; procedure TPythonIIForm.SynParamCompletionExecute(Kind: SynCompletionType; Sender: TObject; var CurrentInput: WideString; var x, y: Integer; var CanExecute: Boolean); var locline, lookup: String; TmpX, StartX, ParenCounter, TmpLocation : Integer; FoundMatch : Boolean; DisplayText, DocString : string; p : TPoint; LookUpObject, PyDocString : Variant; begin with TSynCompletionProposal(Sender).Editor do begin locLine := LineText; //go back from the cursor and find the first open paren TmpX := CaretX; StartX := CaretX; if TmpX > length(locLine) then TmpX := length(locLine) else dec(TmpX); FoundMatch := False; TmpLocation := 0; while (TmpX > 0) and not(FoundMatch) do begin if LocLine[TmpX] = ',' then begin inc(TmpLocation); dec(TmpX); end else if LocLine[TmpX] = ')' then begin //We found a close, go till it's opening paren ParenCounter := 1; dec(TmpX); while (TmpX > 0) and (ParenCounter > 0) do begin if LocLine[TmpX] = ')' then inc(ParenCounter) else if LocLine[TmpX] = '(' then dec(ParenCounter); dec(TmpX); end; if TmpX > 0 then dec(TmpX); //eat the open paren end else if locLine[TmpX] = '(' then begin //we have a valid open paren, lets see what the word before it is StartX := TmpX; while (TmpX > 0) and not(locLine[TmpX] in IdentChars+['.']) do // added [.] Dec(TmpX); if TmpX > 0 then begin lookup := GetWordAtPos(LocLine, TmpX, IdentChars+['.'], True, False, True); try //Evaluate the lookup expression and get the hint text fShowOutput := False; // Do not show Traceback for errors LookUpObject := II.evalcode(lookup); DisplayText := II.get_arg_text(LookUpObject); FoundMatch := True; except DisplayText := ''; FoundMatch := False; end; fShowOutput := True; if not(FoundMatch) then begin TmpX := StartX; dec(TmpX); end; end; end else dec(TmpX) end; end; if FoundMatch then begin PyDocString := Import('inspect').getdoc(LookUpObject); if not VarIsNone(PyDocString) then DocString := GetNthLine(PyDocString, 1) else DocString := ''; // CanExecute := (DisplayText <> '') or (DocString <> ''); CanExecute := True; end else CanExecute := False; if CanExecute then begin with TSynCompletionProposal(Sender) do begin if DisplayText = '' then begin FormatParams := False; DisplayText := '\style{~B}' + SNoParameters + '\style{~B}'; end else begin FormatParams := True; end; if (DocString <> '') then DisplayText := DisplayText + sLineBreak; Form.CurrentIndex := TmpLocation; ItemList.Text := DisplayText + DocString; end; // position the hint window at and just below the opening bracket p := SynEdit.ClientToScreen(SynEdit.RowColumnToPixels( SynEdit.BufferToDisplayPos(BufferCoord(Succ(StartX), SynEdit.CaretY)))); Inc(p.y, SynEdit.LineHeight); x := p.X; y := p.Y; end else begin TSynCompletionProposal(Sender).ItemList.Clear; TSynCompletionProposal(Sender).InsertList.Clear; end; end; function TPythonIIForm.FormHelp(Command: Word; Data: Integer; var CallHelp: Boolean): Boolean; Var KeyWord : string; begin Keyword := SynEdit.WordAtCursor; if not PyIDEMainForm.PythonKeywordHelpRequested and not PyIDEMainForm.MenuHelpRequested and (Keyword <> '') then begin CallHelp := not CommandsDataModule.ShowPythonKeywordHelp(KeyWord); Result := True; end else begin CallHelp := True; Result := False; end; end; procedure TPythonIIForm.InputBoxExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); // InputBox function Var PCaption, PPrompt, PDefault : PChar; S : string; begin with GetPythonEngine do if PyArg_ParseTuple( args, 'sss:InputBox', [@PCaption, @PPrompt, @PDefault] ) <> 0 then begin S := PDefault; if InputQuery(PCaption, PPrompt, S) then Result := PyString_FromString(PChar(S)) else Result := ReturnNone; end else Result := nil; end; procedure TPythonIIForm.StatusWriteExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); // statusWrite Var Msg : PChar; begin with GetPythonEngine do if PyArg_ParseTuple( args, 's:statusWrite', [@Msg] ) <> 0 then begin PyIDEMainForm.WriteStatusMsg(Msg); Application.ProcessMessages; Result := ReturnNone; end else Result := nil; end; procedure TPythonIIForm.MessageWriteExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); // messageWrite Var Msg, FName : PChar; LineNo, Offset : integer; S : string; begin FName := nil; LineNo := 0; Offset := 0; with GetPythonEngine do if PyArg_ParseTuple( args, 's|sii:messageWrite', [@Msg, @FName, @LineNo, @Offset] ) <> 0 then begin if Assigned(FName) then S := FName else S := ''; MessagesWindow.AddMessage(Msg, S, LineNo, Offset); Application.ProcessMessages; Result := ReturnNone; end else Result := nil; end; procedure TPythonIIForm.Get8087CWExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); begin Result := GetPythonEngine.PyLong_FromUnsignedLong(Get8087CW); end; procedure TPythonIIForm.UnMaskFPUExceptionsExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); begin MaskFPUExceptions(False); CommandsDataModule.PyIDEOptions.MaskFPUExceptions := False; Result := GetPythonEngine.ReturnNone; end; procedure TPythonIIForm.MaskFPUExceptionsExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); begin MaskFPUExceptions(True); CommandsDataModule.PyIDEOptions.MaskFPUExceptions := True; Result := GetPythonEngine.ReturnNone; end; procedure TPythonIIForm.testResultStartTestExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); begin UnitTestWindow.StartTest(VarPythonCreate(Args).GetItem(0)); Result := GetPythonEngine.ReturnNone; end; procedure TPythonIIForm.testResultStopTestExecute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); begin UnitTestWindow.StopTest(VarPythonCreate(Args).GetItem(0)); Result := GetPythonEngine.ReturnNone; end; procedure TPythonIIForm.testResultAddSuccess(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); begin UnitTestWindow.AddSuccess(VarPythonCreate(Args).GetItem(0)); Result := GetPythonEngine.ReturnNone; end; procedure TPythonIIForm.testResultAddFailure(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); begin UnitTestWindow.AddFailure(VarPythonCreate(Args).GetItem(0), VarPythonCreate(Args).GetItem(1)); Result := GetPythonEngine.ReturnNone; end; procedure TPythonIIForm.testResultAddError(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); begin UnitTestWindow.AddError(VarPythonCreate(Args).GetItem(0), VarPythonCreate(Args).GetItem(1)); Result := GetPythonEngine.ReturnNone; end; procedure TPythonIIForm.FormActivate(Sender: TObject); begin inherited; if not HasFocus then begin FGPanelEnter(Self); PostMessage(SynEdit.Handle, WM_SETFOCUS, 0, 0); end; end; procedure TPythonIIForm.TBMThemeChange(var Message: TMessage); begin inherited; if Message.WParam = TSC_VIEWCHANGE then begin // Update the gutter of the PythonII editor PyIDEMainForm.ThemeEditorGutter(SynEdit.Gutter); SynEdit.InvalidateGutter; end; end; procedure TPythonIIForm.InterpreterPopUpPopup(Sender: TObject); begin actCleanUpNameSpace.Checked := CommandsDataModule.PyIDEOptions.CleanupMainDict; actCleanUpSysModules.Checked := CommandsDataModule.PyIDEOptions.CleanupSysModules; end; procedure TPythonIIForm.WMAPPENDTEXT(var Message: TMessage); Var WS : WideString; begin fCriticalSection.Acquire; try if fOutputStream.Size > 0 then begin SetLength(WS, fOutputStream.Size div 2); fOutputStream.Position := 0; fOutputStream.Read(WS[1], Length(WS)*2); AppendText(WS); fOutputStream.Size := 0; end; finally fCriticalSection.Release; end; end; function TPythonIIForm.IsEmpty : Boolean; begin Result := (SynEdit.Lines.Count = 0) or ((SynEdit.Lines.Count = 1) and (SynEdit.Lines[0] = '')); end; function TPythonIIForm.CanFind: boolean; begin Result := not IsEmpty; end; function TPythonIIForm.CanFindNext: boolean; begin Result := not IsEmpty and (CommandsDataModule.EditorSearchOptions.SearchText <> ''); end; function TPythonIIForm.CanReplace: boolean; begin Result := not IsEmpty; end; procedure TPythonIIForm.ExecFind; begin CommandsDataModule.ShowSearchReplaceDialog(SynEdit, FALSE); end; procedure TPythonIIForm.ExecFindNext; begin CommandsDataModule.DoSearchReplaceText(SynEdit, FALSE, FALSE); end; procedure TPythonIIForm.ExecFindPrev; begin CommandsDataModule.DoSearchReplaceText(SynEdit, FALSE, TRUE); end; procedure TPythonIIForm.ExecReplace; begin CommandsDataModule.ShowSearchReplaceDialog(SynEdit, TRUE); end; procedure TPythonIIForm.RegisterHistoryCommands; begin // Register the Recall History Command with SynEdit.Keystrokes.Add do begin ShortCut := Menus.ShortCut(VK_UP, [ssAlt]); Command := ecRecallCommandPrev; end; with SynEdit.Keystrokes.Add do begin ShortCut := Menus.ShortCut(VK_DOWN, [ssAlt]); Command := ecRecallCommandNext; end; with SynEdit.Keystrokes.Add do begin ShortCut := Menus.ShortCut(VK_ESCAPE, []); Command := ecRecallCommandEsc; end; end; procedure TPythonIIForm.SynEditReplaceText(Sender: TObject; const ASearch, AReplace: WideString; Line, Column: Integer; var Action: TSynReplaceAction); var APos: TPoint; EditRect: TRect; begin if ASearch = AReplace then Action := raSkip else begin APos := SynEdit.ClientToScreen( SynEdit.RowColumnToPixels( SynEdit.BufferToDisplayPos( BufferCoord(Column, Line) ) ) ); EditRect := ClientRect; EditRect.TopLeft := ClientToScreen(EditRect.TopLeft); EditRect.BottomRight := ClientToScreen(EditRect.BottomRight); if ConfirmReplaceDialog = nil then ConfirmReplaceDialog := TConfirmReplaceDialog.Create(Application); ConfirmReplaceDialog.PrepareShow(EditRect, APos.X, APos.Y, APos.Y + SynEdit.LineHeight, ASearch); case ConfirmReplaceDialog.ShowModal of mrYes: Action := raReplace; mrYesToAll: Action := raReplaceAll; mrNo: Action := raSkip; else Action := raCancel; end; end; end; end.
unit ibSHSQLEditor; interface uses SysUtils, Classes, Contnrs, Dialogs, Types, Forms, Controls, SHDesignIntf, ibSHDesignIntf, ibSHDriverIntf, ibSHMessages, ibSHTool, ibSHValues, pSHIntf, pSHSqlTxtRtns, pSHStrUtil; type TibSHSQLEditor = class(TibBTTool, IibSHSQLEditor, IibSHDDLInfo, IibSHBranch, IfbSHBranch) private FSQL: TStrings; FDDL: TStrings; FAutoCommit: Boolean; FExecuteSelected: Boolean; FRetrievePlan: Boolean; FRetrieveStatistics: Boolean; FAfterExecute: string; FRecordCount: Integer; FResultType: string; FThreadResults: Boolean; FIsolationLevel: string; FTransactionParams: TStringList; FData: TSHComponent; function GetSQL: TStrings; procedure SetSQL(Value: TStrings); function GetDDL: TStrings; procedure SetDDL(Value: TStrings); {IibSHSQLEditor, IibSHDDLInfo} function GetAutoCommit: Boolean; procedure SetAutoCommit(Value: Boolean); function GetExecuteSelected: Boolean; procedure SetExecuteSelected(Value: Boolean); function GetRetrievePlan: Boolean; procedure SetRetrievePlan(Value: Boolean); function GetRetrieveStatistics: Boolean; procedure SetRetrieveStatistics(Value: Boolean); function GetAfterExecute: string; procedure SetAfterExecute(Value: string); function GetRecordCountFrmt: string; function GetResultType: string; procedure SetResultType(Value: string); function GetThreadResults: Boolean; procedure SetThreadResults(Value: Boolean); function GetIsolationLevel: string; procedure SetIsolationLevel(Value: string); function GetTransactionParams: TStrings; procedure SetTransactionParams(Value: TStrings); procedure SetRecordCount; function GetData: IibSHData; function GetStatistics: IibSHStatistics; protected function QueryInterface(const IID: TGUID; out Obj): HResult; override; stdcall; procedure SetOwnerIID(Value: TGUID); override; function GetState: TSHDBComponentState; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; property ThreadResults: Boolean read GetThreadResults write SetThreadResults; property ResultType: string read GetResultType write SetResultType; property AfterExecute: string read GetAfterExecute write SetAfterExecute; property SQL: TStrings read GetSQL write SetSQL; property DDL: TStrings read GetDDL write SetDDL; property Data: IibSHData read GetData; property Statistics: IibSHStatistics read GetStatistics; property AutoCommit: Boolean read GetAutoCommit write SetAutoCommit; published property RetrievePlan: Boolean read GetRetrievePlan write SetRetrievePlan; property RetrieveStatistics: Boolean read GetRetrieveStatistics write SetRetrieveStatistics; // property AutoCommit: Boolean read GetAutoCommit write SetAutoCommit; property ExecuteSelected: Boolean read GetExecuteSelected write SetExecuteSelected; // property ResultType: string read GetResultType write SetResultType; // property AfterExecute: string read GetAfterExecute write SetAfterExecute; property IsolationLevel: string read GetIsolationLevel write SetIsolationLevel; property TransactionParams: TStrings read GetTransactionParams write SetTransactionParams; // property ThreadResults: Boolean read GetThreadResults write SetThreadResults; end; TibSHSQLEditorFactory = class(TibBTToolFactory) end; procedure Register(); implementation uses ibSHConsts, ibSHSQLs, ibSHSQLEditorActions, ibSHSQLEditorEditors; procedure Register(); begin SHRegisterImage(GUIDToString(IibSHSQLEditor), 'SQLEditor.bmp'); SHRegisterImage(TibSHSQLEditorPaletteAction.ClassName, 'SQLEditor.bmp'); SHRegisterImage(TibSHSQLEditorFormAction_SQLText.ClassName, 'Form_DMLText.bmp'); SHRegisterImage(TibSHSQLEditorFormAction_QueryResults.ClassName, 'Form_Data_Grid.bmp'); SHRegisterImage(TibSHSQLEditorFormAction_BlobEditor.ClassName, 'Form_Data_Blob.bmp'); SHRegisterImage(TibSHSQLEditorFormAction_DataForm.ClassName, 'Form_Data_VCL.bmp'); SHRegisterImage(TibSHSQLEditorFormAction_QueryStatistics.ClassName, 'Form_QueryStatistics.bmp'); SHRegisterImage(TibSHSQLEditorFormAction_DDLText.ClassName, 'Form_DDLText.bmp'); SHRegisterImage(TibSHSQLEditorToolbarAction_PrevQuery.ClassName, 'Button_Query_Prev.bmp'); SHRegisterImage(TibSHSQLEditorToolbarAction_NextQuery.ClassName, 'Button_Query_Next.bmp'); SHRegisterImage(TibSHSQLEditorToolbarAction_Run.ClassName, 'Button_Run.bmp'); SHRegisterImage(TibSHSQLEditorToolbarAction_RunAndFetchAll.ClassName, 'Button_RunAndFetch.bmp'); SHRegisterImage(TibSHSQLEditorToolbarAction_Prepare.ClassName, 'Button_RunPrepare.bmp'); SHRegisterImage(TibSHSQLEditorToolbarAction_Commit.ClassName, 'Button_TrCommit.bmp'); SHRegisterImage(TibSHSQLEditorToolbarAction_Rollback.ClassName, 'Button_TrRollback.bmp'); SHRegisterImage(SCallStatistics, 'Form_QueryStatistics.bmp'); SHRegisterComponents([ TibSHSQLEditor, TibSHSQLEditorFactory]); SHRegisterActions([ TibSHSQLEditorPaletteAction, TibSHSQLEditorFormAction_SQLText, TibSHSQLEditorFormAction_QueryResults, TibSHSQLEditorFormAction_DataForm, TibSHSQLEditorFormAction_BlobEditor, TibSHSQLEditorFormAction_QueryStatistics, TibSHSQLEditorFormAction_DDLText, // TibSHSQLEditorToolbarAction_, TibSHSQLEditorToolbarAction_Run, TibSHSQLEditorToolbarAction_RunAndFetchAll, // TibSHSQLEditorToolbarAction_, TibSHSQLEditorToolbarAction_Prepare, // TibSHSQLEditorToolbarAction_EndTransactionSeparator, TibSHSQLEditorToolbarAction_Commit, TibSHSQLEditorToolbarAction_Rollback, TibSHSQLEditorToolbarAction_PrevQuery, TibSHSQLEditorToolbarAction_NextQuery]); SHRegisterActions([ TibSHSQLEditorEditorAction_LoadLastContext, TibSHSQLEditorEditorAction_RecordCount, TibSHSQLEditorEditorAction_CreateNew]); SHRegisterPropertyEditor(IibSHSQLEditor, SCallAfterExecute, TibBTAfterExecutePropEditor); SHRegisterPropertyEditor(IibSHSQLEditor, SCallResultType, TibBTResultTypePropEditor); SHRegisterPropertyEditor(IibSHSQLEditor, SCallIsolationLevel, TibBTIsolationLevelPropEditor); end; { TibSHSQLEditor } constructor TibSHSQLEditor.Create(AOwner: TComponent); begin inherited Create(AOwner); FSQL := TStringList.Create; FDDL := TStringList.Create; FExecuteSelected := True; FRetrievePlan := True; FRetrieveStatistics := True; FAfterExecute := Format('%s', [AfterExecutes[1]]); FResultType := Format('%s', [ResultTypes[0]]); FTransactionParams := TStringList.Create; FRecordCount := -2; end; destructor TibSHSQLEditor.Destroy; begin FSQL.Free; FDDL.Free; if Assigned(FData) then FData.Free; inherited Destroy; end; function TibSHSQLEditor.GetSQL: TStrings; begin Result := FSQL; end; procedure TibSHSQLEditor.SetSQL(Value: TStrings); begin FSQL.Assign(Value); end; function TibSHSQLEditor.GetDDL: TStrings; begin Result := FDDL; end; procedure TibSHSQLEditor.SetDDL(Value: TStrings); begin FDDL.Assign(Value); end; function TibSHSQLEditor.GetAutoCommit: Boolean; begin Result := FAutoCommit; end; procedure TibSHSQLEditor.SetAutoCommit(Value: Boolean); var I: Integer; vSQLEditorForm: IibSHSQLEditorForm; vMsg: string; begin if FAutoCommit <> Value then begin if Data.Transaction.InTransaction then begin if Data.Dataset.Active then vMsg := SCloseResult else vMsg := SCommitTransaction; if Designer.ShowMsg(vMsg, mtConfirmation) then begin Data.Transaction.Commit; for I := 0 to Pred(ComponentForms.Count) do if Supports(ComponentForms[I], IibSHSQLEditorForm, vSQLEditorForm) then begin vSQLEditorForm.ShowTransactionCommited; Break; end; end else Exit; end; if Value then begin MakePropertyInvisible('IsolationLevel'); MakePropertyInvisible('TransactionParams'); end else begin MakePropertyVisible('IsolationLevel'); if AnsiSameText(IsolationLevel, IsolationLevels[4]) then MakePropertyVisible('TransactionParams'); end; FAutoCommit := Value; Designer.UpdateObjectInspector; end; end; function TibSHSQLEditor.GetExecuteSelected: Boolean; deprecated; begin Result := FExecuteSelected; end; procedure TibSHSQLEditor.SetExecuteSelected(Value: Boolean); deprecated; begin FExecuteSelected := Value; end; function TibSHSQLEditor.GetRetrievePlan: Boolean; begin Result := FRetrievePlan; end; procedure TibSHSQLEditor.SetRetrievePlan(Value: Boolean); begin FRetrievePlan := Value; end; function TibSHSQLEditor.GetAfterExecute: string; begin Result := FAfterExecute; end; function TibSHSQLEditor.GetRetrieveStatistics: Boolean; begin Result := FRetrieveStatistics; end; procedure TibSHSQLEditor.SetRetrieveStatistics(Value: Boolean); begin FRetrieveStatistics := Value and Assigned(Statistics); end; procedure TibSHSQLEditor.SetAfterExecute(Value: string); begin FAfterExecute := Value; end; function TibSHSQLEditor.GetRecordCountFrmt: string; begin case FRecordCount of -2: Result := EmptyStr; -1: Result := Format('%s', [SCantCountRecords]); 0: Result := Format('%s', [SEmpty]); else Result := FormatFloat('###,###,###,###', FRecordCount); end; end; function TibSHSQLEditor.GetResultType: string; begin Result := FResultType; end; procedure TibSHSQLEditor.SetResultType(Value: string); begin FResultType := Value; end; function TibSHSQLEditor.GetThreadResults: Boolean; begin Result := FThreadResults; end; procedure TibSHSQLEditor.SetThreadResults(Value: Boolean); begin FThreadResults := Value; end; function TibSHSQLEditor.GetIsolationLevel: string; begin Result := FIsolationLevel; end; procedure TibSHSQLEditor.SetIsolationLevel(Value: string); begin if not AnsiSameText(FIsolationLevel, Value) then begin if not AnsiSameText(Value, IsolationLevels[4]) then begin MakePropertyInvisible('TransactionParams'); end else begin MakePropertyVisible('TransactionParams'); end; FIsolationLevel := Value; Designer.UpdateObjectInspector; end; end; function TibSHSQLEditor.GetTransactionParams: TStrings; begin Result := FTransactionParams; end; procedure TibSHSQLEditor.SetTransactionParams(Value: TStrings); begin if Assigned(Value) and not AnsiSameText(FTransactionParams.Text, Value.Text) then FTransactionParams.Assign(Value); end; procedure TibSHSQLEditor.SetRecordCount; var vSQLEditorForm: IibSHSQLEditorForm; vSQLText: string; vFromClauseCoord: TPoint; S: string; vDRVParams: IibSHDRVParams; vInputParameters: IibSHInputParameters; vCanContinue: Boolean; vComponentClass: TSHComponentClass; vComponent: TSHComponent; begin FRecordCount := -1; if GetComponentFormIntf(IibSHSQLEditorForm, vSQLEditorForm) then begin vSQLText := vSQLEditorForm.SQLText; if Supports(BTCLDatabase.DRVDatabase,IibSHDRVDatabaseExt) then s:= (BTCLDatabase.DRVDatabase as IibSHDRVDatabaseExt).GetRecordCountSelect(vSQLText) else begin if (Length(vSQLText) > 0) and (PosExtCI('DISTINCT', vSQLText, CharsBeforeClause,CharsAfterClause) = 0) and (PosExtCI('UNION', vSQLText, CharsBeforeClause,CharsAfterClause) = 0) then begin vFromClauseCoord := DispositionFrom(vSQLText); S := Copy(vSQLText, vFromClauseCoord.X, MaxInt); S :=Format(FormatSQL(SQL_GET_RECORD_COUNT_FROM_SQL_TEXT), [S]); end else s:=''; end; if S<>'' then begin BTCLDatabase.DRVQuery.SQL.Text :=S; vComponentClass := Designer.GetComponent(IibSHInputParameters); vCanContinue := False; if Assigned(vComponentClass) and Supports(BTCLDatabase.DRVQuery, IibSHDRVParams, vDRVParams) then begin vComponent := vComponentClass.Create(nil); try if Supports(vComponent, IibSHInputParameters, vInputParameters) then begin vCanContinue := vInputParameters.InputParameters(vDRVParams); vInputParameters := nil; end; finally FreeAndNil(vComponent); end; vDRVParams := nil; end; if vCanContinue then begin try Screen.Cursor := crHourGlass; //if BTCLDatabase.DRVQuery.ExecSQL(, [], False) then if not BTCLDatabase.DRVQuery.Transaction.InTransaction then BTCLDatabase.DRVQuery.Transaction.StartTransaction; BTCLDatabase.DRVQuery.Execute; FRecordCount := BTCLDatabase.DRVQuery.GetFieldIntValue(0); finally BTCLDatabase.DRVQuery.Transaction.Commit; Screen.Cursor := crDefault; end; end; end; end; end; function TibSHSQLEditor.GetData: IibSHData; begin Supports(FData, IibSHData, Result); end; function TibSHSQLEditor.GetStatistics: IibSHStatistics; begin Supports(FData, IibSHStatistics, Result); end; function TibSHSQLEditor.QueryInterface(const IID: TGUID; out Obj): HResult; var vStatistics: IibSHStatistics; begin if IsEqualGUID(IID, IibSHStatistics) and Assigned(Data) then begin if Supports(Data, IibSHStatistics, vStatistics) then IInterface(Obj) := vStatistics; if Pointer(Obj) <> nil then Result := S_OK else Result := E_NOINTERFACE; end else if IsEqualGUID(IID, IibSHData) and Assigned(Data) then begin IInterface(Obj) := Data; if Pointer(Obj) <> nil then Result := S_OK else Result := E_NOINTERFACE; end else Result := inherited QueryInterface(IID, Obj); end; procedure TibSHSQLEditor.SetOwnerIID(Value: TGUID); var vComponentClass: TSHComponentClass; begin if not IsEqualGUID(OwnerIID, Value) then begin inherited SetOwnerIID(Value); if Assigned(BTCLDatabase) then begin if Assigned(FData) then FData.Free; vComponentClass := Designer.GetComponent(IibSHData); if Assigned(vComponentClass) then FData := vComponentClass.Create(Self); AutoCommit := BTCLDatabase.DatabaseAliasOptions.DML.AutoCommit; IsolationLevel := BTCLDatabase.DatabaseAliasOptions.DML.IsolationLevel; TransactionParams := BTCLDatabase.DatabaseAliasOptions.DML.TransactionParams; end; end; end; function TibSHSQLEditor.GetState: TSHDBComponentState; begin Result := csAlter; end; procedure TibSHSQLEditor.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); end; initialization Register; end.
unit ControllerObjectCommandList; interface uses ControllerObjectCommandItem, ControllerDataTypes; type TControllerObjectCommandList = class protected FCurrentCommand, FMaxCommand: integer; FCommands: array of TControllerObjectCommandItem; public // Constructors and Destructors. constructor Create; destructor Destroy; override; procedure Clear; // Adds & Removes procedure Add(_Command: longint; var _Params: TCommandParams); // Gets function GetCommand(_ID: integer): TControllerObjectCommandItem; function GetCurrentCommand: TControllerObjectCommandItem; function HasCommandsToBeExecuted: boolean; // Properties property CurrentCommandID: integer read FCurrentCommand; property CurrentCommand: TControllerObjectCommandItem read GetCurrentCommand; property Command[_ID: integer]: TControllerObjectCommandItem read GetCommand; end; implementation uses Math; constructor TControllerObjectCommandList.Create; begin FCurrentCommand := 0; FMaxCommand := -1; SetLength(FCommands, 0); end; destructor TControllerObjectCommandList.Destroy; begin Clear; inherited Destroy; end; procedure TControllerObjectCommandList.Clear; var i: integer; begin for i := Low(FCommands) to min(FMaxCommand, High(FCommands)) do begin FCommands[i].Free; end; SetLength(FCommands, 0); FMaxCommand := -1; FCurrentCommand := 0; end; procedure TControllerObjectCommandList.Add(_Command: longint; var _Params: TCommandParams); begin inc(FMaxCommand); if FMaxCommand > High(FCommands) then begin SetLength(FCommands, High(FCommands) + 50); end; FCommands[FMaxCommand] := TControllerObjectCommandItem.Create(_Command, _Params); end; function TControllerObjectCommandList.GetCommand(_ID: integer): TControllerObjectCommandItem; begin if (_ID >= 0) and (_ID <= FMaxCommand) then begin Result := FCommands[_ID]; end else begin Result := nil; end; end; function TControllerObjectCommandList.GetCurrentCommand: TControllerObjectCommandItem; begin if FMaxCommand >= 0 then begin Result := FCommands[FCurrentCommand]; inc(FCurrentCommand); end else Result := nil; end; function TControllerObjectCommandList.HasCommandsToBeExecuted: boolean; begin Result := FCurrentCommand <= FMaxCommand; end; end.
unit PaidePrinter; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, siComp, siLangRT, uFrmMemo, uParentAll; type TFrmParentPrint = class(TFrmParentAll) procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } protected MyMemo : TFrmMemo; procedure ImpMemoDBInfo(Text:String); procedure ImpMemoNoEmptyLine(Text:String); public { Public declarations } end; var FrmParentPrint: TFrmParentPrint; implementation uses uDM; {$R *.DFM} procedure TFrmParentPrint.ImpMemoNoEmptyLine(Text:String); var i : Integer; begin if Trim(Text) = '' then Exit; MyMemo.MemoClear; MyMemo.AddText(Text); for i:=0 to MyMemo.MemoLineCount-1 do if not MyMemo.MemoEmptyLine(i) then DM.PrintLine(MyMemo.MemoReadLine(i)); end; procedure TFrmParentPrint.ImpMemoDBInfo(Text:String); var i : Integer; begin if Trim(Text) = '' then Exit; MyMemo.MemoClear; MyMemo.AddText(Text); for i:=0 to MyMemo.MemoLineCount-1 do DM.PrintLine(MyMemo.MemoReadLine(i)); end; procedure TFrmParentPrint.FormCreate(Sender: TObject); begin inherited; MyMemo := TFrmMemo.Create(Self); end; procedure TFrmParentPrint.FormDestroy(Sender: TObject); begin inherited; FreeAndNil(MyMemo); end; end.
namespace org.me.openglapplication; //Sample app by Brian Long (http://blong.com) { This example demonstrates a number of things: - two different OpenGL views, one drawing a spinning coloured square, the other drawing a spinning, transparent cube - how to get OpenGL to draw on a transparent background so you see the previously active view - how to pass information to launched activities via Intent - how to construct a class from a type name - how to implement an About box - how to set up an options menu - how to use ListActivity, a handy Activity descendant that manages a scrolling list of items in conjunction with an adapter } interface uses java.util, android.os, android.app, android.content, android.util, android.view, android.widget, android.util; type MainActivity = public class(ListActivity) private //List menu items const ID_OPENGL_SQUARE = 0; const ID_OPENGL_SQUARE_TRANSLUCENT = 1; const ID_OPENGL_CUBE = 2; const ID_OPENGL_CUBE_TRANSLUCENT = 3; //Options menu items const ID_ABOUT = 1; public method onCreate(savedInstanceState: Bundle); override; method onListItemClick(l: ListView; v: View; position: Integer; id: Int64); override; method onCreateOptionsMenu(menu: Menu): Boolean; override; method onOptionsItemSelected(item: MenuItem): Boolean; override; //Misc const Tag = "OpenGLApp"; end; implementation method MainActivity.onCreate(savedInstanceState: Bundle); begin inherited; var rows := Resources.StringArray[R.array.menu_titles]; var rowSubtitles := Resources.StringArray[R.array.menu_subtitles]; if rows.length <> rowSubtitles.length then Log.e(Tag, "Menu titles & subtitles have mismatched lengths"); var listViewContent := new ArrayList<Map<String, Object>>(); for i: Integer := 0 to rows.length - 1 do begin var map := new HashMap<String, Object>(); map.put("heading", rows[i]); map.put("subheading", rowSubtitles[i]); listViewContent.add(map); end; //Set up adapter for the ListView using an Android list item template //ListAdapter := new SimpleAdapter(Self, listViewContent, Android.R.Layout.simple_expandable_list_item_2, // ["heading", "subheading"], [Android.R.id.text1, Android.R.id.text2]); //Set up adapter for the ListView using a custom list item template ListAdapter := new SimpleAdapter(Self, listViewContent, R.layout.listitem_twolines, ["heading", "subheading"], [Android.R.id.text1, Android.R.id.text2]); end; method MainActivity.onListItemClick(l: ListView; v: View; position: Integer; id: Int64); begin var i := new Intent(Self, typeOf(OpenGLActivity)); case position of ID_OPENGL_SQUARE: i.putExtra(OpenGLActivity.OpenGLRendererClass, typeOf(GLSquareRenderer).Name); ID_OPENGL_SQUARE_TRANSLUCENT: begin i.putExtra(OpenGLActivity.OpenGLRendererClass, typeOf(GLSquareRenderer).Name); i.putExtra(OpenGLActivity.IsTranslucent, True); end; ID_OPENGL_CUBE: i.putExtra(OpenGLActivity.OpenGLRendererClass, typeOf(GLCubeRenderer).Name); else begin i.putExtra(OpenGLActivity.OpenGLRendererClass, typeOf(GLCubeRenderer).Name); i.putExtra(OpenGLActivity.IsTranslucent, True); end; end; startActivity(i); end; method MainActivity.onCreateOptionsMenu(menu: Menu): Boolean; begin var item := menu.add(0, ID_ABOUT, 0, R.string.about_menu); //Options menu items support icons item.Icon := Android.R.drawable.ic_menu_info_details; Result := True; end; method MainActivity.onOptionsItemSelected(item: MenuItem): Boolean; begin if item.ItemId = ID_ABOUT then begin startActivity(new Intent(Self, typeOf(AboutActivity))); exit True end; exit False; end; end.
unit FileUtil; {******************************************************************************* Program Modifications: -------------------------------------------------------------------------------- Date UserId Description ------------------------------------------------------------------------------- 11-29-2006 GN01 Modified the file version display *******************************************************************************} interface uses Windows, SysUtils, Classes, Consts; type EInvalidDest = class(EStreamError); EFCantMove = class(EStreamError); TVerInfo = class private fVersBuffer : string; fCompanyNameText : string; fFileDescriptionText : string; fFileVersionText : string; fInternalNameText : string; fLegalCopyrightText : string; fLegalTrademarksText : string; fOriginalFilenameText : string; fProductNameText : string; fProductVersionText : string; fCommentsText : string; public Constructor Create(f:string); destructor Destroy; override; property CompanyNameText : string read fCompanyNameText; property FileDescriptionText : string read fFileDescriptionText; property FileVersionText : string read fFileVersionText; property InternalNameText : string read fInternalNameText; property LegalCopyrightText : string read fLegalCopyrightText; property LegalTrademarksText : string read fLegalTrademarksText; property OriginalFilenameText : string read fOriginalFilenameText; property ProductNameText : string read fProductNameText; property ProductVersionText : string read fProductVersionText; property CommentsText : string read fCommentsText; end; procedure CopyFile(const FileName, DestName: string); procedure MoveFile(const FileName, DestName: string); function GetFileSize(const FileName: string): LongInt; function FileDateTime(const FileName: string): TDateTime; function HasAttr(const FileName: string; Attr: Word): Boolean; function ExecuteFile(const FileName, Params, DefaultDir: string; ShowCmd: Integer): THandle; Function GetFileVersion(const FileName: string):string; function GetComputerNetName: string; Function GetUserFromWindows: string; implementation uses Forms, ShellAPI; const SInvalidDest = 'Destination %s does not exist'; SFCantMove = 'Cannot move file %s'; procedure CopyFile(const FileName, DestName: TFileName); var CopyBuffer: Pointer; { buffer for copying } BytesCopied: Longint; Source, Dest: Integer; { handles } Destination: TFileName; { holder for expanded destination name } const ChunkSize: Longint = 8192; { copy in 8K chunks } begin Destination := ExpandFileName(DestName); { expand the destination path } //if HasAttr(Destination, faDirectory) then { if destination is a directory... } // Destination := Destination + '\' + ExtractFileName(FileName); { ...clone file name } GetMem(CopyBuffer, ChunkSize); { allocate the buffer } try Source := FileOpen(FileName, fmShareDenyWrite); { open source file } if Source < 0 then raise EFOpenError.CreateFmt(SFOpenError, [FileName]); try Dest := FileCreate(Destination); { create output file; overwrite existing } if Dest < 0 then raise EFCreateError.CreateFmt(SFCreateError, [Destination]); try repeat BytesCopied := FileRead(Source, CopyBuffer^, ChunkSize); { read chunk } if BytesCopied > 0 then { if we read anything... } FileWrite(Dest, CopyBuffer^, BytesCopied); { ...write chunk } until BytesCopied < ChunkSize; { until we run out of chunks } finally FileClose(Dest); { close the destination file } end; finally FileClose(Source); { close the source file } end; finally FreeMem(CopyBuffer, ChunkSize); { free the buffer } end; end; { MoveFile procedure } { Moves the file passed in FileName to the directory specified in DestDir. Tries to just rename the file. If that fails, try to copy the file and delete the original. Raises an exception if the source file is read-only, and therefore cannot be deleted/moved. } procedure MoveFile(const FileName, DestName: string); var Destination: string; begin Destination := ExpandFileName(DestName); { expand the destination path } if not RenameFile(FileName, Destination) then { try just renaming } begin if HasAttr(FileName, faReadOnly) then { if it's read-only... } raise EFCantMove.Create(Format(SFCantMove, [FileName])); { we wouldn't be able to delete it } CopyFile(FileName, Destination); { copy it over to destination...} // DeleteFile(FileName); { ...and delete the original } end; end; { GetFileSize function } { Returns the size of the named file without opening the file. If the file doesn't exist, returns -1. } function GetFileSize(const FileName: string): LongInt; var SearchRec: TSearchRec; begin if FindFirst(ExpandFileName(FileName), faAnyFile, SearchRec) = 0 then Result := SearchRec.Size else Result := -1; end; function FileDateTime(const FileName: string): System.TDateTime; begin Result := FileDateToDateTime(FileAge(FileName)); end; function HasAttr(const FileName: string; Attr: Word): Boolean; begin Result := (FileGetAttr(FileName) and Attr) = Attr; end; function ExecuteFile(const FileName, Params, DefaultDir: string; ShowCmd: Integer): THandle; var zFileName, zParams, zDir: array[0..79] of Char; begin Result := ShellExecute(Application.MainForm.Handle, nil, StrPCopy(zFileName, FileName), StrPCopy(zParams, Params), StrPCopy(zDir, DefaultDir), ShowCmd); end; Constructor TVerInfo.Create(f:string); var dataSize : integer; Dummy : integer; TempString : String; begin dataSize := GetFileVersionInfoSize(PChar(f), Dummy); if not (dataSize<=0) then begin SetLength(fVersBuffer,dataSize); SetLength(TempString,dataSize); GetFileVersionInfo(PChar(f),Dummy,DataSize,PChar(fVersBuffer)); VerQueryValue(PChar(fVersBuffer),'\StringFileInfo\040904E4\CompanyName', Pointer(TempString),DataSize); fCompanyNameText := StrPas(Pchar(TempString)); VerQueryValue(PChar(fVersBuffer),'\StringFileInfo\040904E4\FileDescription', Pointer(TempString),DataSize); fFileDescriptionText := StrPas(Pchar(TempString)); VerQueryValue(PChar(fVersBuffer),'\StringFileInfo\040904E4\FileVersion', Pointer(TempString),DataSize); fFileVersionText := StrPas(Pchar(TempString)); VerQueryValue(PChar(fVersBuffer),'\StringFileInfo\040904E4\InternalName', Pointer(TempString),DataSize); fInternalNameText := StrPas(Pchar(TempString)); VerQueryValue(PChar(fVersBuffer),'\StringFileInfo\040904E4\LegalCopyright', Pointer(TempString),DataSize); fLegalCopyrightText := StrPas(Pchar(TempString)); VerQueryValue(PChar(fVersBuffer),'\StringFileInfo\040904E4\LegalTrademarks', Pointer(TempString),DataSize); fLegalTrademarksText := StrPas(Pchar(TempString)); VerQueryValue(PChar(fVersBuffer),'\StringFileInfo\040904E4\OriginalFilename' , Pointer(TempString),DataSize); fOriginalFilenameText := StrPas(Pchar(TempString)); VerQueryValue(PChar(fVersBuffer),'\StringFileInfo\040904E4\ProductName', Pointer(TempString),DataSize); fProductNameText := StrPas(Pchar(TempString)); VerQueryValue(PChar(fVersBuffer),'\StringFileInfo\040904E4\ProductVersion', Pointer(TempString),DataSize); fProductVersionText := StrPas(Pchar(TempString)); VerQueryValue(PChar(fVersBuffer),'\StringFileInfo\040904E4\Comments', Pointer(TempString),DataSize); fCommentsText := StrPas(Pchar(TempString)); end; end; destructor TVerInfo.Destroy; begin inherited; end; {GN01 Function GetFileVersion(const FileName: string):string; var v1:TVerInfo; begin result:=''; v1:=TVerInfo.Create(FileName); result:=v1.fFileVersionText; v1.destroy; end; } function GetFileVersion(const FileName: TFileName): string; var size, len: integer; handle: THandle; buffer: pchar; pinfo: ^TVSFixedFileInfo; Major, Minor, Release, Build: word; begin Result := ''; size := GetFileVersionInfoSize(Pointer(FileName), handle); if size > 0 then begin GetMem(buffer, size); if GetFileVersionInfo(Pointer(FileName), 0, size, buffer) then if VerQueryValue(buffer, '\', pointer(pinfo), len) then begin Major := HiWord(pinfo.dwFileVersionMS); Minor := LoWord(pinfo.dwFileVersionMS); Release := HiWord(pinfo.dwFileVersionLS); Build := LoWord(pinfo.dwFileVersionLS); //gn01: Result := Format('Version %d.%d.%d%s%d%s', [Major, Minor, Release, '(Build', Build, ')']); Result := Format('Version %d.%d%s%d%s', [Major, Minor, '(Build', Build, ')']); end; FreeMem(buffer); end; end; function GetComputerNetName: string; var buffer: array[0..255] of char; size: dword; begin size := 256; if GetComputerName(buffer, size) then Result := buffer else Result := '' end; Function GetUserFromWindows: string; Var UserName : string; UserNameLen : Dword; Begin UserNameLen := 255; SetLength(userName, UserNameLen) ; If GetUserName(PChar(UserName), UserNameLen) Then Result := Copy(UserName,1,UserNameLen - 1) Else Result := 'Unknown'; End; end.
unit BufferedStream_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TFormReaderWriter = class(TForm) btnWrite: TButton; btnRead: TButton; btnReadBuffered: TButton; Label1: TLabel; Memo1: TMemo; procedure btnWriteClick(Sender: TObject); procedure btnReadClick(Sender: TObject); procedure btnReadBufferedClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormReaderWriter: TFormReaderWriter; implementation {$R *.dfm} uses System.Diagnostics; procedure TFormReaderWriter.btnReadBufferedClick(Sender: TObject); var buffStr: TBufferedFileStream; Total: Integer; sw: TStopwatch; ch: Char; begin sw := TStopwatch.StartNew; buffStr := TBufferedFileStream.Create('test.txt', fmOpenRead ); try Total := 0; while buffStr.Read (ch, 1) = 1 do begin if ch = #13 then Inc(Total); end; Memo1.Lines.Add ('Lines: ' + Total.ToString); finally buffStr.Free; end; sw.Stop; Memo1.Lines.Add ('msec: ' + sw.ElapsedMilliseconds.ToString); end; procedure TFormReaderWriter.btnWriteClick(Sender: TObject); var sw: TStreamWriter; I: Integer; begin sw := TStreamWriter.Create( 'test.txt', False, TEncoding.UTF8); try // write 100K lines sw.WriteLine ('Hello, world'); for I := 1 to 99999 do sw.WriteLine ('Hello ' + I.ToString); finally sw.Free; end; Memo1.Lines.Add ('File written'); end; procedure TFormReaderWriter.btnReadClick(Sender: TObject); var fStr: TFileStream; Total: Integer; sw: TStopwatch; ch: Char; begin sw := TStopwatch.StartNew; fStr := TFileStream.Create('test.txt', fmOpenRead ); try Total := 0; while fStr.Read (ch, 1) = 1 do begin if ch = #13 then Inc(Total); end; Memo1.Lines.Add ('Lines: ' + Total.ToString); finally fStr.Free; end; sw.Stop; Memo1.Lines.Add ('msec: ' + sw.ElapsedMilliseconds.ToString); end; end.
unit HlpBlake2SIvBuilder; {$I ..\..\Include\HashLib.inc} interface uses {$IFDEF DELPHI} HlpBitConverter, {$ENDIF DELPHI} HlpConverters, HlpBlake2STreeConfig, HlpIBlake2SConfig, HlpIBlake2STreeConfig, HlpHashLibTypes; resourcestring SInvalidHashSize = '"HashSize" Must Be Greater Than 0 And Less Than or Equal To 32'; SInvalidKeyLength = '"Key" Length Must Not Be Greater Than 32'; SInvalidPersonalisationLength = '"Personalisation" Length Must Be Equal To 8'; SInvalidSaltLength = '"Salt" Length Must Be Equal To 8'; STreeIncorrectInnerHashSize = 'Tree Inner Hash Size Must Not Be Greater Than 32'; type TBlake2SIvBuilder = class sealed(TObject) strict private class var FSequentialTreeConfig: IBlake2STreeConfig; class procedure VerifyConfigS(const config: IBlake2SConfig; const treeConfig: IBlake2STreeConfig; isSequential: Boolean); static; class constructor Blake2SIvBuilder(); public class function ConfigS(const config: IBlake2SConfig; var treeConfig: IBlake2STreeConfig): THashLibUInt32Array; static; end; implementation { TBlake2SIvBuilder } class procedure TBlake2SIvBuilder.VerifyConfigS(const config: IBlake2SConfig; const treeConfig: IBlake2STreeConfig; isSequential: Boolean); begin // digest length if ((config.HashSize <= 0) or (config.HashSize > 32)) then begin raise EArgumentOutOfRangeHashLibException.CreateRes(@SInvalidHashSize); end; // Key length if (config.Key <> Nil) then begin if (System.Length(config.Key) > 32) then begin raise EArgumentOutOfRangeHashLibException.CreateRes(@SInvalidKeyLength); end; end; // Salt length if (config.Salt <> Nil) then begin if (System.Length(config.Salt) <> 8) then begin raise EArgumentOutOfRangeHashLibException.CreateRes(@SInvalidSaltLength); end; end; // Personalisation length if (config.Personalisation <> Nil) then begin if (System.Length(config.Personalisation) <> 8) then begin raise EArgumentOutOfRangeHashLibException.CreateRes (@SInvalidPersonalisationLength); end; end; // Tree InnerHashSize if (treeConfig <> Nil) then begin if ((not isSequential) and ((treeConfig.InnerHashSize <= 0))) then begin raise EArgumentOutOfRangeHashLibException.Create ('treeConfig.TreeIntermediateHashSize'); end; if (treeConfig.InnerHashSize > 32) then begin raise EArgumentOutOfRangeHashLibException.CreateRes (@STreeIncorrectInnerHashSize); end; end; end; class constructor TBlake2SIvBuilder.Blake2SIvBuilder; begin FSequentialTreeConfig := TBlake2STreeConfig.Create(); FSequentialTreeConfig.FanOut := 1; FSequentialTreeConfig.MaxDepth := 1; FSequentialTreeConfig.LeafSize := 0; FSequentialTreeConfig.NodeOffset := 0; FSequentialTreeConfig.NodeDepth := 0; FSequentialTreeConfig.InnerHashSize := 0; FSequentialTreeConfig.IsLastNode := False; end; class function TBlake2SIvBuilder.ConfigS(const config: IBlake2SConfig; var treeConfig: IBlake2STreeConfig): THashLibUInt32Array; var isSequential: Boolean; tempBuffer: THashLibByteArray; begin isSequential := treeConfig = Nil; if (isSequential) then begin treeConfig := FSequentialTreeConfig; end; VerifyConfigS(config, treeConfig, isSequential); System.SetLength(tempBuffer, 32); tempBuffer[0] := config.HashSize; tempBuffer[1] := System.Length(config.Key); if treeConfig <> Nil then begin tempBuffer[2] := treeConfig.FanOut; tempBuffer[3] := treeConfig.MaxDepth; TConverters.ReadUInt32AsBytesLE(treeConfig.LeafSize, tempBuffer, 4); tempBuffer[8] := Byte(treeConfig.NodeOffset); tempBuffer[9] := Byte(treeConfig.NodeOffset shr 8); tempBuffer[10] := Byte(treeConfig.NodeOffset shr 16); tempBuffer[11] := Byte(treeConfig.NodeOffset shr 24); tempBuffer[12] := Byte(treeConfig.NodeOffset shr 32); tempBuffer[13] := Byte(treeConfig.NodeOffset shr 40); tempBuffer[14] := treeConfig.NodeDepth; tempBuffer[15] := treeConfig.InnerHashSize; end; if config.Salt <> Nil then begin System.Move(config.Salt[0], tempBuffer[16], 8 * System.SizeOf(Byte)); end; if config.Personalisation <> Nil then begin System.Move(config.Personalisation[0], tempBuffer[24], 8 * System.SizeOf(Byte)); end; System.SetLength(Result, 8); TConverters.le32_copy(PByte(tempBuffer), 0, PCardinal(Result), 0, System.Length(tempBuffer) * System.SizeOf(Byte)); end; end.
unit LocalizarBase.View; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Base.View, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Silver, cxControls, cxContainer, cxEdit, dxGDIPlusClasses, Vcl.ExtCtrls, cxLabel, Vcl.StdCtrls, cxButtons, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB, cxDBData, cxTextEdit, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinBlack, dxSkinDarkRoom, dxSkinSilver; type TFLocalizarView = class(TFBaseView) Panel6: TPanel; Panel7: TPanel; DbDados: TcxGrid; VwDados: TcxGridDBTableView; LvDados: TcxGridLevel; PnPesquisa: TPanel; ImPesquisa: TImage; TePesquisa: TcxTextEdit; cxLabel2: TcxLabel; FdDados: TFDMemTable; DsDados: TDataSource; private { Private declarations } public { Public declarations } end; var FLocalizarView: TFLocalizarView; implementation {$R *.dfm} end.
unit uMediana; 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.Imaging.jpeg, Vcl.Buttons, System.Actions, Vcl.ActnList; type TforMediana = class(TForm) edtValores: TEdit; ltbValores: TListBox; edtMediana: TEdit; labMediana: TLabel; ltbOrdenada: TListBox; labValoresAdd: TLabel; panelTexto: TPanel; labTitulo: TLabel; lblTexto: TLabel; Image1: TImage; labValoresOrd: TLabel; labValores: TLabel; Calcular: TSpeedButton; spbFechar: TSpeedButton; spbLimpar: TSpeedButton; spbAdicionar: TSpeedButton; actList: TActionList; actAdicionar: TAction; actCalcular: TAction; actLimpar: TAction; actFechar: TAction; procedure FormCreate(Sender: TObject); procedure actAdicionarExecute(Sender: TObject); procedure actCalcularExecute(Sender: TObject); procedure actLimparExecute(Sender: TObject); procedure actFecharExecute(Sender: TObject); private { Private declarations } public { Public declarations } end; var forMediana: TforMediana; cont : integer; //variaveis globais do formMediana valores: array of real; implementation {$R *.dfm} procedure TforMediana.actAdicionarExecute(Sender: TObject); begin if edtValores.Text = '' then //erro quando num tem valor no campo e clicar para adicionar begin Application.MessageBox('Informe valor para adicionar','Por favor',MB_ICONEXCLAMATION+MB_OK); end else begin SetLength(valores, cont+1); //informando a variavel valores e cont valores[Cont]:= StrToFloat(edtValores.Text); //adicionando o conteudo de edtValores.Text a variavel array valores edtValores.clear; ltbValores.Items.Add('Valor ' + floattostr(cont+1) + ' = ' + floatToStr(valores[cont])); //adiciona valores no listBox valores Cont:= Cont + 1; //aumenta o contador end; end; procedure TforMediana.actCalcularExecute(Sender: TObject); var mediana1,mediana2,atual,proximo: integer; //variaveis para calculo da mediana posMediana1,posMediana2,temp: real; begin ltbOrdenada.Clear; if cont < 1 then //erro quando for calcular sem adicionar valores begin Application.MessageBox('Adicione dados para obter a mediana ','Por favor',MB_ICONEXCLAMATION+MB_OK); exit; end; for atual := Low(valores) to (High(valores)-1) do //colocar os valores em ordem crescente com 2 for begin for proximo := atual+1 to High(valores) do begin if valores[atual] > valores[proximo] then //condição para que se troque valor de posição begin temp:= valores[atual]; //coloca valor atual em uma variavel temporaria valores[atual]:= valores[proximo]; //atribui o valor da proxima para a atual valores[proximo]:= temp; //atribui o valor da variavel temporaria a proxima end; end; end; for atual := Low(valores) to High(valores) do //um for para varrer quantidade de numeros adicionados begin ltbOrdenada.Items.Add('Valor ' + floattostr(atual+1) + ' = ' + FloatToStr(valores[atual])); //adiciona valores no listBox ordenados end; if (cont mod 2 <> 0) and (cont > 1) then //condição para calcular mediana quando o numero de valores é impar begin posMediana1:= atual/2; //calcula o numero da posição da mediana mediana1:= trunc(posMediana1); //transforma o numero da posição de real para inteiro edtMediana.Text:= FloatToStr((valores[mediana1])); // coloca o valor da mediana no edtMediana.Text end else if cont mod 2 = 0 then //condição para calcular mediana quando numero de valores é par begin posMediana1:= ((atual-1)/2); //calcular a posição 1 da mediana posMediana2:= (((atual-1)/2)+1); //calcular a posição 2 da mediana mediana1:= trunc(posMediana1); //transforma o numero da posição 1 de real para inteiro mediana2:= trunc(posMediana2); //transforma o numero da posição 2 de real para inteiro edtMediana.Text:= FloatToStr((valores[mediana1]+ valores[mediana2])/2);// coloca o valor da mediana no edtMediana.Text end; end; procedure TforMediana.actFecharExecute(Sender: TObject); begin edtValores.Text:=''; // limpar os dados quando fechar o formMediana edtMediana.Text:=''; cont:=0; edtValores.Clear; ltbValores.Clear; ltbOrdenada.Clear; close; //fechar o showModal da formMediana end; procedure TforMediana.actLimparExecute(Sender: TObject); begin edtValores.Text:=''; //limpando todos os dados de formMediana para iniciar novo calculo com novos valores edtMediana.Text:=''; cont:=0; edtValores.Clear; ltbValores.Clear; ltbOrdenada.Clear; end; procedure TforMediana.FormCreate(Sender: TObject); begin lblTexto.Caption:= //ao criar o formMediana, exibir esse texto no lblTexto.caption dentro do panelTexto 'Para calcular a mediana'+ #13 + 'devemos, em primeiro lugar,'+ #13 + 'ordenar os dados do menor'+ #13 + 'para o maior valor. Se o'+ #13 + 'número de observações for'+ #13 + 'ímpar, a mediana será a'+ #13 + 'observação central. Se o '+ #13 + 'número de observações for '+ #13 + 'par, a mediana será a '+ #13 + 'média aritmética das duas'+ #13 + 'observações centrais.'+ #13 + 'Notação:'; end; end.
unit TestUContasReceberVO; interface uses TestFramework, SysUtils, Atributos, UUnidadeVO, UCondominioVO, Generics.Collections, UGenericVO, Classes, Constantes, UHistoricoVO, UPlanoContasVO, UContasReceberVO; type TestTContasReceberVO = class(TTestCase) strict private FContasReceberVO: TContasReceberVO; public procedure SetUp; override; procedure TearDown; override; published procedure TestValidarCamposErro; procedure TestValidarCampos; procedure TestValidarBaixaErro; procedure TestValidarBaixa; end; implementation procedure TestTContasReceberVO.SetUp; begin FContasReceberVO := TContasReceberVO.Create; end; procedure TestTContasReceberVO.TearDown; begin FContasReceberVO.Free; FContasReceberVO := nil; end; procedure TestTContasReceberVO.TestValidarCampos; var ContasReceber : TContasReceberVO; begin ContasReceber:= TContasReceberVO.Create; ContasReceber.DtCompetencia := StrToDate('01/01/2016'); ContasReceber.DtVencimento := StrToDate('20/01/2016'); ContasReceber.NrDocumento := 'Teste 01'; ContasReceber.VlValor := StrToFloat('10,00'); try ContasReceber.ValidarCampos; Check(true,'sucesso!') except on E: Exception do Check(false,'Erro'); end; end; procedure TestTContasReceberVO.TestValidarCamposErro; var ContasReceber : TContasReceberVO; begin ContasReceber:= TContasReceberVO.Create; ContasReceber.DtCompetencia := StrToDate('01/01/2016'); ContasReceber.DtVencimento := StrToDate('20/01/2016'); ContasReceber.NrDocumento := 'Teste 01'; ContasReceber.VlValor := StrToFloat('0'); try ContasReceber.ValidarCampos; Check(false,'Erro!') except on E: Exception do Check(true,'sucesso!'); end; end; procedure TestTContasReceberVO.TestValidarBaixa; var ContasReceber : TContasReceberVO; begin ContasReceber := TContasReceberVO.Create; ContasReceber:= TContasReceberVO.Create; ContasReceber.DtCompetencia := StrToDate('01/01/2016'); ContasReceber.DtVencimento := StrToDate('20/01/2016'); ContasReceber.NrDocumento := 'Teste 01'; ContasReceber.VlValor := StrToFloat('10,00'); ContasReceber.DtBaixa := StrToDate('20/01/2016'); ContasReceber.VlPago := StrToFloat('10,00'); ContasReceber.VlBaixa := StrToFloat('10,00'); ContasReceber.IdContaBaixa := StrToInt('4'); try ContasReceber.ValidarBaixa; Check(True,'Sucesso!') except on E: Exception do Check(false,'Erro'); end; end; procedure TestTContasReceberVO.TestValidarBaixaErro; var ContasReceber : TContasReceberVO; begin ContasReceber := TContasReceberVO.Create; ContasReceber:= TContasReceberVO.Create; ContasReceber.DtCompetencia := StrToDate('01/01/2016'); ContasReceber.DtVencimento := StrToDate('20/01/2016'); ContasReceber.NrDocumento := 'Teste 01'; ContasReceber.VlValor := StrToFloat('10,00'); ContasReceber.DtBaixa := StrToDate('20/01/2016'); ContasReceber.VlPago := StrToFloat('10,00'); ContasReceber.VlBaixa := StrToFloat('0'); ContasReceber.IdContaBaixa := StrToInt('4'); try ContasReceber.ValidarBaixa; Check(false,'Erro!') except on E: Exception do Check(true,'Sucesso'); end; end; initialization RegisterTest(TestTContasReceberVO.Suite); end.
unit UFNMFacade; {$WARN SYMBOL_PLATFORM OFF} interface uses ActiveX, Mtsobj, Mtx, ComObj, FNMFacade_TLB, StdVcl, ComDllPub, SysUtils, StrUtils, DBClient, DateUtils,Classes, Variants; const DateTimeFmtStr = 'yyyy-mm-dd 07:00:00'; type TFNMFacadeLib = class(TMtsAutoObject, IFNMFacadeLib) protected function GetSql(sQueryType, sCondition: Widestring): Widestring; procedure GetQueryData(var vData: OleVariant; const sType, sCondition: WideString; var sErrorMsg: WideString); safecall; procedure GetMultiData(var vData0, vData1, vData2: OleVariant; const sType, sSQLText: WideString; var sErrorMsg: WideString); safecall; procedure SaveDataBySQL(const sType, sCondition: WideString; var sErrorMsg: WideString); safecall; procedure SaveDataBySQLEx(const sType, sCondition: WideString; var Result, sErrorMsg: WideString); safecall; procedure GetReceiveInfo(var vData: OleVariant; const sNote_NO, sCurrent_Department, sType: WideString; var sErrorMsg: WideString); safecall; procedure SaveReceiveInfo(const sNote_NO, sCurrent_Department, sOperator, sType: WideString; var sErrorMsg: WideString); safecall; procedure CancelFabricInfo(const sNote_NO, sOperator, sType: WideString; var sErrorMsg: WideString); safecall; procedure ServerTime(var currTime: OleVariant); safecall; procedure GetStockInfo(var vData: OleVariant; const sCondition: WideString; var sErrorMsg: WideString); safecall; procedure GetSendInfo(var vData0, vData1, vData2: OleVariant; const sNote_NO, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); safecall; procedure SaveSendInfo(const sFNCardList, sDestination, sCurrent_Department, sOperator: WideString; iType: Integer; var sNote_NO, sErrorMsg: WideString); safecall; procedure GetPrintFNCardInfo(const sCurrent_Department, sCondition: WideString; iType: Integer; var vData: OleVariant; var sErrorMsg: WideString); safecall; procedure SavePrintFNCardInfo(const sFabric_NO_List, sCar_NO: WideString; bIs_CutCloth, bIs_RepairCard: Integer; const sOperator: WideString; var sFN_Card, sErrorMsg: WideString); safecall; procedure SaveSplitFabricInfo(const sFabric_NO: WideString; dSplit_Quantity: Double; const sCurrent_Department, sOperator: WideString; var sNew_Fabric_NO, sErrorMsg: WideString); safecall; procedure GetSplitFabricInfo(var vData: OleVariant; const sFabric_NO, sCurrent_Department: WideString; var sErrorMsg: WideString); safecall; procedure GetReportInfo(const sNote_NO: WideString; iType: Integer; const sCurrent_Department, sPrinter: WideString; var vData0, vData1, vData2: OleVariant; var sErrorMsg: WideString); safecall; procedure SaveUnionFNCardInfo(const sFabric_NO_List, sFN_Card, sCar_NO: WideString; iType: Integer; const sReason, sCurrent_Department, sOperator: WideString; var sNew_FN_Card, sErrorMsg: WideString); safecall; procedure GetUnionFNCardInfo(var vData: OleVariant; const sFN_Card, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); safecall; procedure GetBaseTableInfo(var vData: OleVariant; const sTableName: WideString; var sErrorMsg: WideString); safecall; procedure SaveBaseTableInfo(var vData: OleVariant; const sTableName, sKeyField: WideString; var sErrorMsg: WideString); safecall; procedure SaveWorkerStationInfo(const sWorkerList, sMachine_ID, sCurrent_Department, sOperator: WideString; var sErrorMsg: WideString); safecall; procedure SaveHoldInfo(bIs_Hold, iUnHoldiden: Integer; const iGFKeyValue, sOperationCode, sFnCard: WideString; bIseffectReair: Integer; const sReason, sOperator: WideString; var sErrorMsg: WideString); safecall; procedure SaveGIRepairInfo(const sFabric_NO_List, sCurrent_Department: WideString; var sErrorMsg: WideString); safecall; procedure GetGIRepairInfo(var vData: OleVariant; const sCurrent_Department: WideString; var sErrorMsg: WideString); safecall; procedure GetMachineTaskInfo(var vData: OleVariant; const sMachine_ID, sCurrent_Department: WideString; var sErrorMsg: WideString); safecall; procedure SetMachineOperation(const sFN_Card: WideString; iStep_NO: Integer; const sMachine_ID, sCar_NO: WideString; dSpeed, dWidth: Double; const sOperate_Time, sWorkerList, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); safecall; procedure GetJobTraceInfo(var vData: OleVariant; const sFN_Card, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); safecall; procedure GetWIPInfo(var vData0, vData1, vData2: OleVariant; const sCurrent_Department: WideString; var sErrorMsg: WideString); safecall; procedure GetPlanInfo(var vData0, vData1, vData2: OleVariant; const sMachine_Model, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); safecall; procedure GetChemicalIn_OutDtl(const sDataClass: WideString; dDate: TDateTime; const sCurrent_Department: WideString; var vData: OleVariant; var sErrorMsg: WideString); safecall; procedure GetTheMatterFabric(const sCurrent_Department: WideString; dDate: TDateTime; out vData0, vData1: OleVariant; out sErrorMsg: WideString); safecall; procedure GetSampleList(const sFN_Card, sSample_Code: WideString; out vData: OleVariant; out sErrorMsg: WideString); safecall; procedure SaveChemicalInDtl(vData: OleVariant; out sErrorMsg: WideString); safecall; procedure SaveChemicalOutDtl(vData: OleVariant; out sErrorMsg: WideString); safecall; procedure GetOTDInfo(var vData: OleVariant; const sBegin_Time, sEnd_Time, sQuery_Type, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); safecall; procedure GetWorkerPrizeOrErrorInfo(var vData: OleVariant; const sQuery_Date, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); safecall; procedure GetSCInfo(var vData0, vData1, vData2: OleVariant; const sContract_NO, sCurrent_Department: WideString; var sErrorMsg: WideString); safecall; procedure SaveSCInfo(const sContract_NO, sFNCardList, sCurrent_Department, sOperator: WideString; var sErrorMsg: WideString); safecall; procedure GetFabricReportInfo(var vData: OleVariant; const sBegin_Time, sEnd_Time, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); safecall; procedure AutoArrangePlan(const sOperation_Code, sCurrent_Department: WideString; var sErrorMsg: WideString); safecall; procedure SaveChemicalStockEdit(const sDataType: WideString; vData: OleVariant; const sOperator: WideString; out sErrorMsg: WideString); safecall; procedure CancelPrintFNCardInfo(const sFN_Card, sCurrent_Department, sOperator: WideString; var sErrorMsg: WideString); safecall; procedure GetGIInfo(const sSource, sCurrent_Department: WideString; iType: Integer; var vData: OleVariant; var sErrorMsg: WideString); safecall; procedure SaveGIInfo(const sFabricNOList, sSource, sCurrent_Department, sOperator: WideString; var sErrorMsg: WideString); safecall; procedure GetItemList(var sNoteNOList: OleVariant; const sCode, sCurrent_Department, sType: WideString; var sErrorMsg: WideString); safecall; procedure ChangeGFNO(const sCode, sGFKey, sJob_NO, sReason, sChanger, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); safecall; procedure SaveDistributeInfo(vData: OleVariant; const sFabricNOStr, sMachine_ID, sCurrent_Department: WideString; var sErrorMsg: WideString); safecall; procedure SaveSuspendInfo(const sMachine_ID, sSuspend_Code, sBegin_Time, sEnd_Time, sCurrent_Department, sRemark: WideString; var sErrorMsg: WideString); safecall; procedure GetQyDetail(iQueryIden: Integer; vCondition: OleVariant; out vData: OleVariant; out sErrorMsg: WideString); safecall; procedure GetQyMaster(iQueryIden: Integer; const sPreDeclareVars, sCondition: WideString; out vData: OleVariant; out sErrorMsg: WideString); safecall; procedure GetQyDictionary(const sQyDicName: WideString; out vData: OleVariant; out sErrorMsg: WideString); safecall; procedure AdjustJobTraceDtlInfo(vData: OleVariant; const sIdenList, sOperator, sCurrent_Department: WideString; var sErrorMsg: WideString); safecall; procedure GetJobTraceDtlInfo(var vData: OleVariant; const sParam, sBegin_Time, sEnd_Time, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); safecall; procedure TerminalQuery(var vData: OleVariant; const sParam, sBegin_Time, sEnd_Time, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); safecall; procedure SaveOTDInfo(var vData: OleVariant; iType: Integer; var sErrorMsg: WideString); safecall; procedure SaveCarInfo(const sFNCard, sNewCarNO, sOperator, sAppName, sComputerName: WideString; out sErrorMsg: WideString); safecall; procedure GetShrinkageAnalysisInfo(var vData: OleVariant; const sBegin_Date, sEnd_Date, sCurrent_Department: WideString; var sErrorMsg: WideString); safecall; procedure SaveShrinkageAnalysisInfo(var vData: OleVariant; const sOperator: WideString; var sErrorMsg: WideString); safecall; procedure ChangeMaterialType(const sCode, sMaterial_Type, sDuty_Department, sReason, sChanger, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); safecall; procedure CreateOTDInfo(IType: Integer; var sErrorMsg: WideString); safecall; procedure CancelFIInfo(const sNote_NO, sFabric_NO_List, sOperator: WideString; var sErrorMsg: WideString); safecall; procedure GetChemicalData(iType: Integer; const sCurrent_Department: WideString; dQueryDate: TDateTime; var vData: OleVariant; var sErrorMsg: WideString); safecall; procedure SaveChemicalData(iType: Integer; var vData: OleVariant; var sErrorMsg: WideString); safecall; procedure GetArtAnalysisData(var vData: OleVariant; dQueryDate: TDateTime; const sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); safecall; procedure SaveArtAnalysisData(var vData: OleVariant; var sErrorMsg: WideString); safecall; procedure GetUrgentPpoInfo(var vData: OleVariant; const sGF_NO: WideString; var sErrorMsg: WideString); safecall; procedure SaveUrgentPpoInfo(var vData: OleVariant; var sErrorMsg: WideString); safecall; procedure SaveRepairReason(var vData: OleVariant; iType: Integer; var sErrorMsg: WideString); safecall; procedure DeleteRepairReason(const sReason_Code, sItem_Name: WideString; iType: Integer; var sErrorMsg: WideString); safecall; procedure SaveOTDReason(var vData: OleVariant; iType: Integer; var sErrorMsg: WideString); safecall; procedure SaveReceiveBenchMark(var vData: OleVariant; iCount: Integer; var sErrorMsg: WideString); safecall; procedure SaveMutexChemical(var vData: OleVariant; iCount: Integer; var sErrorMsg: WideString); safecall; procedure GetInnerRepairInfo(const sCurrent_Department, sDatetime: WideString; var vData: OleVariant; var sErrorMsg: WideString); safecall; procedure SaveIgnoredInnerRepairInfo(vData: OleVariant; var sErrorMsg: WideString); safecall; procedure GetRecipeChemical(const sBatchNO: WideString; var vData: OleVariant; var sErrorMsg: WideString); safecall; procedure SaveData(const sType: WideString; vData: OleVariant; var sErrorMsg: WideString); safecall; procedure SaveSDTraceInfo(var vData: OleVariant; iType: Integer; var sErrorMsg: WideString); safecall; procedure SaveRSTraceInfo(var vData: OleVariant; var sErrorMsg: WideString); safecall; procedure SaveSampleInfo(var vParam: OleVariant; var sErrorMsg: WideString); safecall; procedure SaveMultiData(const sTable1, sTable2: WideString; var vData1, vData2: OleVariant; const sSQLText_Before, sSQLText_After, sKey1, sKey2: WideString; var sErrorMsg: WideString); safecall; procedure GetQueryBySQL(var vData: OleVariant; const sSQL: WideString; var sErrMsg: WideString); safecall; procedure SaveSQLData(const sSQL: WideString; var sErrMsg: WideString); safecall; { Protected declarations } end; implementation uses ComServ, DB, Math; function TFNMFacadeLib.GetSql(sQueryType, sCondition: Widestring): Widestring; var fullsql: OleVariant; sqlText,sErrorMsg: WideString; begin try Result := ''; sqlText:='SELECT Query_Text FROM dbo.fnSQLList WITH(NOLOCK) WHERE Query_Type = ' + QuotedStr(Trim(sQueryType)); FNMDAOInfo.GetCommonFieldValue(fullsql,sqlText,sErrorMsg); if VarIsStr(fullsql) and (fullsql <> '') then Result := fullsql + ' ' + sCondition; SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.GetQueryData(var vData: OleVariant; const sType, sCondition: WideString; var sErrorMsg: WideString); var sSQL: WideString; begin try sSQL := GetSql(sType, sCondition); FNMDAOInfo.GetCommonData(vData, sSQL, sErrorMsg); SetComplete; except on e: Exception do begin sErrorMsg := e.Message; SetAbort; end; end; end; procedure TFNMFacadeLib.GetMultiData(var vData0, vData1, vData2: OleVariant; const sType, sSQLText: WideString; var sErrorMsg: WideString); var sSQL: WideString; begin { try sSQL := GetSql(sType, sSQLText); FNMDAOInfo.GetMultiDataSet(sSQL, vData0, vData1, vData2, sErrorMsg); SetComplete; except on e: Exception do begin sErrorMsg := e.Message; SetAbort; end; end; } end; procedure TFNMFacadeLib.SaveDataBySQL(const sType, sCondition: WideString; var sErrorMsg: WideString); var sSQLText: WideString; begin try sSQLText := GetSql(sType, sCondition); FNMDAOUpt.ExeCommonSql(sSQLText, sErrorMsg); if sErrorMsg='' then SetComplete; except on e: Exception do begin sErrorMsg := e.Message; SetAbort; end; end; end; procedure TFNMFacadeLib.SaveDataBySQLEx(const sType, sCondition: WideString; var Result, sErrorMsg: WideString); var sSQLText: WideString; begin try sSQLText := GetSql(sType, sCondition); sSQLText := sSQLText +',:@Result OUTPUT'; FNMDAOUpt.ExeCommonSqlWithResult(sSQLText, '@Result', Result, sErrorMsg); if Result <>'' then SetComplete else SetAbort; except SetAbort; raise; end; end; procedure TFNMFacadeLib.GetReceiveInfo(var vData: OleVariant; const sNote_NO, sCurrent_Department, sType: WideString; var sErrorMsg: WideString); var sqlText:WideString; begin { try sqlText:='EXEC dbo.usp_GetReceiveInfo '+QuotedStr(sNote_NO)+','+ QuotedStr(sCurrent_Department)+','+QuotedStr(sType); FNMDAOInfo.GetCommonDataSet(vData,sqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.SaveReceiveInfo(const sNote_NO,sCurrent_Department, sOperator, sType: WideString; var sErrorMsg: WideString); var sqlText: WideString; begin { try sqlText:='EXEC dbo.usp_SaveReceiveInfo '+QuotedStr(sNote_NO)+','+ QuotedStr(sCurrent_Department)+','+QuotedStr(sOperator)+ ','+ QuotedStr(sType); FNMDAOUpt.ExeCommonSql(sqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.CancelFabricInfo(const sNote_NO, sOperator, sType: WideString; var sErrorMsg: WideString); var sqlText: WideString; begin { try sqlText:='EXEC dbo.usp_CancelFabricInfo '+QuotedStr(sNote_NO)+ ','+ QuotedStr(sOperator)+','+QuotedStr(sType); FNMDAOUpt.ExeCommonSql(sqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.ServerTime(var currTime: OleVariant); var sqlText,sErrorMsg:WideString; begin try sqlText:='SELECT GETDATE()'; FNMDAOInfo.GetCommonFieldValue(currTime,sqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.GetStockInfo(var vData: OleVariant; const sCondition: WideString; var sErrorMsg: WideString); var sqlText:WideString; begin //获取未分布信息 { try sqlText:='SELECT * FROM dbo.uvw_fnStock '+ 'WHERE '+sCondition; FNMDAOInfo.GetCommonDataSet(vData,sqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.GetSendInfo(var vData0, vData1, vData2: OleVariant; const sNote_NO, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); var sqlText:WideString; begin //获取送布前质量CHECK信息或送布信息 { try sqlText := 'EXEC dbo.usp_GetSendInfo '+QuotedStr(sNote_NO)+',' + QuotedStr(sCurrent_Department)+','+IntToStr(iType); FNMDAOInfo.GetMultiDataSet(sqlText,vData0,vData1,vData2,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.SaveSendInfo(const sFNCardList, sDestination, sCurrent_Department, sOperator: WideString; iType: Integer; var sNote_NO, sErrorMsg: WideString); var sqlText: WideString; begin { try if iType = 0 then sqlText:=Format('EXEC dbo.usp_SaveSendInfo ''%s'', ''%s'', ''%s'', ''%s'',:@Note_NO OUTPUT', [sFNCardList, sDestination, sCurrent_Department, sOperator]) else sqlText:=Format('EXEC dbo.usp_ChangeStockDepartmentInfo ''%s'', ''%s'', ''%s'', ''%s'',:@Note_NO OUTPUT', [sFNCardList, sDestination, sCurrent_Department, sOperator]); FNMDAOUpt.ExeCommonSqlWithResult(sqlText, '@Note_NO', sNote_NO, sErrorMsg); if sNote_NO <>'' then SetComplete else SetAbort; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.GetPrintFNCardInfo(const sCurrent_Department, sCondition: WideString; iType: Integer; var vData: OleVariant; var sErrorMsg: WideString); var sqlText:WideString; begin { try sqlText:='EXEC dbo.usp_GetPrintFNCardInfo '+ QuotedStr(sCurrent_Department)+','+ QuotedStr(sCondition)+','+IntToStr(iType); FNMDAOInfo.GetCommonDataSet(vData, sqlText, sErrorMsg); SetComplete; except SetAbort; raise; end;} end; procedure TFNMFacadeLib.SavePrintFNCardInfo(const sFabric_NO_List, sCar_NO: WideString; bIs_CutCloth, bIs_RepairCard: Integer; const sOperator: WideString; var sFN_Card, sErrorMsg: WideString); var sFabricNOList: String; sqlText:WideString; begin { try sFabricNOList := StringReplace(sFabric_NO_List, '`', '#96#', [rfReplaceAll]); SqlText:=Format('EXEC dbo.usp_SavePrintFNCardInfo ''%s'', ''%s'', %d, %d, ''%s'', :@FN_Card OUTPUT', [ sFabricNOList, sCar_NO, bIs_CutCloth, bIs_RepairCard, sOperator]); FNMDAOUpt.ExeCommonSqlWithResult(sqlText, '@FN_Card', sFN_Card, sErrorMsg); if sFN_Card <>'' then SetComplete else SetAbort; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.SaveSplitFabricInfo(const sFabric_NO: WideString; dSplit_Quantity: Double; const sCurrent_Department, sOperator: WideString; var sNew_Fabric_NO, sErrorMsg: WideString); var sqlText:WideString; begin { sqlText:='EXEC dbo.usp_SaveSplitFabricInfo '+QuotedStr(sFabric_NO)+','+ FloatToStr(dSplit_Quantity)+','+QuotedStr(sCurrent_Department)+','+ QuotedStr(sOperator)+',:@New_Fabric_NO OUTPUT'; try FNMDAOUpt.ExeCommonSqlWithResult(sqlText,'@New_Fabric_NO',sNew_Fabric_NO,sErrorMsg); if sNew_Fabric_NO <>'' then SetComplete else SetAbort; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.GetSplitFabricInfo(var vData: OleVariant; const sFabric_NO, sCurrent_Department: WideString; var sErrorMsg: WideString); var sqlText:WideString; begin { sqlText:='SELECT a.FN_Card,a.Fabric_NO,' + #13#10 + ' a.Car_NO,a.Quantity,' + #13#10 + ' a.GF_ID,c.GF_NO,a.Job_NO,b.PPO_NO,b.Customer,b.Delivery_Date,' + #13#10 + ' RTRIM(c.Warp_Count)+''X''+RTRIM(c.Weft_Count) AS WarpWeft_Count,' + #13#10 + ' RTRIM(CONVERT(varchar(20),c.Warp_Density))+''X''+RTRIM(CONVERT(varchar(20),c.Warp_Density))AS WarpWeft_Density,' + #13#10 + ' (SELECT Operate_Time FROM FNMDB.dbo.fnReceiveHdr WITH(NOLOCK) WHERE' + #13#10 + ' Note_NO = a.Note_NO) AS Receive_Date,a.Source,a.Remark' + #13#10 + 'FROM FNMDB.dbo.fnStock a WITH(NOLOCK)' + #13#10 + ' LEFT JOIN PPODB.dbo.arJobMaster b WITH(NOLOCK) ON a.GF_ID = b.GF_ID AND a.Job_NO = b.Job_NO' + #13#10 + ' LEFT JOIN PDMDB.dbo.tdBasicInfo c WITH(NOLOCK) ON c.GF_ID= a.GF_ID' + #13#10 + 'WHERE a.Fabric_NO = '+QuotedStr(sFabric_NO)+' AND a.Current_Department='+ QuotedStr(sCurrent_Department); try FNMDAOInfo.GetCommonDataSet(vData,sqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.GetReportInfo(const sNote_NO: WideString; iType: Integer; const sCurrent_Department, sPrinter: WideString; var vData0, vData1, vData2: OleVariant; var sErrorMsg: WideString); var sqlText:WideString; begin { try sqlText:=Format('EXEC dbo.usp_GetReportInfo ''%s'', %d, ''%s'', ''%s''', [sNote_NO, iType, sCurrent_Department,sPrinter]); FNMDAOInfo.GetMultiDataSet(sqlText,vData0,vData1,vData2,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.SaveUnionFNCardInfo(const sFabric_NO_List, sFN_Card, sCar_NO: WideString; iType: Integer; const sReason, sCurrent_Department, sOperator: WideString; var sNew_FN_Card, sErrorMsg: WideString); var sqlText:WideString; begin { try sqlText:=Format('EXEC dbo.usp_SaveUnionFNCardInfo ''%s'', ''%s'', ''%s'', %d, ''%s'', ''%s'', ''%s'', :@New_FN_Card OUTPUT', [ sFabric_NO_List, sFN_Card, sCar_NO, iType, sReason, sCurrent_Department, sOperator]); FNMDAOUpt.ExeCommonSqlWithResult(sqlText,'@New_FN_Card',sNew_FN_Card,sErrorMsg); if sNew_FN_Card <>'' then SetComplete else SetAbort; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.GetUnionFNCardInfo(var vData: OleVariant; const sFN_Card, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); var sqlText:WideString; begin { try sqlText := 'EXEC dbo.usp_GetUnionFNCardInfo '+QuotedStr(sFN_Card)+','+QuotedStr(sCurrent_Department)+','+IntToStr(iType); FNMDAOInfo.GetCommonDataSet(vData,sqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.GetBaseTableInfo(var vData: OleVariant; const sTableName: WideString; var sErrorMsg: WideString); var sqlText:WideString; begin try sqlText:='EXEC dbo.usp_GetBaseTableInfo '+sTablename; FNMDAOInfo.GetCommonDataSet(vData,sqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveBaseTableInfo(var vData: OleVariant; const sTableName, sKeyField: WideString; var sErrorMsg: WideString); var sqlText:WideString; begin try sqlText := 'SELECT * FROM '+sTablename+' WHERE 1=2'; if Trim(sKeyField)='' then //将所有字段作为更新条件 FNMDAOUpt.SaveDataset(vData,sqlText,sErrorMsg,False) else //将所有KEY+修改过的字段作为更新条件 FNMDAOUpt.SaveMultiDataset(vData,sqlText,sKeyField,'',sErrorMsg,False); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveWorkerStationInfo(const sWorkerList,sMachine_ID, sCurrent_Department, sOperator: WideString; var sErrorMsg: WideString); var sqlText:WideString; begin { try sqlText:='EXEC dbo.usp_SaveWorkerStationInfo '+QuotedStr(sWorkerList)+','+ QuotedStr(sMachine_ID)+','+QuotedStr(sCurrent_Department)+','+QuotedStr(sOperator); FNMDAOUpt.ExeCommonSql(sqlText, sErrorMsg); //sErrorMsg:=sqlText; SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.SaveHoldInfo(bIs_Hold, iUnHoldiden: Integer; const iGFKeyValue, sOperationCode, sFnCard: WideString; bIseffectReair: Integer; const sReason, sOperator: WideString; var sErrorMsg: WideString); var SqlText: WideString; begin { try SqlText:=Format('EXEC dbo.usp_SaveHoldInfo %d, %d, ''%s'', ''%s'', ''%s'', %d, ''%s'', ''%s''', [ bIs_Hold, iUnHoldiden, iGFKeyValue, sOperationCode, sFnCard, bIseffectReair, sReason, sOperator]); FNMDAOInfo.ExeCommonSql(SqlText,sErrorMsg); //sErrorMsg:=SqlText; SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.SaveGIRepairInfo(const sFabric_NO_List, sCurrent_Department: WideString; var sErrorMsg: WideString); var SqlText:WideString; begin { try SqlText:='EXEC dbo.usp_SaveGIRepairInfo '+QuotedStr(sFabric_NO_List)+','+ QuotedStr(sCurrent_Department); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.GetGIRepairInfo(var vData: OleVariant; const sCurrent_Department: WideString; var sErrorMsg: WideString); var SqlText:WideString; begin { try SqlText := 'SELECT a.Fabric_NO,a.Quantity,a.GF_ID,a.GF_NO'+#13#10+ 'FROM dbo.uvw_fnGIRepair a WITH(NOLOCK)'+#13#10+ 'WHERE a.Current_Department ='+QuotedStr(sCurrent_Department); FNMDAOInfo.GetCommonDataSet(vData,SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.GetMachineTaskInfo(var vData: OleVariant; const sMachine_ID, sCurrent_Department: WideString; var sErrorMsg: WideString); var SqlText:WideString; begin try SqlText := 'EXEC dbo.usp_GetMachineTaskInfo '+QuotedStr(sMachine_ID)+','+QuotedStr(sCurrent_Department); FNMDAOInfo.GetCommonDataSet(vData,SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SetMachineOperation(const sFN_Card: WideString; iStep_NO: Integer; const sMachine_ID, sCar_NO: WideString; dSpeed, dWidth: Double; const sOperate_Time, sWorkerList, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); var SqlText:WideString; begin SqlText:='EXEC dbo.usp_SetMachineOperation '+QuotedStr(sFN_Card)+','+IntToStr(iStep_NO)+','+ QuotedStr(sMachine_ID)+','+ QuotedStr(sCar_NO)+','+FloatToStr(dSpeed)+','+ FloatToStr(dWidth)+','+QuotedStr(sOperate_Time)+','+QuotedStr(sWorkerList)+','+ QuotedStr(sCurrent_Department)+','+ IntToStr(iType); try FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); //sErrorMsg:=SqlText; SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.GetJobTraceInfo(var vData: OleVariant; const sFN_Card, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); var SqlText:WideString; begin try SqlText := 'EXEC dbo.usp_GetJobTraceInfo '+QuotedStr(sFN_Card)+','+QuotedStr(sCurrent_Department)+','+IntToStr(iType); FNMDAOInfo.GetCommonDataSet(vData,SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.GetWIPInfo(var vData0, vData1, vData2: OleVariant; const sCurrent_Department: WideString; var sErrorMsg: WideString); var SqlText: String; begin { try SqlText := 'EXEC dbo.usp_GetWIPInfo '+QuotedStr(sCurrent_Department); FNMDAOInfo.GetMultiDataSet(SqlText,vData0,vData1,vData2, sErrorMsg); SetComplete; except SetAbort; raise; end;} end; procedure TFNMFacadeLib.GetPlanInfo(var vData0, vData1, vData2: OleVariant; const sMachine_Model, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); var SqlText: WideString; const SELECTSQL: string = 'SELECT Iden,GF_ID,Job_NO,FN_Card,Quantity,Step_NO,Operation_Code,Machine_ID,'+#13#10+ ' White_Type,Seconds,Prepare_Type,Prepare_Minute,Current_Department,Plan_Begin_Time,'+#13#10+ ' Plan_End_Time,Fact_Begin_Time,Fact_End_Time,Planner,Plan_Time'+#13#10+ 'FROM dbo.fnPlan WITH(NOLOCK) WHERE Fact_End_Time IS NULL'; begin try if iType = 0 then SqlText := 'EXEC dbo.usp_GetPlanTaskInfo '+QuotedStr(sMachine_Model)+','+ QuotedStr(sCurrent_Department) else SqlText := 'EXEC dbo.usp_GetPlanListInfo '+QuotedStr(sCurrent_Department)+#13#10+SELECTSQL; FNMDAOInfo.GetMultiDataSet(SqlText, vData0, vData1, vData2, sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.GetChemicalIn_OutDtl(const sDataClass: WideString; dDate: TDateTime; const sCurrent_Department: WideString; var vData: OleVariant; var sErrorMsg: WideString); var SqlText: WideString; begin { try if sDataClass = 'INDATA' then SqlText := 'SELECT a.Iden, a.In_Date, a.Note_NO, a.Price, a.Chemical_ID, b.Chemical_Name, b.Chemical_Type, a.Source, ' + 'a.In_Quantity, a.Enable_Quantity, b.Unit, a.Current_Department, a.Operator, a.Operate_Time ' + 'FROM dbo.fnChemicalIn a WITH(NOLOCK) LEFT JOIN PUBDB..pbChemicalList b ON a.Chemical_ID=b.Chemical_ID ' + 'WHERE a.In_Date BETWEEN '''+ FormatDateTime(DateTimeFmtStr, dDate) +''' AND ''' + FormatDateTime(DateTimeFmtStr, IncDay(dDate)) + ''' ' + 'AND a.Current_Department = ''' + sCurrent_Department+ ''''; if sDataClass = 'OUTDATA' then SqlText :='SELECT a.Iden, a.In_Iden, a.Chemical_ID, b.Chemical_Name, b.Chemical_Type, a.Out_Date, ' + 'a.Used_QTY, b.Unit, a.Use_Department, a.Operator, a.Operate_Time, a.Current_Department ' + 'FROM dbo.fnChemicalOut a WITH(NOLOCK) LEFT JOIN PUBDB..pbChemicalList b WITH(NOLOCK) ON a.Chemical_ID=b.Chemical_ID ' + 'WHERE a.Out_Date BETWEEN '''+ FormatDateTime(DateTimeFmtStr, dDate) +''' AND ''' + FormatDateTime(DateTimeFmtStr, IncDay(dDate)) + ''' ' + 'AND a.Current_Department = ''' + sCurrent_Department+ ''''; FNMDAOInfo.GetCommonDataSet(vData, SqlText, sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.GetTheMatterFabric( const sCurrent_Department: WideString; dDate: TDateTime; out vData0, vData1: OleVariant; out sErrorMsg: WideString); var SqlText: WideString; vData2: OleVariant; begin try SqlText := 'EXEC dbo.usp_GetDefectAnalysisData '+QuotedStr(DateToStr(dDate))+','+QuotedStr(sCurrent_Department); FNMDAOInfo.GetMultiDataSet(SqlText, vData0, vData1, vData2, sErrorMsg); //sErrorMsg:=SqlText; SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.GetSampleList(const sFN_Card,sSample_Code: WideString; out vData: OleVariant; out sErrorMsg: WideString); var SqlText: WideString; begin try if sFN_Card = '' then begin SqlText := 'SELECT * FROM dbo.fnSampleItemList WITH(NOLOCK) WHERE Sample_code = ''' + sSample_Code + '''' end else begin SqlText := 'DECLARE @Fabric_NO varchar(200), @Samplelist varchar(300) ' + 'SELECT @Fabric_NO='''', @Samplelist='''' '+ 'SELECT @Fabric_NO =@Fabric_NO+ Fabric_NO+''(''+STR(Internal_Repair_Times,1)+'')''+''(''+STR(External_Repair_Times,1)+'')''+char(13) ' + 'FROM dbo.fnStock WITH(NOLOCK) WHERE FN_Card = ''' + sFN_Card +'''' + 'SELECT @Samplelist = @Samplelist + RTRIM(Sample_Name) + ''='' + RTRIM(cast(Sample_QTY as char(5))) + char(13) ' + 'FROM dbo.fnSampleItemList WITH(NOLOCK) WHERE Sample_Code = '''+ sSample_Code + '''' + 'SELECT @Fabric_NO AS Fabric_NO, ''' + sSample_Code + ''', @Samplelist AS Samplelist '; end; FNMDAOInfo.GetCommonDataSet(vData, SqlText, sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveChemicalInDtl(vData: OleVariant; out sErrorMsg: WideString); const INSERTFNCHEMICALINSQL = 'INSERT INTO dbo.fnChemicalIn (In_Date, Note_NO, Price, Chemical_ID, Source, In_Quantity, Enable_Quantity, Current_Department, Operator) '#13#10 + 'VALUES(''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ''%s'')'#13#10; var SqlText: String; cds_ChemicalInDtl: TClientDataSet; begin { SqlText:=''; try try cds_ChemicalInDtl:=TClientDataSet.Create(nil); cds_ChemicalInDtl.Data:=vData; with cds_ChemicalInDtl do begin First; while not Eof do begin SqlText:=SqlText + Format(INSERTFNCHEMICALINSQL,[ FieldByName('In_Date').AsString, FieldByName('Note_NO').AsString, FieldByName('Price').AsString, FieldByName('Chemical_ID').AsString, FieldByName('Source').AsString, FieldByName('In_Quantity').AsString, FieldByName('In_Quantity').AsString, FieldByName('Current_Department').AsString, FieldByName('Operator').AsString]); Next; end; end; if SqlText <> '' then FNMDAOUpt.ExeCommonSql(SqlText, sErrorMsg); //sErrorMsg:=SqlText; SetComplete; except SetAbort; raise; end finally FreeAndNil(cds_ChemicalInDtl); end; } end; procedure TFNMFacadeLib.SaveChemicalOutDtl(vData: OleVariant;out sErrorMsg: WideString); var SqlText: String; ExecResult: WideString; begin { try ExecResult:= ''; SqlText:=Format('EXEC dbo.usp_SaveChemicalOut ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', :@ExecReslut OUTPUT', [vData[0], vData[1], vData[2], vData[3], vData[4], vData[5], vData[6]]); FNMDAOUpt.ExeCommonSqlWithResult(SqlText, '@ExecReslut', ExecResult, sErrorMsg); if ExecResult <> '' then sErrorMsg:=sErrorMsg + ExecResult; SetComplete; except SetAbort; raise; end;} end; procedure TFNMFacadeLib.GetOTDInfo(var vData: OleVariant;const sBegin_Time, sEnd_Time, sQuery_Type, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); var SqlText: string; begin { try case iType of 0: SqlText := 'SELECT * FROM dbo.uvw_fnOTD WHERE Last_Received_Date= '+QuotedStr(sBegin_Time)+ ' AND Current_Department= '+QuotedStr(sCurrent_Department); 1,2: SqlText := 'EXEC dbo.usp_GetOTDInfo '+ QuotedStr(sBegin_Time)+','+ QuotedStr(sEnd_Time)+ ','+QuotedStr(sCurrent_Department)+','+QuotedStr(sQuery_Type)+','+ IntToStr(iType); 3: SqlText := 'EXEC dbo.usp_GetSpecialOTDInfo '+ QuotedStr(sBegin_Time)+','+ QuotedStr(sEnd_Time)+ ','+QuotedStr(sCurrent_Department)+','+QuotedStr(sQuery_Type)+',0'; end; if iType = 0 then SqlText := 'SELECT * FROM dbo.uvw_fnOTD WHERE Last_Received_Date= '+QuotedStr(sBegin_Time)+ ' AND Current_Department= '+QuotedStr(sCurrent_Department) else SqlText := 'EXEC dbo.usp_GetOTDInfo '+ QuotedStr(sBegin_Time)+','+ QuotedStr(sEnd_Time)+ ','+QuotedStr(sCurrent_Department)+','+QuotedStr(sQuery_Type)+','+IntToStr(iType); FNMDAOInfo.GetCommonDataSet(vData,SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.GetWorkerPrizeOrErrorInfo(var vData: OleVariant; const sQuery_Date, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); var SqlText: string; begin try if iType = 0 then SqlText := 'SELECT * FROM dbo.fnWorkerPrize WHERE Prize_Date= '+QuotedStr(sQuery_Date)+ ' AND Current_Department= '+QuotedStr(sCurrent_Department) else SqlText := 'SELECT * FROM dbo.fnWorkerError WHERE Error_Date= '+ QuotedStr(sQuery_Date)+ ' AND Current_Department= '+QuotedStr(sCurrent_Department); FNMDAOInfo.GetCommonDataSet(vData,SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; //获取外发回来信息 procedure TFNMFacadeLib.GetSCInfo(var vData0, vData1, vData2: OleVariant; const sContract_NO, sCurrent_Department: WideString; var sErrorMsg: WideString); var SqlText: string; begin { try SqlText := 'EXEC dbo.usp_GetSCInfo '+QuotedStr(sContract_NO)+','+ QuotedStr(sCurrent_Department); FNMDAOInfo.GetMultiDataSet(SqlText,vData0,vData1,vData2,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; //保存回收外发信息 procedure TFNMFacadeLib.SaveSCInfo(const sContract_NO, sFNCardList, sCurrent_Department, sOperator: WideString; var sErrorMsg: WideString); var SqlText: string; begin { try SqlText:='EXEC dbo.usp_SaveSCInfo '+QuotedStr(sContract_NO)+','+QuotedStr(sFNCardList)+','+ QuotedStr(sCurrent_Department)+','+QuotedStr(sOperator); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; //获取布的入库/库存/出库信息 procedure TFNMFacadeLib.GetFabricReportInfo(var vData: OleVariant; const sBegin_Time, sEnd_Time, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); var SqlText: string; begin { try SqlText := 'EXEC dbo.usp_GetFabricReportInfo '+QuotedStr(sBegin_Time)+ ','+ QuotedStr(sEnd_Time)+','+ QuotedStr(sCurrent_Department)+','+IntToStr(iType); FNMDAOInfo.GetCommonDataSet(vData,SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; //自动排机 procedure TFNMFacadeLib.AutoArrangePlan(const sOperation_Code, sCurrent_Department: WideString; var sErrorMsg: WideString); var SqlText: string; begin try SqlText := 'EXEC dbo.usp_AutoArrangePlan '+QuotedStr(sOperation_Code)+','+ QuotedStr(sCurrent_Department); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; //修改化工料信息 procedure TFNMFacadeLib.SaveChemicalStockEdit(const sDataType: WideString; vData: OleVariant; const sOperator: WideString; out sErrorMsg: WideString); var SqlText: String; begin //不用做虚拟出库和虚拟入库,客户端已控制 { try if sDataType = 'ChemicalInData' then begin SqlText:= Format('UPDATE dbo.fnChemicalIn SET Note_NO = ''%s'', Price = ''%s'', Chemical_ID = ''%s'', Source = ''%s'', ' + 'In_Quantity = ''%s'',Enable_Quantity = ''%s'', Operator = ''%s'', Operate_Time = GETDATE() ' + 'where Iden = ''%s'' ', [vData[0], vData[1], vData[2], vData[3], vData[4], vData[5], sOperator, vData[6]]); end; if sDataType = 'ChemicalOutData' then begin SqlText:= format('UPDATE dbo.fnChemicalOut SET Used_QTY = ''%s'', Use_Department = ''%s'', Operator = ''%s'', Operate_Time = GETDATE() ' + 'where Iden = ''%s'' ', [vData[0], vData[1], sOperator, vData[2]]); if vData[3] <> 0 then SqlText:=SqlText + format('UPDATE dbo.fnChemicalIn SET Enable_Quantity = Enable_Quantity + %s where Iden = ''%s'' ', [vData[3], vData[4]]); end; if SqlText <> '' then FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; //取消打卡 procedure TFNMFacadeLib.CancelPrintFNCardInfo(const sFN_Card, sCurrent_Department, sOperator: WideString; var sErrorMsg: WideString); var SqlText: string; begin { try SqlText := 'EXEC dbo.usp_CancelPrintCard '+QuotedStr(sFN_Card)+','+QuotedStr(sCurrent_Department)+','+QuotedStr(sOperator); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; //获取收坯信息 procedure TFNMFacadeLib.GetGIInfo(const sSource, sCurrent_Department: WideString; iType: Integer; var vData: OleVariant; var sErrorMsg: WideString); var SqlText: string; begin { try SqlText:='EXEC dbo.usp_GetGIStockInfo '+QuotedStr(sSource)+','+QuotedStr(sCurrent_Department) +',' + IntToStr(iType); FNMDAOInfo.GetCommonDataSet(vData,SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end;} end; //保存收坯信息 procedure TFNMFacadeLib.SaveGIInfo(const sFabricNOList, sSource, sCurrent_Department, sOperator: WideString; var sErrorMsg: WideString); var sqlText: string; begin try sqlText :='DECLARE @Result varchar(100)'+#13+ Format('EXEC QCMDB.DBO.usp_giSavePayFNInfo 1, ''%s'', ''%s'', ''%s'', ''%s'', @Result OUTPUT'#13#10, [sFabricNOList, sSource, sCurrent_Department, sOperator]) + 'SET @Result = SUBSTRING(@Result,CHARINDEX(''--'',@Result)+2,20) '+#13+ Format('EXEC FNMDB.dbo.usp_SaveReceiveInfo @Result, ''%s'', ''%s'', ''%s'''#13#10, [sCurrent_Department, sOperator, sSource]); FNMDAOUpt.ExeCommonSql(SqlText, sErrorMsg); //sErrorMsg:=sqlText; SetComplete; except SetAbort; raise; end; end; //获取单据列表 procedure TFNMFacadeLib.GetItemList(var sNoteNOList: OleVariant; const sCode, sCurrent_Department, sType: WideString; var sErrorMsg: WideString); var SqlText: string; begin try SqlText:='EXEC dbo.usp_GetItemList '+ QuotedStr(sCode)+','+ QuotedStr(sCurrent_Department)+','+QuotedStr(sType); FNMDAOInfo.GetCommonFieldValue(sNoteNOList,SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; //修改品名 procedure TFNMFacadeLib.ChangeGFNO(const sCode, sGFKey, sJob_NO, sReason, sChanger, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); var SqlText: string; begin { try SqlText := 'EXEC dbo.usp_ChangeGFNO '+QuotedStr(sCode)+','+QuotedStr(sGFKey)+','+ QuotedStr(sJob_NO)+','+QuotedStr(sReason)+','+QuotedStr(sChanger)+','+ QuotedStr(sCurrent_Department)+','+IntToStr(iType); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; //保存分布信息 procedure TFNMFacadeLib.SaveDistributeInfo(vData: OleVariant; const sFabricNOStr, sMachine_ID, sCurrent_Department: WideString; var sErrorMsg: WideString); var sqlText,sqlUpdateText:WideString; begin try sqlText := 'SELECT * FROM dbo.uvw_fnStock WHERE 1=2'; sqlUpdateText := 'EXEC dbo.usp_SaveDistributeYield '+QuotedStr(sMachine_ID)+','+ QuotedStr(sFabricNOStr)+','+QuotedStr(sCurrent_Department); FNMDAOUpt.SaveMultiDataset(vData,sqlText,'Fabric_NO',sqlUpdateText,sErrorMsg,False); SetComplete; except SetAbort; raise; end; end; //记录机台停机信息 procedure TFNMFacadeLib.SaveSuspendInfo(const sMachine_ID, sSuspend_Code, sBegin_Time, sEnd_Time, sCurrent_Department, sRemark: WideString; var sErrorMsg: WideString); var SqlText: String; begin try sqlText := Format('EXEC dbo.usp_SaveSuspendInfo ''%s'', ''%s'', ''%s'', ''%s'',''%s'', ''%s''', [sMachine_ID,sSuspend_Code,sBegin_Time,sEnd_Time,sCurrent_Department,sRemark]); FNMDAOUpt.ExeCommonSql(sqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.GetQyDetail(iQueryIden: Integer; vCondition: OleVariant; out vData: OleVariant; out sErrorMsg: WideString); var SqlText:WideString; begin try SqlText:=Format('EXEC dbo.usp_GetQyDetail %d, ''%s'', ''%s'', ''%s'', ''%s''', [iQueryIden, vCondition[0], vCondition[1], vCondition[2], vCondition[3]]); FNMDAOInfo.GetCommonDataSet(vData, SqlText, sErrorMsg); //sErrorMsg:=SqlText; SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.GetQyMaster(iQueryIden: Integer; const sPreDeclareVars, sCondition: WideString; out vData: OleVariant; out sErrorMsg: WideString); var SqlText:WideString; begin try SqlText:=Format('EXEC dbo.usp_GetqyMaster %d, ''%s'', ''%s''', [iQueryIden, StringReplace(sPreDeclareVars, '''', '''''', [rfReplaceAll]), StringReplace(sCondition, '''', '''''', [rfReplaceAll])]); FNMDAOInfo.GetCommonDataSet(vData, SqlText, sErrorMsg); //sErrorMsg:=SqlText; SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.GetQyDictionary(const sQyDicName: WideString; out vData: OleVariant; out sErrorMsg: WideString); var SqlText:WideString; begin try SqlText:=Format('EXEC dbo.usp_GetQyDictionary ''%s''', [sQyDicName]); FNMDAOInfo.GetCommonDataSet(vData, sqlText, sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.AdjustJobTraceDtlInfo(vData: OleVariant; const sIdenList, sOperator, sCurrent_Department: WideString; var sErrorMsg: WideString); var SqlText: String; cdsJobTraceDtl: TClientDataSet; sList:TStringList; i: Integer; begin cdsJobTraceDtl:=nil; sList := nil; try cdsJobTraceDtl:=TClientDataSet.Create(nil); sList :=TStringList.Create; try cdsJobTraceDtl.Data:=vData; sList.Text := sIdenList; sqlText := ''; for i := 0 to sList.Count-1 do with cdsJobTraceDtl do begin if Locate('Iden',sList[i],[]) then sqlText := sqlText+#13+Format('EXEC dbo.usp_AdjustJobTraceDtlInfo %d,''%s'',%5.2f,''%s'',''%s'',''%s'',''%s'',''%s''', [FieldByName('Iden').AsInteger,FieldByName('Machine_ID').AsString,FieldByName('Speed').AsFloat,FieldByName('Befor_Operator').AsString, FieldByName('Middle_Operator').AsString,FieldByName('After_Operator').AsString,sCurrent_Department,sOperator]); end; cdsJobTraceDtl.Close; FNMDAOUpt.ExeCommonSql(sqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; finally FreeAndNil(cdsJobTraceDtl); FreeAndNil(sList); end; end; procedure TFNMFacadeLib.GetJobTraceDtlInfo(var vData: OleVariant; const sParam, sBegin_Time, sEnd_Time, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); var SqlText:WideString; begin try SqlText := 'SELECT a.Iden,dbo.udf_GetGFNO(c.GF_ID) AS GF_NO,a.FN_Card,a.Quantity,a.Step_NO,b.Operation_CHN,a.Machine_ID,a.Speed, '+ ' a.Begin_Time,a.End_Time,a.Befor_Operator,a.Middle_Operator,a.After_Operator,a.Operator,a.Operate_Time,c.GF_ID,c.Job_NO,a.Operation_Code '+ 'FROM dbo.fnJobTraceDtl a '+ ' JOIN dbo.fnOperationHdrList b ON a.Operation_Code = b.Operation_Code '+ ' JOIN dbo.fnJobTraceHdr c ON c.FN_Card = a.FN_Card '+ 'WHERE a.Current_Department='+QuotedStr(sCurrent_Department)+' AND a.Operation_Code<>''999'''; if iType = 0 then SqlText := SqlText+' AND a.Machine_ID = '+QuotedStr(sParam)+ ' AND a.Begin_Time BETWEEN '+QuotedStr(sBegin_Time) + 'AND '+QuotedStr(sEnd_Time)+ ' ORDER BY a.FN_Card,a.Begin_Time ' else SqlText := SqlText+' AND a.FN_Card = '+QuotedStr(sParam) + ' ORDER BY a.FN_Card,a.Step_NO '; FNMDAOInfo.GetCommonDataSet(vData,SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.TerminalQuery(var vData: OleVariant; const sParam, sBegin_Time, sEnd_Time, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); var SqlText:WideString; begin try SqlText := 'EXEC dbo.usp_TerminalQuery '+QuotedStr(sBegin_Time)+',' +QuotedStr(sEnd_Time)+','+QuotedStr(sCurrent_Department)+','+QuotedStr(sParam)+','+IntToStr(iType); FNMDAOInfo.GetCommonDataSet(vData,SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveOTDInfo(var vData: OleVariant; iType: Integer; var sErrorMsg: WideString); const //更新fnJobTraceHdr表,以免坯布更新不及时导致后整状态出错 UPDATEOTDSQL = 'UPDATE dbo.fnOTD SET Quality_Type = ''%s'',Second_Reason = ''%s'',Third_Reason = ''%s'',Four_Reason = ''%s'',Remark = ''%s'', Updater = ''%s'', Update_Time = GETDATE(),Is_Active = ''%s'' '+#13+ 'WHERE GF_ID = ''%s'' AND Job_NO = ''%s'' AND Current_Department = ''%s''' + #13#10 + 'UPDATE dbo.fnJobTraceHdr SET GF_ID = GF_ID WHERE GF_ID = ''%s'' AND Job_NO = ''%s'' AND Current_Department = ''%s''' + #13#10 ; const UPDATESPECIALOTDSQL = 'UPDATE dbo.fnSpecialOTD SET Remark = ''%s'', Updater = ''%s'', Update_Time = GETDATE(),Is_Active = ''%s'' '+#13+ 'WHERE GF_ID = ''%s'' AND Job_NO = ''%s'' AND Special_Type = ''%s'' AND Current_Department = ''%s'''+#13#10; var SqlText: WideString; i: Integer; begin try case iType of 0: SaveBaseTableInfo(vData, 'dbo.uvw_fnOTD', 'Job_NO,GF_ID,Current_Department', sErrorMsg); 1: begin for i := 0 to VarArrayHighBound(vData, 1) do SqlText := SqlText+Format(UPDATEOTDSQL,[vData[i][0],vData[i][1],vData[i][2],vData[i][3],vData[i][4],vData[i][5],vData[i][6],vData[i][7],vData[i][8],vData[i][9],vData[i][7],vData[i][8],vData[i][9]]); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); end; 2: begin for i := 0 to VarArrayHighBound(vData, 1) do SqlText := SqlText+Format(UPDATESPECIALOTDSQL,[vData[i][0],vData[i][1],vData[i][2],vData[i][3],vData[i][4],vData[i][5],vData[i][6]]); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); end; end; { if iType = 0 then SaveBaseTableInfo(vData, 'dbo.uvw_fnOTD', 'Job_NO,GF_ID,Current_Department', sErrorMsg) else begin for i := 0 to VarArrayHighBound(vData, 1) do SqlText := SqlText+Format(UPDATEOTDSQL,[vData[i][0],vData[i][1],vData[i][2],vData[i][3],vData[i][4],vData[i][5],vData[i][6]]); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); end; } SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveCarInfo(const sFNCard, sNewCarNO, sOperator, sAppName, sComputerName: WideString; out sErrorMsg: WideString); var SqlText: WideString; begin { SqlText:='DECLARE @OldCarNO varchar(10), @NewCarNO varchar(10), @FNCard char(9)'#13#10 + Format('SELECT @OldCarNO = Car_NO, @NewCarNO = ''%s'', @FNCard = ''%s'' FROM dbo.fnJobTraceHdr WHERE FN_Card = ''%s'' '#13#10, [sNewCarNO, sFNCard, sFNCard]) + 'IF @OldCarNO IS NULL '#13#10 + 'BEGIN '#13#10 + ' RAISERROR (''卡号不存在'', 16, 1) '#13#10 + ' RETURN '#13#10 + 'END '#13#10 + 'INSERT INTO dbo.fnModifyDataLog(Operator, Operate_Time, Operate_Type, Application_Name, Host_Name, Table_Name, Remark) '#13#10 + Format(' VALUES(''%s'', GETDATE(), ''更改车牌号'', ''%s'', ''%s'', ''CarNO'', @FNCard + '':'' + @OldCarNO + ''->'' + ''%s'') '#13#10, [sOperator, sAppName, sComputerName, sNewCarNO]) + 'UPDATE dbo.fnJobTraceHdr SET Car_NO = @NewCarNO WHERE FN_Card = @FNCard '#13#10 + 'UPDATE dbo.fnStock SET Car_NO = @NewCarNO WHERE FN_Card = @FNCard '; // sErrorMsg:=SqlText; try FNMDAOUpt.ExeCommonSql(SqlText, sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.GetShrinkageAnalysisInfo(var vData: OleVariant; const sBegin_Date, sEnd_Date, sCurrent_Department: WideString; var sErrorMsg: WideString); var SqlText:WideString; begin try SqlText := 'SELECT * FROM dbo.uvw_fnShrinkageAnalysis WITH(NOLOCK) '+ 'WHERE Inspect_Time BETWEEN '+QuotedStr(sBegin_Date)+' AND '+ QuotedStr(sEnd_Date)+' AND Receive_Note_NO like '+QuotedStr(sCurrent_Department+'%'); FNMDAOInfo.GetCommonDataSet(vData,SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveShrinkageAnalysisInfo(var vData: OleVariant; const sOperator: WideString; var sErrorMsg: WideString); const UPDATEShrinkSQL = 'UPDATE QCMDB.dbo.fiShrinkDtl SET Reason = ''%s'' '+ ',Operator = ''%s'',Operate_Time = GETDATE() '+ ' WHERE Iden = %s'#13#10; var SqlText: WideString; i: Integer; begin try for i := 0 to VarArrayHighBound(vData, 1) do SqlText := SqlText + Format(UPDATEShrinkSQL, [vData[i][0],sOperator,vData[i][1]]); FNMDAOUpt.ExeCommonSql(SqlText, sErrorMsg); //sErrorMsg:=SqlText; SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.ChangeMaterialType(const sCode, sMaterial_Type, sDuty_Department, sReason, sChanger, sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); var SqlText: string; begin { try SqlText := 'EXEC dbo.usp_ChangeMaterialType '+QuotedStr(sCode)+','+QuotedStr(sMaterial_Type)+','+ QuotedStr(sDuty_Department)+','+ QuotedStr(sReason)+','+QuotedStr(sChanger)+','+ QuotedStr(sCurrent_Department)+','+IntToStr(iType); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.CreateOTDInfo(IType: Integer; var sErrorMsg: WideString); var SqlText: string; begin try case IType of 0: SqlText := 'EXEC dbo.usp_AutoCreateOTDInfo '+QuotedStr(DateToStr(Now)); 1: SqlText := 'EXEC dbo.usp_AutoCreateSpecialOTDInfo '; end; FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.CancelFIInfo(const sNote_NO, sFabric_NO_List, sOperator: WideString; var sErrorMsg: WideString); var sqlText: WideString; sFabricNOList: String; begin { try sFabricNOList := StringReplace(sFabric_NO_List, '`', '#96#', [rfReplaceAll]); sqlText:='EXEC dbo.usp_CancelFIInfo '+QuotedStr(sNote_NO)+ ','+ QuotedStr(sFabricNOList)+','+QuotedStr(sOperator); FNMDAOUpt.ExeCommonSql(sqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.GetChemicalData(iType: Integer; const sCurrent_Department: WideString; dQueryDate: TDateTime; var vData: OleVariant; var sErrorMsg: WideString); var SqlText:WideString; begin { try case iType of 0: SqlText := 'SELECT Chemical_Type,Chemical_ID, '+QuotedStr(DateToStr(dQueryDate)) + ' AS Create_Date,Chemical_Name, Remain AS Last_Remain, '+ 'In_Qty-In_Qty AS In_Qty, Out_Qty-Out_Qty AS Out_Qty, Remain-Remain AS Remain,Price ' + 'INTO #Temp01 '+ 'FROM dbo.fnChemicalCheck a WITH(NOLOCK) '+ 'WHERE Remain > 0 AND Current_Department = ' + QuotedStr(sCurrent_Department) + ' AND Create_Date = (SELECT MAX(Create_Date) FROM dbo.fnChemicalCheck WITH(NOLOCK) '+ ' WHERE Current_Department = a.Current_Department AND Create_Date < '+ QuotedStr(DateToStr(dQueryDate)) +')'+ ' SELECT * FROM #Temp01 DROP TABLE #Temp01'; 1: SqlText := 'EXEC dbo.usp_GetChemicalReport ' + QuotedStr(DateToStr(dQueryDate)) + ',' + QuotedStr(sCurrent_Department); 2: SqlText := 'SELECT a.Method_ENG, a.Chemical_Name, a.Chemical_Ratio, a.Job_NO, b.GF_NO, a.Product_QTY, '+ 'a.Need_Quantity, a.Stock_Quantity, a.Apply_Quantity, a.Is_Apply,a.Iden, a.GF_ID '+ 'FROM dbo.fnApplySpecialChemical a WITH(NOLOCK) '+ ' INNER JOIN PDMDB.dbo.tdGFID b WITH(NOLOCK) ON b.GF_ID = a.GF_ID '+ 'WHERE a.Is_Apply = 0 AND a.Current_Department = '+ QuotedStr(sCurrent_Department); end; FNMDAOInfo.GetCommonDataSet(vData,SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.SaveChemicalData(iType: Integer; var vData: OleVariant; var sErrorMsg: WideString); const INSERTCHEMICALCHECKSQL = 'INSERT INTO dbo.fnChemicalCheck(Create_Date, Chemical_ID, '+ 'Chemical_Name, Chemical_Type, In_QTY, Out_QTY, Remain, Price, '+ 'Current_Department, Operator, Operate_Time) '+ 'VALUES (''%s'',''%s'',''%s'',''%s'',''%s'',''%s'',''%s'',''%s'',''%s'',''%s'',GETDATE())' +#13#10; const UPDATEAPPLYSPECIALCHEMICALSQL = 'UPDATE dbo.fnApplySpecialChemical SET Stock_Quantity = ''%s'',Apply_Quantity = ''%s'',Is_Apply = ''%s'', Appler = ''%s'', Apply_Time = GETDATE() '+#13+ 'WHERE Iden = ''%s'' AND Current_Department = ''%s'''+#13#10; var SqlText: WideString; i: Integer; begin try case iType of 0: begin SqlText := 'DELETE FROM dbo.fnChemicalCheck WHERE Create_Date >= ' + QuotedStr(vData[0][0]) + ' AND Current_Department = '+ QuotedStr(vData[0][8]) + #13#10; for i := 0 to VarArrayHighBound(vData, 1) do SqlText := SqlText+Format(INSERTCHEMICALCHECKSQL,[vData[i][0],vData[i][1],vData[i][2],vData[i][3],vData[i][4],vData[i][5],vData[i][6],vData[i][7],vData[i][8],vData[i][9]]); end; 1: SqlText :=Format('EXEC dbo.usp_AdjustChemicalData ''%s'',''%s'',''%s'',''%s'',''%s''',[vData[0][0], vData[0][1], vData[0][2], vData[0][3], vData[0][4]]); 2: begin SqlText := ''; for i := 0 to VarArrayHighBound(vData, 1) do SqlText := SqlText+Format(UPDATEAPPLYSPECIALCHEMICALSQL,[vData[i][0],vData[i][1],vData[i][2],vData[i][3],vData[i][4],vData[i][5]]); end; end; FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.GetArtAnalysisData(var vData: OleVariant; dQueryDate: TDateTime; const sCurrent_Department: WideString; iType: Integer; var sErrorMsg: WideString); var sCondition, SqlText:WideString; begin try // 2011-11-2 // SqlText := 'SELECT a.Create_Date, a.FN_Card, a.Type, a.Job_NO, b.GF_NO, a.Quantity, ' + // 'c.Reason_Info, a.Checker, a.Worker0, a.Qty0, a.Worker1, a.Qty1,Remark '+ // 'FROM dbo.fnArtAnalysis a WITH(NOLOCK) '+ // ' INNER JOIN PDMDB.dbo.tdGFID b WITH(NOLOCK) ON b.GF_ID = a.GF_ID '+ // ' INNER JOIN dbo.fnRepairReasonHdrList c WITH(NOLOCK) ON c.Reason_Code = a.Reason_Code '+ // 'WHERE a.Create_Date = ' + QuotedStr(DateToStr(dQueryDate)) +' AND a.Current_Department = '+ // QuotedStr(sCurrent_Department) + ' AND a.Type = ' + IntToStr(iType); sCondition := QuotedStr(DateToStr(dQueryDate))+',' + QuotedStr(sCurrent_Department)+',' + IntToStr(iType); SqlText := GetSql('GetArtAnalysisData', sCondition); FNMDAOInfo.GetCommonDataSet(vData,SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveArtAnalysisData(var vData: OleVariant; var sErrorMsg: WideString); const INSERTCHEMICALCHECKSQL = 'UPDATE dbo.fnArtAnalysis SET Worker0 =''%s'',Qty0 = ''%s'', Worker1 =''%s'',Qty1 = ''%s'', '+ ' Remark = ''%s'',Operator =''%s'', Operate_Time = GETDATE() '+ 'WHERE Create_Date = ''%s'' AND FN_Card = ''%s'' AND Type = ''%s'' AND Current_Department = ''%s'' ' + #13#10; var SqlText: WideString; i: Integer; begin try for i := 0 to VarArrayHighBound(vData, 1) do SqlText := SqlText+Format(INSERTCHEMICALCHECKSQL,[vData[i][3],vData[i][4],vData[i][5],vData[i][6],vData[i][7],vData[i][8],vData[i][0],vData[i][1],vData[i][2],vData[i][9]]); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.GetUrgentPpoInfo(var vData: OleVariant; const sGF_NO: WideString; var sErrorMsg: WideString); var SqlText:WideString; begin { try SqlText := 'EXEC dbo.usp_GetUrgentPpoInfo ' + QuotedStr(sGF_NO); FNMDAOInfo.GetCommonDataSet(vData,SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; } end; procedure TFNMFacadeLib.SaveUrgentPpoInfo(var vData: OleVariant; var sErrorMsg: WideString); const UPDATEPBPRODUCTTRACEFNQCSQL = 'UPDATE PUBDB.dbo.pbProductTraceFNQC SET FN_Special_Status =''%s'' '+ 'WHERE Job_NO = ''%s'' AND GF_ID = ''%s'' ' + #13#10; var SqlText: WideString; i: Integer; begin try for i := 0 to VarArrayHighBound(vData, 1) do SqlText := SqlText+Format(UPDATEPBPRODUCTTRACEFNQCSQL,[vData[i][0],vData[i][1],vData[i][2]]); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveRepairReason(var vData: OleVariant; iType: Integer; var sErrorMsg: WideString); const INSERT_HDR_SQL = 'DECLARE @Reason_Code char(5) '+ #13 + ' SELECT @Reason_Code = (SELECT ''FR''+RIGHT(''000''+CONVERT(varchar,MAX(RIGHT(Reason_Code,3)) + 1),3) FROM dbo.fnRepairReasonHdrList WITH(NOLOCK)) ' +#13+ ' INSERT INTO dbo.fnRepairReasonHdrList(Reason_Code, Reason_Type,' + 'Reason_Info, Quality_Operation, Quality_Type, Department, Remark, '+ 'Repair_Operation, Is_Active,Operator, Operate_Time)'+#13+ 'VALUES(@Reason_Code, ''%s'',''%s'',''%s'',''%s'',''%s'',''%s'',''%s'',''%s'',''%s'',GETDATE())'; UPDATE_HDR_SQL = 'UPDATE dbo.fnRepairReasonHdrList SET Reason_Type = ''%s'',' + 'Reason_Info = ''%s'', Quality_Operation = ''%s'', Quality_Type = ''%s'', Department = ''%s'', Remark = ''%s'', '+ 'Repair_Operation = ''%s'', Is_Active = ''%s'',Operator = ''%s'', Operate_Time = GETDATE() ' + #13 + 'WHERE Reason_Code = ''%s'''; INSERT_DTL_SQL = 'INSERT INTO dbo.fnRepairReasonDtlList(Reason_Code,Item_Name,Enum_Value) '+ #13 + 'VALUES(''%s'', ''%s'',''%s'')'; UPDATE_DTL_SQL = 'UPDATE dbo.fnRepairReasonDtlList SET Item_Name = ''%s'',Enum_Value = ''%s'' '+#13+ 'WHERE Reason_Code = ''%s'''; var SqlText: WideString; begin try if iType = 0 then if vData[0][0] = '' then //new SqlText := Format(INSERT_HDR_SQL,[vData[0][1],vData[0][2],vData[0][3],vData[0][4],vData[0][5],vData[0][6],vData[0][7],vData[0][8],vData[0][9]]) else //edit SqlText := Format(UPDATE_HDR_SQL,[vData[0][1],vData[0][2],vData[0][3],vData[0][4],vData[0][5],vData[0][6],vData[0][7],vData[0][8],vData[0][9],vData[0][0]]) else if vData[0][0] = '1' then //new SqlText := Format(INSERT_DTL_SQL,[vData[0][1],vData[0][2],vData[0][3]]) else //edit SqlText := Format(UPDATE_DTL_SQL,[vData[0][2],vData[0][3],vData[0][1]]); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.DeleteRepairReason(const sReason_Code, sItem_Name: WideString; iType: Integer; var sErrorMsg: WideString); var SqlText: WideString; begin try if iType = 0 then SqlText := 'UPDATE dbo.fnRepairReasonHdrList SET Is_Active = 0 WHERE Reason_Code = ' + QuotedStr(sReason_Code) else SqlText := 'DELETE dbo.fnRepairReasonDtlList WHERE Reason_Code = ' + QuotedStr(sReason_Code) + ' AND Item_Name = ' + QuotedStr(sItem_Name); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveOTDReason(var vData: OleVariant; iType: Integer; var sErrorMsg: WideString); const INSERT_OTDREASON_SQL = ' INSERT INTO dbo.fnOTDReasonList(First_Reason,Second_Reason,Third_Reason,Four_Reason, Remark, Operator, Operate_Time)'+#13+ 'VALUES(''%s'', ''%s'',''%s'',''%s'',''%s'',''%s'',GETDATE())'; UPDATE_OTDREASON_SQL = 'UPDATE dbo.fnOTDReasonList SET First_Reason = ''%s'',' + 'Second_Reason = ''%s'', Third_Reason = ''%s'', Four_Reason = ''%s'',Remark = ''%s'', '+ 'Operator = ''%s'', Operate_Time = GETDATE() ' + #13 + 'WHERE Iden = ''%s'''; DELETE_OTDREASON_SQL = 'DELETE dbo.fnOTDReasonList WHERE Iden = ''%s'''; var SqlText: WideString; begin try if iType = 0 then SqlText := Format(INSERT_OTDREASON_SQL,[vData[0][1],vData[0][2],vData[0][3],vData[0][4],vData[0][5],vData[0][6]]) else if iType = 1 then //edit SqlText := Format(UPDATE_OTDREASON_SQL,[vData[0][1],vData[0][2],vData[0][3],vData[0][4],vData[0][5],vData[0][6],vData[0][0]]) else //DELETE SqlText := Format(DELETE_OTDREASON_SQL,[vData[0][0]]); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveReceiveBenchMark(var vData: OleVariant; iCount: Integer; var sErrorMsg: WideString); const UPDATE_RECEIVEBENCHMARK_SQL = 'UPDATE dbo.fnReceiveBenchmarkList SET Quantity= ''%s'',Operator = ''%s'', Operate_Time = GETDATE() WHERE GF_Type = ''%s'' AND Quantity <> ''%s'''+#13; var SqlText: WideString; i: Integer; begin try SqlText := ''; for i := 0 to iCount - 1 do SqlText := SqlText + Format(UPDATE_RECEIVEBENCHMARK_SQL,[Copy(vData[i][0],Pos('=',vData[i][0])+1,10),vData[i][1],Copy(vData[i][0],1,Pos('=',vData[i][0])-1),Copy(vData[i][0],Pos('=',vData[i][0])+1,10)]); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveMutexChemical(var vData: OleVariant; iCount: Integer; var sErrorMsg: WideString); const INSERT_MUTEXCHEMICAL_SQL = 'INSERT INTO dbo.fnMutexChemicalList(Chemical_ID,Mutex_ID,Operator,Operate_Time) VALUES(''%s'',''%s'', ''%s'',GETDATE())'+#13; var i: Integer; SqlText: WideString; begin try SqlText := 'DELETE dbo.fnMutexChemicalList'+#13; for i := 0 to iCount - 1 do SqlText := SqlText + Format(INSERT_MUTEXCHEMICAL_SQL,[vData[i][0],vData[i][1],vData[i][2]]); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.GetInnerRepairInfo(const sCurrent_Department, sDatetime: WideString; var vData: OleVariant; var sErrorMsg: WideString); { cuijf 2008-6-16 改用Check_Time时间查询 const QuerySQLTEXT = 'DECLARE @BeginTime datetime, @EndTime datetime'#13#10 + 'SET @BeginTime = ''%s'''#13#10 + 'SET @BeginTime = CONVERT(varchar(10), @BeginTime, 120) + '' 07:00:00'''#13#10 + 'SET @EndTime = CONVERT(varchar(10), @BeginTime + 1, 120) + '' 07:00:00'''#13#10 + 'SELECT a.Iden, dbo.udf_GetGFNO(GF_ID) AS GF_NO, Quantity, FN_Card,'#13#10 + ' b.Reason_Info, b.Quality_Type,'#13#10 + ' dbo.udf_GetInnerRepairOperations(-1, a.Iden) AS Repair_Operations,'#13#10 + ' a.Remark AS Org_Remark, a.Operator, a.Operate_Time, Is_Ignore, Ignore_Remark, Ignorer, Ignore_Time,'#13#10 + ' CONVERT(bit, 0) AS Changed'#13#10 + ' INTO #TmpTable'#13#10 + ' FROM dbo.fnRepairOperation a WITH(NOLOCK)'#13#10 + ' INNER JOIN dbo.fnRepairReasonHdrList b WITH(NOLOCK) ON a.Reason_Code = b.Reason_Code'#13#10 + 'WHERE a.Operate_Time BETWEEN @BeginTime AND @EndTime'#13#10 + ' AND Internal_External = 0'#13#10 + ' AND Current_Department = ''%s'''#13#10 + 'ORDER BY a.Operate_Time'#13#10 + 'SELECT * FROM #TmpTable'#13#10 + 'DROP TABLE #TmpTable'; } var SqlText: WideString; begin try //SqlText:=Format(QuerySQLTEXT, [sDatetime, sCurrent_Department]); SqlText := 'EXEC FNMDB..usp_fnGetInnerRepairInfo '+ QuotedStr(sDatetime)+','''','+ QuotedStr(sCurrent_Department); FNMDAOInfo.GetCommonDataSet(vData, SqlText, sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveIgnoredInnerRepairInfo(vData: OleVariant; var sErrorMsg: WideString); const UpdateRepairReasonHdr = 'UPDATE FNMDB.dbo.fnRepairOperation SET Is_Ignore = %d, Ignore_Remark = ''%s'', Ignorer = ''%s'', Ignore_Time = GETDATE() WHERE Iden = %d'#13#10; var i: Integer; SqlText: WideString; TempDataSet: TClientDataSet; begin try TempDataSet:=TClientDataSet.Create(nil); try TempDataSet.Data:=vData; SqlText:=''; for i := 0 to TempDataSet.RecordCount - 1 do begin SqlText:=SqlText + Format(UpdateRepairReasonHdr, [ IfThen(TempDataSet.FieldByName('Is_Ignore').AsBoolean, 1, 0), TempDataSet.FieldByName('Ignore_Remark').AsString, TempDataSet.FieldByName('Ignorer').AsString, TempDataSet.FieldByName('Iden').AsInteger ]); TempDataSet.Next; end; finally TempDataSet.Free end; FNMDAOUpt.ExeCommonSql(SqlText, sErrorMsg); //sErrorMsg:=SqlText; SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.GetRecipeChemical(const sBatchNO: WideString; var vData: OleVariant; var sErrorMsg: WideString); var SqlText: WideString; begin SqlText := ' select d.* from dbo.fnOperationRecipeBatch a (NOLOCK) ' +' join dbo.fnOperationRecipeDtl d (NOLOCK) ON d.Recipe_NO = a.Recipe_NO where a.Batch_NO= '+ QuotedStr(sBatchNO); try FNMDAOInfo.GetCommonDataSet(vData, SqlText, sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveData(const sType: WideString; vData: OleVariant; var sErrorMsg: WideString); var sKey, sSQL, sSQLAfter: WideString; begin if sType= 'RecipeChemical' then begin sSQL := ' select * from dbo.fnOperationRecipeDtl where 1=2'; //用sErrorMsg传缸号过来用 sSQLAfter := 'Exec usp_fnExportRecipeToCS '+ sErrorMsg; sKey := 'Recipe_NO,Chemical_ID'; end else if sType= 'FIDutyPoints' then begin sSQL := 'select * from fnFIDuty where 1=2'; sKey := 'Fabric_NO,Worker_ID'; end; try FNMDAOUpt.SaveMultiDataSet(vData, sSQL, sKey, sSQLAfter, sErrorMsg, false); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveSDTraceInfo(var vData: OleVariant; iType: Integer; var sErrorMsg: WideString); const INSERTSDTRACESQL = 'INSERT INTO dbo.fnSDTrace(GF_ID, Job_NO, Trace_Text, FN_Delivery_Date, Operation_Code, Recipients, Is_Email, Current_Department, Operator, Operate_Time) ' + 'VALUES(''%s'',''%s'' ,''%s'' ,''%s'' ,''%s'' ,''%s'' ,''%s'' ,''%s'' ,''%s'' ,GETDATE())'+#13#10; UPDATESDTRACESQL = 'UPDATE dbo.fnSDTrace SET Trace_Text = ''%s'', FN_Delivery_Date = ''%s'', Operation_Code = ''%s'', Recipients = ''%s'', Is_Email = ''%s'', Operator = ''%s'', Operate_Time = GETDATE() ' + 'WHERE GF_ID= ''%s'' AND Job_NO = ''%s'' AND Current_Department = ''%s'''+#13#10; RELEASESDTRACESQL = 'UPDATE dbo.fnSDTrace SET Releaser = ''%s'', Release_Time = GETDATE() ' + 'WHERE GF_ID= ''%s'' AND Job_NO = ''%s'' AND Current_Department = ''%s'''+#13#10; HOLDSQL = 'INSERT dbo.fnHold(GF_ID, Operation_Code, Hold_Reason, Holder, Is_EffectRepair) '+ ' VALUES(''%s'',''%s'',''重要试样跟踪'', ''%s'', 0) '+#13#10; RELEASEHOLDSQ = 'UPDATE dbo.fnHold SET Release_Reason =''解除重要试样跟踪'', Releaser = ''%s'', Release_Time = GETDATE() '+ 'WHERE GF_ID = ''%s'' AND Operation_Code = ''%s'' AND Hold_Reason = ''重要试样跟踪'''+#13#10; var SqlText: WideString; i: Integer; begin try case iType of 0: begin for i := 0 to VarArrayHighBound(vData, 1) do SqlText := SqlText+Format(INSERTSDTRACESQL,[vData[i][0],vData[i][1],vData[i][2],vData[i][3],vData[i][4],vData[i][5],vData[i][6],vData[i][7],vData[i][8]]) +Format(HOLDSQL,[vData[i][0],vData[i][4],vData[i][8]]); end; 1: begin for i := 0 to VarArrayHighBound(vData, 1) do SqlText := SqlText+Format(UPDATESDTRACESQL,[vData[i][2],vData[i][3],vData[i][4],vData[i][5],vData[i][6],vData[i][8],vData[i][0],vData[i][1],vData[i][7]]); end; 2: begin for i := 0 to VarArrayHighBound(vData, 1) do SqlText := SqlText+Format(RELEASESDTRACESQL,[vData[i][3],vData[i][0],vData[i][1],vData[i][2]]) +Format(RELEASEHOLDSQ,[vData[i][3],vData[i][0],vData[i][4]]); end; end; FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveRSTraceInfo(var vData: OleVariant; var sErrorMsg: WideString); const UPDATERSTRACESQL = 'UPDATE dbo.fnRSTrace SET Times_1 = ''%s'', Times_2 = ''%s'', Times_3 = ''%s'', Operator = ''%s'', Operate_Time = GETDATE() ' + 'WHERE GF_ID= ''%s'' AND Job_NO = ''%s'''+#13#10; var SqlText: WideString; i:Integer; begin try for i := 0 to VarArrayHighBound(vData, 1) do SqlText := SqlText+Format(UPDATERSTRACESQL,[vData[i][0],vData[i][1],vData[i][2],vData[i][3],vData[i][4],vData[i][5]]); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveSampleInfo(var vParam: OleVariant; var sErrorMsg: WideString); var i:Integer; SqlText: String; const INSERTSAMPLEINFOSQL ='INSERT INTO dbo.fnSampleInfo(GF_ID,Job_NO,Fabric_NO, Internal_Repair_Times, External_Repair_Times, Step_NO,Operation_Code, Machine_ID,Sample_Code,Actual_Sample_QTY,Sampler,Sample_Time,Current_Department) '+#13+ 'VALUES(''%s'', ''%s'', ''%s'',''%s'', ''%s'',''%s'',''%s'', ''%s'', ''%s'',''%s'', ''%s'', GETDATE(), ''%s'')'+#13#10; begin try for i := 0 to VarArrayHighBound(vParam, 1) do SqlText := SqlText+Format(INSERTSAMPLEINFOSQL,[vParam[i][0], vParam[i][1],LeftStr(vParam[i][2],12),MidStr(vParam[i][2],14,1),MidStr(vParam[i][2],17,1), vParam[i][3],vParam[i][4],vParam[i][5],vParam[i][6],vParam[i][7],vParam[i][8],vParam[i][9]]); FNMDAOUpt.ExeCommonSql(SqlText,sErrorMsg); SetComplete; except SetAbort; raise; end; end; procedure TFNMFacadeLib.SaveMultiData(const sTable1, sTable2: WideString; var vData1, vData2: OleVariant; const sSQLText_Before, sSQLText_After, sKey1, sKey2: WideString; var sErrorMsg: WideString); var sSQL1, sSQL2: widestring; begin try if sTable1 <> '' then sSQL1 := 'select * from ' + sTable1 + ' where 1=2' else sSQL1 := ''; //sSQL1:='exec Wmsdb.dbo.usp_stTableInfo '+QuotedStr(sTable1); if sTable2 <> '' then sSQL2 := 'select * from ' + sTable2 + ' where 1=2' else sSQL2 := ''; //SaveMultiData为一个保存多表的通用函数 //vData1为第一个表数据集,vData2为第二个表的数据集,sSQLText1为取第一个表 //表结构的SQL语句,sSQLText2为取第二个表表结构的SQL语句, //sSQLText_After为保存完两个表后要执行的SQL语句 //sSQLText_Before为保存两个表之前要执行的SQL语句 //一般两个表为主表和明细表,sSQLText_After和sSQLText_Before为保存明细表时需要 //更新回状态的SQL语句 FNMDAOUpt.SaveMultiData(vData1, vData2, sSQL1, sSQL2, sSQLText_Before, sSQLText_After, sKey1, sKey2, sErrorMsg); SetComplete; except on e: Exception do begin sErrorMsg := e.Message; setabort; end; end; end; procedure TFNMFacadeLib.GetQueryBySQL(var vData: OleVariant; const sSQL: WideString; var sErrMsg: WideString); begin try FNMDAOInfo.GetCommonData(vData, sSQL, sErrMsg); SetComplete; except on e: Exception do begin sErrMsg := e.Message; SetAbort; end; end; end; procedure TFNMFacadeLib.SaveSQLData(const sSQL: WideString; var sErrMsg: WideString); begin try FNMDAOUpt.ExeCommonSql(sSQL, sErrMsg); if sErrMsg='' then SetComplete; except on e: Exception do begin sErrMsg := e.Message; SetAbort; end; end; end; initialization TAutoObjectFactory.Create(ComServer, TFNMFacadeLib, Class_FNMFacadeLib, ciMultiInstance, tmNeutral); end.
unit GUIDs; interface Uses classes,sysutils; function CreateObjectID :String; type PGUID = ^TGUID; TGUID = record D1: LongWord; D2: Word; D3: Word; D4: array[0..7] of Byte; end; TCLSID = TGUID; EOleError = class(Exception); EOleSysError = class(EOleError) private FErrorCode: HRESULT; public constructor Create(const Message: string; ErrorCode: HRESULT; HelpContext: Integer); property ErrorCode: HRESULT read FErrorCode write FErrorCode; end; {$EXTERNALSYM CoCreateGuid} function CoCreateGuid(var guid: TGUID): HResult; stdcall; {$EXTERNALSYM CoTaskMemFree} procedure CoTaskMemFree(pv: Pointer); stdcall; {$EXTERNALSYM StringFromCLSID} function StringFromCLSID(const clsid: TCLSID; out psz: PWideChar): HResult; stdcall; implementation const ole32 = 'ole32.dll'; oleaut32 = 'oleaut32.dll'; function CoCreateGuid; external ole32 name 'CoCreateGuid'; function StringFromCLSID; external ole32 name 'StringFromCLSID'; procedure CoTaskMemFree; external ole32 name 'CoTaskMemFree'; function Succeeded(Res: HResult): Boolean; begin Result := Res and $80000000 = 0; end; procedure OleError(ErrorCode: HResult); begin raise EOleSysError.Create('', ErrorCode, 0); end; procedure OleCheck(Result: HResult); begin if not Succeeded(Result) then OleError(Result); end; { EOleSysError } const SOleError = 'OLE error %.8x'; constructor EOleSysError.Create(const Message: string; ErrorCode: HRESULT; HelpContext: Integer); var S: string; begin S := Message; if S = '' then begin S := SysErrorMessage(ErrorCode); if S = '' then FmtStr(S, SOleError, [ErrorCode]); end; inherited CreateHelp(S, HelpContext); FErrorCode := ErrorCode; end; function GUIDToString(const ClassID: TGUID): string; var P: PWideChar; begin OleCheck(StringFromCLSID(ClassID, P)); Result := P; CoTaskMemFree(P); end; function CreateObjectID :String; var newGUID:TGUID; begin {} CoCreateGuid(newGuid); result:= GUidTostring(newGUID); end; end.
unit TpClassInfo; interface uses Classes; type TTpClassInfo = class(TStringList) private function GetDisplayName(const inClassName: string): string; public property DisplayName[const inClassName: string]: string read GetDisplayName; end; function TurboClassInfo: TTpClassInfo; implementation var SingletonClassInfo: TTpClassInfo; function TurboClassInfo: TTpClassInfo; begin if SingletonClassInfo = nil then SingletonClassInfo := TTpClassInfo.Create; Result := SingletonClassInfo; end; { TTpClassInfo } function TTpClassInfo.GetDisplayName(const inClassName: string): string; var i: Integer; begin i := IndexOfName(inClassName); if (i < 0) then Result := inClassName else Result := ValueFromIndex[i]; end; end.
unit Settings; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ipControls, ipButtons, StdCtrls, ipEdit, ipPlacemnt, ipOther, ExtCtrls, ipHTMLHelp; type TfmSettings = class(TipHTMLHelpForm) bOK: TipButton; bCancel: TipButton; PageControl: TPageControl; TabSheet1: TTabSheet; Label1: TLabel; eID: TipEditTS; Storage: TipFormStorage; GroupBox1: TGroupBox; rbPhone: TRadioButton; rbRegular: TRadioButton; TabSheet2: TTabSheet; Label16: TLabel; eHost: TipEditTS; Label18: TLabel; eLogin: TipEditTS; Label19: TLabel; ePassword: TipPasswordEditTS; eTo: TipEditTS; Label23: TLabel; eFrom: TipEditTS; Label21: TLabel; Label2: TLabel; rgAuth: TRadioGroup; ePort: TipEditTS; Label3: TLabel; seUndo: TipSpinEditTS; bHelp: TipButton; ePwd: TipEditTS; Label4: TLabel; Label5: TLabel; Label6: TLabel; bInfo: TipButton; Label7: TLabel; eJCHost: TipEditTS; eJCPort: TipEditTS; Label8: TLabel; procedure bInfoClick(Sender: TObject); private { Private declarations } public class function ShowInfo: boolean; end; var fmSettings: TfmSettings; implementation {$R *.dfm} uses Main, Info, SmtpProt, ipUtils, mwCustomEdit; { TfmSettings } class function TfmSettings.ShowInfo: boolean; begin with TfmSettings.Create(Application) do try rbRegular.Hint:=ReplaceStr(rbRegular.Hint,'|',#13#10); rbPhone.Hint:=ReplaceStr(rbPhone.Hint,'|',#13#10); with fmMain.Settings do begin eID.Text:=Ident; ePwd.Text:=Password; rbRegular.Checked:=not PhoneStyle; rbPhone.Checked:=PhoneStyle; eJCHost.Text:=JCHost; eJCPort.Text:=IntToStr(JCPort); end; with fmMain.SMTP do begin eHost.Text:=Host; ePort.Text:=Port; eLogin.Text:=Username; ePassword.Text:=Password; eFrom.Text:=HdrFrom; eTo.Text:=HdrTo; rgAuth.ItemIndex:=integer(AuthType); end; with fmMain.Editor do begin seUndo.Value:=MaxUndo; end; Result:=ShowModal=mrOK; if Result then begin with fmMain.Settings do begin Ident:=eID.Text; Password:=ePwd.Text; PhoneStyle:=rbPhone.Checked; JCHost:=eJCHost.Text; JCPort:=StrToIntDef(eJCPort.Text,80); end; with fmMain.SMTP do begin Host:=eHost.Text; Port:=ePort.Text; Username:=eLogin.Text; Password:=ePassword.Text; HdrFrom:=eFrom.Text; FromName:=HdrFrom; HdrTo:=eTo.Text; RcptName.Text:=eTo.Text; AuthType:=TSmtpAuthType(rgAuth.ItemIndex); end; with fmMain.Editor do begin MaxUndo:=seUndo.Value; end; end; finally Free; end; end; procedure TfmSettings.bInfoClick(Sender: TObject); begin TfmInfo.ShowInfo; end; end.
unit uReportByNationalityForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,dmNationalityMain, StdCtrls, Buttons, frxDesgn, frxClass, frxDBSet, cxDropDownEdit, cxCalendar, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox; type TReportForm = class(TForm) Label1: TLabel; NationalityComboBox: TcxLookupComboBox; Label3: TLabel; CurDateEdit: TcxDateEdit; FRDataSet: TfrxDBDataset; Designer: TfrxDesigner; OkButton: TBitBtn; CancelButton: TBitBtn; Report: TfrxReport; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure OkButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public DataModule:TMainDM; DesignReport:Boolean; end; var ReportForm: TReportForm; implementation {$R *.dfm} procedure TReportForm.FormClose(Sender: TObject; var Action: TCloseAction); begin DataModule.NationalityDataSet.Close; end; procedure TReportForm.FormShow(Sender: TObject); begin DataModule.NationalityDataSet.Open; FRDataSet.DataSource:=DataModule.ReportDataSource; NationalityComboBox.Properties.ListSource:=DataModule.NationalityDataSource; end; procedure TReportForm.OkButtonClick(Sender: TObject); begin with DataModule.ReportDataSet do begin Close; ParamByName('ID_NATIONALITY').Value:=NationalityComboBox.EditValue; ParamByName('REPORT_DATE').Value:=CurDateEdit.Date; Open; end; with DataModule.ConstsQuery do begin Close; Open; end; Report.LoadFromFile('Reports\Asup\AsupNationalityReport.fr3'); Report.Variables['CUR_DATE']:=QuotedStr(DateToStr(CurDateEdit.Date)); Report.Variables['FIRM_NAME']:= QuotedStr(DataModule.ConstsQuery['FIRM_NAME']); Report.Variables['NATIONALITY']:=QuotedStr(NationalityComboBox.EditText); if DesignReport=True then Report.DesignReport else Report.ShowReport; end; procedure TReportForm.FormCreate(Sender: TObject); begin CurDateEdit.Date:=Date(); end; end.
unit UDPages; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, UCrpe32; type TCrpePagesDlg = class(TForm) btnOk: TButton; btnCancel: TButton; pnlPages: TPanel; editStartPageNumber: TEdit; lblStartPageNumber: TLabel; sbFirst: TSpeedButton; sbPrevious: TSpeedButton; sbNext: TSpeedButton; sbLast: TSpeedButton; pnlMonitor: TPanel; cbMonitor: TCheckBox; Label1: TLabel; editStart: TEdit; Label2: TLabel; editLatest: TEdit; Label3: TLabel; editDisplayed: TEdit; btnGoToPage: TButton; editGoToPage: TEdit; Timer1: TTimer; lblInstructions: TLabel; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure UpdatePages; procedure InitializeControls(OnOff: boolean); procedure sbFirstClick(Sender: TObject); procedure sbPreviousClick(Sender: TObject); procedure btnGoToPageClick(Sender: TObject); procedure sbNextClick(Sender: TObject); procedure sbLastClick(Sender: TObject); procedure cbMonitorClick(Sender: TObject); procedure editGoToPageEnter(Sender: TObject); procedure editGoToPageExit(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnOkClick(Sender: TObject); procedure editStartPageNumberEnter(Sender: TObject); procedure editStartPageNumberExit(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FormDeactivate(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; rStartPage : LongInt; PrevNum : string; end; var CrpePagesDlg: TCrpePagesDlg; bPages : boolean; implementation {$R *.DFM} uses UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.FormCreate(Sender: TObject); begin bPages := True; LoadFormPos(Self); end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.FormShow(Sender: TObject); begin {Store current VCL settings} rStartPage := Cr.Pages.StartPageNumber; editGoToPage.Text := '1'; editStartPageNumber.Text := '1'; UpdatePages; end; {------------------------------------------------------------------------------} { UpdatePages } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.UpdatePages; var OnOff : Boolean; begin OnOff := not IsStrEmpty(Cr.ReportName); InitializeControls(OnOff); if OnOff then begin editStartPageNumber.Text := IntToStr(Cr.Pages.StartPageNumber); cbMonitor.Checked := (Cr.ReportWindowHandle > 0); Timer1.Enabled := cbMonitor.Checked; end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TSpeedButton then TSpeedButton(Components[i]).Enabled := OnOff; if Components[i] is TCheckBox then TCheckBox(Components[i]).Enabled := OnOff; if Components[i] is TEdit then begin if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { sbFirstClick } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.sbFirstClick(Sender: TObject); begin Cr.Pages.First; end; {------------------------------------------------------------------------------} { sbPreviousClick } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.sbPreviousClick(Sender: TObject); begin Cr.Pages.Previous; end; {------------------------------------------------------------------------------} { btnGoToPageClick } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.btnGoToPageClick(Sender: TObject); begin if IsNumeric(editGoToPage.Text) then Cr.Pages.GoToPage(StrToInt(editGoToPage.Text)); end; {------------------------------------------------------------------------------} { sbNextClick } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.sbNextClick(Sender: TObject); begin Cr.Pages.Next; end; {------------------------------------------------------------------------------} { sbLastClick } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.sbLastClick(Sender: TObject); begin Cr.Pages.Last; end; {------------------------------------------------------------------------------} { editGoToPageEnter } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.editGoToPageEnter(Sender: TObject); begin PrevNum := editGoToPage.Text; end; {------------------------------------------------------------------------------} { editGoToPageExit } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.editGoToPageExit(Sender: TObject); begin if not IsNumeric(editGoToPage.Text) then editGoToPage.Text := PrevNum; end; {------------------------------------------------------------------------------} { editStartPageNumberEnter } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.editStartPageNumberEnter(Sender: TObject); begin PrevNum := editStartPageNumber.Text; end; {------------------------------------------------------------------------------} { editStartPageNumberExit } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.editStartPageNumberExit(Sender: TObject); begin if not IsNumeric(editStartPageNumber.Text) then editStartPageNumber.Text := PrevNum; Cr.Pages.StartPageNumber := StrToInt(editStartPageNumber.Text); end; {------------------------------------------------------------------------------} { cbMonitorClick } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.cbMonitorClick(Sender: TObject); begin Timer1.Enabled := (Cr.ReportWindowHandle > 0) and cbMonitor.Checked; end; {------------------------------------------------------------------------------} { Timer1Timer } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.Timer1Timer(Sender: TObject); begin editStart.Text := IntToStr(Cr.Pages.GetStart); editLatest.Text := IntToStr(Cr.Pages.GetLatest); editDisplayed.Text := IntToStr(Cr.Pages.GetDisplayed); cbMonitor.Checked := (Cr.ReportWindowHandle > 0); Timer1.Enabled := cbMonitor.Checked; end; {------------------------------------------------------------------------------} { FormDeactivate } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.FormDeactivate(Sender: TObject); begin if not IsStrEmpty(Cr.ReportName) then begin editGoToPageExit(Self); editStartPageNumberExit(Self); end; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); if not IsStrEmpty(Cr.ReportName) then begin editGoToPageExit(Self); editStartPageNumberExit(Self); end; Close; end; {------------------------------------------------------------------------------} { btnCancelClick } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.btnCancelClick(Sender: TObject); begin Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpePagesDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Timer1.Enabled := False; if ModalResult = mrCancel then Cr.Pages.StartPageNumber := rStartPage; bPages := False; Release; end; end.
// Wheberson Hudson Migueletti, em Brasília, 18 de novembro de 2000. // Referências: [1] BDE32.hlp // [2] \Delphi 3\Source\VCL\DBTables.pas unit DelphiBDE; interface uses Windows, SysUtils, Classes, Bde, DB, DBCommon, DBTables; procedure GetTableNames (const DatabaseName, Pattern: String; Extensions, SystemTables: Boolean; List: TStrings); function RestructureTable (Table: TTable; FieldDefs: TFieldDefs): Boolean; implementation // Captura os nomes das tabelas de um "Database". O método "Session.GetTableNames" mostra a caixa de diálogo do "Login" enquanto esta rotina não procedure GetTableNames (const DatabaseName, Pattern: String; Extensions, SystemTables: Boolean; List: TStrings); var SPattern: array[0..127] of Char; Flag : Boolean; Cursor : HDBICur; WildCard: PChar; Name : String; Desc : TBLBaseDesc; Database: TDatabase; begin List.BeginUpdate; try List.Clear; Database:= Session.FindDatabase (DatabaseName); Flag := not Assigned (Database); if Flag then begin Database := TDatabase.Create (nil); Database.DatabaseName := DatabaseName; Database.KeepConnection:= False; Database.Temporary := True; end; try Database.LoginPrompt:= False; WildCard := nil; try Database.Open; if Pattern <> '' then WildCard:= AnsiToNative (Database.Locale, Pattern, SPattern, SizeOf (SPattern)-1); Check (DbiOpenTableList (Database.Handle, False, SystemTables, WildCard, Cursor)); try while DbiGetNextRecord (Cursor, dbiNOLOCK, @Desc, nil) = 0 do with Desc do begin if Extensions and (szExt[0] <> #0) then StrCat (StrCat (szName, '.'), szExt); NativeToAnsi (Database.Locale, szName, Name); List.Add (Name); end; finally DbiCloseCursor (Cursor); end; except end; finally if Flag then Database.Free; end; finally List.EndUpdate; end; end; function RestructureTable (Table: TTable; FieldDefs: TFieldDefs): Boolean; var TableDesc: CRTblDesc; Locale : TLocale; procedure EncodeFieldDesc (var FieldDesc: FLDDesc; N: Integer; const Name: String; DataType: TFieldType; Size, Precision: Word); begin with FieldDesc do begin AnsiToNative (Locale, Name, szName, SizeOf (szName) - 1); iFldNum := N; iFldType:= FldTypeMap[DataType]; iSubType:= FldSubTypeMap[DataType]; case DataType of ftString, ftBytes, ftVarBytes, ftBlob, ftMemo, ftGraphic, ftFmtMemo, ftParadoxOle, ftDBaseOle, ftTypedBinary: iUnits1:= Size; ftBCD : begin iUnits2:= Size; iUnits1:= 32; if Precision > 0 then iUnits1:= Precision; end; end; end; end; function IsDBaseTable: Boolean; begin Result:= (Table.TableType = ttDBase) or (CompareText (ExtractFileExt (Table.TableName), '.DBF') = 0); end; function GetStandardLanguageDriver: String; var DriverName: String; Buffer : array[0..DBIMAXNAMELEN - 1] of Char; begin if not Table.Database.IsSQLBased then begin DriverName:= TableDesc.szTblType; if DriverName = '' then if IsDBaseTable then DriverName:= szDBASE else DriverName:= szPARADOX; if DbiGetLdName (PChar (DriverName), nil, Buffer) = 0 then Result:= Buffer; end else Result := ''; end; function GetDriverTypeName (Buffer: PChar): PChar; var Length: Word; begin Result:= Buffer; Check (DbiGetProp (hDBIObj (Table.DBHandle), dbDATABASETYPE, Buffer, SizeOf (DBINAME), Length)); if StrIComp (Buffer, szCFGDBSTANDARD) = 0 then begin Result:= TableDesc.szTblType; if Assigned (Result) then Result:= StrCopy (Buffer, Result); end; end; var Props : CURProps; DriverTypeName: DBINAME; SQLLName : DBIName; hDb : HDBIDb; I : Integer; PSQLLName : PChar; Ops : PCROpType; Flds, HFlds : PFLDDesc; NewFlds : PFLDDesc; LName : String; TempLocale : TLocale; begin Result:= False; if Table.Active = False then raise EDatabaseError.Create ('Table must be opened to restructure'); if Table.Exclusive = False then raise EDatabaseError.Create ('Table must be opened exclusively to restructure'); NewFlds:= AllocMem (FieldDefs.Count*SizeOf (FLDDesc)); try FillChar (NewFlds^, FieldDefs.Count*SizeOf (FLDDesc), 0); FillChar (TableDesc, SizeOf (TableDesc), 0); TableDesc.pfldDesc:= AllocMem (FieldDefs.Count*SizeOf (FLDDesc)); try HFlds:= AllocMem (Table.FieldDefs.Count*SizeOf (FLDDesc)); try Flds:= HFlds; FillChar (Flds^, Table.FieldDefs.Count*SizeOf (FLDDesc), 0); Check (DbiSetProp (hDBIObj (Table.Handle), curxltMODE, Integer (xltNONE))); Check (DbiGetCursorProps (Table.Handle, Props)); Check (DbiGetFieldDescs (Table.Handle, Flds)); StrPCopy (TableDesc.szTblName, Props.szName); StrPCopy (TableDesc.szTblType, Props.szTableType); TempLocale:= nil; LName := GetStandardLanguageDriver; Locale := Table.Locale; if (LName <> '') and (OsLdLoadBySymbName (PChar (LName), TempLocale) = 0) then Locale:= TempLocale; try for I:= 0 to FieldDefs.Count-1 do with FieldDefs[I] do EncodeFieldDesc (PFieldDescList (NewFlds)^[I], I+1, Name, DataType, Size, Precision); finally if Assigned (TempLocale) then OsLdUnloadObj (TempLocale); end; PSQLLName:= nil; if Table.Database.IsSQLBased then if DbiGetLdNameFromDB (Table.DBHandle, nil, SQLLName) = 0 then PSQLLName:= SQLLName; Check (DbiTranslateRecordStructure (nil, FieldDefs.Count, NewFlds, GetDriverTypeName (DriverTypeName), PSQLLName, TableDesc.pfldDesc, False)); TableDesc.pecrFldOp:= AllocMem (FieldDefs.Count*SizeOf (CROpType)); try Ops:= TableDesc.pecrFldOp; for I:= 0 to FieldDefs.Count-1 do begin with PFieldDescList (TableDesc.pfldDesc)^[I] do if I >= Table.FieldDefs.Count then Ops^:= crAdd else begin if (CompareText (Flds.szName, szName) <> 0) or (Flds.iFldType <> iFldType) or (Flds.iLen <> iLen) or (Flds.iFldNum <> iFldNum) then Ops^:= crMODIFY else Ops^:= crNOOP; Inc (Flds); end; Inc (Ops); end; Check (DbiGetObjFromObj (hDBIObj (Table.Handle), objDATABASE, hDBIObj (hDb))); // Get the database handle from the table's cursor handle... TableDesc.iFldCount:= FieldDefs.Count; Table.Close; Check (DbiDoRestructure (hDb, 1, @TableDesc, nil, nil, nil, False)); Result:= True; finally FreeMem (TableDesc.pecrFldOp); end; finally FreeMem (HFlds); end; finally FreeMem (TableDesc.pfldDesc); end; finally FreeMem (NewFlds); end; end; end.
unit API_Files; interface uses System.Classes ,System.SysUtils; type TFilesEngine = class public class function GetTextFromFile(FileName: String): String; class procedure SaveTextToFile(FileName, Text: String); class procedure AppendToFile(FileName, Text: String); end; implementation class procedure TFilesEngine.AppendToFile(FileName, Text: String); var EditFile: TextFile; begin try AssignFile(EditFile, FileName); Append(EditFile); WriteLn(EditFile, Text); CloseFile(EditFile); except end; end; class function TFilesEngine.GetTextFromFile(FileName: string): string; var SL: TStringList; begin if FileExists(FileName) then begin SL := TStringList.Create; try SL.LoadFromFile(FileName); Result := SL.Text; finally SL.Free; end; end; end; class procedure TFilesEngine.SaveTextToFile(FileName, Text: String); var SL: TStringList; begin SL := TStringList.Create; try SL.Text := Text; SL.SaveToFile(FileName); finally SL.Free; end; end; end.
program svctest; {$mode objfpc}{$H+} uses cthreads, unixtype, fosillu_libscf, fosillu_nvpair, fosillu_libzfs, fosillu_zfs, Classes, fos_illumos_defs,fosillu_mnttab,fosillu_libzonecfg, ctypes, sysutils, strutils; var h : Pscf_handle_t; res : integer; g_pg : Pscf_propertygroup_t; g_prop : Pscf_property_t; g_val : Pscf_value_t; {* * Convenience libscf wrapper functions. * * * Get the single value of the named property in the given property group, * which must have type ty, and put it in *vp. If ty is SCF_TYPE_ASTRING, vp * is taken to be a char **, and sz is the size of the buffer. sz is unused * otherwise. Return 0 on success, -1 if the property doesn't exist, has the * wrong type, or doesn't have a single value. If flags has EMPTY_OK, don't * complain if the property has no values (but return nonzero). If flags has * MULTI_OK and the property has multiple values, succeed with E2BIG. * } function pg_get_single_val(pg : Pscf_propertygroup_t; const propname : string; ty : scf_type_t ; vp : pointer ; sz : size_t ; flags : uint_t):cint; begin if ty<>SCF_TYPE_ASTRING then abort; if scf_pg_get_property(pg, @propname[1], g_prop) = -1 then begin writeln('GET PROP ERROR : ',scf_error); abort; end; if (scf_property_is_type(g_prop, ty) <> SCF_SUCCESS) then begin writeln('type mismatch'); abort; end; if (scf_property_get_value(g_prop, g_val) <> SCF_SUCCESS) then begin writeln('GET PROP VAL ERROR : ',scf_error); abort; end; result := scf_value_get_astring(g_val, vp, sz); end; { char *buf, root[MAXPATHLEN]; size_t buf_sz; int ret = -1, r; boolean_t multi = B_FALSE; assert((flags & ~(EMPTY_OK | MULTI_OK)) == 0); if (scf_pg_get_property(pg, propname, g_prop) == -1) { if (scf_error() != SCF_ERROR_NOT_FOUND) scfdie(); goto out; } if (scf_property_is_type(g_prop, ty) != SCF_SUCCESS) { if (scf_error() == SCF_ERROR_TYPE_MISMATCH) goto misconfigured; scfdie(); } if (scf_property_get_value(g_prop, g_val) != SCF_SUCCESS) { switch (scf_error()) { case SCF_ERROR_NOT_FOUND: if (flags & EMPTY_OK) goto out; goto misconfigured; case SCF_ERROR_CONSTRAINT_VIOLATED: if (flags & MULTI_OK) { multi = B_TRUE; break; } goto misconfigured; case SCF_ERROR_PERMISSION_DENIED: default: scfdie(); } } switch (ty) { case SCF_TYPE_ASTRING: r = scf_value_get_astring(g_val, vp, sz) > 0 ? SCF_SUCCESS : -1; break; case SCF_TYPE_BOOLEAN: r = scf_value_get_boolean(g_val, (uint8_t *)vp); break; case SCF_TYPE_COUNT: r = scf_value_get_count(g_val, (uint64_t *)vp); break; case SCF_TYPE_INTEGER: r = scf_value_get_integer(g_val, (int64_t *)vp); break; case SCF_TYPE_TIME: { int64_t sec; int32_t ns; r = scf_value_get_time(g_val, &sec, &ns); ((struct timeval *)vp)->tv_sec = sec; ((struct timeval *)vp)->tv_usec = ns / 1000; break; } case SCF_TYPE_USTRING: r = scf_value_get_ustring(g_val, vp, sz) > 0 ? SCF_SUCCESS : -1; break; default: #ifndef NDEBUG uu_warn("%s:%d: Unknown type %d.\n", __FILE__, __LINE__, ty); #endif abort(); } if (r != SCF_SUCCESS) scfdie(); ret = multi ? E2BIG : 0; goto out; misconfigured: buf_sz = max_scf_fmri_length + 1; buf = safe_malloc(buf_sz); if (scf_property_to_fmri(g_prop, buf, buf_sz) == -1) scfdie(); uu_warn(gettext("Property \"%s\" is misconfigured.\n"), buf); free(buf); out: if (ret != 0 || g_zonename == NULL || (strcmp(propname, SCF_PROPERTY_LOGFILE) != 0 && strcmp(propname, SCF_PROPERTY_ALT_LOGFILE) != 0)) return (ret); /* * If we're here, we have a log file and we have specified a zone. * As a convenience, we're going to prepend the zone path to the * name of the log file. */ root[0] = '\0'; (void) zone_get_rootpath(g_zonename, root, sizeof (root)); (void) strlcat(root, vp, sizeof (root)); (void) snprintf(vp, sz, "%s", root); return (ret); } { * * As pg_get_single_val(), except look the property group up in an * instance. If "use_running" is set, and the running snapshot exists, * do a composed lookup there. Otherwise, do an (optionally composed) * lookup on the current values. Note that lookups using snapshots are * always composed. * } function inst_get_single_val(inst : Pscf_instance_t ; const pgname,propname : string; ty : scf_type_t ; vp : pointer ; sz : size_t ; flags : uint_t ; use_running, composed : cint) : cint; var snap : Pscf_snapshot_t = nil; //rpg : Pscf_propertygroup_t; //test : string; begin // rpg := scf_pg_create(h); Result := scf_instance_get_pg_composed(inst, snap, @pgname[1], g_pg); if Result=-1 then begin writeln('scf composed : ',scf_error); abort; end; if assigned(snap) then scf_snapshot_destroy(snap); if Result=-1 then exit; if assigned(g_pg) then Result := pg_get_single_val(g_pg, propname, ty, vp, sz, flags); end; { scf_snapshot_t *snap = NULL; int r; if (use_running) snap = get_running_snapshot(inst); if (composed || use_running) r = scf_instance_get_pg_composed(inst, snap, pgname, g_pg); else r = scf_instance_get_pg(inst, pgname, g_pg); if (snap) scf_snapshot_destroy(snap); if (r == -1) return (-1); r = pg_get_single_val(g_pg, propname, ty, vp, sz, flags); return (r); } { * Get a string property from the restarter property group of the given * instance. Return an empty string on normal problems. } procedure get_restarter_string_prop(inst : Pscf_instance_t ; const pname : string ; var value : string); var len : cint; begin SetLength(value,1024); len := inst_get_single_val(inst, SCF_PG_RESTARTER, pname ,SCF_TYPE_ASTRING, @value[1], length(value), 0, 0, 1); if (len <> 0) then SetLength(value,len) else value := ''; end; function list_instance(dummy : pointer ; wip : Pscf_walkinfo_t):cint;cdecl; var fmri,state:string; scope :string; len : cint; begin if assigned(wip^.pg) then begin state := SCF_STATE_STRING_LEGACY; end else begin get_restarter_string_prop(wip^.inst,SCF_PROPERTY_STATE,state); end; scope := ''; if assigned(wip^.scope) then begin setlength(scope,256); len := scf_scope_get_name(wip^.scope, @scope[1], Length(scope)); SetLength(scope,len); end; fmri := PChar(wip^.fmri); writeln( fmri,' STATE = ',state,' ',scope); result := 0; end; procedure error_cb(param1 : PChar ; p2 : array of const); begin writeln('ERROR CALLBACK?'); end; var fmri : string; err : scf_error_t; //wit : scf_walkinfo_t; begin writeln('FOS SVCS Test'); h := scf_handle_create(Pscf_version_t(1)); res := scf_handle_bind(h); g_pg := scf_pg_create(h); g_prop := scf_property_create(h); g_val := scf_value_create(h); err := scf_walk_fmri(h, 0, nil, SCF_WALK_MULTIPLE + SCF_WALK_LEGACY, @list_instance , nil, nil,@error_cb); //writeln('SCF Handle :',integer(h)); //fmri := 'svc:/network/iscsi/target:default'+#0; //res := smf_enable_instance(@fmri[1],0); // writeln('Enable Test ',res); //res := scf_simple_walk_instances(SCF_STATE_ALL,pointer(4711),@simple_walk); end.
unit UInfoSistemas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Mask, Vcl.DBCtrls, Datasnap.DBClient, Vcl.ComCtrls, //Uses REST Web.HTTPApp, REST.Types, REST.Client, Data.Bind.Components, Data.Bind.ObjectScope, System.Json, //Uses E-mail/XML IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdMessage, IdAttachmentFile, Xml.xmldom, Xml.XMLIntf, Xml.XMLDoc; type TForm1 = class(TForm) tabCliente: TClientDataSet; tabClienteID: TIntegerField; tabClienteNOME: TStringField; DBNavigator1: TDBNavigator; dsCliente: TDataSource; pnGrid: TPanel; gdCliente: TDBGrid; pnCampos: TPanel; tabClienteIDENTIDADE: TStringField; tabClienteCPF: TStringField; tabClienteTELEFONE: TStringField; tabClienteEMAIL: TStringField; tabClienteCEP: TStringField; tabClienteLOGRADOURO: TStringField; tabClienteNUMERO: TStringField; tabClienteCOMPLEMENTO: TStringField; tabClienteBAIRRO: TStringField; tabClienteCIDADE: TStringField; tabClienteESTADO: TStringField; tabClientePAIS: TStringField; pgCadastro: TPageControl; tabDados: TTabSheet; tabEndereco: TTabSheet; lblId: TLabel; edtId: TDBEdit; lblNome: TLabel; edtNome: TDBEdit; lblRG: TLabel; edtRG: TDBEdit; lblCPF: TLabel; edtCPF: TDBEdit; lblTelefone: TLabel; edtTelefone: TDBEdit; lblEmail: TLabel; edtEmail: TDBEdit; lblCEP: TLabel; edtCEP: TDBEdit; lblLogradouro: TLabel; edtLogradouro: TDBEdit; lblNumero: TLabel; edtNumero: TDBEdit; lblComplemento: TLabel; edtComplemento: TDBEdit; lblBairro: TLabel; edtBairro: TDBEdit; lblCidade: TLabel; edtCidade: TDBEdit; lblEstado: TLabel; edtEstado: TDBEdit; lblPais: TLabel; edtPais: TDBEdit; RESTClient1: TRESTClient; RESTRequest1: TRESTRequest; RESTResponse1: TRESTResponse; btnBuscar: TButton; pnBottons: TPanel; Panel2: TPanel; btnGravar: TButton; Panel1: TPanel; btnEnviaEmail: TButton; procedure btnBuscarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure tabClienteBeforePost(DataSet: TDataSet); procedure btnEnviaEmailClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnGravarClick(Sender: TObject); procedure tabClienteNewRecord(DataSet: TDataSet); private { Private declarations } iSequencialId : Integer; procedure BuscaCep(); public { Public declarations } end; var Form1: TForm1; const _USERNAME = 'joaovictor.brasil1992@gmail.com'; _PASSWORD = 'jvob2012'; _FILENAME = 'CADASTRO_'; implementation {$R *.dfm} procedure TForm1.BuscaCep(); var aRetorno : TJSONObject; aMensagem : String; begin aMensagem := EmptyStr; try RESTRequest1.Resource := 'ws/{CEP}/json/'; RESTRequest1.Params.AddUrlSegment('CEP', edtCEP.Text); RESTRequest1.Execute; aRetorno := RESTRequest1.Response.JSONValue as TJSONObject; except on e:Exception do begin ShowMessage('Erro no WebService tente mais tarde!'); raise; end; end; case RESTRequest1.Response.StatusCode of 400 : aMensagem := 'CEP inválido'; 404 : aMensagem := 'URL inválida'; end; //Se a resposta da requisicao retornar 1 registro "erro" = true (Erro devolvido quando o CEP é inesistente) if (aRetorno.Count = 1) then aMensagem := 'CEP inesistente'; if aMensagem <> EmptyStr then ShowMessage(aMensagem) else begin edtNumero.SetFocus; edtLogradouro.Text := aRetorno.Get('logradouro').JsonValue.Value; edtBairro.Text := aRetorno.Get('bairro').JsonValue.Value; edtCidade.Text := aRetorno.Get('localidade').JsonValue.Value; edtEstado.Text := aRetorno.Get('uf').JsonValue.Value; end; aRetorno := nil; aRetorno.Free; end; procedure TForm1.btnGravarClick(Sender: TObject); begin if not (tabCliente.State in [dsEdit, dsInsert]) then tabCliente.Edit; tabCliente.Post; end; procedure TForm1.btnEnviaEmailClick(Sender: TObject); var //EMAIL DATA : TIdMessage; SMTP : TIdSMTP; SSL : TIdSSLIOHandlerSocketOpenSSL; // XML FILENAME : string; XMLDocument : TXMLDocument; NodeTabela : IXMLNode; NodeRegistro : IXMLNode; NodeEndereco : IXMLNode; begin try //Criando nome do arquivo FILENAME := _FILENAME + tabClienteID.AsString + '.xml'; //Gerando o xml XMLDocument := TXMLDocument.Create(Self); try XMLDocument.Active := True; NodeTabela := XMLDocument.AddChild('Cadastro'); NodeRegistro := NodeTabela.AddChild('Registro'); NodeRegistro.ChildValues['Id'] := tabClienteID.AsString; NodeRegistro.ChildValues['Nome'] := tabClienteNOME.AsString; NodeRegistro.ChildValues['RG'] := tabClienteIDENTIDADE.AsString; NodeRegistro.ChildValues['CPF'] := tabClienteCPF.AsString; NodeRegistro.ChildValues['Telefone'] := tabClienteTELEFONE.AsString; NodeRegistro.ChildValues['Email'] := tabClienteEMAIL.AsString; //Identando o XML NodeEndereco := NodeRegistro.AddChild('Endereco'); NodeEndereco.ChildValues['CEP'] := tabClienteCEP.AsString; NodeEndereco.ChildValues['Logradouro'] := tabClienteLOGRADOURO.AsString; NodeEndereco.ChildValues['Numero'] := tabClienteNUMERO.AsString; NodeRegistro.ChildValues['Complemento'] := tabClienteCOMPLEMENTO.AsString; NodeEndereco.ChildValues['Bairro'] := tabClienteBAIRRO.AsString; NodeRegistro.ChildValues['Cidade'] := tabClienteCIDADE.AsString; NodeEndereco.ChildValues['UF'] := tabClienteESTADO.AsString; NodeEndereco.ChildValues['Pais'] := tabClientePAIS.AsString; XMLDocument.SaveToFile(FILENAME); finally XMLDocument.Free; end; SMTP := TIdSMTP.Create(nil); DATA := TIdMessage.Create(nil); SSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil); SSL.SSLOptions.Method := sslvTLSv1; SSL.SSLOptions.Mode := sslmUnassigned; SSL.SSLOptions.VerifyMode := []; SSL.SSLOptions.VerifyDepth := 0; DATA.From.Address := _USERNAME; DATA.Recipients.EMailAddresses := tabClienteEMAIL.AsString; DATA.subject := 'Cadastro efetuado com sucesso'; DATA.body.text := 'Segue anexo XML com informações de cadastro.'; TIdAttachmentFile.Create(DATA.MessageParts, FILENAME); SMTP.IOHandler := SSL; SMTP.Host := 'smtp.gmail.com'; SMTP.Port := 465; SMTP.username := _USERNAME; SMTP.password := _PASSWORD; SMTP.UseTLS := utUseImplicitTLS; SMTP.AuthType := satDefault; // Conexão e autenticação try SMTP.Connect; SMTP.Authenticate; except on E:Exception do begin MessageDlg('Erro ao autenticar : ' + E.Message, mtWarning, [mbOK], 0); Abort; end; end; // Envio da mensagem try SMTP.Send(DATA); MessageDlg('Mensagem enviada com sucesso!', mtInformation, [mbOK], 0); except On E:Exception do begin MessageDlg('Erro ao enviar o email: ' + E.Message, mtWarning, [mbOK], 0); end; end; finally SMTP.Free; DATA.Free; SSL.Free; end; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin tabCliente.Close; end; procedure TForm1.FormShow(Sender: TObject); begin tabCliente.CreateDataSet; pgCadastro.ActivePageIndex := 0; edtNome.SetFocus; iSequencialId := 0; end; procedure TForm1.tabClienteBeforePost(DataSet: TDataSet); begin if (tabCliente.State in [dsInsert]) then begin iSequencialId := iSequencialId + 1; tabClienteID.AsInteger := iSequencialId; end; end; procedure TForm1.tabClienteNewRecord(DataSet: TDataSet); begin pgCadastro.ActivePage := tabDados; end; procedure TForm1.btnBuscarClick(Sender: TObject); Begin BuscaCep(); end; end.
unit VSelRecSoporteForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, RXSpin, StdCtrls, Mask, ToolEdit, ComCtrls, ExtCtrls; type TSelRecSoporteForm = class(TForm) Label2: TLabel; FechaSoporteEdit: TDateEdit; soportesListView: TListView; Panel2: TPanel; Panel1: TPanel; newButton: TButton; modifyButton: TButton; delSoporteButton: TButton; genSopButton: TButton; TerminarBtn: TButton; StatusBar1: TStatusBar; vinculadosListView: TListView; prnSopButton: TButton; procedure TerminarBtnClick(Sender: TObject); procedure FechaSoporteEditChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure soportesListViewSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); private { Private declarations } protected FOnChangeFechaSoporte: TNotifyEvent; FOnChangeSelected: TNotifyEvent; procedure changeFechaSoporte; procedure changeSelectedSoporte; procedure setFechaSoporte( aDate: TDateTime ); function getFechaSoporte: TDateTime; procedure setOnChangeFechaSoporte( aEventHandler: TNotifyEvent ); public property FechaSoporte: TDateTime read getFechaSoporte write setFechaSoporte; property OnChangeFechaSoporte: TNotifyEvent read FOnChangeFechaSoporte write setOnChangeFechaSoporte; property OnChangeSelected: TNotifyEvent read FOnChangeSelected write FOnChangeSelected; end; implementation {$R *.dfm} (***** MÉTODOS PRIVADOS *****) procedure TSelRecSoporteForm.changeFechaSoporte; begin if assigned( FOnChangeFechaSoporte ) then FOnChangeFechaSoporte( Self ); end; procedure TSelRecSoporteForm.changeSelectedSoporte; begin if assigned( FOnChangeSelected ) then FOnChangeSelected( self ); end; //**** soporte a las propiedades **** procedure TSelRecSoporteForm.setFechaSoporte( aDate: TDateTime ); begin FechaSoporteEdit.Date := aDate; changeFechaSoporte(); end; function TSelRecSoporteForm.getFechaSoporte: TDateTime; begin Result := FechaSoporteEdit.Date; end; procedure TSelRecSoporteForm.setOnChangeFechaSoporte( aEventHandler: TNotifyEvent ); begin FOnChangeFechaSoporte := aEventHandler ; changeFechaSoporte(); end; (********* EVENTOS *********) procedure TSelRecSoporteForm.FormCreate(Sender: TObject); begin FOnChangeFechaSoporte := nil; FOnChangeSelected := nil; end; procedure TSelRecSoporteForm.FechaSoporteEditChange(Sender: TObject); begin changeFechaSoporte(); end; procedure TSelRecSoporteForm.TerminarBtnClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TSelRecSoporteForm.soportesListViewSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin // modifyButton.Enabled := Selected; (por el momento no se puede modificar) delSoporteButton.Enabled := Selected; genSopButton.Enabled := Selected; prnSopButton.Enabled := Selected; changeSelectedSoporte(); end; end.
unit uModAuthUser; interface uses uModApp, System.Generics.Collections; type TModAuthGroup = class; TModUserMenuItem = class; TModAuthUser = class(TModApp) private FUserMenuItems: TObjectList<TModUserMenuItem>; FUSR_GROUP: TModAuthGroup; FUSR_FULLNAME: String; FUSR_USERNAME: String; FUSR_PASSWD: String; FUSR_STATUS: Integer; FUSR_DESCRIPTION: String; function GetUserMenuItems: TObjectList<TModUserMenuItem>; public class function GetPrimaryField: String; override; class function GetTableName: String; override; property UserMenuItems: TObjectList<TModUserMenuItem> read GetUserMenuItems write FUserMenuItems; published property USR_GROUP: TModAuthGroup read FUSR_GROUP write FUSR_GROUP; property USR_FULLNAME: String read FUSR_FULLNAME write FUSR_FULLNAME; // [AttributeOfCode] property USR_USERNAME: String read FUSR_USERNAME write FUSR_USERNAME; property USR_PASSWD: String read FUSR_PASSWD write FUSR_PASSWD; property USR_STATUS: Integer read FUSR_STATUS write FUSR_STATUS; property USR_DESCRIPTION: String read FUSR_DESCRIPTION write FUSR_DESCRIPTION; end; TModAuthGroup = class(TModApp) private FGRO_NAME: String; FGRO_DESCRIPTION: String; public class function GetTableName: String; override; published [AttributeOfCode] property GRO_NAME: String read FGRO_NAME write FGRO_NAME; property GRO_DESCRIPTION: String read FGRO_DESCRIPTION write FGRO_DESCRIPTION; end; TModMenu = class(TModApp) private FAplikasi: string; FMenuCaption: string; FMenuName: string; published [AttributeOfSize('120')] property Aplikasi: string read FAplikasi write FAplikasi; [AttributeOfSize('120')] property MenuCaption: string read FMenuCaption write FMenuCaption; [AttributeOfCode, AttributeOfSize('120')] property MenuName: string read FMenuName write FMenuName; end; TModUserMenuItem = class(TModApp) private FMenu: TModMenu; FAuthUser: TModAuthUser; public published property Menu: TModMenu read FMenu write FMenu; [AttributeOfHeader] property AuthUser: TModAuthUser read FAuthUser write FAuthUser; end; implementation class function TModAuthUser.GetPrimaryField: String; begin Result := 'AUT$USER_ID'; end; class function TModAuthUser.GetTableName: String; begin Result := 'AUT$USER'; end; function TModAuthUser.GetUserMenuItems: TObjectList<TModUserMenuItem>; begin if FUserMenuItems = nil then FUserMenuItems := TObjectList<TModUserMenuItem>.Create; Result := FUserMenuItems; end; class function TModAuthGroup.GetTableName: String; begin Result := 'AUT$GROUP'; end; initialization TModAuthUser.RegisterRTTI; TModAuthGroup.RegisterRTTI; // TModAuthUserGroup.RegisterRTTI; end.
unit feli_access_level; {$mode objfpc} interface type FeliAccessLevel = class(TObject) public const anonymous = 'anonymous'; participator = 'participator'; organiser = 'organiser'; admin = 'admin'; end; implementation end.
unit base64; interface // encode 8-bit string function Base64Encode(const S: AnsiString): AnsiString; function Base64Decode(const S: AnsiString): AnsiString; // encode 16-bit string function Base64EncodeW(const S: WideString): AnsiString; function Base64DecodeW(const S: AnsiString): WideString; //low level worker functions. //WARNING: incorect usage will effect in Acces Violation! {------------------------------------------------------------------------------------------------------------------------ contract: Src: Pointer - Pointer to begn of buffer of Encoder: binary data to encode Decoder: Base64 encoded string of 8-bit characters to decode SrcLength: integer - length of source data buffer, in bytes. Dst: Pointer - pointer to putput buffer. if nil, then no conversion is made, and function will return length of buffer to allocate, to pass it as Dst. Result - return length of output, in bytes NOTE: if nil is passed as Dst to DecodeBuffer, then retured number of bytes is maximum required buffer size. it is possible number of really returned bytes will be lower, an this exact number will be returned in second call, with Dst set to output buffer. ------------------------------------------------------------------------------------------------------------------------} function EncodeBuffer(Src: Pointer; SrcLength: integer; Dst: Pointer): integer; forward; function DecodeBuffer(Src: Pointer; SrcLength: integer; Dst: Pointer): integer; forward; implementation {$IFOPT C+} //if compiled with assertions enabled uses Windows, sysutils; {$ENDIF} type PInteger = ^Integer; PByte = ^Byte; { Base64 encode and decode a string } const Base64AlphabetLookup: array [0..63] of AnsiChar = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; Base64PadingCharacter: AnsiChar = '='; Base64AlphabetRevLookup: array [0..$ff] of Byte = ( $0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0, $0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$3E,$0,$0,$0,$3F,$34,$35,$36,$37,$38,$39,$3A,$3B,$3C,$3D,$0,$0,$0,$0,$0,$0, $0,$0,$1,$2,$3,$4,$5,$6,$7,$8,$9,$A,$B,$C,$D,$E,$F,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$0,$0,$0,$0,$0, $0,$1A,$1B,$1C,$1D,$1E,$1F,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2A,$2B,$2C,$2D,$2E,$2F,$30,$31,$32,$33,$0,$0,$0,$0,$0, $0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0, $0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0, $0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0, $0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0 ); function EncodeBuffer(Src: Pointer; SrcLength: integer; Dst: Pointer): integer; var i, tripletsCount: integer; InputPoint: PAnsiChar; OutputPoint: PInteger; begin if SrcLength = 0 then begin Result := 0; Exit; end; tripletsCount := SrcLength div 3; Result := tripletsCount * 4; if SrcLength mod 3 <> 0 then //partial triplet at end, output will be padded inc(Result, 4); if Dst = nil then Exit; InputPoint := Src; OutputPoint := PInteger(Dst); //process full triplets for i:= 1 to tripletsCount do begin OutputPoint^ := (Byte(Base64AlphabetLookup[(PByte(InputPoint)^ and $FC) shr 2])) + (Byte(Base64AlphabetLookup[((PByte(InputPoint)^ and $03) shl 4) + ((PByte(InputPoint + 1)^ and $F0) shr 4)]) shl 8) + (Byte(Base64AlphabetLookup[((PByte(InputPoint + 1)^ and $0F) shl 2) + ((PByte(InputPoint + 2)^ and $C0) shr 6)]) shl 16) + (Byte(Base64AlphabetLookup[PByte(InputPoint + 2)^ and $3F]) shl 24); Inc(OutputPoint); Inc(InputPoint, 3); end; //deal with last, partial triplet if SrcLength mod 3 = 1 then //one character reminder OutputPoint^ := (Byte(Base64AlphabetLookup[(PByte(InputPoint)^ and $FC) shr 2])) + (Byte(Base64AlphabetLookup[(PByte(InputPoint)^ and $03) shl 4]) shl 8) + (Byte(Base64PadingCharacter) shl 16) or (Byte(Base64PadingCharacter) shl 24); if SrcLength mod 3 = 2 then //two characters reminder OutputPoint^ := (Byte(Base64AlphabetLookup[(PByte(InputPoint)^ and $FC) shr 2])) + (Byte(Base64AlphabetLookup[((PByte(InputPoint)^ and $03) shl 4) + ((PByte(InputPoint + 1)^ and $F0) shr 4)]) shl 8) + (Byte(Base64AlphabetLookup[(PByte(InputPoint + 1)^ and $0F) shl 2]) shl 16) + (Byte(Base64PadingCharacter) shl 24); end; function DecodeBuffer(Src: Pointer; SrcLength: integer; Dst: Pointer): integer; var partialTripletParts: integer; InputPoint, InputEnd: PAnsiChar; OutputPoint: PAnsiChar; Input6bits1, Input6bits2, Input6bits3, Input6bits4: Byte; function GetNextInputTriplet(): Boolean; begin while (InputPoint < InputEnd) and (InputPoint^ in [' ', #13, #10]) do Inc(InputPoint); //skip white spaces if (InputPoint >= InputEnd) or (InputPoint^ = Base64PadingCharacter) then begin partialTripletParts := 0; Result := False; Exit; end; Input6bits1 := Base64AlphabetRevLookup[PByte(InputPoint)^]; Inc(InputPoint); while (InputPoint < InputEnd) and (InputPoint^ in [' ', #13, #10]) do Inc(InputPoint); //skip white spaces if (InputPoint >= InputEnd) or (InputPoint^ = Base64PadingCharacter) then begin partialTripletParts := 1; Result := False; Exit; end; Input6bits2 := Base64AlphabetRevLookup[PByte(InputPoint)^]; Inc(InputPoint); while (InputPoint < InputEnd) and (InputPoint^ in [' ', #13, #10]) do Inc(InputPoint); //skip white spaces if (InputPoint >= InputEnd) or (InputPoint^ = Base64PadingCharacter) then begin partialTripletParts := 2; Result := False; Exit; end; Input6bits3 := Base64AlphabetRevLookup[PByte(InputPoint)^]; Inc(InputPoint); while (InputPoint < InputEnd) and (InputPoint^ in [' ', #13, #10]) do Inc(InputPoint); //skip white spaces if (InputPoint >= InputEnd) or (InputPoint^ = Base64PadingCharacter) then begin partialTripletParts := 3; Result := False; Exit; end; Input6bits4 := Base64AlphabetRevLookup[PByte(InputPoint)^]; Inc(InputPoint); Result := True; end; begin if SrcLength = 0 then begin Result := 0; Exit; end; Result := ((SrcLength + 3) div 4) * 3; if Dst = nil then Exit; InputPoint := PAnsiChar(Src); InputEnd := InputPoint + SrcLength; OutputPoint := PAnsiChar(Dst); while GetNextInputTriplet() do begin PInteger(OutputPoint)^ := (Input6bits1 shl 2) + ((Input6bits2 and $30) shr 4) + ((Input6bits2 and $0F) shl 12) + ((Input6bits3 and $3C) shl 6) + ((Input6bits3 and $03) shl 22) + (Input6bits4 shl 16); Inc(OutputPoint, 3); end; Result := OutputPoint - PAnsiChar(Dst); if partialTripletParts = 0 then Exit; //no partially filled triplets, return now. //last. not full triplet // first output byte if partialTripletParts > 1 then begin PByte(OutputPoint)^ := (Input6bits1 shl 2) + ((Input6bits2 and $30) shr 4); Inc(OutputPoint); Inc(Result); end else begin PByte(OutputPoint)^ := 0; Inc(OutputPoint); end; //second outputbyte if partialTripletParts > 2 then begin PByte(OutputPoint)^ := ((Input6bits2 and $0F) shl 4) + ((Input6bits3 and $3C) shr 2); Inc(OutputPoint); Inc(Result); end else begin PByte(OutputPoint)^ := 0; Inc(OutputPoint); end; //third outputbyte if partialTripletParts > 3 then begin PByte(OutputPoint)^ := ((Input6bits3 and $03) shl 6) + Input6bits4; Inc(Result); end else PByte(OutputPoint)^ := 0; end; function Base64Encode(const S: AnsiString): AnsiString; var len: integer; begin len := EncodeBuffer(PAnsiChar(s), Length(s), nil); if len <= 0 then Result := '' else begin SetLength(Result, len); EncodeBuffer(PAnsiChar(s), Length(s), PAnsiChar(Result)); end; end; function Base64Decode(const S: AnsiString): AnsiString; var len: integer; begin len := DecodeBuffer(PAnsiChar(s), Length(s), nil); if len <= 0 then Result := '' else begin SetLength(Result, len); len := DecodeBuffer(PAnsiChar(s), Length(s), PAnsiChar(Result)); if len <> Length(Result) then SetLength(Result, len); end; end; function Base64EncodeW(const S: WideString): AnsiString; var len: integer; begin len := EncodeBuffer(Pointer(PWideChar(s)), Length(s) * 2, nil); if len <= 0 then Result := '' else begin SetLength(Result, len); EncodeBuffer(Pointer(PWideChar(s)), Length(s) * 2, PChar(Result)); end; end; function Base64DecodeW(const S: AnsiString): WideString; var len: integer; begin len := DecodeBuffer(PChar(s), Length(s), nil); if len <= 0 then Result := '' else begin SetLength(Result, len div 2); len := DecodeBuffer(PChar(s), Length(s), PChar(Result)); if (len div 2) <> Length(Result) then SetLength(Result, len div 2); end; end; {$IFOPT C+} //if compiled with assertions enabled procedure TestsUnit(); begin try //tests Assert(Base64Encode('') = ''); Assert(Base64Encode('f') = 'Zg=='); Assert(Base64Encode('fo') = 'Zm8='); Assert(Base64Encode('foo') = 'Zm9v'); Assert(Base64Encode('foob') = 'Zm9vYg=='); Assert(Base64Encode('fooba') = 'Zm9vYmE='); Assert(Base64Encode('foobar') = 'Zm9vYmFy'); Assert(Base64Decode('') = ''); Assert(Base64Decode('Zg==') = 'f'); Assert(Base64Decode('Zm8=') = 'fo'); Assert(Base64Decode('Zm9v') = 'foo'); Assert(Base64Decode('Zm9vYg==') = 'foob'); Assert(Base64Decode('Zm9vYmE=') = 'fooba'); Assert(Base64Decode('Zm9vYmFy') = 'foobar'); Assert(Base64Decode('Zm'#13#10'9v YmF y') = 'foobar'); Assert(Base64Decode('Zm'#13#10'9v YmE') = 'fooba'); Assert(Base64EncodeW('') = ''); Assert(Base64EncodeW('f') = 'ZgA='); Assert(Base64EncodeW('fo') = 'ZgBvAA=='); Assert(Base64EncodeW('foo') = 'ZgBvAG8A'); Assert(Base64EncodeW('foob') = 'ZgBvAG8AYgA='); Assert(Base64EncodeW('fooba') = 'ZgBvAG8AYgBhAA=='); Assert(Base64EncodeW('foobar') = 'ZgBvAG8AYgBhAHIA'); Assert(Base64DecodeW('') = ''); Assert(Base64DecodeW('ZgA=') = 'f'); Assert(Base64DecodeW('ZgBvAA==') = 'fo'); Assert(Base64DecodeW('ZgBvAG8A') = 'foo'); Assert(Base64DecodeW('ZgBvAG8AYgA=') = 'foob'); Assert(Base64DecodeW('ZgBvAG8AYgBhAA=') = 'fooba'); Assert(Base64DecodeW('ZgBvAG8AYgBhAHIA') = 'foobar'); Assert(Base64DecodeW('ZgB'#13#10'vAG'#13#10'8AYg Bh AHI A') = 'foobar'); Assert(Base64DecodeW('Z'#13#10'gB vAG'#13#10'8AY gBhAA==') = 'fooba'); except on e: Exception do begin MessageBox(0, PChar(e.message), 'base64.pas :: Test fails!', MB_ICONERROR); Halt(1); end; end ; end; initialization TestsUnit(); {$ENDIF} end.
unit InflatablesList_HTML_Preprocessor; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses Classes, AuxTypes, AuxClasses; type TILHTMLInvalidCharBehaviour = (ilicbRemove,ilicbReplace,ilicbLeave); TILHTMLPreprocessor = class(TObject) private fInput: UnicodeString; fOutput: UnicodeString; fInputPos: Integer; fOutputPos: Integer; fLastProgress: Double; fIvalidChars: TILHTMLInvalidCharBehaviour; fOnProgress: TFloatEvent; fRaiseParseErrs: Boolean; protected Function ParseError(const Msg: String): Boolean; overload; virtual; Function ParseError(const Msg: String; Args: array of const): Boolean; overload; virtual; Function ParseErrorInvalidChar(Char: UnicodeChar): Boolean; virtual; procedure DoProgress; virtual; Function CharCurrent: UnicodeChar; virtual; Function CharPrev: UnicodeChar; virtual; Function CharNext: UnicodeChar; virtual; procedure EmitChar(Char: UnicodeChar); virtual; procedure ProcessInvalidChar; virtual; procedure ProcessChar; virtual; public constructor Create; Function Process(Stream: TStream; IsUFT8: Boolean): UnicodeString; virtual; property InvalidCharacterBahaviour: TILHTMLInvalidCharBehaviour read fIvalidChars write fIvalidChars; property OnProgress: TFloatEvent read fOnProgress write fOnProgress; property RaiseParseErrors: Boolean read fRaiseParseErrs write fRaiseParseErrs; end; implementation uses StrRect, InflatablesList_Utils, InflatablesList_HTML_Utils; Function TILHTMLPreprocessor.ParseError(const Msg: String): Boolean; begin Result := fRaiseParseErrs; If fRaiseParseErrs then raise EILHTMLParseError.Create(Msg); end; //------------------------------------------------------------------------------ Function TILHTMLPreprocessor.ParseError(const Msg: String; Args: array of const): Boolean; begin Result := ParseError(IL_Format(Msg,Args)); end; //------------------------------------------------------------------------------ Function TILHTMLPreprocessor.ParseErrorInvalidChar(Char: UnicodeChar): Boolean; begin Result := ParseError('Invalid character (#%.4x).',[Ord(Char)]); end; //------------------------------------------------------------------------------ procedure TILHTMLPreprocessor.DoProgress; var CurrentProgress: Double; begin If Length(fInput) <> 0 then CurrentProgress := fInputPos / Length(fInput) else CurrentProgress := 0.0; If CurrentProgress >= (fLastProgress + 0.0001) then begin fLastProgress := CurrentProgress; If Assigned(fOnProgress) then fOnProgress(Self,CurrentProgress); end; end; //------------------------------------------------------------------------------ Function TILHTMLPreprocessor.CharCurrent: UnicodeChar; begin If (fInputPos >= 1) and (fInputPos <= Length(fInput)) then Result := fInput[fInputPos] else Result := UnicodeChar(#0); end; //------------------------------------------------------------------------------ Function TILHTMLPreprocessor.CharPrev: UnicodeChar; begin If (Pred(fInputPos) >= 1) and (Pred(fInputPos) <= Length(fInput)) then Result := fInput[Pred(fInputPos)] else Result := UnicodeChar(#0); end; //------------------------------------------------------------------------------ Function TILHTMLPreprocessor.CharNext: UnicodeChar; begin If (Succ(fInputPos) >= 1) and (Succ(fInputPos) <= Length(fInput)) then Result := fInput[Succ(fInputPos)] else Result := UnicodeChar(#0); end; //------------------------------------------------------------------------------ procedure TILHTMLPreprocessor.EmitChar(Char: UnicodeChar); begin Inc(fOutputPos); // allocate new space if required If Length(fOutput) < fOutputPos then begin If Length(fOutput) < 1024 then SetLength(fOutput,1024) else SetLength(fOutput,Length(fOutput) * 2); end; fOutput[fOutputPos] := Char; end; //------------------------------------------------------------------------------ procedure TILHTMLPreprocessor.ProcessInvalidChar; begin case fIvalidChars of ilicbRemove: ; // do nothing, char is skipped ilicbReplace: EmitChar(#$FFFD); else {ilicbLeave} EmitChar(CharCurrent); end; end; //------------------------------------------------------------------------------ procedure TILHTMLPreprocessor.ProcessChar; var TempChar: UnicodeChar; Function IsValidCodepoint(High,Low: UnicodeChar): Boolean; var CodePoint: UInt32; begin // check if the codepoint can be in HTML CodePoint := IL_UTF16CodePoint(High,Low); Result := not( ((CodePoint >= $0001) and (CodePoint <= $0008)) or ((CodePoint >= $000E) and (CodePoint <= $001F)) or ((CodePoint >= $007F) and (CodePoint <= $009F)) or ((CodePoint >= $FDD0) and (CodePoint <= $FDEF)) or ((CodePoint or not UInt32($000F0000)) = $FFFE) or ((CodePoint or not UInt32($000F0000)) = $FFFF) or (CodePoint = $000B) or (CodePoint = $10FFFE) or (CodePoint = $10FFFF )); end; begin TempChar := CharCurrent; // detect isolated surrogates If (TempChar >= #$D800) and (TempChar <= #$DBFF) then begin // high surrogate, must be followed by a low surrogate If (CharNext >= #$DC00) and (CharNext <= #$DFFF) then begin // followed by a low surrogate If not IsValidCodepoint(TempChar,CharNext) then begin // the codepoint is invalid If not ParseErrorInvalidChar(TempChar) then begin ProcessInvalidChar; Inc(fInputPos); // skip the next char end; end else EmitChar(TempChar); end else begin // NOT followed by a low surrogate, the next char will be processed in next round If not ParseErrorInvalidChar(TempChar) then ProcessInvalidChar; end; end else If ((CharNext >= #$DC00) and (CharNext <= #$DFFF)) then begin // low surrogate, must be preceded by a high surrogate If not ((CharPrev >= #$D800) and (CharPrev <= #$DBFF)) then begin If not ParseErrorInvalidChar(TempChar) then ProcessInvalidChar; end else EmitChar(TempChar); end else If TempChar = #$000D{CR} then begin // preprocess line breaks EmitChar(#$000A{LF}); If CharNext = #$000A{LF} then Inc(fInputPos); // skip next char when it is LF end else EmitChar(TempChar); Inc(fInputPos); end; //============================================================================== constructor TILHTMLPreprocessor.Create; begin inherited Create; fIvalidChars := ilicbRemove; fRaiseParseErrs := False; end; //------------------------------------------------------------------------------ Function TILHTMLPreprocessor.Process(Stream: TStream; IsUFT8: Boolean): UnicodeString; var UTF8Temp: UTF8String; AnsiTemp: AnsiString; begin fInput := ''; fOutput := ''; fInputPos := 1; fOutputPos := 0; fLastProgress := 0.0; // processing If Stream.Size > 0 then begin // decode stream to unicode string If IsUFT8 then begin SetLength(UTF8Temp,(Stream.Size - Stream.Position) div SizeOf(UTF8Char)); Stream.Read(PUTF8Char(UTF8Temp)^,Length(UTF8Temp) * SizeOf(UTF8Char)); fInput := UTF8ToString(UTF8Temp); end else begin SetLength(AnsiTemp,(Stream.Size - Stream.Position) div SizeOf(AnsiChar)); Stream.Read(PAnsiChar(AnsiTemp)^,Length(AnsiTemp) * SizeOf(AnsiChar)); fInput := UnicodeString(AnsiTemp); end; DoProgress; // preallocate SetLength(fOutput,Length(fInput)); while fInputPos <= Length(fInput) do begin ProcessChar; DoProgress; end; SetLength(fOutput,fOutputPos); end; Result := fOutput; end; end.
unit UPredefinedSizes; interface uses Generics.Collections, System.Types, SysUtils; const AndroidImageCount = 9; iPhoneImageCount = 48; iPadImageCount = 54; type TPredefinedSizes = class private Sizes: TDictionary<String, TSize>; procedure Fill; public constructor Create; destructor Destroy; override; function GetSize(const tag: string): TSize; end; implementation { TPredefinedSizes } constructor TPredefinedSizes.Create; begin Sizes := TDictionary<String, TSize>.Create; Fill; end; destructor TPredefinedSizes.Destroy; begin Sizes.Free; inherited; end; procedure TPredefinedSizes.Fill; begin Sizes.Add('Android_LauncherIcon36', TSize.Create(36, 36)); Sizes.Add('Android_LauncherIcon48', TSize.Create(48, 48)); Sizes.Add('Android_LauncherIcon72', TSize.Create(72, 72)); Sizes.Add('Android_LauncherIcon96', TSize.Create(96, 96)); Sizes.Add('Android_LauncherIcon144', TSize.Create(144, 144)); Sizes.Add('Android_SplashImage426', TSize.Create(426, 320)); Sizes.Add('Android_SplashImage470', TSize.Create(470, 320)); Sizes.Add('Android_SplashImage640', TSize.Create(640, 480)); Sizes.Add('Android_SplashImage960', TSize.Create(960, 720)); Sizes.Add('iPhone_AppIcon57', TSize.Create(57, 57)); Sizes.Add('iPhone_AppIcon60', TSize.Create(60, 60)); Sizes.Add('iPhone_AppIcon87', TSize.Create(87, 87)); Sizes.Add('iPhone_AppIcon114', TSize.Create(114, 114)); Sizes.Add('iPhone_AppIcon120', TSize.Create(120, 120)); Sizes.Add('iPhone_AppIcon180', TSize.Create(180, 180)); Sizes.Add('iPhone_Launch320', TSize.Create(320, 480)); Sizes.Add('iPhone_Launch640', TSize.Create(640, 960)); Sizes.Add('iPhone_Launch640x1136', TSize.Create(640, 1136)); Sizes.Add('iPhone_Launch750', TSize.Create(750, 1334)); Sizes.Add('iPhone_Launch1242', TSize.Create(1242, 2208)); Sizes.Add('iPhone_Launch2208', TSize.Create(2208, 1242)); Sizes.Add('iPhone_Spotlight29', TSize.Create(29, 29)); Sizes.Add('iPhone_Spotlight40', TSize.Create(40, 40)); Sizes.Add('iPhone_Spotlight58', TSize.Create(58, 58)); Sizes.Add('iPhone_Spotlight80', TSize.Create(80, 80)); Sizes.Add('iPad_AppIcon72', TSize.Create(72, 72)); Sizes.Add('iPad_AppIcon76', TSize.Create(76, 76)); Sizes.Add('iPad_AppIcon144', TSize.Create(144, 144)); Sizes.Add('iPad_AppIcon152', TSize.Create(152, 152)); Sizes.Add('iPad_Launch768', TSize.Create(768, 1004)); Sizes.Add('iPad_Launch768x1024', TSize.Create(768, 1024)); Sizes.Add('iPad_Launch1024', TSize.Create(1024, 748)); Sizes.Add('iPad_Launch1024x768', TSize.Create(1024, 768)); Sizes.Add('iPad_Launch1536', TSize.Create(1536, 2008)); Sizes.Add('iPad_Launch1536x2048', TSize.Create(1536, 2048)); Sizes.Add('iPad_Launch2048', TSize.Create(2048, 1496)); Sizes.Add('iPad_Launch2048x1536', TSize.Create(2048, 1536)); Sizes.Add('iPad_SpotLight40', TSize.Create(40, 40)); Sizes.Add('iPad_SpotLight50', TSize.Create(50, 50)); Sizes.Add('iPad_SpotLight80', TSize.Create(80, 80)); Sizes.Add('iPad_SpotLight100', TSize.Create(100, 100)); Sizes.Add('iPad_Setting29', TSize.Create(29, 29)); Sizes.Add('iPad_Setting58', TSize.Create(58, 58)); end; function TPredefinedSizes.GetSize(const tag: string): TSize; begin if not Sizes.TryGetValue(tag, Result) then raise Exception.Create('Size unknown: ' + tag); end; end.
{ @abstract(Provides UltraEdit highlighting schemes import and export) @authors(Vitalik [just_vitalik@yahoo.com]) @created(2005) @lastmod(2006-06-30) } {$IFNDEF QSynUniFormatUltraEdit} unit SynUniFormatUltraEdit; {$ENDIF} interface uses {$IFDEF SYN_CLX} QClasses, QGraphics, QSynUniFormat, QSynUniClasses, QSynUniRules, SynUniHighlighter, {$ELSE} Classes, Graphics, SynUniFormat, SynUniClasses, SynUniRules, SynUniHighlighter, {$ENDIF} SysUtils; type TSynUniFormatUltraEdit = class(TSynUniFormat) public class function Import(SynUniSyn: TSynUniSyn; FileList: TStringList): boolean; class function ImportFromStream(AObject: TObject; Stream: TStream): boolean; override; class function ImportFromFile(AObject: TObject; FileName: string): boolean; override; end; implementation (* function Test(FileName: string): boolean; var i, cur: integer; buf: string; isLoading: boolean; begin Form1.Memo1.Clear; if not Assigned(UltraEditFile) then if FileName <> '' then begin UltraEditFile := TStringList.Create; UltraEditFile.LoadFromFile(FileName); UltraEditFileName := FileName; UltraEditFilePos := 0; Form1.Memo1.Lines.Add('File was loaded...'); end else begin Form1.Memo1.Lines.Add('File was not assigned and not loaded...'); Result := False; Exit; end else begin if (FileName = UltraEditFileName) and (UltraEditFilePos >= UltraEditFile.Count-1) or (FileName = '') then begin if Assigned(UltraEditFile) then begin UltraEditFile.Free; UltraEditFile := nil; end; UltraEditFileName := ''; UltraEditFilePos := 0; Form1.Memo1.Lines.Add('Variables are deleted...'); Form1.Memo1.Lines.Add('Exit: 1.'); Result := False; Exit; end; if FileName <> UltraEditFileName then begin UltraEditFile.LoadFromFile(FileName); UltraEditFileName := FileName; UltraEditFilePos := 0; Form1.Memo1.Lines.Add('New File was loaded!'); end; end; isLoading := False; for i := UltraEditFilePos to UltraEditFile.Count-1 do begin buf := UltraEditFile.Strings[i]; UltraEditFilePos := i; if buf = '' then continue; if copy(buf, 1, 2) = '/L' then begin if not isLoading then isLoading := True else begin // isLoading = True? Result := True; Exit; {TrySaveFile(); ResetSynUniSyn;} end; if (buf[4] = '"') or (buf[5] = '"') then begin cur := pos('"', copy(buf, pos('"',buf)+1, length(buf)-pos('"',buf))) + pos('"', buf); Form1.Memo1.Lines.Add(' Name: ' + copy(buf, pos('"',buf)+1, cur-pos('"',buf)-1)); end; end else begin if not isLoading then isLoading := True; if copy(buf, 1, 13) = '/Delimiters =' then Form1.Memo1.Lines.Add(' Delimiters: ' + copy(buf, pos('=',buf)+1, length(buf)-pos('=',buf)+1)) else if copy(buf, 1, 2) = '/C' then begin if buf[4] = '"' then begin cur := pos('"', copy(buf, 5, length(buf)-4)) + 4; Form1.Memo1.Lines.Add(' C' + buf[3] + ' "' + copy(buf, 5, cur-5) + '"'); end else Form1.Memo1.Lines.Add(' C' + buf[3] + ' "<' + 'noname' + '>"'); end else end; end; Form1.Memo1.Lines.Add(''); Form1.Memo1.Lines.Add('File has finished...'); Result := True; end; *) //------------------------------------------------------------------------------ {* * * * * * * * * * * * TSynUniFormatUltraEdit * * * * * * * * * * * * * * * *} //------------------------------------------------------------------------------ class function TSynUniFormatUltraEdit.Import(SynUniSyn: TSynUniSyn; FileList: TStringList): boolean; var i, j, qn1, qn2, bn1, bn2, cur, Nc: integer; qc1, qc2: char; word, buf: string; Cnames: array [1..8] of string; Created: array [1..8] of integer; isLoading: boolean; keyword: TSynKeyList; const colors: array [1..8] of TColor = (clBlue, clRed, $0080FF, clGreen, clMaroon, clBlue, clBlue, clBlue); badsymb: array [0..8] of char = ('\', '/', ':', '*', '?', '"', '<', '>', '|'); LINE_COMMENT = 1; BLOCK_COMMENT = 2; STRING_CHARS = 3; LINE_COMM_NUM = 4; SINGLE_WORD = 5; WHOLE_STRING = 6; ESCAPE_CHAR = 7; function GetAttribute(Key: string; Style: integer): boolean; var pos_start, space1_pos, space2_pos, len: integer; begin Result := False; if pos(key, buf) = 0 then Exit; pos_start := pos(key, buf) + length(key); if (Style = LINE_COMMENT) or (Style = BLOCK_COMMENT) or (Style = STRING_CHARS) then begin if Style = LINE_COMMENT then len := 5 else if Style = BLOCK_COMMENT then len := 19 else if Style = STRING_CHARS then len := 2 else len := 5; word := copy(buf, pos_start, len); space1_pos := pos(' ', word); if space1_pos > 0 then if space1_pos = 1 then begin space2_pos := pos(' ', copy(word, 2, len-1)); if space2_pos > 0 then word := copy(word, 1, space2_pos); end else word := copy(word, 1, space1_pos-1) end else if Style = LINE_COMM_NUM then begin len := StrToInt(buf[pos_start]); word := copy(buf, pos_start+1, len); space1_pos := pos(' ', word); if space1_pos > 0 then end else if Style = WHOLE_STRING then word := copy(buf, pos_start, length(buf) - pos_start + 1) else if Style = ESCAPE_CHAR then word := buf[pos_start] else if Style = SINGLE_WORD then ; if word <> '' then Result := True; end; function GetToken2: string; begin cur := pos(' ', buf); if cur > 0 then begin Result := copy(buf, 1, cur-1); buf := copy(buf, cur+1, length(buf)-cur); end else begin Result := buf; buf := ''; end; end; procedure RefreshScheme(ARange: TSynRange); var i: integer; begin with ARange, SynUniSyn do begin for i := 0 to RangeCount - 1 do begin with Ranges[i] do ActiveScheme.AddStyle(Name, Attributes.Foreground, Attributes.Background, Attributes.Style); RefreshScheme(Ranges[i]); end; for i := 0 to KeyListCount - 1 do with KeyLists[i] do ActiveScheme.AddStyle(Name, Attributes.Foreground, Attributes.Background, Attributes.Style); for i := 0 to ARange.SetCount - 1 do with Sets[i] do ActiveScheme.AddStyle(Name, Attributes.Foreground, Attributes.Background, Attributes.Style); end; end; var FilePos: integer; FileName: string; begin //Result := False; with SynUniSyn do begin FilePos := 0; if not Assigned(FileList) then if FileName <> '' then begin //'File was loaded.' FileList := TStringList.Create; FileList.LoadFromFile(FileName); FileName := FileName; FilePos := 0; end else begin //'File was not assigned and not loaded. Exiting...' Result := False; Exit; end else begin { if (FileName = FileName) and (FilePos >= FileList.Count-1) or (FileName = '') then begin //'Variables are deleted. Exiting...' if Assigned(FileList) then begin FileList.Free; FileList := nil; end; FileName := ''; FilePos := 0; Result := False; Exit; end;} if FileName <> FileName then begin //'New File was loaded.' FileList.LoadFromFile(FileName); FileName := FileName; FilePos := 0; end; end; MainRules.Clear; isLoading := False; qc1 := #0; qc2 := #0; Nc := 0; qn1 := -1; qn2 := -1; for i := FilePos to FileList.Count-1 do begin buf := FileList.Strings[i]; FilePos := i; if buf = '' then continue; if copy(buf, 1, 2) = '/L' then begin if not isLoading then isLoading := True else begin // isLoading = True? Info.Author.Remark := 'Created with UltraEdit Converter. (c) Vitalik'; Result := True; Exit; end; Nc := 0; bn1 := -1; bn2 := -1; qn1 := -1; qn2 := -1; qc1 := #0; qc2 := #0; for j := 1 to 8 do begin Cnames[j] := ''; Created[j] := -1; end; if (buf[4] = '"') or (buf[5] = '"') then begin cur := pos('"', copy(buf, pos('"',buf)+1, length(buf)-pos('"',buf))) + pos('"', buf); Info.General.Name := copy(buf, pos('"',buf)+1, cur-pos('"',buf)-1); end; if Info.General.Name = '' then Info.General.Name := ExtractFileName(FileName); if GetAttribute('File Extensions = ', WHOLE_STRING) then begin Info.General.Extensions := word; end; MainRules.AddSet('Numbers', ['0','1','2','3','4','5','6','7','8','9'], clRed); if GetAttribute('Nocase', SINGLE_WORD) then MainRules.CaseSensitive := False else MainRules.CaseSensitive := True; if not GetAttribute('Noquote', SINGLE_WORD) then begin if not GetAttribute('String Chars = ', STRING_CHARS) then word := '"'''; qn1 := MainRules.RangeCount; qc1 := word[1]; with MainRules.AddRange(qc1, qc1, 'String', clGray) do CloseOnEol := True; if length(word) > 1 then begin qn2 := MainRules.RangeCount; qc2 := word[2]; with MainRules.AddRange(qc2, qc2, 'String', clGray) do CloseOnEol := True; end; if GetAttribute('Escape Char = ', ESCAPE_CHAR) then begin with MainRules.Ranges[qn1].AddKeyList('Escape', clGray) do KeyList.Text := word + word + #13#10 + word + qc1; if qn2 > -1 then with MainRules.Ranges[qn2].AddKeyList('Escape', clGray) do KeyList.Text := word + word + #13#10 + word + qc2; end; end; if GetAttribute('Line Comment = ', LINE_COMMENT) then begin with MainRules.AddRange(word, '', 'Line Comment', clTeal) do CloseOnEol := True; end; if GetAttribute('Line Comment Alt = ', LINE_COMMENT) then begin with MainRules.AddRange(word, '', 'Line Comment Alt', clTeal) do CloseOnEol := True; end; if GetAttribute('Line Comment Num = ', LINE_COMM_NUM) then begin with MainRules.AddRange(word, '', 'Line Comment Num', clTeal) do CloseOnEol := True; end; if GetAttribute('Block Comment On = ', BLOCK_COMMENT) then begin bn1 := MainRules.RangeCount; with MainRules.AddRange(word, '', 'Block Comment', clTeal) do CloseOnEol := True; end; if GetAttribute('Block Comment Off = ', BLOCK_COMMENT) then begin if bn1 = -1 then MainRules.AddRange('', word, 'Block Comment', clTeal) else begin MainRules.Ranges[bn1].CloseToken.Symbols[0] := word; MainRules.Ranges[bn1].CloseOnEol := False; end; end; if GetAttribute('Block Comment On Alt = ', BLOCK_COMMENT) then begin bn2 := MainRules.RangeCount; with MainRules.AddRange(word, '', 'Block Comment Alt', clTeal) do CloseOnEol := True; end; if GetAttribute('Block Comment Off Alt = ', BLOCK_COMMENT) then begin if bn2 = -1 then MainRules.AddRange('', word, 'Block Comment Alt', clTeal) else begin MainRules.Ranges[bn2].CloseToken.Symbols[0] := word; MainRules.Ranges[bn2].CloseOnEol := False; end; end; end else begin if not isLoading then isLoading := True; if copy(buf, 1, 13) = '/Delimiters =' then MainRules.SetDelimiters(StrToSet(copy(buf, pos('=',buf)+1, length(buf)-pos('=',buf)+1))) else if copy(buf, 1, 2) = '/C' then begin Nc := StrToInt(buf[3]); if buf[4] = '"' then begin cur := pos('"', copy(buf, 5, length(buf)-4)) + 4; Cnames[Nc] := copy(buf, 5, cur-5); if Created[Nc] > -1 then // already created MainRules.KeyLists[Created[Nc]].Name := Cnames[Nc]; end else if Created[Nc] = -1 then // haven't created Cnames[Nc] := 'Word list ' + IntToStr(Nc); end else if (buf[1] = '/') and (buf[2] <> '/') then // "/XXXXXXX = ...." else begin if (buf[1] = qc1) and (qn1 <> -1) then begin MainRules.Ranges[qn1].Attributes.Foreground := colors[Nc]; MainRules.Ranges[qn1].Attributes.ParentForeground := False; end; if (buf[1] = qc2) and (qn2 <> -1) then begin MainRules.Ranges[qn2].Attributes.Foreground := colors[Nc]; MainRules.Ranges[qn2].Attributes.ParentForeground := False; end; word := GetToken2; if word = '**' then begin repeat word := GetToken2; with MainRules.AddRange(word, '', Cnames[Nc], colors[Nc]) do begin Delimiters := MainRules.Delimiters; CloseOnTerm := True; end; until buf = ''; end else begin if Created[Nc] = -1 then begin Created[Nc] := MainRules.KeyListCount; keyword := MainRules.AddKeyList(Cnames[Nc], colors[Nc]); end else keyword := MainRules.KeyLists[Created[Nc]]; if word = '//' then word := GetToken2; keyword.KeyList.Add(word); while buf <> '' do begin word := GetToken2; keyword.KeyList.Add(word); end; end; end; end; end; Info.Author.Copyright := 'Created with UltraEdit Converter. (c) Vitalik'; { Fill schemes } SynUniSyn.ActiveScheme := SynUniSyn.Schemes.AddScheme('Default'); RefreshScheme(MainRules); //Result := True; (* if n = 1 then begin // The One Name := ChangeFileExt(FileName, '.hgl'); { TrySaveFile();} end else begin // The Last Name := ChangeFileExt(Info.General.Name, '.hgl'); for j := 0 to 8 do while Pos(badsymb[j], Name) > 0 do Name[Pos(badsymb[j], Name)] := ' '; { TrySaveFile();} end;*) end; Result := True; end; //------------------------------------------------------------------------------ class function TSynUniFormatUltraEdit.ImportFromStream(AObject: TObject; Stream: TStream): boolean; var FileList: TStringList; begin FileList := TStringList.Create; FileList.LoadFromStream(Stream); Result := Import(TSynUniSyn(AObject), FileList); FreeAndNil(FileList); end; //------------------------------------------------------------------------------ class function TSynUniFormatUltraEdit.ImportFromFile(AObject: TObject; FileName: string): boolean; var FileList: TStringList; begin FileList := TStringList.Create; FileList.LoadFromFile(FileName); Result := Import(TSynUniSyn(AObject), FileList); FreeAndNil(FileList); end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdFTP, ComCtrls, ShellCtrls; type TForm1 = class(TForm) Button1: TButton; IdFTP1: TIdFTP; ShellTreeView1: TShellTreeView; private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure FTPDirToTreeView(AFTP: TidFTP; ATree: TTreeView; ADirectory: string; AItem: TTreeNode; AIncludeFiles: Boolean); var ItemTemp: TTreeNode; LS: TStringList; i: integer; begin ATree.Items.BeginUpdate; LS := TStringList.Create; try if ADirectory <> '' then AFTP.ChangeDir(ADirectory); AFTP.TransferType := ftASCII; AFTP.List(LS); if AnsiPos('total', LS[0]) > 0 then LS.Delete(0); LS.Sorted := True; if LS.Count <> 0 then begin for i := 0 to LS.Count - 1 do begin try if Pos('.', LS.Strings[i]) = 0 then begin AItem := ATree.Items.AddChild(AItem, Trim(Copy(LS.Strings[i], Pos(':', LS.Strings[i]) + 3, Length(LS.Strings[i])) + '/')); ItemTemp := AItem.Parent; FTPDirToTreeView(AFTP, ATree, ADirectory + Trim(Copy(LS.Strings[i], Pos(':', LS.Strings[i]) + 3, Length(LS.Strings[i]))) + '/', AItem, AIncludeFiles); AItem := ItemTemp; end else if (AIncludeFiles) and (Pos('.', LS.Strings[i]) <> 0) then ATree.Items.AddChild(AItem, LS.Strings[i]); except end; end; end; finally ATree.Items.EndUpdate; LS.Free; end; end; procedure FTPDirToTreeView(AFTP: TIdFTP; ATree: TTreeView; const ADirectory: string; AItem: TTreeNode; AIncludeFiles: Boolean); var TempItem: TTreeNode; I: Integer; DirList: TIdFTPListItems; DirItem: TIdFTPListItem; LS: TStringList; begin LS := TStringList.Create; try LS.Sorted := True; ATree.Items.BeginUpdate; try if (ADirectory <> '') then AFTP.ChangeDir(ADirectory); AFTP.TransferType := ftASCII; AFTP.List(nil); DirList := AFTP.DirectoryListing; for i := 0 to DirList.Count - 1 do begin try DirItem := DirList.Items[i]; if (DirItem.ItemType = ditDirectory) then begin TempItem := ATree.Items.AddChild(AItem, Trim(DirItem.FileName) + '/'); LS.AddObject(Trim(DirItem.FileName), TempItem); end else begin if (AIncludeFiles) then ATree.Items.AddChild(AItem, DirItem.FileName); end; except end; end; for i := 0 to LS.Count - 1 do begin FTPDirToTreeView(AFTP, ATree, ADirectory + LS.Strings[i] + '/', TTreeNode(LS.Objects[i]), AIncludeFiles); end; finally ATree.Items.EndUpdate; end; finally LS.Free; end; end; Usage: procedure TForm1.IdFTP1AfterClientLogin(Sender: TObject); begin tvFileList.Items.BeginUpdate; Screen.Cursor := crHourGlass; try tvFileList.Items.Clear; FTPDirToTreeView(idFTP1, tvFileList, '/', nil, True); finally Screen.Cursor := crDefault; tvFileList.Items.EndUpdate; end; end; procedure TForm1.Button1Click(Sender: TObject); begin idFTP1.Connect; 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 uCEFDisplayHandler; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses {$IFDEF DELPHI16_UP} System.Classes, {$ELSE} Classes, {$ENDIF} uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefDisplayHandlerOwn = class(TCefBaseRefCountedOwn, ICefDisplayHandler) protected procedure OnAddressChange(const browser: ICefBrowser; const frame: ICefFrame; const url: ustring); virtual; procedure OnTitleChange(const browser: ICefBrowser; const title: ustring); virtual; procedure OnFaviconUrlChange(const browser: ICefBrowser; iconUrls: TStrings); virtual; procedure OnFullScreenModeChange(const browser: ICefBrowser; fullscreen: Boolean); virtual; function OnTooltip(const browser: ICefBrowser; var text: ustring): Boolean; virtual; procedure OnStatusMessage(const browser: ICefBrowser; const value: ustring); virtual; function OnConsoleMessage(const browser: ICefBrowser; const message, source: ustring; line: Integer): Boolean; virtual; function OnAutoResize(const browser: ICefBrowser; const new_size: PCefSize): Boolean; virtual; public constructor Create; virtual; end; TCustomDisplayHandler = class(TCefDisplayHandlerOwn) protected FEvent: IChromiumEvents; procedure OnAddressChange(const browser: ICefBrowser; const frame: ICefFrame; const url: ustring); override; procedure OnTitleChange(const browser: ICefBrowser; const title: ustring); override; procedure OnFaviconUrlChange(const browser: ICefBrowser; iconUrls: TStrings); override; procedure OnFullScreenModeChange(const browser: ICefBrowser; fullscreen: Boolean); override; function OnTooltip(const browser: ICefBrowser; var text: ustring): Boolean; override; procedure OnStatusMessage(const browser: ICefBrowser; const value: ustring); override; function OnConsoleMessage(const browser: ICefBrowser; const message, source: ustring; line: Integer): Boolean; override; function OnAutoResize(const browser: ICefBrowser; const new_size: PCefSize): Boolean; override; public constructor Create(const events: IChromiumEvents); reintroduce; virtual; destructor Destroy; override; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFBrowser, uCEFFrame; procedure cef_display_handler_on_address_change(self: PCefDisplayHandler; browser: PCefBrowser; frame: PCefFrame; const url: PCefString); stdcall; begin with TCefDisplayHandlerOwn(CefGetObject(self)) do OnAddressChange( TCefBrowserRef.UnWrap(browser), TCefFrameRef.UnWrap(frame), cefstring(url)) end; procedure cef_display_handler_on_title_change(self: PCefDisplayHandler; browser: PCefBrowser; const title: PCefString); stdcall; begin with TCefDisplayHandlerOwn(CefGetObject(self)) do OnTitleChange(TCefBrowserRef.UnWrap(browser), CefString(title)); end; procedure cef_display_handler_on_favicon_urlchange(self: PCefDisplayHandler; browser: PCefBrowser; icon_urls: TCefStringList); stdcall; var list: TStringList; i: Integer; str: TCefString; begin list := TStringList.Create; try for i := 0 to cef_string_list_size(icon_urls) - 1 do begin FillChar(str, SizeOf(str), 0); cef_string_list_value(icon_urls, i, @str); list.Add(CefStringClearAndGet(str)); end; with TCefDisplayHandlerOwn(CefGetObject(self)) do OnFaviconUrlChange(TCefBrowserRef.UnWrap(browser), list); finally list.Free; end; end; procedure cef_display_handler_on_fullscreen_mode_change(self: PCefDisplayHandler; browser: PCefBrowser; fullscreen: Integer); stdcall; begin with TCefDisplayHandlerOwn(CefGetObject(self)) do OnFullScreenModeChange(TCefBrowserRef.UnWrap(browser), fullscreen <> 0); end; function cef_display_handler_on_tooltip(self: PCefDisplayHandler; browser: PCefBrowser; text: PCefString): Integer; stdcall; var t: ustring; begin t := CefStringClearAndGet(text^); with TCefDisplayHandlerOwn(CefGetObject(self)) do Result := Ord(OnTooltip( TCefBrowserRef.UnWrap(browser), t)); text^ := CefStringAlloc(t); end; procedure cef_display_handler_on_status_message(self: PCefDisplayHandler; browser: PCefBrowser; const value: PCefString); stdcall; begin with TCefDisplayHandlerOwn(CefGetObject(self)) do OnStatusMessage(TCefBrowserRef.UnWrap(browser), CefString(value)); end; function cef_display_handler_on_console_message(self: PCefDisplayHandler; browser: PCefBrowser; const message: PCefString; const source: PCefString; line: Integer): Integer; stdcall; begin with TCefDisplayHandlerOwn(CefGetObject(self)) do Result := Ord(OnConsoleMessage(TCefBrowserRef.UnWrap(browser), CefString(message), CefString(source), line)); end; function cef_display_handler_on_auto_resize(self: PCefDisplayHandler; browser: PCefBrowser; const new_size: PCefSize): Integer; stdcall; begin Result := Ord(TCefDisplayHandlerOwn(CefGetObject(self)).OnAutoResize(TCefBrowserRef.UnWrap(browser), new_size)); end; constructor TCefDisplayHandlerOwn.Create; begin inherited CreateData(SizeOf(TCefDisplayHandler)); with PCefDisplayHandler(FData)^ do begin on_address_change := cef_display_handler_on_address_change; on_title_change := cef_display_handler_on_title_change; on_favicon_urlchange := cef_display_handler_on_favicon_urlchange; on_fullscreen_mode_change := cef_display_handler_on_fullscreen_mode_change; on_tooltip := cef_display_handler_on_tooltip; on_status_message := cef_display_handler_on_status_message; on_console_message := cef_display_handler_on_console_message; on_auto_resize := cef_display_handler_on_auto_resize; end; end; procedure TCefDisplayHandlerOwn.OnAddressChange(const browser: ICefBrowser; const frame: ICefFrame; const url: ustring); begin end; function TCefDisplayHandlerOwn.OnConsoleMessage(const browser: ICefBrowser; const message, source: ustring; line: Integer): Boolean; begin Result := False; end; function TCefDisplayHandlerOwn.OnAutoResize(const browser: ICefBrowser; const new_size: PCefSize): Boolean; begin Result := False; end; procedure TCefDisplayHandlerOwn.OnFaviconUrlChange(const browser: ICefBrowser; iconUrls: TStrings); begin end; procedure TCefDisplayHandlerOwn.OnFullScreenModeChange(const browser: ICefBrowser; fullscreen: Boolean); begin end; procedure TCefDisplayHandlerOwn.OnStatusMessage(const browser: ICefBrowser; const value: ustring); begin end; procedure TCefDisplayHandlerOwn.OnTitleChange(const browser: ICefBrowser; const title: ustring); begin end; function TCefDisplayHandlerOwn.OnTooltip(const browser: ICefBrowser; var text: ustring): Boolean; begin Result := False; end; // TCustomDisplayHandler constructor TCustomDisplayHandler.Create(const events: IChromiumEvents); begin inherited Create; FEvent := events; end; destructor TCustomDisplayHandler.Destroy; begin FEvent := nil; inherited Destroy; end; procedure TCustomDisplayHandler.OnAddressChange(const browser : ICefBrowser; const frame : ICefFrame; const url : ustring); begin if (FEvent <> nil) then FEvent.doOnAddressChange(browser, frame, url); end; function TCustomDisplayHandler.OnConsoleMessage(const browser : ICefBrowser; const message : ustring; const source : ustring; line : Integer): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnConsoleMessage(browser, message, source, line) else Result := inherited OnConsoleMessage(browser, message, source, line); end; function TCustomDisplayHandler.OnAutoResize(const browser: ICefBrowser; const new_size: PCefSize): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnAutoResize(browser, new_size) else Result := inherited OnAutoResize(browser, new_size); end; procedure TCustomDisplayHandler.OnFaviconUrlChange(const browser: ICefBrowser; iconUrls: TStrings); begin if (FEvent <> nil) then FEvent.doOnFaviconUrlChange(browser, iconUrls); end; procedure TCustomDisplayHandler.OnFullScreenModeChange(const browser: ICefBrowser; fullscreen: Boolean); begin if (FEvent <> nil) then FEvent.doOnFullScreenModeChange(browser, fullscreen); end; procedure TCustomDisplayHandler.OnStatusMessage(const browser: ICefBrowser; const value: ustring); begin if (FEvent <> nil) then FEvent.doOnStatusMessage(browser, value); end; procedure TCustomDisplayHandler.OnTitleChange(const browser: ICefBrowser; const title: ustring); begin if (FEvent <> nil) then FEvent.doOnTitleChange(browser, title); end; function TCustomDisplayHandler.OnTooltip(const browser: ICefBrowser; var text: ustring): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnTooltip(browser, text) else Result := inherited OnTooltip(browser, text); end; end.
unit camera_u; {$mode objfpc}{$H+} interface uses Classes, SysUtils, gl, GLext, matrix; type // Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods Camera_Movement = ( FORWARD, BACKWARD, LEFT, RIGHT ); const DEFAULT_YAW = -90.0; DEFAULT_PITCH = 0.0; DEFAULT_SPEED = 2.5; DEFAULT_SENSITIVITY = 0.1; DEFAULT_ZOOM = 45.0; type // An abstract camera class that processes input and calculates the corresponding Euler Angles, Vectors and Matrices for use in OpenGL TCamera = class public // camera Attributes Position: Tvector3_single; Front: Tvector3_single; Up: Tvector3_single; Right: Tvector3_single; WorldUp: Tvector3_single; // euler Angles Yaw: Single; Pitch: Single; // camera options MovementSpeed: Single; MouseSensitivity: Single; Zoom: Single; // constructor with vectors constructor Create(const position_: Tvector3_single); constructor Create(const position_, up_: Tvector3_single; const yaw_: Single = DEFAULT_YAW; const pitch_: Single = DEFAULT_PITCH); // constructor with scalar values constructor Create(const posX, posY, posZ, upX, upY, upZ, yaw_, pitch_: Single); // returns the view matrix calculated using Euler Angles and the LookAt Matrix function GetViewMatrix:Tmatrix4_single; // processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems) procedure ProcessKeyboard(const direction: Camera_Movement; const deltaTime: Single); // 7.5camera_exercise1 keyboard processing version procedure ProcessKeyboardGround(const direction: Camera_Movement; const deltaTime: Single); // processes input received from a mouse input system. Expects the offset value in both the x and y direction. procedure ProcessMouseMovement(xoffset, yoffset: Single; const constrainPitch: GLboolean = GL_TRUE); // processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis procedure ProcessMouseScroll(const yoffset: Single); private procedure updateCameraVectors; end; implementation uses UMyMatrixExt, math; { TCamera } constructor TCamera.Create(const position_: Tvector3_single); var upVec: Tvector3_single; begin upVec.init(0.0, 1.0, 0.0); Create(position_, upVec); end; // constructor with vectors constructor TCamera.Create(const position_, up_: Tvector3_single; const yaw_: Single; const pitch_: Single); begin Position := position_; WorldUp := up_; Yaw := yaw_; Pitch := pitch_; Front.init(0.0, 0.0, -1.0); MovementSpeed := DEFAULT_SPEED; MouseSensitivity := DEFAULT_SENSITIVITY; Zoom := DEFAULT_ZOOM; end; // constructor with scalar values constructor TCamera.Create(const posX, posY, posZ, upX, upY, upZ, yaw_, pitch_: Single); begin Position.init(posX, posY, posZ); WorldUp.init(upX, upY, upZ); Yaw := yaw_; Pitch := pitch_; Front.init(0.0, 0.0, -1.0); MovementSpeed := DEFAULT_SPEED; MouseSensitivity := DEFAULT_SENSITIVITY; Zoom := DEFAULT_ZOOM; end; // returns the view matrix calculated using Euler Angles and the LookAt Matrix function TCamera.GetViewMatrix: Tmatrix4_single; begin Result := LookAt(Position, Position + Front, WorldUp); end; // processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems) procedure TCamera.ProcessKeyboard(const direction: Camera_Movement; const deltaTime: Single); var velocity: Single; begin velocity := MovementSpeed * deltaTime; if direction = Camera_Movement.FORWARD then Position := Position + Front * velocity; if direction = Camera_Movement.BACKWARD then Position := Position - Front * velocity; if direction = Camera_Movement.LEFT then Position := Position - Right * velocity; if direction = Camera_Movement.RIGHT then Position := Position + Right * velocity; end; // 7.5camera_exercise1 keyboard processing version procedure TCamera.ProcessKeyboardGround(const direction: Camera_Movement; const deltaTime: Single); begin ProcessKeyboard(direction, deltaTime); // make sure the user stays at the ground level Position.data[1] := 0.0; // <-- this one-liner keeps the user at the ground level (xz plane) end; // processes input received from a mouse input system. Expects the offset value in both the x and y direction. procedure TCamera.ProcessMouseMovement(xoffset, yoffset: Single; const constrainPitch: GLboolean); begin xoffset := xoffset * MouseSensitivity; yoffset := yoffset * MouseSensitivity; Yaw := Yaw + xoffset; Pitch := Pitch + yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if constrainPitch = GL_TRUE then begin if Pitch > 89.0 then Pitch := 89.0; if Pitch < -89.0 then Pitch := -89.0; end; // update Front, Right and Up Vectors using the updated Euler angles updateCameraVectors; end; // processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis procedure TCamera.ProcessMouseScroll(const yoffset: Single); begin Zoom := Zoom - yoffset; if Zoom < 1.0 then Zoom := 1.0; if Zoom > 45.0 then Zoom := 45.0; end; procedure TCamera.updateCameraVectors; begin Front.data[0] := cos(DegToRad(Yaw)) * cos(DegToRad(Pitch)); Front.data[1] := sin(DegToRad(Pitch)); Front.data[2] := sin(DegToRad(Yaw)) * cos(DegToRad(Pitch)); Front := NormalizeVector3(Front); Right := NormalizeVector3(Front >< WorldUp); Up := NormalizeVector3(Right >< Front); end; end.
unit Undo_Engine; interface uses HVA,math3d,Voxel,VH_Global,VH_Types; var Undo,Redo : TUndo_Redo; Procedure ResetUndoRedo; Procedure ResetUndo; Procedure ResetRedo; Procedure AddHVAToUndo(const HVA : PHVA; Frame,Section : Integer); Procedure AddVOXELToUndo(const Voxel : PVoxel; Frame,Section : Integer); Procedure DoUndo; Procedure DoRedo; Function IsUndo : Boolean; Function IsRedo : Boolean; implementation Procedure ResetUndo; begin Undo.Data_No := 0; SetLength(Undo.Data,0); end; Procedure ResetRedo; begin Redo.Data_No := 0; SetLength(Redo.Data,0); end; Procedure ResetUndoRedo; begin Redo.Data_No := 0; SetLength(Redo.Data,0); end; Procedure AddHVAToUndo(const HVA : PHVA; Frame,Section : Integer); begin Inc(Undo.Data_No); SetLength(Undo.Data,Undo.Data_No); Undo.Data[Undo.Data_No-1]._Type := HVhva; Undo.Data[Undo.Data_No-1].HVA := HVA; Undo.Data[Undo.Data_No-1].Frame := Frame; Undo.Data[Undo.Data_No-1].Section := Section; Undo.Data[Undo.Data_No-1].TransformMatrix := HVA.TransformMatrixs[Frame*HVA.Header.N_Sections+Section]; Undo.Data[Undo.Data_No-1].Voxel := nil; Undo.Data[Undo.Data_No-1].Offset := SetVector(0,0,0); Undo.Data[Undo.Data_No-1].Size := SetVector(0,0,0); end; Procedure AddVOXELToUndo(const Voxel : PVoxel; Frame,Section : Integer); begin Inc(Undo.Data_No); SetLength(Undo.Data,Undo.Data_No); Undo.Data[Undo.Data_No-1]._Type := HVvoxel; Undo.Data[Undo.Data_No-1].HVA := nil; Undo.Data[Undo.Data_No-1].Frame := Frame; Undo.Data[Undo.Data_No-1].Section := Section; Undo.Data[Undo.Data_No-1].Voxel := Voxel; Undo.Data[Undo.Data_No-1].Offset.x := Voxel.Section[Section].Tailer.MaxBounds[1] + (-(Voxel.Section[Section].Tailer.MaxBounds[1]-Voxel.Section[Section].Tailer.MinBounds[1])/2); Undo.Data[Undo.Data_No-1].Offset.y := Voxel.Section[Section].Tailer.MaxBounds[2] + (-(Voxel.Section[Section].Tailer.MaxBounds[2]-Voxel.Section[Section].Tailer.MinBounds[2])/2); Undo.Data[Undo.Data_No-1].Offset.z := Voxel.Section[Section].Tailer.MaxBounds[3] + (-(Voxel.Section[Section].Tailer.MaxBounds[3]-Voxel.Section[Section].Tailer.MinBounds[3])/2); Undo.Data[Undo.Data_No-1].Size.x := Voxel^.Section[Section].Tailer.MaxBounds[1]-Voxel^.Section[Section].Tailer.MinBounds[1]; Undo.Data[Undo.Data_No-1].Size.y := Voxel^.Section[Section].Tailer.MaxBounds[2]-Voxel^.Section[Section].Tailer.MinBounds[2]; Undo.Data[Undo.Data_No-1].Size.z := Voxel^.Section[Section].Tailer.MaxBounds[3]-Voxel^.Section[Section].Tailer.MinBounds[3]; end; Procedure DoUndo_Redo(var Undo,Redo : TUndo_Redo); var HVA : PHVA; Voxel : PVoxel; NB,NB2 : TVector3f; begin inc(Redo.Data_No); SetLength(Redo.Data,Redo.Data_No); Redo.Data[Redo.Data_No-1]._Type := Undo.Data[Undo.Data_No-1]._Type; Redo.Data[Redo.Data_No-1].HVA := CurrentHVA;//Undo.Data[Undo.Data_No-1].HVA; Redo.Data[Redo.Data_No-1].Frame := Undo.Data[Undo.Data_No-1].Frame; Redo.Data[Redo.Data_No-1].Section := Undo.Data[Undo.Data_No-1].Section; Redo.Data[Redo.Data_No-1].Voxel := CurrentVoxel;// Undo.Data[Undo.Data_No-1].Voxel; Redo.Data[Redo.Data_No-1].Offset.x := CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MaxBounds[1] + (-(CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MaxBounds[1]-CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MinBounds[1])/2); Redo.Data[Redo.Data_No-1].Offset.y := CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MaxBounds[2] + (-(CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MaxBounds[2]-CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MinBounds[2])/2); Redo.Data[Redo.Data_No-1].Offset.z := CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MaxBounds[3] + (-(CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MaxBounds[3]-CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MinBounds[3])/2); Redo.Data[Redo.Data_No-1].Size.x := CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MaxBounds[1]-CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MinBounds[1]; Redo.Data[Redo.Data_No-1].Size.y := CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MaxBounds[2]-CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MinBounds[2]; Redo.Data[Redo.Data_No-1].Size.z := CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MaxBounds[3]-CurrentVoxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MinBounds[3]; { Redo.Data[Redo.Data_No-1].Offset := Undo.Data[Undo.Data_No-1].Offset; Redo.Data[Redo.Data_No-1].Size := Undo.Data[Undo.Data_No-1].Size; } Redo.Data[Redo.Data_No-1].TransformMatrix := CurrentHVA.TransformMatrixs[Undo.Data[Undo.Data_No-1].Frame*CurrentHVA.Header.N_Sections+Undo.Data[Undo.Data_No-1].Section]; //Redo.Data[Redo.Data_No-1].TransformMatrix := Undo.Data[Undo.Data_No-1].TransformMatrix; if Undo.Data[Undo.Data_No-1]._Type = HVhva then begin HVA := Undo.Data[Undo.Data_No-1].HVA; HVA.TransformMatrixs[Undo.Data[Undo.Data_No-1].Frame*HVA.Header.N_Sections+Undo.Data[Undo.Data_No-1].Section] := Undo.Data[Undo.Data_No-1].TransformMatrix; end else begin Voxel := Undo.Data[Undo.Data_No-1].Voxel; NB.x := 0-(Undo.Data[Undo.Data_No-1].Size.x/2); NB.y := 0-(Undo.Data[Undo.Data_No-1].Size.y/2); NB.z := 0-(Undo.Data[Undo.Data_No-1].Size.z/2); NB2.x := (Undo.Data[Undo.Data_No-1].Size.x/2); NB2.y := (Undo.Data[Undo.Data_No-1].Size.y/2); NB2.z := (Undo.Data[Undo.Data_No-1].Size.z/2); NB.X := NB.X + Undo.Data[Undo.Data_No-1].Offset.x; NB.Y := NB.Y + Undo.Data[Undo.Data_No-1].Offset.y; NB.Z := NB.Z + Undo.Data[Undo.Data_No-1].Offset.z; NB2.X := NB2.X + Undo.Data[Undo.Data_No-1].Offset.x; NB2.Y := NB2.Y + Undo.Data[Undo.Data_No-1].Offset.y; NB2.Z := NB2.Z + Undo.Data[Undo.Data_No-1].Offset.z; Voxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MinBounds[1] := NB.X; Voxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MinBounds[2] := NB.Y; Voxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MinBounds[3] := NB.Z; Voxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MaxBounds[1] := NB2.X; Voxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MaxBounds[2] := NB2.Y; Voxel.Section[Undo.Data[Undo.Data_No-1].Section].Tailer.MaxBounds[3] := NB2.Z; end; Dec(Undo.Data_No); SetLength(Undo.Data,Undo.Data_No); end; Procedure DoUndo; begin DoUnDo_ReDo(Undo,Redo); end; Procedure DoRedo; begin DoUnDo_ReDo(Redo,Undo); end; Function IsUndo : Boolean; begin Result := false; if Undo.Data_No > 0 then Result := true; end; Function IsRedo : Boolean; begin Result := false; if Redo.Data_No > 0 then Result := true; end; begin ResetUndoRedo; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Implements a multi-proxy objects, useful for discreet LOD. } unit VXS.MultiProxy; interface uses System.Classes, System.SysUtils, VXS.OpenGL, VXS.PersistentClasses, VXS.Context, VXS.Scene, VXS.VectorGeometry, VXS.Silhouette, VXS.RenderContextInfo, VXS.BaseClasses, VXS.VectorTypes; type TVXMultiProxy = class; { MasterObject description for a MultiProxy object. } TVXMultiProxyMaster = class(TCollectionItem) private FMasterObject: TVXBaseSceneObject; FDistanceMin, FDistanceMin2: Single; FDistanceMax, FDistanceMax2: Single; FVisible: Boolean; protected function GetDisplayName: String; override; procedure SetMasterObject(const val: TVXBaseSceneObject); procedure SetDistanceMin(const val: Single); procedure SetDistanceMax(const val: Single); procedure SetVisible(const val: Boolean); public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; function OwnerObject: TVXMultiProxy; procedure NotifyChange; published { Specifies the Master object which will be proxy'ed. } property MasterObject: TVXBaseSceneObject read FMasterObject write SetMasterObject; { Minimum visibility distance (inclusive). } property DistanceMin: Single read FDistanceMin write SetDistanceMin; { Maximum visibility distance (exclusive). } property DistanceMax: Single read FDistanceMax write SetDistanceMax; { Determines if the master object can be visible (proxy'ed). Note: the master object's distance also has to be within DistanceMin and DistanceMax. } property Visible: Boolean read FVisible write SetVisible default True; end; { Collection of TVXMultiProxyMaster. } TVXMultiProxyMasters = class(TOwnedCollection) protected procedure SetItems(index: Integer; const val: TVXMultiProxyMaster); function GetItems(index: Integer): TVXMultiProxyMaster; procedure Update(Item: TCollectionItem); override; public constructor Create(AOwner: TPersistent); function Add: TVXMultiProxyMaster; overload; function Add(master: TVXBaseSceneObject; DistanceMin, DistanceMax: Single): TVXMultiProxyMaster; overload; property Items[index: Integer]: TVXMultiProxyMaster read GetItems write SetItems; default; procedure Notification(AComponent: TComponent); procedure NotifyChange; procedure EndUpdate; override; end; { Multiple Proxy object. This proxy has multiple master objects, which are individually made visible depending on a distance to the camera criterion. It can be used to implement discreet level of detail directly for static objects, or objects that go through cyclic animation. For dimensionsn raycasting and silhouette purposes, the first master is used (item zero in the MasterObjects collection). } TVXMultiProxy = class(TVXSceneObject) private FMasterObjects: TVXMultiProxyMasters; FRendering: Boolean; // internal use (loop protection) protected procedure SetMasterObjects(const val: TVXMultiProxyMasters); procedure Notification(AComponent: TComponent; Operation: TOperation); override; function PrimaryMaster: TVXBaseSceneObject; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure DoRender(var rci: TVXRenderContextInfo; renderSelf, renderChildren: Boolean); override; function AxisAlignedDimensionsUnscaled: TVector; override; function RayCastIntersect(const rayStart, rayVector: TVector; intersectPoint: PVector = nil; intersectNormal: PVector = nil) : Boolean; override; function GenerateSilhouette(const silhouetteParameters: TVXSilhouetteParameters): TVXSilhouette; override; published property MasterObjects: TVXMultiProxyMasters read FMasterObjects write SetMasterObjects; property ObjectsSorting; property Direction; property PitchAngle; property Position; property RollAngle; property Scale; property ShowAxes; property TurnAngle; property Up; property Visible; property OnProgress; property Behaviours; end; // ------------------------------------------------------------- implementation // ------------------------------------------------------------- // ------------------ // ------------------ TVXMultiProxyMaster ------------------ // ------------------ constructor TVXMultiProxyMaster.Create(Collection: TCollection); begin inherited Create(Collection); FVisible := True; end; destructor TVXMultiProxyMaster.Destroy; begin MasterObject := nil; inherited Destroy; end; procedure TVXMultiProxyMaster.Assign(Source: TPersistent); begin if Source is TVXMultiProxyMaster then begin MasterObject := TVXMultiProxyMaster(Source).MasterObject; FDistanceMin := TVXMultiProxyMaster(Source).FDistanceMin; FDistanceMin2 := TVXMultiProxyMaster(Source).FDistanceMin2; FDistanceMax := TVXMultiProxyMaster(Source).FDistanceMax; FDistanceMax2 := TVXMultiProxyMaster(Source).FDistanceMax2; FVisible := TVXMultiProxyMaster(Source).FVisible; NotifyChange; end else inherited; end; function TVXMultiProxyMaster.OwnerObject: TVXMultiProxy; begin Result := TVXMultiProxy(TVXMultiProxyMasters(Collection).GetOwner); end; procedure TVXMultiProxyMaster.NotifyChange; begin TVXMultiProxyMasters(Collection).NotifyChange; end; function TVXMultiProxyMaster.GetDisplayName: String; begin if MasterObject <> nil then Result := MasterObject.Name else Result := '???'; Result := Result + Format(' [%.2f; %.2f[', [DistanceMin, DistanceMax]); if not Visible then Result := Result + ' (hidden)'; end; procedure TVXMultiProxyMaster.SetMasterObject(const val: TVXBaseSceneObject); begin if FMasterObject <> val then begin if Assigned(FMasterObject) then FMasterObject.RemoveFreeNotification(OwnerObject); FMasterObject := val; if Assigned(FMasterObject) then FMasterObject.FreeNotification(OwnerObject); NotifyChange; end; end; procedure TVXMultiProxyMaster.SetDistanceMin(const val: Single); begin if FDistanceMin <> val then begin FDistanceMin := val; FDistanceMin2 := Sqr(val); NotifyChange; end; end; procedure TVXMultiProxyMaster.SetDistanceMax(const val: Single); begin if FDistanceMax <> val then begin FDistanceMax := val; FDistanceMax2 := Sqr(val); NotifyChange; end; end; procedure TVXMultiProxyMaster.SetVisible(const val: Boolean); begin if FVisible <> val then begin FVisible := val; NotifyChange; end; end; // ------------------ // ------------------ TVXMultiProxyMasters ------------------ // ------------------ constructor TVXMultiProxyMasters.Create(AOwner: TPersistent); begin inherited Create(AOwner, TVXMultiProxyMaster) end; procedure TVXMultiProxyMasters.SetItems(index: Integer; const val: TVXMultiProxyMaster); begin inherited Items[index] := val; end; function TVXMultiProxyMasters.GetItems(index: Integer): TVXMultiProxyMaster; begin Result := TVXMultiProxyMaster(inherited Items[index]); end; procedure TVXMultiProxyMasters.Update(Item: TCollectionItem); begin inherited; NotifyChange; end; function TVXMultiProxyMasters.Add: TVXMultiProxyMaster; begin Result := (inherited Add) as TVXMultiProxyMaster; end; function TVXMultiProxyMasters.Add(master: TVXBaseSceneObject; DistanceMin, DistanceMax: Single): TVXMultiProxyMaster; begin BeginUpdate; Result := (inherited Add) as TVXMultiProxyMaster; Result.MasterObject := master; Result.DistanceMin := DistanceMin; Result.DistanceMax := DistanceMax; EndUpdate; end; procedure TVXMultiProxyMasters.Notification(AComponent: TComponent); var i: Integer; begin for i := 0 to Count - 1 do with Items[i] do if FMasterObject = AComponent then FMasterObject := nil; end; procedure TVXMultiProxyMasters.NotifyChange; begin if (UpdateCount = 0) and (GetOwner <> nil) and (GetOwner is TVXUpdateAbleComponent) then TVXUpdateAbleComponent(GetOwner).NotifyChange(Self); end; procedure TVXMultiProxyMasters.EndUpdate; begin inherited EndUpdate; // Workaround for a bug in VCL's EndUpdate if UpdateCount = 0 then NotifyChange; end; // ------------------ // ------------------ TVXMultiProxy ------------------ // ------------------ constructor TVXMultiProxy.Create(AOwner: TComponent); begin inherited Create(AOwner); ObjectStyle := ObjectStyle + [osDirectDraw]; FMasterObjects := TVXMultiProxyMasters.Create(Self); end; destructor TVXMultiProxy.Destroy; begin inherited Destroy; FMasterObjects.Free; end; procedure TVXMultiProxy.Notification(AComponent: TComponent; Operation: TOperation); begin if Operation = opRemove then FMasterObjects.Notification(AComponent); inherited; end; procedure TVXMultiProxy.SetMasterObjects(const val: TVXMultiProxyMasters); begin FMasterObjects.Assign(val); StructureChanged; end; procedure TVXMultiProxy.Assign(Source: TPersistent); begin if Source is TVXMultiProxy then begin MasterObjects := TVXMultiProxy(Source).MasterObjects; end; inherited; end; procedure TVXMultiProxy.DoRender(var rci: TVXRenderContextInfo; renderSelf, renderChildren: Boolean); var i: Integer; oldProxySubObject: Boolean; mpMaster: TVXMultiProxyMaster; master: TVXBaseSceneObject; d2: Single; begin if FRendering then Exit; FRendering := True; try d2 := VectorDistance2(rci.cameraPosition, AbsolutePosition); for i := 0 to MasterObjects.Count - 1 do begin mpMaster := MasterObjects[i]; if mpMaster.Visible then begin master := mpMaster.MasterObject; if (master <> nil) and (d2 >= mpMaster.FDistanceMin2) and (d2 < mpMaster.FDistanceMax2) then begin oldProxySubObject := rci.proxySubObject; rci.proxySubObject := True; glMultMatrixf(PGLFloat(master.Matrix)); master.DoRender(rci, renderSelf, (master.Count > 0)); rci.proxySubObject := oldProxySubObject; end; end; end; // now render self stuff (our children, our effects, etc.) if renderChildren and (Count > 0) then Self.renderChildren(0, Count - 1, rci); // if masterGotEffects then // FMasterObject.Effects.RenderPostEffects(Scene.CurrentBuffer, rci); finally FRendering := False; end; ClearStructureChanged; end; function TVXMultiProxy.PrimaryMaster: TVXBaseSceneObject; begin if MasterObjects.Count > 0 then Result := MasterObjects[0].MasterObject else Result := nil; end; function TVXMultiProxy.AxisAlignedDimensionsUnscaled: TVector; var master: TVXBaseSceneObject; begin master := PrimaryMaster; if Assigned(master) then begin Result := master.AxisAlignedDimensionsUnscaled; end else Result := inherited AxisAlignedDimensionsUnscaled; end; function TVXMultiProxy.RayCastIntersect(const rayStart, rayVector: TVector; intersectPoint: PVector = nil; intersectNormal: PVector = nil): Boolean; var localRayStart, localRayVector: TVector; master: TVXBaseSceneObject; begin master := PrimaryMaster; if Assigned(master) then begin SetVector(localRayStart, AbsoluteToLocal(rayStart)); SetVector(localRayStart, master.LocalToAbsolute(localRayStart)); SetVector(localRayVector, AbsoluteToLocal(rayVector)); SetVector(localRayVector, master.LocalToAbsolute(localRayVector)); NormalizeVector(localRayVector); Result := master.RayCastIntersect(localRayStart, localRayVector, intersectPoint, intersectNormal); if Result then begin if Assigned(intersectPoint) then begin SetVector(intersectPoint^, master.AbsoluteToLocal(intersectPoint^)); SetVector(intersectPoint^, LocalToAbsolute(intersectPoint^)); end; if Assigned(intersectNormal) then begin SetVector(intersectNormal^, master.AbsoluteToLocal(intersectNormal^)); SetVector(intersectNormal^, LocalToAbsolute(intersectNormal^)); end; end; end else Result := False; end; function TVXMultiProxy.GenerateSilhouette(const silhouetteParameters: TVXSilhouetteParameters): TVXSilhouette; var master: TVXBaseSceneObject; begin master := PrimaryMaster; if Assigned(master) then Result := master.GenerateSilhouette(silhouetteParameters) else Result := nil; end; // ------------------------------------------------------------- initialization // ------------------------------------------------------------- RegisterClasses([TVXMultiProxy]); end.
unit ViewTributacaoIcms; {$mode objfpc}{$H+} interface uses HTTPDefs, BrookRESTActions, BrookUtils, FPJson, SysUtils, BrookHTTPConsts; type TViewTributacaoIcmsOptions = class(TBrookOptionsAction) end; TViewTributacaoIcmsRetrieve = class(TBrookRetrieveAction) procedure Request({%H-}ARequest: TRequest; AResponse: TResponse); override; end; TViewTributacaoIcmsShow = class(TBrookShowAction) end; TViewTributacaoIcmsCreate = class(TBrookCreateAction) end; TViewTributacaoIcmsUpdate = class(TBrookUpdateAction) end; TViewTributacaoIcmsDestroy = class(TBrookDestroyAction) end; implementation procedure TViewTributacaoIcmsRetrieve.Request(ARequest: TRequest; AResponse: TResponse); var VRow: TJSONObject; IdOperacao: String; IdGrupo: String; UfDestino: String; begin IdOperacao := Values['id_operacao'].AsString; IdGrupo := Values['id_grupo'].AsString; UfDestino := Values['uf_destino'].AsString; Values.Clear; Table.Where('ID_TRIBUT_OPERACAO_FISCAL = "' + IdOperacao + '" and ID_TRIBUT_GRUPO_TRIBUTARIO = "' + IdGrupo + '" and UF_DESTINO = "' + UfDestino + '"'); if Execute then begin Table.GetRow(VRow); try Write(VRow.AsJSON); finally FreeAndNil(VRow); end; end else begin AResponse.Code := BROOK_HTTP_STATUS_CODE_NOT_FOUND; AResponse.CodeText := BROOK_HTTP_REASON_PHRASE_NOT_FOUND; end; // inherited Request(ARequest, AResponse); end; initialization TViewTributacaoIcmsOptions.Register('view_tributacao_icms', '/view_tributacao_icms'); TViewTributacaoIcmsRetrieve.Register('view_tributacao_icms', '/view_tributacao_icms/:id_operacao/:id_grupo/:uf_destino/'); TViewTributacaoIcmsShow.Register('view_tributacao_icms', '/view_tributacao_icms/:id'); TViewTributacaoIcmsCreate.Register('view_tributacao_icms', '/view_tributacao_icms'); TViewTributacaoIcmsUpdate.Register('view_tributacao_icms', '/view_tributacao_icms/:id'); TViewTributacaoIcmsDestroy.Register('view_tributacao_icms', '/view_tributacao_icms/:id'); end.
unit Server.Entities.Game; interface uses Spring, Neon.Core.Attributes, Generics.Collections, Common.Entities.Player, Common.Entities.Card, Common.Entities.Round, Common.Entities.Bet, Common.Entities.GameSituation, Common.Entities.GameType, Spring.Collections.Stacks; type TPlayerCards=class(TPlayer) private FIndex: Integer; FCards: TCards; FPoints: Double; FResults: Smallint; public property Index:Integer read FIndex; property Cards:TCards read FCards write FCards; property Points:Double read FPoints write FPoints; property Results:Smallint read FResults write FResults; constructor Create(const AName:String; const AIndex:Integer; const AScore:Integer); destructor Destroy;override; procedure Assign(const ASource:TPlayer);override; end; TGameRounds=Spring.Collections.TList<TGameRound>; TGame=class private FID:TGUID; FTalon:TPlayerCards; FActive: Boolean; FRounds: TGameRounds; FBets: TBets; FSituation: TGameSituation<TPlayerCards>; FActGame: TGameType; FLastFinalBidder: String; FTalonRounds: Integer; FDoubles:TList<Smallint>; function GetActRound: TGameRound; function GetPlayers: TPlayers<TPlayerCards>; function GetPlayersTeam1: TPlayers<TPlayerCards>; function GetPlayersTeam2: TPlayers<TPlayerCards>; function GetTeam1Names: String; function GetTeam2Names: String; //function Clone:TGame; public // [NeonInclude(Include.Always)] property ID:TGUID read FID write FID; property Active:Boolean read FActive write FActive; property Players: TPlayers<TPlayerCards> read GetPlayers; property Talon:TPlayerCards read FTalon write FTalon; property Bets:TBets read FBets write FBets; property LastFinalBidder:String read FLastFinalBidder write FLastFinalBidder; property Rounds:TGameRounds read FRounds write FRounds; property ActRound:TGameRound read GetActRound; property TalonRounds:Integer read FTalonRounds write FTalonRounds; property Situation:TGameSituation<TPlayerCards> read FSituation write FSituation; property ActGame:TGameType read FActGame write FActGame; property PlayersTeam1:TPlayers<TPlayerCards> read GetPlayersTeam1; property PlayersTeam2:TPlayers<TPlayerCards> read GetPlayersTeam2; property Team1Names:String read GetTeam1Names; property Team2Names:String read GetTeam2Names; property Doubles:TList<Smallint> read FDoubles write FDoubles; constructor Create(const APlayers:TPlayers<TPlayer>=nil); destructor Destroy;override; function FindPlayer(const APlayerName:String):TPlayerCards; function TeamOf(const APlayerName:String):TTeam; end; TGames=Spring.Collections.Stacks.TObjectStack<TGame>; implementation uses SysUtils; { TGame } (* function TGame.Clone: TGame; var i: Integer; begin Result:=TGame.Create; Result.FID:=FID; Result.FActive:=FActive; for i := 0 to Players.Count-1 do begin // Result.Players.Add(TPlayerCards.Create); Result.Players[i].Assign(Players[i]); end; Result.Talon.Assign(Talon); end; *) constructor TGame.Create(const APlayers:TPlayers<TPlayer>=nil); var i:Integer; player:TPlayer; begin inherited Create; SysUtils.CreateGUID(FID); FSituation:=TGameSituation<TPlayerCards>.Create; for i:=0 to 3 do begin if Assigned(APlayers) then Players.Add(TPlayerCards.Create(APlayers[i].Name,i,APlayers[i].Score)) else Players.Add(TPlayerCards.Create('',i,0)) end; FTalon:=TPlayerCards.Create('TALON',-1,0); for player in APlayers do player.BetState:=btNone; FBets:=TBets.Create(True); FRounds:=TGameRounds.Create; FDoubles:=TList<Smallint>.Create; FActive:=True; end; destructor TGame.Destroy; begin FreeAndNil(FSituation); FreeAndNil(FTalon); FreeAndNil(FBets); FreeAndNil(FRounds); FreeAndNil(FDoubles); inherited; end; function TGame.FindPlayer(const APlayerName: String): TPlayerCards; var itm:TPlayerCards; begin Result:=Nil; if Uppercase(APlayerName)='TALON' then Result:=FTalon else begin for itm in Players do begin if itm.Name=APlayername then begin Result:=itm; Break; end; end; end; end; function TGame.GetActRound: TGameRound; begin if FRounds.Count=0 then Result:=Nil else Result:=FRounds.Last end; function TGame.GetPlayers: TPlayers<TPlayerCards>; begin Result:=FSituation.Players; end; function TGame.GetPlayersTeam1: TPlayers<TPlayerCards>; var player:TPlayerCards; begin Result:=TPlayers<TPlayerCards>.Create(False); for player in FSituation.Players do begin if player.Team=ttTeam1 then Result.Add(player) end; end; function TGame.GetPlayersTeam2: TPlayers<TPlayerCards>; var player:TPlayerCards; begin Result:=TPlayers<TPlayerCards>.Create(False); for player in FSituation.Players do begin if player.Team=ttTeam2 then Result.Add(player) end; end; function TGame.GetTeam1Names: String; var player:TPlayerCards; plist:TPlayers<TPlayerCards>; begin Result:=''; plist:=GetPlayersTeam1; try for player in pList do Result:=Result+','+player.Name; if Length(Result)>0 then Result:=Copy(Result,2,Length(Result)); finally FreeAndNil(pList); end; end; function TGame.GetTeam2Names: String; var player:TPlayerCards; plist:TPlayers<TPlayerCards>; begin Result:=''; plist:=GetPlayersTeam2; try for player in pList do Result:=Result+','+player.Name; if Length(Result)>0 then Result:=Copy(Result,2,Length(Result)); finally FreeAndNil(pList); end; end; function TGame.TeamOf(const APlayerName: String): TTeam; begin Result:=Players.Find(APlayerName).Team end; { TPlayerCards } procedure TPlayerCards.Assign(const ASource:TPlayer); begin inherited Assign(ASource); if ASource is TPlayerCards then begin FIndex:=TPlayerCards(ASource).Index; FCards.Assign(TPlayerCards(ASource).Cards); FPoints:=TPlayerCards(ASource).Points; end; end; constructor TPlayerCards.Create(const AName:String; const AIndex:Integer; const AScore:Integer); begin inherited Create(AName); FIndex:=AIndex; Score:=AScore; FCards:=TCards.Create; end; destructor TPlayerCards.Destroy; begin FreeAndNil(FCards); inherited; end; end.
unit Magento.MediaGalleryEntries; interface uses Magento.Interfaces, System.JSON; type TMagentoMediaGalleryEntries = class (TInterfacedObject, iMagentoMediaGalleryEntries) private FParent : iMagentoEntidadeProduto; FJSON : TJSONObject; FJSONArray : TJSONArray; public constructor Create(Parent : iMagentoEntidadeProduto); destructor Destroy; override; class function New(Parent : iMagentoEntidadeProduto) : iMagentoMediaGalleryEntries; function MediaType(value : String) : iMagentoMediaGalleryEntries; function &Label(value : String) : iMagentoMediaGalleryEntries; function Position(value : Integer) : iMagentoMediaGalleryEntries; function Disabled(value : Boolean) : iMagentoMediaGalleryEntries; function &File(value : String) : iMagentoMediaGalleryEntries; function Types : iMagentoMediaGalleryEntries; function Content : iMagentoMediaGaleryContent; overload; function Content(value : TJSONObject) : iMagentoMediaGalleryEntries; overload; function &End : iMagentoEntidadeProduto; end; implementation { TMagentoMediaGalleryEntries } uses Magento.Factory; function TMagentoMediaGalleryEntries.&End: iMagentoEntidadeProduto; begin FJSONArray.Add(FJSON); FParent.MediaGalleryEntries(FJSONArray); Result := FParent; end; function TMagentoMediaGalleryEntries.&File( value: String): iMagentoMediaGalleryEntries; begin Result := Self; FJSON.AddPair('file', value); end; function TMagentoMediaGalleryEntries.&Label( value: String): iMagentoMediaGalleryEntries; begin Result := Self; FJSON.AddPair('label', value); end; function TMagentoMediaGalleryEntries.Content( value: TJSONObject): iMagentoMediaGalleryEntries; begin Result := Self; FJSON.AddPair('content',value); end; function TMagentoMediaGalleryEntries.Content: iMagentoMediaGaleryContent; begin Result := TMagentoFactory.New.MediaGalleryContent(Self); end; constructor TMagentoMediaGalleryEntries.Create(Parent : iMagentoEntidadeProduto); begin FParent := Parent; FJSON := TJSONObject.Create; FJSONArray := TJSONArray.Create; end; destructor TMagentoMediaGalleryEntries.Destroy; begin inherited; end; function TMagentoMediaGalleryEntries.Disabled( value: Boolean): iMagentoMediaGalleryEntries; begin Result := Self; FJSON.AddPair('disabled', TJSONBool.Create(value)); end; function TMagentoMediaGalleryEntries.MediaType( value: String): iMagentoMediaGalleryEntries; begin Result := Self; FJSON.AddPair('mediaType', value); end; class function TMagentoMediaGalleryEntries.New(Parent : iMagentoEntidadeProduto) : iMagentoMediaGalleryEntries; begin Result := self.Create(Parent); end; function TMagentoMediaGalleryEntries.Position( value: Integer): iMagentoMediaGalleryEntries; begin Result := Self; FJSON.AddPair('position', TJSONNumber.Create(value)); end; function TMagentoMediaGalleryEntries.Types: iMagentoMediaGalleryEntries; var lJSONArray : TJSONArray; begin Result := Self; lJSONArray := TJSONArray.Create; lJSONArray.Add('image'); lJSONArray.Add('thumbnail'); lJSONArray.Add('small_image'); FJSON.AddPair('types', lJSONArray); end; end.
unit ufrmDialogDaftarKompetitor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ufrmMasterDialog, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxRadioGroup, System.Actions, Vcl.ActnList, ufraFooterDialog3Button, uClientClasses, uInterface, uModKompetitor; type TfrmDialogDaftarKompetitor = class(TfrmMasterDialog, ICRUDAble) chkIsActive: TCheckBox; edtCompCode: TEdit; edtNama: TEdit; lbl1: TLabel; lbl2: TLabel; procedure actDeleteExecute(Sender: TObject); procedure actSaveExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FModKompetitor: TModKompetitor; procedure ClearForm; function GetModKompetitor: TModKompetitor; function IsValidate: Boolean; procedure SavingData; property ModKompetitor: TModKompetitor read GetModKompetitor write FModKompetitor; public procedure LoadData(AID: string); end; var frmDialogDaftarKompetitor: TfrmDialogDaftarKompetitor; implementation uses uTSCommonDlg, DB, uConstanta, uAppUtils, uDMClient; {$R *.dfm} procedure TfrmDialogDaftarKompetitor.actDeleteExecute(Sender: TObject); begin inherited; if TAppUtils.Confirm(CONF_VALIDATE_FOR_DELETE) then begin try DMClient.CrudClient.DeleteFromDB(ModKompetitor); TAppUtils.Information(CONF_DELETE_SUCCESSFULLY); ModalResult := mrOk; except TAppUtils.Error(ER_DELETE_FAILED); raise; end; end; end; procedure TfrmDialogDaftarKompetitor.actSaveExecute(Sender: TObject); begin inherited; if IsValidate then SavingData; end; procedure TfrmDialogDaftarKompetitor.ClearForm; begin edtCompCode.Clear; edtNama.Clear; chkIsActive.Checked := True; end; procedure TfrmDialogDaftarKompetitor.FormCreate(Sender: TObject); begin inherited; ClearForm; Self.AssignKeyDownEvent; end; procedure TfrmDialogDaftarKompetitor.FormDestroy(Sender: TObject); begin frmDialogDaftarKompetitor := nil; end; function TfrmDialogDaftarKompetitor.GetModKompetitor: TModKompetitor; begin if not Assigned(FModKompetitor) then FModKompetitor := TModKompetitor.Create; Result := FModKompetitor; end; function TfrmDialogDaftarKompetitor.IsValidate: Boolean; begin Result := False; if edtCompCode.Text = '' then begin TAppUtils.Warning('Competitor Code belum diisi'); exit; end else if edtNama.Text = '' then begin TAppUtils.Warning('Competitor Name belum diisi'); exit; end else Result := True; end; procedure TfrmDialogDaftarKompetitor.LoadData(AID: string); begin if Assigned(FModKompetitor) then FreeAndNil(FModKompetitor); FModKompetitor := DMClient.CrudClient.Retrieve(TModKompetitor.ClassName, AID) as TModKompetitor; edtCompCode.Text := ModKompetitor.KOMPT_CODE; edtNama.Text := ModKompetitor.KOMPT_NAME; chkIsActive.Checked := ModKompetitor.KOMPT_IS_ACTIVE = 1; end; procedure TfrmDialogDaftarKompetitor.SavingData; begin ModKompetitor.KOMPT_CODE := edtCompCode.Text; ModKompetitor.KOMPT_NAME := edtNama.Text; ModKompetitor.KOMPT_IS_ACTIVE := TAppUtils.BoolToInt(chkIsActive.Checked); Try DMClient.CrudClient.SaveToDB(ModKompetitor); TAppUtils.Information(CONF_ADD_SUCCESSFULLY); ModalResult := mrOk; except TAppUtils.Error(ER_INSERT_FAILED); Raise; End; end; end.
unit uSaque; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, uRelatorioSaque; type TFrmSaque = class(TFrame) Label1: TLabel; BtnConfirmar: TButton; BtnCancelar: TButton; BtnUm: TButton; Btn2: TButton; Btn3: TButton; Btn4: TButton; Btn5: TButton; Btn6: TButton; Btn7: TButton; Btn8: TButton; Btn9: TButton; Btn0: TButton; BtnClear: TButton; PnlValor: TPanel; BtnBackspace: TButton; procedure BtnUmClick(Sender: TObject); procedure Btn2Click(Sender: TObject); procedure Btn3Click(Sender: TObject); procedure Btn4Click(Sender: TObject); procedure Btn5Click(Sender: TObject); procedure Btn6Click(Sender: TObject); procedure Btn7Click(Sender: TObject); procedure Btn8Click(Sender: TObject); procedure Btn9Click(Sender: TObject); procedure Btn0Click(Sender: TObject); procedure BtnClearClick(Sender: TObject); procedure BtnBackspaceClick(Sender: TObject); procedure BtnConfirmarClick(Sender: TObject); procedure BtnCancelarClick(Sender: TObject); private { Private declarations } public procedure Tecla(Valor: integer); { Processa a tecla pressionada } procedure ValorSaque (ValorTotal : Integer); function TotalNotas(csNota, csRestoAnterior, csRestoAtual, csValor: Integer) : Integer; var FrmRelatorioSaque : TFrmRelatorioSaque; end; implementation uses uFormPrincipal; {$R *.dfm} procedure TFrmSaque.BtnUmClick(Sender: TObject); begin Tecla(1); end; procedure TFrmSaque.Tecla(Valor: integer); begin if PnlValor.Caption = '0' then PnlValor.Caption := IntToStr(Valor) else PnlValor.Caption := PnlValor.Caption + IntToStr(Valor); end; function TFrmSaque.TotalNotas(csNota, csRestoAnterior, csRestoAtual, csValor: Integer): Integer; begin csNota := csRestoAnterior div csValor ; csRestoAtual := csRestoAnterior mod csValor ; Result := csRestoAtual; end; procedure TFrmSaque.ValorSaque(ValorTotal: Integer); var n100,n50,n20,n10,n5,n2,n1 : integer; r100,r50,r20,r10,r5,r2,r1 : integer; begin ValorTotal := StrToInt(PnlValor.Caption); while ValorTotal <> 0 do begin if ValorTotal >= 100 then ValorTotal:= TotalNotas(n100, ValorTotal, r100, 100) ; if (ValorTotal < 100) and (ValorTotal > 0) then ValorTotal:= TotalNotas(n50, ValorTotal, r50, 50); if (ValorTotal < 50) and (ValorTotal >= 20) then ValorTotal:= TotalNotas(n20, ValorTotal, r20, 20); if (ValorTotal < 20) and (ValorTotal > 0)then ValorTotal:= TotalNotas(n10, ValorTotal, r10, 10); if True then Exit; end; end; procedure TFrmSaque.Btn2Click(Sender: TObject); begin Tecla(2); end; procedure TFrmSaque.Btn3Click(Sender: TObject); begin Tecla(3); end; procedure TFrmSaque.Btn4Click(Sender: TObject); begin Tecla(4); end; procedure TFrmSaque.Btn5Click(Sender: TObject); begin Tecla(5); end; procedure TFrmSaque.Btn6Click(Sender: TObject); begin Tecla(6); end; procedure TFrmSaque.Btn7Click(Sender: TObject); begin Tecla(7); end; procedure TFrmSaque.Btn8Click(Sender: TObject); begin Tecla(8); end; procedure TFrmSaque.Btn9Click(Sender: TObject); begin Tecla(9); end; procedure TFrmSaque.Btn0Click(Sender: TObject); begin Tecla(0); end; procedure TFrmSaque.BtnCancelarClick(Sender: TObject); begin FrmPrincipal.AlterarTela(1); PnlValor.Caption := '0'; end; procedure TFrmSaque.BtnClearClick(Sender: TObject); begin PnlValor.Caption := '0'; end; procedure TFrmSaque.BtnConfirmarClick(Sender: TObject); begin if PnlValor.Caption <> '0'then begin FrmPrincipal.AlterarTela(5); ValorSaque(StrToInt(PnlValor.Caption)); end else ShowMessage('Informe um valor maior que ZERO.'); end; procedure TFrmSaque.BtnBackspaceClick(Sender: TObject); begin if Length(PnlValor.Caption) <= 1 then PnlValor.Caption := '0' else PnlValor.Caption := copy(PnlValor.Caption, 1, Length(PnlValor.Caption)-1); end; end.
{ Date : 05/06/2009 13:29:37 Modifié par Cirec pour assurer la compatibilité avec unicode de Delphi2009 } (* Algorithme LEA-128 (Lossy Elimination Algorithm - Algorithme de perte de données par élimination). Auteur : Bacterius. Algorithme de perte de données par élimination : on élimine la donnée et on en tire son empreinte. Effectivement, cet algorithme va réduire une donnée de taille variable (de 1 octet, 12 mégas, ou même 1 gigaoctet) en sa représentation unique (de taille fixe : 16 octets). Chaque donnée aura une représentation unique (théoriquement : mais en pratique, il y aura toujours des collisions, car il y a plus de possibilités de messages que de possibilités de hash : d'après le principe des tiroirs). Mathématiquement, si Hash(x) est la fonction par laquelle passe la donnée x, et H le hash de cette donnée x, on a : y <> x Hash(x) = H Hash(y) <> H Cet algorithme de hachage est basé sur un hachage par blocs de 512 bits, c'est à dire que à chaque bloc de 512 bits, un certain nombre d'opérations va s'effectuer. Voici un schéma : ________________________________________________________________________________ VALEURS DE DEPART | MESSAGE | A B C D | | | | | | ? ? ? ? <---- PREMIER BLOC 512 BITS DU MESSAGE (altération de A, B, C, D) | | | | | ? ? ? ? <---- SECOND BLOC 512 BITS DU MESSAGE (altération de A, B, C, D) | | | | | ? ? ? ? <---- TROISIEME BLOC 512 BITS DU MESSAGE (altération de A, B, C, D) | | | | | ................. etc ... | | | | | W X Y Z <---- HACHAGES (altérés) \ | | / | Hachage <---- de 128 bits, c'est la réunion de W, X, Y et Z (32 bits chacun) ________________________________________________________________________________ Remarque : si la taille du message de départ n'est pas multiple de 64 octets (512 bits), un dépassement de buffer pourrait survenir. C'est pourquoi l'on a introduit la notion de remplissage ou "padding", qui est appliqué même si la taille du message est multiple de 64 octets. Cela consiste à ajouter un bit à 1 à la fin du message, suivi par autant de bits à 0 que nécessaire. Exemple pour un message de 3 octets : 110111011001011101101110 ... 10000000 Octet 1|Octet 2|Octet 3| ... Padding| L'algorithme de hachage tient surtout à la façon dont sont altérées les valeurs A, B, C et D à chaque double mot du message. HashTable contient les 4 valeurs de départ. Elles représentent la "signature" de l'algorithme. Si vous changez ces valeurs, les hachages changeront également. HashTransform permet un effet d'avalanche (gros changements du hash pour petite modification du message) plus rapide. Si vous changez une ou plusieurs de ces valeurs, tous les hachages seront différents. Cet algorithme est assez rapide, et le test de collisions n'est pas terminé. Comme pour tous les algorithmes de hash, on s'efforce de faire des hachages les moins similaires possibles pour des petits changements. Essayez avec "a", puis "A", puis "b", vous verrez ! ¤ Les fonctions - Hash : cette fonction effectue le hachage d'une donnée Buffer, de taille Size. Il s'agit de la fonction de base pour hacher un message. - HashToString : cette fonction convertit un hachage en une chaîne lisible. - StringToHash : cette fonction convertit une chaîne lisible en hash, si celle-ci peut correspondre à un hash. En cas d'erreur, toutes les valeurs du hash sont nulles. - SameHash : cette fonction compare deux hachages et dit si celles-ci sont identiques. Renvoie True le cas échéant, False sinon. - HashCrypt : cette fonction crypte un hachage tout en conservant son aspect. - HashUncrypt : cette fonction décrypte un hachage crypté avec la bonne clef. - IsHash : cette fonction vérifie si la chaîne passée peut être ou est un hachage. - HashStr : cette fonction effectue le hachage d'une chaîne de caractères. - HashInt : cette fonction effectue le hachage d'un entier sur 32 bits. Attention : la fonction effectue le hachage de l'entier directement, elle ne convertit absolument pas l'entier en texte ! - HashFile : cette fonction effectue le hachage du contenu d'un fichier. ¤ Collisions. Dans tout algorithme de hachage existent des collisions. Cela découle logiquement de l'affirmation suivante : Il y a un nombre limité de hachages possibles (2^128). Mais il existe une infinité de messages possibles, si l'on ne limite pas les caractères. Cependant, l'algorithme peut réduire le nombre de collisions, qui, théoriquement infini, ne l'est pas à l'échelle humaine. Si l'on suppose qu'à l'échelle humaine, nous ne tenons compte, schématiquement, de messages de 10 octets maximum (c'est un exemple), l'on a une possibilité de combinaisons de 255^10 octets, sur une possibilité de 2^128 hachages. Il est donc possible de n'avoir aucune collision, puisqu'il y a plus de possibilités de hachages que de possibilités de combinaisons. ¤ Protection additionnelle Un hash est déjà théoriquement impossible à inverser. Cependant, cela est possible à l'échelle mondiale avec un réseau de super-calculateurs, moyennant tout de même une quantité de temps impressionnante (avec les 80 et quelques supercalculateurs de IBM, l'on ne met que 84 ans à trouver le message (de 10 caractères) correspondant au hachage). Vous pouvez donc ajouter des protections supplémentaires : - Le salage : cela consiste à ajouter une donnée supplémentaire au message avant hachage. Cela rend le hachage moins vulnérable aux attaques par dictionnaire. Par exemple, si vous avez un mot de passe "chat", quand quelqu'un va attaquer le hachage de "chat", il va rapidement le trouver dans le dictionnaire, va s'apercevoir que le hachage est le même, et va déduire qu'il s'agit de votre mot de passe. Pour éviter ça, vous allez ajouter une donnée moins évidente au message, disons "QS77". Vous allez donc hacher le mot de passe "QS77chat" ( ou "chatQS77"). Ce mot ne figure evidemment pas dans le dictionnaire. Le pirate va donc avoir un problème, et va alors eventuellement laisser tomber, ou bien changer de technique, et attaquer par force brute (tester toutes les combinaisons possibles). Si vous avez un mot de passe de 5 caractères ASCII, cela lui prendra au plus 5 jours. Si vous avez un mot de passe de 10 caractères, cela mettra 70 milliards d'années. Donc, optez pour un mot de passe d'au moins 6 caractères (et eventuellement, rajoutez un caractère spécial, comme un guillemet, pour forcer le pirate à attaquer en ASCII et non pas en alphanumérique (il lui faudrait plus de temps de tester les 255 caractères ASCII que seulement les 26 lettres de l'alphabet et les nombres ...)). - Le cryptage : cela consiste à crypter le hachage par-dessus (tout en lui faisant garder son aspect de hachage ! Par exemple, si vous avez un hachage "A47F", n'allez pas le crypter en "%E#!", il apparaîtrait evident qu'il est crypté !). Cela a pour effet de compliquer encore plus le travail du pirate, qui, inconsciemment, sera en train d'essayer de percer un mauvais hachage ! Si le cryptage est bien réalisé, il peut s'avérer plus qu'efficace. Cependant, pensez à conserver la clef de cryptage/décryptage, sans quoi, si pour une raison ou pour une autre vous aviez à récupérer le hash d'origine (cela peut arriver parfois), vous devriez tester toutes les clefs ... Une fonction de cryptage et une de décryptage est fournie dans cette unité. - Le byteswap : cela consiste à "swapper" les octets du hachage. Cela revient à crypter le hachage puisque cette opération est réversible "permutative" (la fonction de cryptage joue également le rôle de la fonction de décryptage). Ajouter une petite protection ne coûte rien de votre côté, et permet de se protéger plus qu'efficacement contre des attaques. Même si un hash en lui-même est déjà pas mal, mieux vaut trop que pas assez ! ¤ Autres utilités du hash - générateur de nombres aléatoires : l'algorithme de hachage est si particulier pour le MD5 par exemple, qu'il a été déclaré comme efficace en tant que générateur de nombres pseudo-aléatoires, et il a passé avec succès tous les tests statistiques. L'algorithme LEA n'est pas garanti d'être efficace comme générateur de nombres pseudo-aléatoires. } *) unit LEA_Hash; interface uses Windows, SysUtils, Dialogs; const { Ces valeurs sont pseudo-aléatoires (voir plus bas) et sont distinctes (pas de doublon) } { Notez que le hachage d'une donnée nulle (de taille 0) renverra HashTable (aucune altération) } HashTable: array [$0..$3] of Longword = ($CF306227, $4FCE8AC8, $ACE059ED, $4E3079A6); { MODIFIER CES VALEURS ENTRAINERA UNE MODIFICATION DE TOUS LES HACHAGES } type THash = record { La structure d'un hash LEA sur 128 bits } A, B, C, D: Longword; { Les quatre double mots } end; TLEACallback = procedure (BlockIndex: Longword; BlockCount: Longword); stdcall; function Hash (const Buffer; const Size: Longword; Callback: TLEACallback = nil): THash; function HashStr (const Str : AnsiString ): THash; function HashInt (const Int : Integer ): THash; function HashFile (const FilePath: String; Callback: TLEACallback = nil): THash; function HashToString (const Hash : THash ): AnsiString; function StringToHash (const Str : AnsiString ): THash; function SameHash (const A, B : THash ): Boolean; function Same (A, B: Pointer; SzA, SzB: Longword): Boolean; function HashCrypt (const Hash : AnsiString; Key: Longword): AnsiString; function HashUncrypt (const Hash : AnsiString; Key: Longword): AnsiString; function IsHash (const Hash : AnsiString ): Boolean; implementation const Power2: array [$1..$20] of Longword =($00000001, $00000002, $00000004, $00000008, $00000010, $00000020, $00000040, $00000080, $00000100, $00000200, $00000400, $00000800, $00001000, $00002000, $00004000, $00008000, $00010000, $00020000, $00040000, $00080000, $00100000, $00200000, $00400000, $00800000, $01000000, $02000000, $04000000, $08000000, $10000000, $20000000, $40000000, $80000000); function RShl(A, B: Longword): Longword; begin Result := (A shl B) or (B shl $20); end; type PLEABuf = ^TLEABuf; TLEABuf = array [$0..$F] of Longword; procedure LEAInternal(var A, B, C, D: Longword; Buf: TLEABuf); Var I: Integer; begin for I := $1 to $F do { Pour chaque double mot du buffer } begin { On incrémente chaque valeur A, B, C et D, puis on l'altère } Inc(A, Buf[I] + (B or (C xor (not D)))); A := ((A shl $6) xor (A shr $D)) + Buf[Pred(I)]; Inc(B, Buf[I] + (C or (D xor (not A)))); B := ((B shl $A) xor (B shr $5)) + Buf[Pred(I)]; Inc(C, Buf[I] + (D or (A xor (not B)))); C := ((C shl $3) xor (C shr $C)) + Buf[Pred(I)]; Inc(D, Buf[I] + (A or (B xor (not C)))); D := ((D shl $E) xor (D shr $9)) + Buf[Pred(I)]; end; end; function Hash(const Buffer; const Size: Longword; Callback: TLEACallback = nil): THash; Var V: PLEABuf; Sz, Cnt: Longword; Buf: TLEABuf; E: Pointer; BlockCount: Longword; begin { On récupère les valeurs du tableau } Move(HashTable, Result, $10); { Si buffer vide, on a les valeurs initiales } if Size = $0 then Exit; { On calcule le padding } Cnt := $0; Sz := Size; repeat Inc(Sz) until Sz mod $40 = $0; { On calcule le nombre de blocs } BlockCount := Sz div $40; { On prend le début du buffer } V := @Buffer; { On calcule la fin du buffer } E := Ptr(Longword(@Buffer) + Sz); with Result do repeat { Pour chaque double mot du message, tant qu'on est pas arrivé à la fin ... } begin ZeroMemory(@Buf, $40); if Size - Cnt > $3F then Move(V^, Buf, $40) else begin Move(V^, Buf, Size - Cnt); FillMemory(Ptr(Longword(@Buf) + Succ(Size - Cnt)), 1, $80); end; { On effectue une altération complexe } LEAInternal(A, B, C, D, Buf); { On appelle le callback } if Assigned(Callback) then Callback(Cnt div $40, BlockCount); Inc(V); { On passe aux 512 bits suivants ! } Inc(Cnt, $40); { On incrémente ce qui a été fait } { Ne pas modifier les lignes de calcul, sinon cela peut ne plus marcher } end until V = E; end; function HashStr(const Str: AnsiString): THash; begin { On va envoyer le pointeur sur la chaîne à la fonction Hash. } Result := Hash(PAnsiChar(Str)^, Length(Str)); end; function HashInt(const Int: Integer): THash; begin { On envoie directement le nombre dans le buffer. } Result := Hash(Int, SizeOf(Integer)); end; function HashFile(const FilePath: String; Callback: TLEACallback = nil): THash; Var H, M: Longword; P: Pointer; begin { On va mettre à 0 pour cette fonction, car autant il n'était pas possible que les fonctions précédentes n'échouent, celle-ci peut échouer pour diverses raisons. } ZeroMemory(@Result, 16); { On ouvre le fichier } H := CreateFile(PChar(FilePath), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN, 0); { Si erreur d'ouverture, on s'en va } if H = INVALID_HANDLE_VALUE then Exit; { CreateFileMapping rejette les fichiers de taille 0 : ainsi, on doit les tester avant } if GetFileSize(H, nil) = 0 then begin Result := Hash('', 0); { On récupère un hash nul } CloseHandle(H); { On libère le handle } Exit; end; { On crée une image mémoire du fichier } try M := CreateFileMapping(H, nil, PAGE_READONLY, 0, 0, nil); try { On récupère un pointeur sur l'image du fichier en mémoire } if M = 0 then Exit; P := MapViewOfFile(M, FILE_MAP_READ, 0, 0, 0); try { On envoie le pointeur au hash, avec comme taille de buffer la taille du fichier } if P = nil then Exit; Result := Hash(P^, GetFileSize(H, nil), Callback); finally { On libère tout ... } UnmapViewOfFile(P); end; finally CloseHandle(M); end; finally CloseHandle(H); end; end; function HashToString(const Hash: THash): AnsiString; begin { On ajoute les quatre entiers l'un après l'autre sous forme héxadécimale ... } Result := AnsiString(Format('%.8x%.8x%.8x%.8x', [Hash.A, Hash.B, Hash.C, Hash.D])); end; function StringToHash(const Str: AnsiString): THash; begin if IsHash(Str) then with Result do begin { Astuce de Delphi : un HexToInt sans trop de problèmes ! Rajouter un "$" devant le nombre et appeller StrToInt. Cette astuce accepte un maximum de 8 caractères après le signe "$". } A := StrToInt(Format('$%s', [Copy(Str, 1, 8)])); B := StrToInt(Format('$%s', [Copy(Str, 9, 8)])); C := StrToInt(Format('$%s', [Copy(Str, 17, 8)])); D := StrToInt(Format('$%s', [Copy(Str, 25, 8)])); end else ZeroMemory(@Result, 16); { Si Str n'est pas un hash, on met tout à 0 } end; function SameHash(const A, B: THash): Boolean; begin { On compare les deux hashs ... } Result := CompareMem(@A, @B, 16); end; function Same(A, B: Pointer; SzA, SzB: Longword): Boolean; begin { Cette fonction va regarder si deux objets mémoire (définis par leur pointeur de début et leur taille) sont identiques en comparant leur hash. } Result := SameHash(Hash(A, SzA), Hash(B, SzB)); end; const Z = #0; { Le caractère nul, plus pratique de l'appeller Z que de faire chr(0) ou #0 } function hxinc(X: AnsiChar): AnsiChar; { Incrémentation héxadécimale } const XInc: array [48..70] of AnsiChar = ('1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', Z, Z, Z, Z, Z, Z, Z, 'B', 'C', 'D', 'E', 'F', '0'); begin if ord(X) in [48..57, 65..70] then Result := XInc[ord(X)] else Result := Z; end; function hxdec(X: AnsiChar): AnsiChar; { Décrémentation héxadécimale ... } const XDec: array [48..70] of AnsiChar = ('F', '0', '1', '2', '3', '4', '5', '6', '7', '8', Z, Z, Z, Z, Z, Z, Z, '9', 'A', 'B', 'C', 'D', 'E'); begin if ord(X) in [48..57, 65..70] then Result := XDec[ord(X)] else Result := Z; end; function HashCrypt(const Hash: AnsiString; Key: Longword): AnsiString; Var I: Integer; begin { Cryptage avec une clef binaire } Result := Hash; if not IsHash(Hash) then Exit; for I := 32 downto 1 do if Key and Power2[I] <> 0 then Result[I] := hxinc(Result[I]) else Result[I] := hxdec(Result[I]); end; function HashUncrypt(const Hash: AnsiString; Key: Longword): AnsiString; Var I: Integer; begin { Décryptage avec une clef binaire } Result := Hash; if not IsHash(Hash) then Exit; for I := 32 downto 1 do if Key and Power2[I] <> 0 then Result[I] := hxdec(Result[I]) else Result[I] := hxinc(Result[I]); end; function IsHash(const Hash: AnsiString): Boolean; Var I: Integer; begin { Vérification de la validité de la chaîne comme hash. } Result := False; if Length(Hash) <> 32 then Exit; { Si la taille est différente de 32, c'est déjà mort ... } { Si l'on rencontre un seul caractère qui ne soit pas dans les règles, on s'en va ... } {$ifndef unicode} for I := 1 to 32 do if not (Hash[I] in ['0'..'9', 'A'..'F', 'a'..'f']) then Exit; {$else} for I := 1 to 32 do if not CharInSet(Hash[I], ['0'..'9', 'A'..'F', 'a'..'f']) then Exit; {$endif} { Si la chaine a passé tous les tests, c'est bon ! } Result := True; end; end.
(*----------------------------------------------------------------------------* * Direct3D sample from DirectX 9.0 SDK December 2006 * * Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) * * * * Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 * * * * Latest version can be downloaded from: * * http://www.clootie.ru * * http://sourceforge.net/projects/delphi-dx9sdk * *----------------------------------------------------------------------------* * $Id: UVAtlasUnit.pas,v 1.15 2007/02/05 22:21:13 clootie Exp $ *----------------------------------------------------------------------------*) {$I DirectX.inc} unit UVAtlasUnit; interface uses Windows, Classes, SysUtils, StrSafe, DXTypes, Direct3D9, D3DX9, DXErr9, DXUTcore, DXUTmisc, CrackDecl; type PSingleArray = ^TSingleArray; TSingleArray = array[0..MaxInt div SizeOf(Single)-1] of Single; const COLOR_COUNT = 8; var ColorList: array [0..COLOR_COUNT-1, 0..2] of Single = ( (1.0, 0.5, 0.5), (0.5, 1.0, 0.5), (1.0, 1.0, 0.5), (0.5, 1.0, 1.0), (1.0, 0.5, 0.75), (0.0, 0.5, 0.75), (0.5, 0.5, 0.75), (0.5, 0.5, 1.0) ); const g_cfEpsilon: Single = 1e-5; //----------------------------------------------------------------------------- type PSettings = ^TSettings; TSettings = record maxcharts, width, height: Integer; maxstretch, gutter: Single; nOutputTextureIndex: Byte; bTopologicalAdjacency: Boolean; bGeometricAdjacency: Boolean; bFalseEdges: Boolean; bFileAdjacency: Boolean; szAdjacencyFilename: WideString; // : array[0..MAX_PATH-1] of WideChar; szFalseEdgesFilename: WideString; // : array[0..MAX_PATH-1] of WideChar; bUserAbort, bSubDirs, bOverwrite, bOutputTexture, bColorMesh: Boolean; bVerbose: Boolean; bOutputFilenameGiven: Boolean; szOutputFilename: WideString; //array[0..MAX_PATH-1] of WideChar; bIMT: Boolean; bTextureSignal: Boolean; bPRTSignal: Boolean; bVertexSignal: Boolean; VertexSignalUsage: TD3DDeclUsage; VertexSignalIndex: Byte; nIMTInputTextureIndex: Byte; szIMTInputFilename: WideString; // array[0..MAX_PATH-1] of WideChar; bResampleTexture: Boolean; ResampleTextureUsage: TD3DDeclUsage; ResampleTextureUsageIndex: LongWord; szResampleTextureFile: WideString; // array[0..MAX_PATH-1] of WideChar; aFiles: array of WideString; //aFiles: {Wide}TStrings; // CGrowableArray<WCHAR*> end; (* //----------------------------------------------------------------------------- CProcessedFileList = class public destructor Destroy; { for( int i=0; i<m_fileList.GetSize(); i++ ) SAFE_DELETE_ARRAY( m_fileList[i] ); m_fileList.RemoveAll(); } function IsInList(strFullPath: PWideChar): Boolean; { for( int i=0; i<m_fileList.GetSize(); i++ ) { if( wcscmp( m_fileList[i], strFullPath ) == 0 ) return true; } //return false; //} procedure Add(strFullPath: PWideChar) { WCHAR* strTemp = new WCHAR[MAX_PATH]; StringCchCopy( strTemp, MAX_PATH, strFullPath ); m_fileList.Add( strTemp ); } protected: CGrowableArray<WCHAR*> m_fileList; }; CProcessedFileList *) var g_ProcessedFileList: TStringList; //----------------------------------------------------------------------------- // Function-prototypes //----------------------------------------------------------------------------- function ParseCommandLine(var pSettings: TSettings): Boolean; function IsNextArg(var strCmdLine: PWideChar; strArg: PWideChar): Boolean; overload; function IsNextArg(const strCmdLine, strArg: WideString): Boolean; overload; function CreateNULLRefDevice: IDirect3DDevice9; procedure SearchDirForFile(const pd3dDevice: IDirect3DDevice9; strDir: PWideChar; strFile: PWideChar; const pSettings: TSettings); procedure SearchSubdirsForFile(const pd3dDevice: IDirect3DDevice9; strDir: PWideChar; strFile: PWideChar; const pSettings: TSettings); function ProcessFile(const pd3dDevice: IDirect3DDevice9; strFile: PWideChar; const pSettings: TSettings): HRESULT; procedure DisplayUsage; function TraceD3DDeclUsageToString(u: TD3DDeclUsage): PWideChar; function LoadFile(szFile: WideString; out ppBuffer: ID3DXBuffer): HRESULT; implementation function GetParamStr(P: PWideChar; var Param: WideString): PWideChar; var i, Len: Integer; Start, S, Q: PWideChar; begin while True do begin while (P[0] <> #0) and (P[0] <= ' ') do P := CharNextW(P); if (P[0] = '"') and (P[1] = '"') then Inc(P, 2) else Break; end; Len := 0; Start := P; while P[0] > ' ' do begin if P[0] = '"' then begin P := CharNextW(P); while (P[0] <> #0) and (P[0] <> '"') do begin Q := CharNextW(P); Inc(Len, Q - P); P := Q; end; if P[0] <> #0 then P := CharNextW(P); end else begin Q := CharNextW(P); Inc(Len, Q - P); P := Q; end; end; SetLength(Param, Len); P := Start; S := Pointer(Param); i := 0; while P[0] > ' ' do begin if P[0] = '"' then begin P := CharNextW(P); while (P[0] <> #0) and (P[0] <> '"') do begin Q := CharNextW(P); while P < Q do begin S[i] := P^; Inc(P); Inc(i); end; end; if P[0] <> #0 then P := CharNextW(P); end else begin Q := CharNextW(P); while P < Q do begin S[i] := P^; Inc(P); Inc(i); end; end; end; Result := P; end; function ParamCount: Integer; var P: PWideChar; S: WideString; begin Result := 0; P := GetParamStr(GetCommandLineW, S); while True do begin P := GetParamStr(P, S); if S = '' then Break; Inc(Result); end; end; function ParamStr(Index: Integer): WideString; var P: PWideChar; Buffer: array[0..260] of WideChar; begin Result := ''; if Index = 0 then SetString(Result, Buffer, GetModuleFileNameW(0, Buffer, SizeOf(Buffer))) else begin P := GetCommandLineW; while True do begin P := GetParamStr(P, Result); if (Index = 0) or (Result = '') then Break; Dec(Index); end; end; end; //-------------------------------------------------------------------------------------- // Parses the command line for parameters. See DXUTInit() for list //-------------------------------------------------------------------------------------- function ParseCommandLine(var pSettings: TSettings): Boolean; var bDisplayHelp: Boolean; strArg: WideString; // array[0..255] of WideChar; strCmdLine: WideString; nNumArgs: Integer; L: Integer; iArg: Integer; begin bDisplayHelp := False; nNumArgs := ParamCount; // WCHAR** pstrArgList = CommandLineToArgvW( GetCommandLine(), &nNumArgs ); iArg:= 1; while (iArg <= nNumArgs) do // for iArg:= 1 to nNumArgs do begin strCmdLine := ParamStr(iArg); Inc(iArg); // Handle flag args if (AnsiChar(strCmdLine[1]) in ['/', '-']) then begin strCmdLine:= Copy(strCmdLine, 2, MaxInt); if IsNextArg(strCmdLine, 'ta') then begin if (pSettings.bGeometricAdjacency or pSettings.bFileAdjacency) then begin WriteLn('Incorrect flag usage: /ta, /ga, and /fa are exclusive'); bDisplayHelp := True; Continue; end; pSettings.bTopologicalAdjacency := True; pSettings.bGeometricAdjacency := False; pSettings.bFileAdjacency := False; Continue; end; if IsNextArg(strCmdLine, 'ga') then begin if (pSettings.bTopologicalAdjacency or pSettings.bFileAdjacency) then begin WriteLn('Incorrect flag usage: /ta, /ga, and /fa are exclusive'); bDisplayHelp := True; Continue; end; pSettings.bTopologicalAdjacency := False; pSettings.bGeometricAdjacency := True; pSettings.bFileAdjacency := False; continue; end; if IsNextArg(strCmdLine, 'fa') then begin if (pSettings.bTopologicalAdjacency or pSettings.bGeometricAdjacency) then begin WriteLn('Incorrect flag usage: /ta, /ga, and /fa are exclusive'); bDisplayHelp := True; end; if (iArg+1 < nNumArgs) then begin pSettings.bTopologicalAdjacency := False; pSettings.bGeometricAdjacency := False; pSettings.bFileAdjacency := True; strArg := ParamStr(iArg); Inc(iArg); pSettings.szAdjacencyFilename := strArg; continue; end; WriteLn('Incorrect flag usage: /fa'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, 'fe') then begin if (iArg+1 < nNumArgs) then begin strArg := ParamStr(iArg); Inc(iArg); pSettings.bFalseEdges := True; pSettings.szFalseEdgesFilename := strArg; Continue; end; WriteLn('Incorrect flag usage: /fe'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, 's') then begin pSettings.bSubDirs := True; Continue; end; if IsNextArg(strCmdLine, 'c') then begin pSettings.bColorMesh := True; Continue; end; if IsNextArg(strCmdLine, 'o') then begin if pSettings.bOverwrite then begin WriteLn('Incorrect flag usage: /f and /o'); bDisplayHelp := True; Continue; end; if (iArg <= nNumArgs) then begin strArg := ParamStr(iArg); Inc(iArg); pSettings.bOutputFilenameGiven := True; pSettings.szOutputFilename:= strArg; Continue; end; WriteLn('Incorrect flag usage: /o'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, 'it') then begin if (pSettings.bPRTSignal or pSettings.bVertexSignal) then begin WriteLn('Incorrect flag usage: /it, /ip, and /iv are exclusive'); bDisplayHelp := True; Continue; end; if (iArg <= nNumArgs) then begin strArg := ParamStr(iArg); Inc(iArg); pSettings.szIMTInputFilename := strArg; pSettings.bIMT := True; pSettings.bTextureSignal := True; Continue; end; WriteLn('Incorrect flag usage: /it'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, 'ip') then begin if (pSettings.bTextureSignal or pSettings.bVertexSignal) then begin WriteLn('Incorrect flag usage: /it, /ip, and /iv are exclusive'); bDisplayHelp := True; Continue; end; if (iArg <= nNumArgs) then begin strArg := ParamStr(iArg); Inc(iArg); pSettings.szIMTInputFilename := strArg; pSettings.bIMT := True; pSettings.bPRTSignal := True; Continue; end; WriteLn('Incorrect flag usage: /ip'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, 'iv') then begin if (pSettings.bTextureSignal or pSettings.bPRTSignal) then begin WriteLn('Incorrect flag usage: /it, /ip, and /iv are exclusive'); bDisplayHelp := True; Continue; end; if (iArg <= nNumArgs) then begin strArg := ParamStr(iArg); Inc(iArg); if lstrcmpiW(PWideChar(strArg), 'COLOR') = 0 then pSettings.VertexSignalUsage := D3DDECLUSAGE_COLOR else if lstrcmpiW(PWideChar(strArg), 'NORMAL') = 0 then pSettings.VertexSignalUsage := D3DDECLUSAGE_NORMAL else if lstrcmpiW(PWideChar(strArg), 'TEXCOORD') = 0 then pSettings.VertexSignalUsage := D3DDECLUSAGE_TEXCOORD else if lstrcmpiW(PWideChar(strArg), 'TANGENT') = 0 then pSettings.VertexSignalUsage := D3DDECLUSAGE_TANGENT else if lstrcmpiW(PWideChar(strArg), 'BINORMAL') = 0 then pSettings.VertexSignalUsage := D3DDECLUSAGE_BINORMAL else begin WriteLn(WideFormat('Incorrect /iv flag usage: unknown usage parameter "%s"', [strArg])); bDisplayHelp := True; continue; end; pSettings.bIMT := True; pSettings.bVertexSignal := True; Continue; end; WriteLn('Incorrect flag usage: /ip'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, 'f') then begin pSettings.bOverwrite := True; if pSettings.bOutputFilenameGiven then begin WriteLn('Incorrect flag usage: /f and /o'); bDisplayHelp := True; end; Continue; end; if IsNextArg(strCmdLine, 't') then begin pSettings.bOutputTexture := True; continue; end; if IsNextArg(strCmdLine, 'v') then begin pSettings.bVerbose := True; Continue; end; if IsNextArg(strCmdLine, 'n') then begin if (iArg <= nNumArgs) then begin strArg := ParamStr(iArg); Inc(iArg); pSettings.maxcharts := StrToInt(strArg); Continue; end; WriteLn('Incorrect flag usage: /n'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, 'w') then begin if (iArg <= nNumArgs) then begin strArg := ParamStr(iArg); Inc(iArg); pSettings.width := StrToInt(strArg); Continue; end; WriteLn('Incorrect flag usage: /w'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, 'h') then begin if (iArg <= nNumArgs) then begin strArg := ParamStr(iArg); Inc(iArg); pSettings.height := StrToInt(strArg); Continue; end; WriteLn('Incorrect flag usage: /h'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, 'st') then begin if (iArg <= nNumArgs) then begin strArg := ParamStr(iArg); Inc(iArg); pSettings.maxstretch := StrToFloat(strArg); Continue; end; WriteLn('Incorrect flag usage: /st'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, 'rt') then begin if (iArg+1 < nNumArgs) then begin pSettings.bResampleTexture := True; strArg := ParamStr(iArg); Inc(iArg); pSettings.szResampleTextureFile := strArg; Continue; end; WriteLn('Incorrect flag usage: /rt'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, 'uvi') then begin if (iArg+1 < nNumArgs) then begin strArg := ParamStr(iArg); Inc(iArg); pSettings.nOutputTextureIndex := StrToInt(strArg); continue; end; WriteLn('Incorrect flag usage: /uvi'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, 'rtu') then begin if (iArg+1 < nNumArgs) then begin strArg := ParamStr(iArg); Inc(iArg); if lstrcmpiW(PWideChar(strArg), 'NORMAL') = 0 then pSettings.ResampleTextureUsage := D3DDECLUSAGE_NORMAL else if lstrcmpiW(PWideChar(strArg), 'POSITION') = 0 then pSettings.ResampleTextureUsage := D3DDECLUSAGE_POSITION else if lstrcmpiW(PWideChar(strArg), 'TEXCOORD') = 0 then pSettings.ResampleTextureUsage := D3DDECLUSAGE_TEXCOORD else if lstrcmpiW(PWideChar(strArg), 'TANGENT') = 0 then pSettings.ResampleTextureUsage := D3DDECLUSAGE_TANGENT else if lstrcmpiW(PWideChar(strArg), 'BINORMAL') = 0 then pSettings.ResampleTextureUsage := D3DDECLUSAGE_BINORMAL else begin WriteLn(Format('Incorrect /rtu flag usage: unknown usage parameter "%s"', [strArg])); bDisplayHelp := True; Continue; end; Continue; end; WriteLn('Incorrect flag usage: /rtu'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, 'rti') then begin if (iArg+1 < nNumArgs) then begin strArg := ParamStr(iArg); Inc(iArg); pSettings.ResampleTextureUsageIndex := StrToInt(strArg); Continue; end; WriteLn('Incorrect flag usage: /rti'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, 'g') then begin if (iArg <= nNumArgs) then begin strArg := ParamStr(iArg); Inc(iArg); pSettings.gutter := StrToFloat(strArg); Continue; end; WriteLn('Incorrect flag usage: /g'); bDisplayHelp := True; Continue; end; if IsNextArg(strCmdLine, '?') then begin DisplayUsage; Result:= False; Exit; end; // Unrecognized flag WriteLn(WideFormat('Unrecognized or incorrect flag usage: %s', [strCmdLine])); bDisplayHelp := True; end else begin // Handle non-flag args as seperate input files // pSettings.aFiles.Add(strCmdLine); L:= Length(pSettings.aFiles); SetLength(pSettings.aFiles, L+1); pSettings.aFiles[L]:= strCmdLine; Continue; end; end; // "for / while" end if (Length(pSettings.aFiles) = 0) then begin DisplayUsage; Result:= False; Exit; end; if bDisplayHelp then begin WriteLn('Type "UVAtlas.exe /?" for a complete list of options'); Result:= False; Exit; end; Result:= True; end; //-------------------------------------------------------------------------------------- function IsNextArg(var strCmdLine: PWideChar; strArg: PWideChar): Boolean; var nArgLen: Integer; begin Result:= True; nArgLen := lstrlenw{wcslen}(strArg); // if _wcsnicmp(strCmdLine, strArg, nArgLen) == 0 && strCmdLine[nArgLen] == 0 ) if (lstrcmpiW(strCmdLine, strArg{, nArgLen}) = 0) and (strCmdLine[nArgLen] = #0) then Exit; Result:= False; end; function IsNextArg(const strCmdLine, strArg: WideString): Boolean; overload; begin Result:= lstrcmpiW(PWideChar(strCmdLine), PWideChar(strArg)) = 0; end; //-------------------------------------------------------------------------------------- function GetNextArg(var strCmdLine: PWideChar; strArg: PWideChar; cchArg: Integer): Boolean; var spacelen: LongWord; strSpace: PWideChar; nArgLen: Integer; begin // Place NULL terminator in strFlag after current token strSpace := strCmdLine; while (strSpace^ <> #0) and (strSpace^ in [WideChar(' ')]) // iswspace(*strSpace) ) do Inc(strSpace); V_(StringCchCopy(strArg, 256, strSpace)); spacelen := strSpace - strCmdLine; strSpace := strArg + (strSpace - strCmdLine); while (strSpace^ <> #0) and not (strSpace^ in [WideChar(' ')]) // iswspace(*strSpace) ) // while( *strSpace && !iswspace(*strSpace) ) do Inc(strSpace); strSpace^ := #0; // Update strCmdLine nArgLen := lstrlenW(strArg); // wcslen strCmdLine := strCmdLine + nArgLen + spacelen; Result:= (nArgLen > 0); end; //-------------------------------------------------------------------------------------- procedure SearchSubdirsForFile(const pd3dDevice: IDirect3DDevice9; strDir: PWideChar; strFile: PWideChar; const pSettings: TSettings); var strFullPath: WideString; strSearchDir: WideString; fileData: TWin32FindDataW; hFindFile: THandle; bSuccess: Boolean; begin // First search this dir for the file SearchDirForFile(pd3dDevice, strDir, strFile, pSettings); if (pSettings.bUserAbort) then Exit; // Then search this dir for other dirs and recurse strSearchDir := WideString(strDir) + '*'; ZeroMemory(@fileData, SizeOf(TWin32FindDataW)); {$IFDEF FPC} hFindFile := FindFirstFileW(PWideChar(strSearchDir), @fileData); {$ELSE} hFindFile := FindFirstFileW(PWideChar(strSearchDir), fileData); {$ENDIF} if (hFindFile <> INVALID_HANDLE_VALUE) then begin bSuccess := True; while bSuccess do begin if (fileData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY <> 0) then begin // Don't process '.' and '..' dirs if (fileData.cFileName[0] <> '.') then begin strFullPath:= strDir + WideString(fileData.cFileName) + '\'; SearchSubdirsForFile(pd3dDevice, PWideChar(strFullPath), strFile, pSettings); end; end; {$IFDEF FPC} bSuccess := FindNextFileW(hFindFile, @fileData); {$ELSE} bSuccess := FindNextFileW(hFindFile, fileData); {$ENDIF} if (pSettings.bUserAbort) then Break; end; Windows.FindClose(hFindFile); end; end; //-------------------------------------------------------------------------------------- procedure SearchDirForFile(const pd3dDevice: IDirect3DDevice9; strDir: PWideChar; strFile: PWideChar; const pSettings: TSettings); var strFullPath: WideString; strSearchDir: WideString; fileData: TWin32FindDataW; hFindFile: THandle; bSuccess: Boolean; begin strSearchDir:= WideString(strDir) + strFile; WriteLn(WideFormat('Searching dir %s for %s', [strDir, strFile])); ZeroMemory(@fileData, SizeOf(TWin32FindDataW)); {$IFDEF FPC} hFindFile := FindFirstFileW(PWideChar(strSearchDir), @fileData); {$ELSE} hFindFile := FindFirstFileW(PWideChar(strSearchDir), fileData); {$ENDIF} if (hFindFile <> INVALID_HANDLE_VALUE) then begin bSuccess := True; while bSuccess do begin if (fileData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0) then begin strFullPath:= strDir + WideString(fileData.cFileName); if (g_ProcessedFileList.IndexOf(strFullPath) = -1) then ProcessFile(pd3dDevice, PWideChar(strFullPath), pSettings); if pSettings.bOutputFilenameGiven // only process 1 file if this option is on then Break; end; {$IFDEF FPC} bSuccess := FindNextFileW(hFindFile, @fileData); {$ELSE} bSuccess := FindNextFileW(hFindFile, fileData); {$ENDIF} if pSettings.bUserAbort then Break; end; Windows.FindClose(hFindFile); end else WriteLn('File(s) not found.'); end; function CheckMeshValidation(const pMesh: ID3DXMesh; out pMeshOut: ID3DXMesh; out ppAdjacency: PDWORD; bTopologicalAdjacency, bGeometricAdjacency: Boolean; const pOrigAdj: ID3DXBuffer): Boolean; var hr: HRESULT; pAdjacencyIn: PDWORD; pAdjacencyAlloc: PDWORD; pErrorsAndWarnings: ID3DXBuffer; s: PAnsiChar; label FAIL; begin Result := True; pAdjacencyIn := nil; pAdjacencyAlloc := nil; if bTopologicalAdjacency or bGeometricAdjacency then begin //todo: Fill bug report on NEW DWORD[...] should be " pNewAdjacency = new DWORD[pTempMesh->GetNumFaces() * 3];" // pAdjacencyAlloc = new DWORD[pMesh->GetNumFaces() * sizeof(DWORD)*3]; GetMem(pAdjacencyAlloc, SizeOf(DWORD)*pMesh.GetNumFaces*3); pAdjacencyIn := pAdjacencyAlloc; end; if bTopologicalAdjacency then begin hr := pMesh.ConvertPointRepsToAdjacency(nil, pAdjacencyIn); if FAILED(hr) then begin WriteLn(WideFormat('ConvertPointRepsToAdjacency() failed: %s', [DXGetErrorString9(hr)])); Result := False; goto FAIL; end; end else if bGeometricAdjacency then begin hr := pMesh.GenerateAdjacency(g_cfEpsilon, pAdjacencyIn); if FAILED(hr) then begin WriteLn(WideFormat('GenerateAdjacency() failed: %s', [DXGetErrorString9(hr)])); Result := False; goto FAIL; end; end else if Assigned(pOrigAdj) then begin pAdjacencyIn := PDWORD(pOrigAdj.GetBufferPointer); end; hr := D3DXValidMesh(pMesh, pAdjacencyIn, @pErrorsAndWarnings); if (nil <> pErrorsAndWarnings) then begin s := PAnsiChar(pErrorsAndWarnings.GetBufferPointer); WriteLn(WideFormat('%s', [s])); SAFE_RELEASE(pErrorsAndWarnings); end; if FAILED(hr) then begin WriteLn(WideFormat('D3DXValidMesh() failed: %s. Attempting D3DXCleanMesh()', [DXGetErrorString9(hr)])); hr := D3DXCleanMesh(D3DXCLEAN_SIMPLIFICATION, pMesh, pAdjacencyIn, pMeshOut, pAdjacencyIn, @pErrorsAndWarnings); if (nil <> pErrorsAndWarnings) then begin s := PAnsiChar(pErrorsAndWarnings.GetBufferPointer); WriteLn(WideFormat('%s', [s])); end; if FAILED(hr) then begin WriteLn(WideFormat('D3DXCleanMesh() failed: %s', [DXGetErrorString9(hr)])); Result := False; goto FAIL; end else begin WriteLn(WideFormat('D3DXCleanMesh() succeeded: %s', [DXGetErrorString9(hr)])); end; end else begin pMeshOut := pMesh; // (*pMeshOut).AddRef; end; FAIL: SAFE_RELEASE(pErrorsAndWarnings); if (Result = False) then begin SAFE_DELETE(pAdjacencyAlloc); // SAFE_DELETE(pMeshOut); //todo: April: Bug report - SAFE_RELEASE pMeshOut:= nil; end; ppAdjacency := pAdjacencyIn; end; //-------------------------------------------------------------------------------------- var {static} s_fLastTime: Double = 0.0; function UVAtlasCallback(fPercentDone: Single; lpUserContext: Pointer): HRESULT; stdcall; var fTime: Double; begin fTime := DXUTGetGlobalTimer.GetTime; if (fTime - s_fLastTime > 0.1) then begin WriteLn(WideFormat('%.2f%% '#9, [fPercentDone*100])); s_fLastTime := fTime; end; Result:= S_OK; end; //-------------------------------------------------------------------------------------- function PerVertexPRTIMT(const pMesh: ID3DXMesh; pPRTBuffer: ID3DXPRTBuffer; const cuNumCoeffs: LongWord; out ppIMTData: ID3DXBuffer): HRESULT; var pPRTSignal: PSingle; uStride: LongWord; hr2: HRESULT; label FAIL; begin pPRTSignal := nil; if not (Assigned(pMesh) and {Assigned(ppIMTData) and }Assigned(pPRTBuffer)) then begin WriteLn('Error: pMesh, ppIMTData and pPRTBuffer must not be NULL'); Result := D3DERR_INVALIDCALL; goto FAIL; end; if (pPRTBuffer.IsTexture) then begin WriteLn('Error: pPRTBuffer must be per-vertex'); Result := D3DERR_INVALIDCALL; goto FAIL; end; uStride := pPRTBuffer.GetNumChannels * pPRTBuffer.GetNumCoeffs * SizeOf(Single); Result := pPRTBuffer.LockBuffer(0, pPRTBuffer.GetNumSamples, pPRTSignal); if FAILED(Result) then begin WriteLn(WideFormat('ID3DXPRTBuffer::LockBuffer() failed: %s', [DXGetErrorString9(Result)])); goto FAIL; end; Result := D3DXComputeIMTFromPerVertexSignal(pMesh, pPRTSignal, cuNumCoeffs, uStride, 0, nil, nil, ppIMTData); if FAILED(Result) then begin WriteLn(WideFormat('D3DXComputeIMTFromVertexSignal() failed: %s', [DXGetErrorString9(Result)])); goto FAIL; end; FAIL: if Assigned(pPRTSignal) then begin hr2 := pPRTBuffer.UnlockBuffer; if FAILED(hr2) then begin WriteLn(WideFormat('ID3DXPRTBuffer::UnlockVertexBuffer() failed: %s!', [DXGetErrorString9(hr2)])); end; pPRTSignal := nil; end; SAFE_RELEASE(pPRTBuffer); //todo: ???????? - maybe handle this in Delphi differently end; //-------------------------------------------------------------------------------------- function PerVertexIMT(const pMesh: ID3DXMesh; const pDecl: TFVFDeclaration; usage: TD3DDeclUsage; usageIndex: DWORD; Crack: CD3DXCrackDecl; out ppIMTData: ID3DXBuffer): HRESULT; var pfVertexData: PSingle; elmt: PD3DVertexElement9; uSignalDimension: LongWord; hr2: HRESULT; label FAIL; begin pfVertexData := nil; if not Assigned(pMesh) then // or not Assigned(ppIMTData) begin WriteLn('Error: some of pMesh and ppIMTData are == NULL'); Result := D3DERR_INVALIDCALL; goto FAIL; end; elmt := GetDeclElement(@pDecl, usage, usageIndex); if (nil = elmt) then begin WriteLn('Error: Requested vertex data not found in mesh'); Result := E_FAIL; goto FAIL; end; uSignalDimension := Crack.GetFields(elmt); Result := pMesh.LockVertexBuffer(D3DLOCK_NOSYSLOCK, Pointer(pfVertexData)); if FAILED(Result) then begin WriteLn(WideFormat('ID3DXMesh.LockVertexBuffer() failed: %s', [DXGetErrorString9(Result)])); goto FAIL; end; Result := D3DXComputeIMTFromPerVertexSignal(pMesh, @PSingleArray(pfVertexData)[elmt.Offset], uSignalDimension, pMesh.GetNumBytesPerVertex, 0, nil, nil, ppIMTData); if FAILED(Result) then begin WriteLn(WideFormat('D3DXComputeIMTFromPerVertexSignal() failed: %s', [DXGetErrorString9(Result)])); goto FAIL; end; FAIL: if Assigned(pfVertexData) then begin hr2 := pMesh.UnlockVertexBuffer; if FAILED(hr2) then begin WriteLn(WideFormat('pMesh.UnlockVertexBuffer() failed: %s!', [DXGetErrorString9(hr2)])); end; pfVertexData := nil; end; end; //-------------------------------------------------------------------------------------- function TextureSignalIMT(const pDevice: IDirect3DDevice9; const pMesh: ID3DXMesh; dwTextureIndex: DWORD; const szFilename: PWideChar; out ppIMTData: ID3DXBuffer): HRESULT; var pTexture: IDirect3DTexture9; begin if not Assigned(pMesh) or not Assigned(szFilename) then // or !ppIMTData) begin WriteLn('rror: some of pMesh, szFilename and ppIMTData are == NULL'); Result := D3DERR_INVALIDCALL; Exit; end; Result := D3DXCreateTextureFromFileExW(pDevice, szFilename, D3DX_FROM_FILE, D3DX_FROM_FILE, 1, 0, D3DFMT_A32B32G32R32F, D3DPOOL_SCRATCH, D3DX_DEFAULT, D3DX_DEFAULT, 0, nil, nil, pTexture); if FAILED(Result) then begin WriteLn(WideFormat('Error: failed to load %s: %s', [szFilename, DXGetErrorString9(Result)])); Exit; end; Result := D3DXComputeIMTFromTexture(pMesh, pTexture, dwTextureIndex, 0, nil, nil, ppIMTData); if FAILED(Result) then begin WriteLn(WideFormat('D3DXComputeIMTFromTexture() failed: %s', [DXGetErrorString9(Result)])); Exit; end; end; //-------------------------------------------------------------------------------------- function PRTSignalIMT(const pMesh: ID3DXMesh; dwTextureIndex: DWORD; pSettings: PSettings; const cuNumCoeffs: LongWord; out ppIMTData: ID3DXBuffer): HRESULT; var pPRTSignal: PSingle; pPRTBuffer: ID3DXPRTBuffer; cuDimension: LongWord; hr2: HRESULT; label FAIL, DONE; begin pPRTSignal := nil; if not Assigned(pMesh) or not Assigned(pSettings) then // or not Assigned(ppIMTData) begin WriteLn('Error: pMesh, pSettings and ppIMTData must not be NULL'); Result := D3DERR_INVALIDCALL; goto FAIL; end; Result := D3DXLoadPRTBufferFromFileW(PWideChar(pSettings.szIMTInputFilename), pPRTBuffer); if FAILED(Result) then begin WriteLn(WideFormat('Error: failed to load %s: %s', [pSettings.szIMTInputFilename, DXGetErrorString9(Result)])); goto FAIL; end; if not pPRTBuffer.IsTexture then begin Result := PerVertexPRTIMT(pMesh, pPRTBuffer, cuNumCoeffs, ppIMTData); goto DONE; end; cuDimension := pPRTBuffer.GetNumChannels * pPRTBuffer.GetNumCoeffs; Result := pPRTBuffer.LockBuffer(0, pPRTBuffer.GetNumSamples, pPRTSignal); if FAILED(Result) then begin WriteLn(WideFormat('ID3DXPRTBuffer.LockBuffer() failed: %s', [DXGetErrorString9(Result)])); goto FAIL; end; Result := D3DXComputeIMTFromPerTexelSignal(pMesh, dwTextureIndex, pPRTSignal, pPRTBuffer.GetWidth, pPRTBuffer.GetHeight, cuNumCoeffs, cuDimension, 0, nil, nil, ppIMTData); if FAILED(Result) then begin WriteLn(WideFormat('D3DXComputeIMTFromPerTexelSignal() failed: %s', [DXGetErrorString9(Result)])); goto FAIL; end; FAIL: DONE: if Assigned(pPRTSignal) then begin hr2 := pPRTBuffer.UnlockBuffer; if FAILED(hr2) then begin WriteLn(WideFormat('"ID3DXPRTBuffer.UnlockVertexBuffer() failed: %s', [DXGetErrorString9(Result)])); end; pPRTSignal := nil; end; SAFE_RELEASE(pPRTBuffer); end; //-------------------------------------------------------------------------------------- function CopyUVs(const pMeshFrom: ID3DXMesh; FromUsage: TD3DDeclUsage; FromIndex: LongWord; const pMeshTo: ID3DXMesh; ToUsage: TD3DDeclUsage; ToIndex: LongWord; const pVertexRemapArray: ID3DXBuffer): HRESULT; var declFrom: TFVFDeclaration; declTo: TFVFDeclaration; declCrackFrom: CD3DXCrackDecl; declCrackTo: CD3DXCrackDecl; pVBFrom: IDirect3DVertexBuffer9; pVBDataFrom: PChar; pVBTo: IDirect3DVertexBuffer9; pVBDataTo: PChar; pdwVertexMapping: PDWORD; NBPVFrom: DWORD; uNumVertsTo: Cardinal; NBPVTo: DWORD; viFrom: LongWord; uvFrom: TD3DXVector2; viTo: LongWord; begin declCrackFrom:= CD3DXCrackDecl.Create; declCrackTo:= CD3DXCrackDecl.Create; pVBDataFrom := nil; pVBDataTo := nil; pdwVertexMapping := nil; if Assigned(pVertexRemapArray) then pdwVertexMapping := PDWORD(pVertexRemapArray.GetBufferPointer); Result:= pMeshFrom.GetDeclaration(declFrom); if V_Failed(Result) then Exit; Result:= declCrackFrom.SetDeclaration(@declFrom); if V_Failed(Result) then Exit; Result:= pMeshTo.GetDeclaration(declTo); if V_Failed(Result) then Exit; Result:= declCrackTo.SetDeclaration(@declTo); if V_Failed(Result) then Exit; Result:= pMeshFrom.GetVertexBuffer(pVBFrom); if V_Failed(Result) then Exit; Result:= pVBFrom.Lock(0, 0, Pointer(pVBDataFrom), D3DLOCK_READONLY); if V_Failed(Result) then Exit; NBPVFrom := pMeshFrom.GetNumBytesPerVertex; declCrackFrom.SetStreamSource(0, pVBDataFrom, NBPVFrom); Result:= pMeshTo.GetVertexBuffer(pVBTo); if V_Failed(Result) then Exit; Result:= pVBTo.Lock(0, 0, Pointer(pVBDataTo), 0 ); if V_Failed(Result) then Exit; uNumVertsTo := pMeshTo.GetNumVertices; NBPVTo := pMeshTo.GetNumBytesPerVertex; declCrackTo.SetStreamSource(0, Pointer(pVBDataTo), NBPVTo); for viTo := 0 to uNumVertsTo - 1 do begin // Use the vertex remap if supplied if Assigned(pdwVertexMapping) then viFrom := PDWordArray(pdwVertexMapping)[viTo] else viFrom := viTo; declCrackFrom.DecodeSemantic(FromUsage, FromIndex, viFrom, PSingle(@uvFrom), 2); declCrackTo.EncodeSemantic(ToUsage, ToIndex, viTo, PSingle(@uvFrom), 2); end; pVBFrom.Unlock; SAFE_RELEASE(pVBFrom); Result:= S_OK; end; //-------------------------------------------------------------------------------------- function ProcessFile(const pd3dDevice: IDirect3DDevice9; strFile: PWideChar; const pSettings: TSettings): HRESULT; var pOrigMesh, pMesh, pMeshValid, pMeshResult, pTexResampleMesh: ID3DXMesh; pMaterials, pEffectInstances, pFacePartitioning, pVertexRemapArray: ID3DXBuffer; pIMTBuffer, pOrigAdj, pFalseEdges: ID3DXBuffer; pGutterHelper: ID3DXTextureGutterHelper; pOriginalTex, pResampledTex: IDirect3DTexture9; pIMTArray: PSingle; pAdjacency: PDWORD; pdwAttributeOut: PDWordArray; declResamp: TFVFDeclaration; decl: TFVFDeclaration; uLen: LongWord; dwNumMaterials, dwNumVerts, dwNumFaces: DWORD; stretchOut: Single; numchartsOut: LongWord; strResult, strResultTexture, szResampledTextureFile: WideString; szResampleTextureFileA, szResampledTextureFileA: PAnsiChar; declCrack: CD3DXCrackDecl; declElem: TD3DVertexElement9; pVertexData: Pointer; pGeneratedMaterials: array[0..COLOR_COUNT-1] of TD3DXMaterial; ustrLen, uPeriodPos: size_t; i: Integer; pdwChartMapping: PDWordArray; dwNumber: DWORD; pMaterialsStruct: PD3DXMaterial; pNormal: PD3DVertexElement9; normal: array[0..2] of Single; texcoords: array[0..1] of Single; strOutputFilename: array[0..MAX_PATH-1] of WideChar; TextureInfo: TD3DXImageInfo; index: DWORD; pDeclElement: PD3DVertexElement9; cdwAdjacencySize: DWORD; cdwFalseEdgesSize: DWORD; pFalseEdgesData: PDWORD; type PD3DXMaterialArray = ^TD3DXMaterialArray; TD3DXMaterialArray = array[0..0] of TD3DXMaterial; label FAIL; begin declCrack:= CD3DXCrackDecl.Create; pIMTArray := nil; pAdjacency := nil; pdwAttributeOut := nil; numchartsOut := 0; szResampleTextureFileA := nil; szResampledTextureFileA := nil; pVertexData := nil; // add _result before the last period in the file name // wprintf( L"Processing file %s\n", strFile, strResult ); WriteLn(WideFormat('Processing file %s', [strFile, strResult])); //todo: two parameters instead of single ???? Result:= StringCchLength(strFile, 1024, ustrLen); if FAILED(Result) then begin WriteLn('Unable to get string length.'); goto FAIL; end; uPeriodPos := ustrLen; for i := 0 to ustrLen - 1 do if (strFile[i] = '.') then uPeriodPos := i; strResult:= Copy(strFile, 0, uPeriodPos) + '_result' + (strFile + uPeriodPos); strResultTexture:= Copy(strFile, 0, uPeriodPos) + '_texture' + (strFile + uPeriodPos); Result:= D3DXLoadMeshFromXW(strFile, D3DXMESH_32BIT or D3DXMESH_SYSTEMMEM, pd3dDevice, @pOrigAdj, @pMaterials, @pEffectInstances, @dwNumMaterials, pOrigMesh); if FAILED(Result) then begin WriteLn('Unable to open mesh'); goto FAIL; end; Result:= pOrigMesh.GetDeclaration(decl); if FAILED(Result) then goto FAIL; uLen := D3DXGetDeclLength(@decl); pDeclElement := GetDeclElement(@decl, D3DDECLUSAGE_TEXCOORD, pSettings.nOutputTextureIndex); if ((pDeclElement <> nil) and (declCrack.GetFields(pDeclElement) < 2)) then begin WriteLn(WideFormat('D3DDECLUSAGE_TEXCOORD[%d] must have at least 2 components. '+ 'Use /uvi to change the index', [pSettings.nOutputTextureIndex])); Result := E_FAIL; goto FAIL; end; if (pDeclElement = nil) then begin WriteLn('Adding texture coordinate slot to vertex decl.'); if (uLen = MAX_FVF_DECL_SIZE) then begin WriteLn('Not enough room to store texture coordinates in mesh'); Result := E_FAIL; goto FAIL; end; declElem.Stream := 0; declElem._Type := D3DDECLTYPE_FLOAT2; declElem.Method := D3DDECLMETHOD_DEFAULT; declElem.Usage := D3DDECLUSAGE_TEXCOORD; declElem.UsageIndex := pSettings.nOutputTextureIndex; AppendDeclElement(@declElem, decl); end; Result := declCrack.SetDeclaration(@decl); if FAILED(Result) then goto FAIL; Result := pOrigMesh.CloneMesh(D3DXMESH_32BIT or D3DXMESH_SYSTEMMEM, @decl, pd3dDevice, pMesh); if FAILED(Result) then begin WriteLn('Unable to clone mesh.'); goto FAIL; end; if (pSettings.bFileAdjacency) then begin WriteLn(WideFormat('Loading adjacency from file %s', [pSettings.szAdjacencyFilename])); SAFE_RELEASE(pOrigAdj); Result := LoadFile(pSettings.szAdjacencyFilename, pOrigAdj); if FAILED(Result) then begin WriteLn(WideFormat('Unable to load adjacency from file: %s!', [pSettings.szAdjacencyFilename])); goto FAIL; end; cdwAdjacencySize := 3*pMesh.GetNumFaces*SizeOf(DWORD); if (cdwAdjacencySize <> pOrigAdj.GetBufferSize) then begin WriteLn(WideFormat('Adjacency from file: %s is incorrect size: %d. Expected: %d!', [pSettings.szAdjacencyFilename, pOrigAdj.GetBufferSize, cdwAdjacencySize])); goto FAIL; end; end; if not CheckMeshValidation(pMesh, pMeshValid, pAdjacency, pSettings.bTopologicalAdjacency, pSettings.bGeometricAdjacency, pOrigAdj) then begin WriteLn('Unable to clean mesh'); goto FAIL; end; WriteLn(WideFormat('Face count: %d', [pMesh.GetNumFaces])); WriteLn(WideFormat('Vertex count: %d', [pMesh.GetNumVertices])); if (pSettings.maxcharts <> 0) then WriteLn(WideFormat('Max charts: %d', [pSettings.maxcharts])) else WriteLn(WideFormat('Max charts: Atlas will be parameterized based solely on stretch', [])); WriteLn(WideFormat('Max stretch: %f', [pSettings.maxstretch])); WriteLn(WideFormat('Texture size: %d x %d', [pSettings.width, pSettings.height])); WriteLn(WideFormat('Gutter size: %f texels', [pSettings.gutter])); WriteLn(WideFormat('Updating UVs in mesh''s D3DDECLUSAGE_TEXCOORD[%d]', [pSettings.nOutputTextureIndex])); if (pSettings.bIMT) then begin if pSettings.bTextureSignal then begin WriteLn(WideFormat('Computing IMT from file %s', [pSettings.szIMTInputFilename])); Result := TextureSignalIMT(pd3dDevice, pMesh, 0, PWideChar(pSettings.szIMTInputFilename), pIMTBuffer); end else if pSettings.bPRTSignal then begin WriteLn(WideFormat('Computing IMT from file %s', [pSettings.szIMTInputFilename])); Result := PRTSignalIMT(pMesh, pSettings.nIMTInputTextureIndex, @pSettings, 3, pIMTBuffer); end else if pSettings.bVertexSignal then begin WriteLn(WideFormat('Computing IMT from %s, Index %d', [declCrack.DeclUsageToString(pSettings.VertexSignalUsage), pSettings.VertexSignalIndex])); Result := PerVertexIMT(pMesh, decl, pSettings.VertexSignalUsage, pSettings.VertexSignalIndex, @declCrack, pIMTBuffer); end else begin Result := E_FAIL; Assert(False); end; if FAILED(Result) then begin WriteLn(WideFormat('warn: IMT computation failed: %s', [DXGetErrorString9(Result)])); WriteLn('warn: proceeding w/out IMT...'); end else begin pIMTArray := pIMTBuffer.GetBufferPointer; end; end; if (pSettings.bFalseEdges) then begin WriteLn(WideFormat('Loading false edges from file %s', [pSettings.szFalseEdgesFilename])); Result := LoadFile(pSettings.szFalseEdgesFilename, pFalseEdges); if FAILED(Result) then begin WriteLn(WideFormat('Unable to load false edges from file: %s!', [pSettings.szFalseEdgesFilename])); goto FAIL; end; cdwFalseEdgesSize := 3*pMeshValid.GetNumFaces*SizeOf(DWORD); if (cdwFalseEdgesSize <> pFalseEdges.GetBufferSize) then begin WriteLn(WideFormat('False edges from file: %s is incorrect size: %d. Expected: %d!', [pSettings.szFalseEdgesFilename, pFalseEdges.GetBufferSize, cdwFalseEdgesSize])); goto FAIL; end; end; WriteLn('Executing D3DXUVAtlasCreate() on mesh...'); if Assigned(pFalseEdges) then pFalseEdgesData := pFalseEdges.GetBufferPointer() else pFalseEdgesData := nil; Result := D3DXUVAtlasCreate(pMeshValid, pSettings.maxcharts, pSettings.maxstretch, pSettings.width, pSettings.height, pSettings.gutter, pSettings.nOutputTextureIndex, pAdjacency, pFalseEdgesData, pIMTArray, UVAtlasCallback, 0.0001, nil, D3DXUVATLAS_DEFAULT, pMeshResult, @pFacePartitioning, @pVertexRemapArray, @stretchOut, @numchartsOut); if FAILED(Result) then begin WriteLn('UV Atlas creation failed: '); case Result of D3DXERR_INVALIDMESH: WriteLn('Non-manifold mesh'); else if (numchartsOut <> 0) and (pSettings.maxcharts < Integer(numchartsOut)) then WriteLn(WideFormat('Minimum number of charts is %d', [numchartsOut])); WriteLn(WideFormat('Error code %s, check debug output for more detail', [DXGetErrorString9(Result)])); WriteLn(WideFormat('Try increasing the max number of charts or max stretch', [])); end; goto FAIL; end; WriteLn(WideFormat('D3DXUVAtlasCreate() succeeded', [])); WriteLn(WideFormat('Output # of charts: %d', [numchartsOut])); WriteLn(WideFormat('Output stretch: %f', [stretchOut])); if pSettings.bResampleTexture then begin WriteLn(WideFormat('Resampling texture %s using data from %s[%d]', [pSettings.szResampleTextureFile, TraceD3DDECLUSAGEtoString(pSettings.ResampleTextureUsage), pSettings.ResampleTextureUsageIndex])); // Read the original texture from the file Result := D3DXCreateTextureFromFileExW(pd3dDevice, PWideChar(pSettings.szResampleTextureFile), D3DX_FROM_FILE, D3DX_FROM_FILE, 1, 0, D3DFMT_FROM_FILE, D3DPOOL_SCRATCH, D3DX_DEFAULT, D3DX_DEFAULT, 0, @TextureInfo, nil, pOriginalTex); if FAILED(Result) then begin WriteLn('Texture creation and loading failed: '); case Result of D3DERR_NOTAVAILABLE: WriteLn('This device does not support the queried technique.'); D3DERR_OUTOFVIDEOMEMORY: WriteLn('Microsoft Direct3D does not have enough display memory to perform the operation.'); D3DERR_INVALIDCALL: WriteLn('The method call is invalid. For example, a method''s parameter may have an invalid value.'); D3DXERR_INVALIDDATA: WriteLn('The data is invalid.'); E_OUTOFMEMORY: WriteLn('Out of memory'); else WriteLn(WideFormat('Error code %s, check debug output for more detail', [DXGetErrorString9(Result)])); end; goto FAIL; end; // Create a new blank texture that is the same size Result := D3DXCreateTexture(pd3dDevice, TextureInfo.Width, TextureInfo.Height, 1, 0, TextureInfo.Format, D3DPOOL_SCRATCH, pResampledTex); if FAILED(Result) then begin WriteLn('Texture creation failed:'); case Result of D3DERR_INVALIDCALL: WriteLn('The method call is invalid. For example, a method''s parameter may have an invalid value.'); D3DERR_NOTAVAILABLE: WriteLn('This device does not support the queried technique.'); D3DERR_OUTOFVIDEOMEMORY: WriteLn('Microsoft Direct3D does not have enough display memory to perform the operation.'); E_OUTOFMEMORY: WriteLn('Out of memory'); else WriteLn(WideFormat('Error code %s, check debug output for more detail', [DXGetErrorString9(Result)])); end; goto FAIL; end; // Get the decl of the original mesh Result := pMeshResult.GetDeclaration(declResamp); if FAILED(Result) then goto FAIL; uLen := D3DXGetDeclLength(@declResamp); // Ensure the decl has a D3DDECLUSAGE_TEXCOORD:0 if (nil = GetDeclElement(@declResamp, D3DDECLUSAGE_TEXCOORD, 0)) then begin if (uLen = MAX_FVF_DECL_SIZE) then begin WriteLn('Not enough room to store texture coordinates in mesh'); Result := E_FAIL; goto FAIL; end; declElem.Stream := 0; declElem._Type := D3DDECLTYPE_FLOAT2; declElem.Method := D3DDECLMETHOD_DEFAULT; declElem.Usage := D3DDECLUSAGE_TEXCOORD; declElem.UsageIndex := 0; AppendDeclElement(@declElem, declResamp); end; // Ensure the decl has a D3DDECLUSAGE_TEXCOORD:1 if (nil = GetDeclElement(@declResamp, D3DDECLUSAGE_TEXCOORD, 1)) then begin if (uLen = MAX_FVF_DECL_SIZE) then begin WriteLn('Not enough room to store texture coordinates in mesh'); Result := E_FAIL; goto FAIL; end; declElem.Stream := 0; declElem._Type := D3DDECLTYPE_FLOAT2; declElem.Method := D3DDECLMETHOD_DEFAULT; declElem.Usage := D3DDECLUSAGE_TEXCOORD; declElem.UsageIndex := 1; AppendDeclElement(@declElem, declResamp); end; // Clone the original mesh to ensure it has 2 D3DDECLUSAGE_TEXCOORD slots Result := pMeshResult.CloneMesh(D3DXMESH_32BIT or D3DXMESH_SYSTEMMEM, @declResamp, pd3dDevice, pTexResampleMesh); if FAILED(Result) then begin WriteLn('Unable to clone mesh.'); goto FAIL; end; // Put new UVAtlas parameterization in D3DDECLUSAGE_TEXCOORD:0 CopyUVs(pMeshResult, D3DDECLUSAGE_TEXCOORD, pSettings.nOutputTextureIndex, // from pTexResampleMesh, D3DDECLUSAGE_TEXCOORD, 0, nil); // to // Put original texture parameterization to D3DDECLUSAGE_TEXCOORD:1 CopyUVs(pOrigMesh, pSettings.ResampleTextureUsage, pSettings.ResampleTextureUsageIndex, // from pTexResampleMesh, D3DDECLUSAGE_TEXCOORD, 1, pVertexRemapArray); // to // Create a gutter helper Result := D3DXCreateTextureGutterHelper(TextureInfo.Width, TextureInfo.Height, pTexResampleMesh, pSettings.gutter, pGutterHelper); if FAILED(Result) then begin WriteLn('Gutter Helper creation failed:'); case Result of D3DERR_INVALIDCALL: WriteLn('The method call is invalid. For example, a method''s parameter may have an invalid value.'); E_OUTOFMEMORY: WriteLn('Out of memory'); else WriteLn(WideFormat('Error code %s, check debug output for more detail', [DXGetErrorString9(Result)])); end; goto FAIL; end; // Call ResampleTex() to convert the texture from the original parameterization in D3DDECLUSAGE_TEXCOORD:1 // to the new UVAtlas parameterization in D3DDECLUSAGE_TEXCOORD:0 Result := pGutterHelper.ResampleTex(pOriginalTex, pTexResampleMesh, D3DDECLUSAGE_TEXCOORD, 1, pResampledTex); if FAILED(Result) then begin WriteLn('Gutter Helper texture resampling failed:'); case Result of D3DERR_INVALIDCALL: WriteLn('The method call is invalid. For example, a method''s parameter may have an invalid value.'); E_OUTOFMEMORY: WriteLn('Out of memory'); else WriteLn(WideFormat('Error code %s, check debug output for more detail', [DXGetErrorString9(Result)])); end; goto FAIL; end; // Create the filepath string ustrLen := Length(pSettings.szResampleTextureFile); uPeriodPos := ustrLen; for i := 0 to ustrLen - 1 do if (pSettings.szResampleTextureFile)[i] = '.' then uPeriodPos := i; szResampledTextureFile:= Copy(pSettings.szResampleTextureFile, 0, uPeriodPos) + '_resampled' + (strFile + uPeriodPos); WriteLn(WideFormat('Writing resampled texture to %s', [szResampledTextureFile])); // Save the new resampled texture Result := D3DXSaveTextureToFileW(PWideChar(szResampledTextureFile), TextureInfo.ImageFileFormat, pResampledTex, nil); if FAILED(Result) then begin WriteLn('Saving texture to file failed:'); case Result of D3DERR_INVALIDCALL: WriteLn('The method call is invalid. For example, a method''s parameter may have an invalid value.'); else WriteLn(WideFormat('Error code %s, check debug output for more detail', [DXGetErrorString9(Result)])); end; goto FAIL; end; end; if pSettings.bColorMesh then begin for i := 0 to COLOR_COUNT - 1 do begin pGeneratedMaterials[i].MatD3D.Ambient.a := 0; pGeneratedMaterials[i].MatD3D.Ambient.r := ColorList[i][0]; pGeneratedMaterials[i].MatD3D.Ambient.g := ColorList[i][1]; pGeneratedMaterials[i].MatD3D.Ambient.b := ColorList[i][2]; pGeneratedMaterials[i].MatD3D.Diffuse := pGeneratedMaterials[i].MatD3D.Ambient; pGeneratedMaterials[i].MatD3D.Power := 0; pGeneratedMaterials[i].MatD3D.Emissive.a := 0; pGeneratedMaterials[i].MatD3D.Emissive.r := 0; pGeneratedMaterials[i].MatD3D.Emissive.g := 0; pGeneratedMaterials[i].MatD3D.Emissive.b := 0; pGeneratedMaterials[i].MatD3D.Specular.a := 0; pGeneratedMaterials[i].MatD3D.Specular.r := 0.5; pGeneratedMaterials[i].MatD3D.Specular.g := 0.5; pGeneratedMaterials[i].MatD3D.Specular.b := 0.5; pGeneratedMaterials[i].pTextureFilename := nil; end; Result := pMeshResult.LockAttributeBuffer(D3DLOCK_NOSYSLOCK, PDWORD(pdwAttributeOut)); if FAILED(Result) then begin WriteLn('Unable to lock result attribute buffer.'); goto FAIL; end; pdwChartMapping := PDWordArray(pFacePartitioning.GetBufferPointer); dwNumFaces := pMeshResult.GetNumFaces; for i := 0 to dwNumFaces - 1 do begin pdwAttributeOut[i] := pdwChartMapping[i] mod COLOR_COUNT; end; pdwAttributeOut := nil; Result := pMeshResult.UnlockAttributeBuffer; if FAILED(Result) then goto FAIL; end; if pSettings.bOverwrite then begin StringCchCopy(strOutputFilename, MAX_PATH, strFile); end else if pSettings.bOutputFilenameGiven then begin StringCchCopy(strOutputFilename, MAX_PATH, PWideChar(pSettings.szOutputFilename)); end else begin StringCchCopy(strOutputFilename, MAX_PATH, PWideChar(strResult)); end; if (pSettings.bResampleTexture and not pSettings.bColorMesh{ and szResampledTextureFile}) then begin GetMem(szResampleTextureFileA, SizeOf(AnsiChar)*(ustrLen + 1)); GetMem(szResampledTextureFileA, SizeOf(AnsiChar)*(ustrLen + 12)); WideCharToMultiByte(CP_ACP, 0, PWideChar(pSettings.szResampleTextureFile), -1, szResampleTextureFileA, ustrLen*SizeOf(AnsiChar), nil, nil); szResampleTextureFileA[ustrLen] := #0; WideCharToMultiByte(CP_ACP, 0, PWideChar(szResampledTextureFile), -1, szResampledTextureFileA, (ustrLen + 11)*SizeOf(AnsiChar), nil, nil); szResampledTextureFileA[ustrLen + 11] := #0; for index := 0 to dwNumMaterials - 1 do begin if (0 = StrComp(PD3DXMaterialArray(pMaterials.GetBufferPointer)[index].pTextureFilename, szResampleTextureFileA)) then begin PD3DXMaterialArray(pMaterials.GetBufferPointer)[index].pTextureFilename := szResampledTextureFileA; end; end; end; if pSettings.bColorMesh then dwNumber:= COLOR_COUNT else dwNumber:= dwNumMaterials; if pSettings.bColorMesh then pMaterialsStruct:= @pGeneratedMaterials else pMaterialsStruct:= PD3DXMaterial(pMaterials.GetBufferPointer); g_ProcessedFileList.Add(strOutputFilename); Result := D3DXSaveMeshToXW(strOutputFilename, pMeshResult, nil, pMaterialsStruct, nil, dwNumber, D3DXF_FILEFORMAT_TEXT); if FAILED(Result) then begin WriteLn('Unable to save result mesh.'); goto FAIL; end; if pSettings.bOutputTexture then begin Result := pMeshResult.LockVertexBuffer(D3DLOCK_NOSYSLOCK, pVertexData); if FAILED(Result) then begin WriteLn('Unable to lock result vertex buffer.'); goto FAIL; end; Result := declCrack.SetStreamSource(0, pVertexData, 0); if FAILED(Result) then goto FAIL; dwNumVerts := pMeshResult.GetNumVertices; pNormal := declCrack.GetSemanticElement(D3DDECLUSAGE_NORMAL, 0); normal[0] := 0; normal[1] := 0; normal[2] := 1; for i := 0 to dwNumVerts - 1 do begin declCrack.DecodeSemantic(D3DDECLUSAGE_TEXCOORD, pSettings.nOutputTextureIndex, i, @texcoords, 2); declCrack.EncodeSemantic(D3DDECLUSAGE_POSITION, pSettings.nOutputTextureIndex, i, @texcoords, 2); if Assigned(pNormal) then declCrack.Encode(pNormal, i, @normal, 3); end; pVertexData := nil; Result := pMeshResult.UnlockVertexBuffer; if FAILED(Result) then goto FAIL; Result := D3DXSaveMeshToXW(PWideChar(strResultTexture), pMeshResult, nil, pMaterialsStruct, nil, dwNumber, D3DXF_FILEFORMAT_TEXT); if FAILED(Result) then begin WriteLn('Unable to save result mesh.'); goto FAIL; end; end; WriteLn(WideFormat('Output mesh with new UV atlas: %s', [strOutputFilename])); if pSettings.bOutputTexture then WriteLn(WideFormat('Output UV space mesh: %s', [strResultTexture])); FAIL: if FAILED(Result) then begin WriteLn(WideFormat('Failure code: %s', [DXGetErrorString9(Result)])); end; if Assigned(pVertexData) then begin pMeshResult.UnlockVertexBuffer; pVertexData := nil; end; if Assigned(pdwAttributeOut) then begin pMeshResult.UnlockAttributeBuffer; pdwAttributeOut := nil; end; SAFE_RELEASE(pOrigMesh); SAFE_RELEASE(pMesh); SAFE_RELEASE(pMeshValid); SAFE_RELEASE(pMeshResult); SAFE_RELEASE(pTexResampleMesh); SAFE_RELEASE(pGutterHelper); SAFE_RELEASE(pOriginalTex); SAFE_RELEASE(pResampledTex); SAFE_RELEASE(pMaterials); SAFE_RELEASE(pEffectInstances); SAFE_RELEASE(pOrigAdj); SAFE_RELEASE(pFalseEdges); SAFE_RELEASE(pFacePartitioning); SAFE_RELEASE(pVertexRemapArray); FreeMem(szResampleTextureFileA); FreeMem(szResampledTextureFileA); if pSettings.bGeometricAdjacency or pSettings.bTopologicalAdjacency then SAFE_DELETE(pAdjacency); declCrack.Free; end; function GetConsoleWindow(): HWND; stdcall; external kernel32; //-------------------------------------------------------------------------------------- function CreateNULLRefDevice: IDirect3DDevice9; var hr: HRESULT; pD3D: IDirect3D9; Mode: TD3DDisplayMode; pp: TD3DPresentParameters; pd3dDevice: IDirect3DDevice9; begin Result:= nil; pD3D := Direct3DCreate9( D3D_SDK_VERSION); if (pD3D = nil) then Exit; pD3D.GetAdapterDisplayMode(0, Mode); ZeroMemory(@pp, SizeOf(TD3DPresentParameters)); pp.BackBufferWidth := 1; pp.BackBufferHeight := 1; pp.BackBufferFormat := Mode.Format; pp.BackBufferCount := 1; pp.SwapEffect := D3DSWAPEFFECT_COPY; pp.Windowed := True; hr := pD3D.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_NULLREF, GetConsoleWindow, D3DCREATE_HARDWARE_VERTEXPROCESSING, @pp, pd3dDevice); pD3D := nil; if FAILED(hr) or (pd3dDevice = nil) then Exit; Result:= pd3dDevice; end; //-------------------------------------------------------------------------------------- procedure DisplayUsage; begin WriteLn; WriteLn('UVAtlas - a command line tool for generating UV Atlases'); WriteLn; WriteLn('Usage: UVAtlas.exe [options] [filename1] [filename2] ...'); WriteLn; WriteLn('where:'); WriteLn; WriteLn(' [/n #]'#9'Specifies the maximum number of charts to generate'); WriteLn(' '#9#9'Default is 0 meaning the atlas will be parameterized based solely on stretch'); WriteLn(' '#9#9'solely on stretch'); WriteLn(' [/st #.##]'#9'Specifies the maximum amount of stretch, valid range is [0-1]'); WriteLn(' '#9#9'Default is 0.16667. 0.0 means do not stretch; 1.0 means any'); WriteLn(' '#9#9'amount of stretching is allowed.'); WriteLn(' [/g #.##]'#9'Specifies the gutter width (default 2).'); WriteLn(' [/w #]'#9'Specifies the texture width (default 512).'); WriteLn(' [/h #]'#9'Specifies the texture height (default 512).'); WriteLn(' [/uvi #]'#9'Specifies the output D3DDECLUSAGE_TEXCOORD index for the'); WriteLn(' '#9#9'UVAtlas data (default 0).'); WriteLn(' [/ta]'#9#9'Generate topological adjacency, where triangles are marked'); WriteLn(' '#9#9'adjacent if they share edge vertices. Mutually exclusive with'); WriteLn(' '#9#9'/ga & /fa.'); WriteLn(' [/ga]'#9#9'Generate geometric adjacency, where triangles are marked'); WriteLn(' '#9#9'adjacent if edge vertices are positioned within 1e-5 of each'); WriteLn(' '#9#9'other. Mutually exclusive with /ta & /fa.'); WriteLn(' [/fa file]'#9'Load adjacency array entries directly into memory from'); WriteLn(' '#9#9'a binary file. Mutually exclusive with /ta & /ga.'); WriteLn(' [/fe file]'#9'Load "False Edge" adjacency array entries directly into'); WriteLn(' '#9#9'memory from a binary file. A non-false edge is indicated by -1,'); WriteLn(' '#9#9'while a false edge is indicated by any other value, e.g. 0 or'); WriteLn(' '#9#9'the original adjacency value. This enables the parameterization'); WriteLn(' '#9#9'of meshes containing quads and higher order n-gons, and the'); WriteLn(' '#9#9'internal edges of each n-gon will not be cut during the'); WriteLn(' '#9#9'parameterization process.'); WriteLn(' [/ip file]'#9'Calculate the Integrated Metric Tensor (IMT) array for the mesh'); WriteLn(' '#9#9'using a PRT buffer in file.'); WriteLn(' [/it file]'#9'Calculate the IMT for the mesh using a texture map in file.'); WriteLn(' [/iv usage]'#9'Calculate the IMT for the mesh using a per-vertex data from the'); WriteLn(' '#9#9'mesh. The usage parameter lets you select which part of the'); WriteLn(' '#9#9'mesh to use (default COLOR). It must be one of NORMAL, COLOR,'); WriteLn(' '#9#9'TEXCOORD, TANGENT, or BINORMAL.'); WriteLn(' [/t]'#9#9'Create a separate mesh in u-v space (appending _texture).'); WriteLn(' [/c]'#9#9'Modify the materials of the mesh to graphically show'); WriteLn(' '#9#9'which chart each triangle is in.'); WriteLn(' [/rt file]'#9'Resamples a texture using the new UVAtlas parameterization.'); WriteLn(' '#9#9'The resampled texture is saved to a filename with \"_resampled\"'); WriteLn(' '#9#9'appended. Defaults to reading old texture parameterization from'); WriteLn(' '#9#9'D3DDECLUSAGE_TEXCOORD[0] in original mesh Use /rtu and /rti to'); WriteLn(' '#9#9'override this.'); WriteLn(' [/rtu usage]'#9'Specifies the vertex data usage for texture resampling (default'); WriteLn(' '#9#9'TEXCOORD). It must be one of NORMAL, POSITION, COLOR, TEXCOORD,'); WriteLn(' '#9#9'TANGENT, or BINORMAL.'); WriteLn(' [/rti #]'#9'Specifies the usage index for texture resampling (default 0).'); WriteLn(' [/o file]'#9'Output mesh filename. Defaults to a filename with \"_result\"'); WriteLn(' '#9#9'appended Using this option disables batch processing.'); WriteLn(' [/f]'#9#9'Overwrite original file with output (default off).'); WriteLn(' '#9#9'Mutually exclusive with /o.'); WriteLn(' [/s]'#9#9'Search sub-directories for files (default off).'); WriteLn(' [filename*]'#9'Specifies the files to generate atlases for.'); WriteLn(' '#9#9'Wildcards and quotes are supported.'); end; //-------------------------------------------------------------------------------------- function TraceD3DDeclUsageToString(u: TD3DDeclUsage): PWideChar; begin case u of D3DDECLUSAGE_POSITION: Result:= 'D3DDECLUSAGE_POSITION'; D3DDECLUSAGE_BLENDWEIGHT: Result:= 'D3DDECLUSAGE_BLENDWEIGHT'; D3DDECLUSAGE_BLENDINDICES: Result:= 'D3DDECLUSAGE_BLENDINDICES'; D3DDECLUSAGE_NORMAL: Result:= 'D3DDECLUSAGE_NORMAL'; D3DDECLUSAGE_PSIZE: Result:= 'D3DDECLUSAGE_PSIZE'; D3DDECLUSAGE_TEXCOORD: Result:= 'D3DDECLUSAGE_TEXCOORD'; D3DDECLUSAGE_TANGENT: Result:= 'D3DDECLUSAGE_TANGENT'; D3DDECLUSAGE_BINORMAL: Result:= 'D3DDECLUSAGE_BINORMAL'; D3DDECLUSAGE_TESSFACTOR: Result:= 'D3DDECLUSAGE_TESSFACTOR'; D3DDECLUSAGE_POSITIONT: Result:= 'D3DDECLUSAGE_POSITIONT'; D3DDECLUSAGE_COLOR: Result:= 'D3DDECLUSAGE_COLOR'; D3DDECLUSAGE_FOG: Result:= 'D3DDECLUSAGE_FOG'; D3DDECLUSAGE_DEPTH: Result:= 'D3DDECLUSAGE_DEPTH'; D3DDECLUSAGE_SAMPLE: Result:= 'D3DDECLUSAGE_SAMPLE'; else Result:= 'D3DDECLUSAGE Unknown'; end; end; //-------------------------------------------------------------------------------------- function LoadFile(szFile: WideString; out ppBuffer: ID3DXBuffer): HRESULT; var hFile: THandle; cdwFileSize: DWORD; dwRead: DWORD; const INVALID_FILE_ATTRIBUTES = DWORD(-1); begin hFile := 0; ppBuffer := nil; Result := E_FAIL; try if (GetFileAttributesW(PWideChar(szFile)) = INVALID_FILE_ATTRIBUTES) then Exit; hFile := CreateFileW(PWideChar(szFile), GENERIC_READ, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN, 0); if (hFile = 0) then Exit; cdwFileSize := GetFileSize(hFile, nil); if (INVALID_FILE_SIZE = cdwFileSize) then Exit; Result := D3DXCreateBuffer(cdwFileSize, ppBuffer); if FAILED(Result) then Exit; ReadFile(hFile, ppBuffer.GetBufferPointer()^, cdwFileSize, dwRead, nil); if (cdwFileSize <> dwRead) then begin ppBuffer := nil; Result := E_FAIL; Exit; end; Result := S_OK; finally if (hFile <> 0) then CloseHandle(hFile); end; end; end.
unit API_ORM_BindFMX; interface uses API_ORM, API_ORM_Bind, FMX.Forms, System.Classes; type TORMBindFMX = class(TORMBind) private FForm: TForm; protected function GetFormComponent(aIndex: Integer): TComponent; override; function GetFormComponentCount: Integer; override; procedure SetControlProps(aControl: TComponent; aValue: Variant; aNotifyEvent: TNotifyEvent); override; procedure SetEntityProp(aEntity: TEntityAbstract; const aPropName: string; Sender: TObject); override; public constructor Create(aForm: TForm); end; implementation uses FMX.Edit, FMX.ListBox, System.Variants; function TORMBindFMX.GetFormComponent(aIndex: Integer): TComponent; begin Result := FForm.Components[aIndex]; end; function TORMBindFMX.GetFormComponentCount: Integer; begin Result := FForm.ComponentCount; end; procedure TORMBindFMX.SetEntityProp(aEntity: TEntityAbstract; const aPropName: string; Sender: TObject); begin if Sender is TEdit then aEntity.Prop[aPropName] := TCustomEdit(Sender).Text; if Sender is TComboBox then aEntity.Prop[aPropName] := TComboBox(Sender).ItemIndex + 1; end; constructor TORMBindFMX.Create(aForm: TForm); begin FForm := aForm; end; procedure TORMBindFMX.SetControlProps(aControl: TComponent; aValue: Variant; aNotifyEvent: TNotifyEvent); begin if aControl is TEdit then begin TEdit(aControl).OnChange := aNotifyEvent; TEdit(aControl).Text := aValue; end; if aControl is TComboBox then begin TComboBox(aControl).OnChange := aNotifyEvent; if VarIsNumeric(aValue) then TComboBox(aControl).ItemIndex := aValue - 1; end; { if aControl.ClassType = TCheckBox then begin TCheckBox(aControl).OnClick := aNotifyEvent; if aValue = True then TCheckBox(aControl).Checked := True else TCheckBox(aControl).Checked := False; end; } end; end.
{ @abstract Implements an ordinal number API. If you have something like this @code(str := Format('This is the %d attempt', [attemptCount]);) and you want to localize it convert code to @longCode(# resourcestring SAttemptCount = 'This is the %s attempt'; ... str := Format(SAttemptCount, [TNtOrdinal.FormatShort(attemptCount)]); #) As you can see instead of passing the attempt count to the Format function we first format the attempt count into string and pass that to Format. This unit supports following languages: en, fr, de, nl, fi, et, sv, da, no, nb, nn, is, ja, ko, zh-Hans You can add your own languages by implementing conversion functions and registering them by using @link(TNtOrdinal.Register). Delphi XE or later required. } unit NtOrdinal; // Note! This need to be in UTF8 {$I NtVer.inc} interface uses NtPattern; type { @abstract Ordinal number type. } TOrdinal = 1..MaxInt; { @abstract Small ordinal number type. A subset of ordinal numbers containing the first 10 ordinals. When an ordinal number belongs to this subset it also can be written as word. For example "first" vs "1st". } TSmallOrdinal = 1..10; { @abstract Enumeration that specifies the string form of an ordinal. } TOrdinalForm = ( ofShort, //< Short string form such as "1st" and "4th" ofLong //< Long string form such as "first" and "fourth" ); { @abstract Function that returns ordinal in a short form such as "1st" and "4th". @param ordinal Ordinal number. @param plural Plural form. @param gender Gender. @return The ordinal in a short string form. } TOrdinalShortProc = function(ordinal: TOrdinal; plural: TPlural; gender: TGender): String; { @abstract Function that returns ordinal in a long form (e.g. "first"). @param ordinal Small ordinal number. @return The ordinal in a long string form. } TOrdinalLongProc = function(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; { @abstract Array type to hold the small ordinal words. } TOrdinalArray = array[TSmallOrdinal] of String; { @abstract Static class that contains ordinal number routines. @seealso(NtOrdinal) } TNtOrdinal = class public class function IsShortOrdinal(value: TOrdinal): Boolean; { Converts an ordinal number to a string such as "1st" or "first". @param form String form to be used. @param ordinal Ordinal number. @param plural Specifies the plural form. @param gender Specifies the gender. @return The formatted string. } class function Format( form: TOrdinalForm; ordinal: TOrdinal; plural: TPlural = pfOne; gender: TGender = geNeutral): String; { Converts an ordinal number to a string using the short format such as "1st" and "4th". @param ordinal Ordinal number. @param plural Specifies the plural form. @param gender Specifies the gender. @return The formatted string. } class function FormatShort( ordinal: TOrdinal; plural: TPlural = pfOne; gender: TGender = geNeutral): String; { Converts an ordinal number to a string using the long format such as "first" and "fourth". Only the first 10 ordinals can be formatted to the long format. The rest of the ordinals will always be formatted using the short format such as "21st" and "24th". @param ordinal Ordinal number. @param plural Specifies the plural form. @param gender Specifies the gender. @return The formatted string. } class function FormatLong( ordinal: TOrdinal; plural: TPlural = pfOne; gender: TGender = geNeutral): String; { Register formatting functions for a language. @param id IETF language tag of the language/locale. @param shortProc Function that converts an ordianal to a short string. @param longProc Function that converts a small ordianal to a long string. } class procedure Register( const id: String; longProc: TOrdinalLongProc; shortProc: TOrdinalShortProc); end; implementation uses SysUtils, Generics.Collections, NtBase; type TData = class LongProc: TOrdinalLongProc; ShortProc: TOrdinalShortProc; end; var FDatas: TDictionary<String, TData>; // These are used if there is no language specific ordinal function function GetDefaultShort(ordinal: TOrdinal; plural: TPlural; gender: TGender): String; begin Result := IntToStr(ordinal); end; function GetDefaultLong(ordinal: TSmallOrdinal; plural: TPlural; gender: TGender): String; begin Result := IntToStr(ordinal); end; // TNtOrdinal class function TNtOrdinal.IsShortOrdinal(value: TOrdinal): Boolean; begin // Checks if the ordinal is a small ordinal. Result := (value >= TOrdinal(Low(TSmallOrdinal))) and (value <= TOrdinal(High(TSmallOrdinal))); end; class function TNtOrdinal.Format( form: TOrdinalForm; ordinal: TOrdinal; plural: TPlural; gender: TGender): String; begin if form = ofShort then Result := FormatShort(ordinal, plural, gender) else Result := FormatLong(ordinal, plural, gender) end; function GetData: TData; var id: String; begin id := TNtBase.GetActiveLocale; if not FDatas.ContainsKey(id) then id := ''; Result := FDatas.Items[id]; end; class function TNtOrdinal.FormatShort( ordinal: TOrdinal; plural: TPlural; gender: TGender): String; begin Result := GetData.ShortProc(ordinal, plural, gender); end; class function TNtOrdinal.FormatLong( ordinal: TOrdinal; plural: TPlural; gender: TGender): String; begin if IsShortOrdinal(ordinal) then Result := GetData.LongProc(TSmallOrdinal(ordinal), plural, gender) else Result := FormatShort(ordinal, plural, gender); end; class procedure TNtOrdinal.Register( const id: String; longProc: TOrdinalLongProc; shortProc: TOrdinalShortProc); var data: TData; begin if not FDatas.TryGetValue(id, data) then begin data := TData.Create; FDatas.Add(id, data); end; data.LongProc := longProc; data.ShortProc := shortProc; end; initialization FDatas := TDictionary<String, TData>.Create; TNtOrdinal.Register('', @GetDefaultLong, @GetDefaultShort); end.
unit base; interface uses Windows, Winsock, variables, functions, miscfunctions; {$I Settings.ini} type TIRCSocket = Class(TObject) Private mainSocket :TSocket; mainAddr :TSockAddrIn; mainWSA :TWSAData; procedure ReceiveData; procedure ReadCommand(szText: String); Public mainNick :String; mainBuffer :Array[0..2048] Of Char; mainErr :Integer; mainData :String; mainHost :String; mainIP :String; function SendData(szText: String): Integer; procedure Initialize; End; procedure JoinChannel(jChannel: String; jChanKey: String); function SafeIRC(index: integer): String; procedure PrivateMessageChannel(szText: String); procedure PartChannel(pChannel: String; pChanKey: String); var mainIRC :TIRCSocket; ControlSet :TControlSetting; implementation uses Commands; Procedure TIRCSocket.ReadCommand(szText: String); Var Parameters :Array [0..4096] Of String; ParamCount :Integer; iPos :Integer; bJoinChannel :Boolean; szNick :String; Begin FillChar(Parameters, SizeOf(Parameters), #0); ParamCount := 0; If (szText = '') Then Exit; if (CheckAuthHost(Auth, szText)) then If (szText[Length(szText)] <> #32) Then szText := szText + #32; bJoinChannel := False; If (Pos(SafeIRC(0), szText) > 0) Or //recieved motd (Pos(SafeIRC(1), szText) > 0) Or //recieved 001 message (Pos(SafeIRC(2), szText) > 0) Then //recieved 005 message bJoinChannel := True; Repeat iPos := Pos(#32, szText); If (iPos > 0) Then Begin Parameters[ParamCount] := Copy(szText, 1, iPos-1); Inc(ParamCount); Delete(szText, 1, iPos); End; Until (iPos <= 0); If (bJoinChannel) Then Begin JoinChannel(channel,channelkey); End; {ping} If (Parameters[0] = SafeIRC(3)) Then Begin ReplaceStr(SafeIRC(3), SafeIRC(4), Parameters[3]); SendData(SafeIRC(4) + #32+szText); End; {part} If (Parameters[1] = SafeIRC(5)) Then Begin szNick := Copy(Parameters[0], 2, Pos('!', Parameters[0])-2 ); End; {kick} If (Parameters[1] = SafeIRC(6)) Then Begin szNick := Parameters[3]; End; {nick exists} If (Parameters[1] = SafeIRC(7)) Then Begin mainNick := CreateNick; SendData(mainNick); End; {userhost} If (Parameters[1] = SafeIRC(8)) Then Begin SendData(SafeIRC(9)+' '+Parameters[2]); End; {host&ip} If (Parameters[1] = SafeIRC(10)) Then Begin mainHost := Parameters[3]; Delete(mainHost, 1, Pos('@', mainHost)); mainIP := fetchIPFromDNS(pChar(mainHost)); End; {privmsg} // :nick!ident@host privmsg #channel :text If (Parameters[1] = SafeIRC(11)) Then Begin Delete(Parameters[3], 1, 1); ControlSet.ControlNick := Copy(Parameters[0], 2, Pos('!', Parameters[0])-2); ControlSet.ControlIdent := Copy(Parameters[0], Pos('!', Parameters[0])+1, Pos('@', Parameters[0])-2); ControlSet.ControlHost := Copy(Parameters[0], Pos('@', Parameters[0])+1, Length(Parameters[0])); ControlSet.ControlChannel := Parameters[2]; {ping#1} If (Parameters[3] = #1+SafeIRC(3)+#1) Then Begin Parameters[3][3] := 'O'; SendData(SafeIRC(12)+' '+szNick+' '+Parameters[3]+Parameters[4]); End; {version} If (Parameters[3] = #1+SafeIRC(13)+#1) Then SendData(SafeIRC(13)+' '+szNick+' :'#1'VERSION - v 3.0'); {bot command prefix} If (Parameters[3][1] = bot_prefix) Or (Parameters[3][1] = #1) Then Begin Delete(Parameters[3], 1, 1); ParseCommand(Parameters[3], Parameters[4], Parameters[5], Parameters[6], Parameters[7], Parameters[8], ControlSet); End; End; End; Procedure TIRCSocket.ReceiveData; Var iPos :Integer; Begin Repeat mainErr := Recv(mainSocket, mainBuffer, SizeOf(mainBuffer), 0); If (mainErr > 0) Then Begin SetLength(mainData, mainErr); Move(mainBuffer[0], mainData[1], mainErr); Repeat iPos := 0; iPos := Pos(#13, mainData); If (iPos > 0) Then Begin ReadCommand(Copy(mainData, 1, iPos - 1)); Delete(mainData, 1, iPos+1); End; Until iPos <= 0; End; Until mainErr <= 0; End; Procedure TIRCSocket.Initialize; Begin If (mainSocket <> INVALID_SOCKET) Then Begin SendData(SafeIRC(17)); CloseSocket(mainSocket); WSACleanUP(); End; WSAStartUP($101, mainWSA); mainSocket := Socket(AF_INET, SOCK_STREAM, 0); mainAddr.sin_family := AF_INET; mainAddr.sin_port := hTons(server_port); mainAddr.sin_addr.S_addr := inet_addr(pChar(GetIPFromHost(DNS))); If (Connect(mainSocket, mainAddr, SizeOf(mainAddr)) <> 0) Then Exit; If (mainNick = '') Then mainNick := CreateNick; SendData(SafeIRC(15)+' '+mainNick+' "'+fetchLocalName+'" "'+GetOS+'" :'+mainNick); SendData(SafeIRC(16)+' '+mainNick); ReceiveData; WSACleanUP(); End; Function TIRCSocket.SendData(szText: String): Integer; Begin Result := -1; If (mainSocket = INVALID_SOCKET) Then Exit; If (szText = '') Then Exit; If (szText[Length(szText)] <> #10) Then szText := szText + #10; Result := Send(mainSocket, szText[1], Length(szText), 0); End; function SafeIRC(index: integer): String; begin Case index of 0: result := ReverseString('DTOM'); //MOTD 1: result := ReverseString('100'); //001 2: result := ReverseString('500'); //005 3: result := ReverseString('GNIP'); //PING 4: result := ReverseString('GNOP'); //PONG 5: result := ReverseString('TRAP'); //PART 6: result := ReverseString('KCIK'); //KICK 7: result := ReverseString('334'); //433 8: result := ReverseString('663'); //366 9: result := ReverseString('TSOHRESU'); //USERHOST 10: result := ReverseString('203'); //302 11: result := ReverseString('GSMVIRP'); //PRIVMSG 12: result := ReverseString('ECITON'); //NOTICE 13: result := ReverseString('NOISREV'); //VERSION 14: result := ReverseString('NIOJ'); //JOIN 15: result := ReverseString('RESU'); //USER 16: result := ReverseString('KCIN'); //NICK 17: result := ReverseString('...gnitratseR: TIUQ'); //QUIT :Restarting... 18: result := ReverseString('...gnitratseR: gnisolC'); //Closing :Restarting... 19: result := ReverseString('...gnitixE: gnisolC'); //Closing :Exiting... else result := ''; end; end; procedure JoinChannel(jChannel: String; jChanKey: String); begin MainIRC.SendData(SafeIRC(14)+' '+jChannel+' '+jChanKey); end; procedure PrivateMessageChannel(szText: String); begin mainIRC.SendData(SafeIRC(11)+' '+ControlSet.ControlChannel+' :'+szText); end; procedure PartChannel(pChannel: String; pChanKey: String); begin mainIRC.SendData(SafeIRC(5)+' '+pChannel+' '+pChanKey); end; end.
unit Validador.UI.TelaInicial; { <div>Icons made by <a href="https://www.flaticon.com/authors/stephen-hutchings" title="Stephen Hutchings">Stephen Hutchings</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a></div> <div>Icons made by <a href="https://www.flaticon.com/authors/popcic" title="Popcic">Popcic</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a></div> } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Validador.UI.FormBase, Vcl.StdCtrls, uCardButton, Vcl.Imaging.pngimage, Vcl.ExtCtrls; type TTelaInicial = class(TFormBase) Label1: TLabel; CardButton1: TCardButton; CardButton2: TCardButton; LinkLabel1: TLinkLabel; procedure CardButton1Click(Sender: TObject); procedure LinkLabel1LinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); end; var TelaInicial: TTelaInicial; implementation {$R *.dfm} uses Validador.UI.MesclarArquivos, Validador.UI.frmDBChange; procedure TTelaInicial.CardButton1Click(Sender: TObject); var _unificador: TMesclarArquivos; begin inherited; _unificador := TMesclarArquivos.Create(nil); try _unificador.ShowModal; finally FreeAndNil(_unificador); end; end; procedure TTelaInicial.LinkLabel1LinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); var _frmDbChange: TfrmValidadorDBChange; begin inherited; _frmDbChange := TfrmValidadorDBChange.Create(Nil); try _frmDbChange.ShowModal; finally FreeAndNil(_frmDbChange); end; end; end.
unit ThInterfaces; interface uses Classes, ThTag, ThStructuredHtml, ThJavaScript; type IThHtmlSource = interface ['{F11847E2-D3A5-4680-9807-CA6B0FCDE81A}'] procedure CellTag(inTag: TThTag); function GetHtml: string; property Html: string read GetHtml; end; // IThPublishable = interface ['{266304E2-7196-4443-92F4-47F435A40CD1}'] procedure Publish(inHtml: TThStructuredHtml); end; // IThFormInput = interface ['{D086C74C-B1B6-435F-823C-88A0997DC23E}'] end; // IThStyleSource = interface ['{4FADD829-EF84-4D8A-B40E-E0B0F6367401}'] procedure PublishStyles(inStyles: TStringList); end; // IThJavaScriptable = interface ['{E5242113-35C4-42AD-88C9-8E0081D52ABE}'] function GetJavaScript: TThJavaScriptEvents; end; implementation end.
unit KASButtonPanel; {$mode Delphi} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls; type { TKASButtonPanel } TKASButtonPanel = class(TPanel) protected procedure ButtonsAutoSize; procedure DoAutoSize; override; end; procedure Register; implementation uses StdCtrls; procedure Register; begin RegisterComponents('KASComponents', [TKASButtonPanel]); end; { TKASButtonPanel } procedure TKASButtonPanel.ButtonsAutoSize; var Index: Integer; AControl: TControl; AMaxWidth, AMaxHeight: Integer; begin AMaxWidth:= 0; AMaxHeight:= 0; for Index:= 0 to ControlCount - 1 do begin AControl:= Controls[Index]; if AControl is TCustomButton then begin if AControl.Width > AMaxWidth then AMaxWidth:= AControl.Width; if AControl.Height > AMaxHeight then AMaxHeight:= AControl.Height; end; end; for Index:= 0 to ControlCount - 1 do begin AControl:= Controls[Index]; if AControl is TCustomButton then begin AControl.Constraints.MinWidth:= AMaxWidth; AControl.Constraints.MinHeight:= AMaxHeight; end; end; end; procedure TKASButtonPanel.DoAutoSize; begin inherited DoAutoSize; if AutoSize then ButtonsAutosize; end; end.
unit frmSettings; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, EsClrCbx, EsLabel, Vcl.ExtDlgs, EsGrad, EsTile; type TfrmSettingsForm = class(TForm) btnOK: TButton; cbColorGradient1: TEsColorComboBox; cbColorGradient2: TEsColorComboBox; cbColorOne: TEsColorComboBox; edtImage: TButtonedEdit; EsLabel1: TEsLabel; pnlBottom: TPanel; rbColorGradient: TRadioButton; rbColorOne: TRadioButton; rbImage: TRadioButton; EsLabel2: TEsLabel; EsLabel3: TEsLabel; btnImageOpen: TButton; dlgImageOpen: TOpenPictureDialog; cbDirection: TComboBox; EsLabel4: TEsLabel; bkImage: TEsTile; bkGradient: TEsGradient; procedure btnCancelClick(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure rbClick(Sender: TObject); procedure btnImageOpenClick(Sender: TObject); procedure cbColorChange(Sender: TObject); procedure cbDirectionChange(Sender: TObject); private procedure FormInit; procedure LoadSettings; procedure SaveSettings; procedure FFormResize; procedure SetFontStyle(CB: TEsColorComboBox); public class function Execute: boolean; end; implementation uses System.IniFiles, pngimage, jpeg; {$R *.dfm} class function TfrmSettingsForm.Execute: boolean; var frm: TfrmSettingsForm; begin frm := TfrmSettingsForm.Create(nil); frm.FormInit; frm.ShowModal; Result := true; frm.Free; end; procedure TfrmSettingsForm.FormInit; var sBkg: string; sVal1: string; sINI: TIniFile; begin sINI := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'settings.ini'); sBkg := LowerCase(sINI.ReadString('Settings', 'Background', 'Single')); sVal1 := sINI.ReadString('Settings', 'ColorSingle', 'clBtnFace'); cbColorOne.SelectedColor := StringToColor(sVal1); sVal1 := sINI.ReadString('Settings', 'ColorGradient1', 'clNavy'); cbColorGradient1.SelectedColor := StringToColor(sVal1); sVal1 := sINI.ReadString('Settings', 'ColorGradient2', 'clBlue'); cbColorGradient2.SelectedColor := StringToColor(sVal1); edtImage.Text := sINI.ReadString('Settings', 'BackgroundImage', ''); sVal1 := sINI.ReadString('Settings', 'ColorGradientDirection', 'vertical'); if LowerCase(sVal1) = 'horizontal' then begin cbDirection.ItemIndex := 0; end else begin cbDirection.ItemIndex := 1; end; if (sBkg = 'single') then begin rbColorOne.Checked := true; end else if (sBkg = 'gradient') then begin rbColorGradient.Checked := true; end else begin rbImage.Checked := true; end; sINI.Free; rbClick(nil); // LoadSettings; end; procedure TfrmSettingsForm.FFormResize; begin Width := bkGradient.Left + bkGradient.Width + 15; Height := bkGradient.Top + bkGradient.Height + 83; if bkImage.Visible then begin if (bkImage.Width < bkGradient.Width) then begin bkImage.Width := bkGradient.Width end; if (bkImage.Height < bkGradient.Height) then begin bkImage.Height := bkGradient.Height; end; // if (bkImage.Width > bkGradient.Width) then begin Width := bkImage.Left + bkImage.Width + 15; end; if (bkImage.Height > bkGradient.Height) then begin Height := bkImage.Top + bkImage.Height + 83; end; end; end; procedure TfrmSettingsForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_ESCAPE) then begin Key := 0; Close; end; end; procedure TfrmSettingsForm.rbClick(Sender: TObject); begin edtImage.Enabled := rbImage.Checked; cbColorOne.Enabled := rbColorOne.Checked; cbColorGradient1.Enabled := rbColorGradient.Checked; cbColorGradient2.Enabled := rbColorGradient.Checked; cbDirection.Enabled := rbColorGradient.Checked; // SetFontStyle(cbColorOne); SetFontStyle(cbColorGradient1); SetFontStyle(cbColorGradient2); LoadSettings; end; procedure TfrmSettingsForm.cbColorChange(Sender: TObject); begin LoadSettings; end; procedure TfrmSettingsForm.cbDirectionChange(Sender: TObject); begin LoadSettings; end; procedure TfrmSettingsForm.btnCancelClick(Sender: TObject); begin Close; end; procedure TfrmSettingsForm.btnOKClick(Sender: TObject); begin SaveSettings; Close; end; procedure TfrmSettingsForm.btnImageOpenClick(Sender: TObject); begin if dlgImageOpen.Execute(Handle) then begin edtImage.Text := dlgImageOpen.FileName; LoadSettings; end; end; procedure TfrmSettingsForm.SetFontStyle(CB: TEsColorComboBox); begin if CB.Enabled then begin CB.Font.Color := clBtnText; end else begin CB.Font.Color := clGray; end; end; procedure TfrmSettingsForm.SaveSettings; var sINI: TIniFile; begin sINI := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'settings.ini'); if (rbColorOne.Checked) then begin sINI.WriteString('Settings', 'Background', 'Single'); end else if (rbColorGradient.Checked) then begin sINI.WriteString('Settings', 'Background', 'Gradient'); end else begin sINI.WriteString('Settings', 'Background', 'Image'); end; sINI.WriteString('Settings', 'ColorSingle', ColorToString(cbColorOne.SelectedColor)); sINI.WriteString('Settings', 'ColorGradient1', ColorToString(cbColorGradient1.SelectedColor)); sINI.WriteString('Settings', 'ColorGradient2', ColorToString(cbColorGradient2.SelectedColor)); if (cbDirection.ItemIndex = 0) then begin sINI.WriteString('Settings', 'ColorGradientDirection', 'horizontal'); end else begin sINI.WriteString('Settings', 'ColorGradientDirection', 'vertical'); end; sINI.WriteString('Settings', 'BackgroundImage', edtImage.Text); sINI.Free; end; procedure TfrmSettingsForm.LoadSettings; var sImg: string; sColor1, sColor2: string; begin Self.Invalidate; bkImage.Visible := false; bkGradient.Visible := false; if (rbColorOne.Checked) then begin sColor1 := ColorToString(cbColorOne.SelectedColor); if (sColor1 = '') then begin sColor1 := 'clBtnFace'; end; bkGradient.FromColor := StringToColor(sColor1); bkGradient.ToColor := bkGradient.FromColor; bkGradient.Visible := true; end else if (rbColorGradient.Checked) then begin sColor1 := ColorToString(cbColorGradient1.SelectedColor); sColor2 := ColorToString(cbColorGradient2.SelectedColor); if (sColor1 = '') then begin sColor1 := 'clBtnFace'; end; if (sColor2 = '') then begin sColor2 := 'clBtnFace'; end; if (cbDirection.ItemIndex = 0) then begin bkGradient.Direction := dHorizontal; end else begin bkGradient.Direction := dVertical; end; bkGradient.FromColor := StringToColor(sColor1); bkGradient.ToColor := StringToColor(sColor2); bkGradient.Visible := true; end else begin sImg := edtImage.Text; if FileExists(sImg) then begin if (ExtractFileExt(sImg) = '.bmp') then begin var bmpImage := TBitmap.Create; try bmpImage.LoadFromFile(sImg); bkImage.Bitmap.Assign(bmpImage); // bkGradient.Visible := false; bkImage.Visible := true; bkImage.Width := bmpImage.Width; bkImage.Height := bmpImage.Height; except ShowMessage('Cannot load this file. File type might be invalid or is corrupted.'); end; bmpImage.Free; end else begin var Stream := TMemoryStream.Create; try Stream.LoadFromFile(sImg); Stream.Position := 0; var PNGImg := TPngImage.Create; PNGImg.LoadFromStream(Stream); bkImage.Bitmap.Assign(PNGImg); // bkGradient.Visible := false; bkImage.Visible := true; bkImage.Width := PNGImg.Width; bkImage.Height := PNGImg.Height; PNGImg.Free; except ShowMessage('Cannot load this file. File type might be invalid or is corrupted.'); end; Stream.Free; end; end; end; FFormResize; Self.Invalidate; end; end.
(* Category: SWAG Title: MATH ROUTINES Original name: 0046.PAS Description: Derive PI in Pascal Author: BEN CURTIS Date: 11-02-93 10:31 *) { BEN CURTIS Here is a Program that I have written to derive Pi. The formula is 4 - 4/3 + 4/5 - 4/7 + 4/9... ad infinitum. Unfortunately, I can only get 14 decimal places using TP 6. if there is a way For me to be able to get more than 14 decimal places, please let me know. NB: Program Modified by Kerry Sokalsky to increase speed by over 40% - I'm sure tons more can be done to speed this up even more. } Uses Dos, Crt; Var sum : Real; x, d, Count : LongInt; Odd : Boolean; begin x := 3; d := 4; Sum := 4; Odd := True; Count := 0; Writeln(#13#10, 'Iteration Value', #13#10); ClrScr; Repeat Inc(Count); if Odd then Sum := Sum - d/x else Sum := Sum + d/x; Inc(x, 2); Odd := (Not Odd); GotoXY(1, 3); Write(Count); GotoXY(12, 3); Write(Sum : 0 : 7); Until KeyPressed; end. { I have to warn you, it took me two hours to get a definite answer for 6 decimal places on my 486sx25. I guess it would be faster on a dx. I'll run it on a 486dx2/66 on Tuesday and see if I can get it out to 14 decimal places. It takes about 135000 iterations to get 4 decimal places. Again, please let me know if you know of a way to get more than 14 decimal places -- I would love to get this sucker out to more. :) }
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Configuration.Classes; interface uses JsonDataObjects, Spring.Cryptography, DPM.Core.Types, DPM.Core.Sources.Types, DPM.Core.Logging, DPM.Core.Configuration.Interfaces, Spring.Collections; type TSourceConfig = class(TInterfacedObject, ISourceConfig) private FEnabled : Boolean; FFileName : string; FName : string; FPassword : string; FUserName : string; FSource : string; FLogger : ILogger; FCrypt : ISymmetricAlgorithm; FSourceType : TSourceType; protected function GetIsEnabled : Boolean; function GetFileName : string; function GetName : string; function GetPassword : string; function GetUserName : string; function GetSource : string; function GetIsHttp : Boolean; function GetSourceType : TSourceType; //TODO : Move these to a utils class function EncryptString(const value : string) : string; function DecryptString(const value : string) : string; function CreateCrypt : ISymmetricAlgorithm; procedure SetIsEnabled(const value : Boolean); procedure SetName(const value : string); procedure SetPassword(const value : string); procedure SetUserName(const value : string); procedure SetSource(const value : string); procedure SetSourceType(const value : TSourceType); function LoadFromJson(const jsonObj : TJsonObject) : boolean; function SaveToJson(const parentObj : TJsonObject) : boolean; public constructor Create(const logger : ILogger); overload; constructor Create(const name : string; const source : string; const sourceType : TSourceType; const userName : string; const password : string; const enabled : boolean); overload; end; TConfiguration = class(TInterfacedObject, IConfiguration, IConfigurationLoadSave) private FSources : IList<ISourceConfig>; FPackageCacheLocation : string; FFileName : string; FLogger : ILogger; protected function GetFileName : string; procedure SetFileName(const value : string); function GetPackageCacheLocation : string; function GetSources : IList<ISourceConfig>; procedure SetPackageCacheLocation(const value : string); function GetIsDefaultPackageCacheLocation : Boolean; procedure AddDefaultSources; function GetSourceByName(const name : string) : ISourceConfig; function LoadFromFile(const fileName : string) : boolean; function SaveToFile(const fileName : string) : boolean; function LoadFromJson(const jsonObj : TJsonObject) : boolean; function SaveToJson(const parentObj : TJsonObject) : boolean; public constructor Create(const logger : ILogger); end; implementation uses System.SysUtils, Spring.Cryptography.DES, DPM.Core.Constants, DPM.Core.Utils.System, DPM.Core.Utils.Strings, DPM.Core.Utils.Enum, VSoft.Uri; { TSourceConfig } constructor TSourceConfig.Create(const logger : ILogger); begin inherited Create; FLogger := logger; FEnabled := true; FCrypt := CreateCrypt; FSourceType := TSourceType.Folder; end; //NOTE : DO NOT CHANGE THIS KEY - YOU WILL BREAK THINGS FOR EXISTING SOURCES! const key : array[0..23] of Byte = ($11, $03, $45, $6, $8A, $8B, $DD, $EF, $EE, $0C, $1A, $38, $26, $41, $32, $A0, $89, $AB, $CD, $EF, $01, $23, $45, $67); constructor TSourceConfig.Create(const name, source : string; const sourceType : TSourceType; const userName, password : string; const enabled : boolean); begin FName := name; FSource := source; FSourceType := sourceType; FUserName := userName; FPassword := password; FEnabled := enabled; end; function TSourceConfig.CreateCrypt : ISymmetricAlgorithm; begin result := TTripleDES.Create; result.CipherMode := TCipherMode.ECB; result.PaddingMode := TPaddingMode.PKCS7; result.Key := TBuffer.Create(key); end; function TSourceConfig.DecryptString(const value : string) : string; var input : TBuffer; output : TBuffer; begin input := TBuffer.FromHexString(value); output := FCrypt.Decrypt(input); result := TEncoding.Unicode.GetString(output.AsBytes); end; function TSourceConfig.EncryptString(const value : string) : string; var input : TBuffer; output : TBuffer; begin input := TBuffer.Create(value); output := FCrypt.Encrypt(input); result := output.ToHexString; end; function TSourceConfig.GetIsEnabled : Boolean; begin result := FEnabled; end; function TSourceConfig.GetFileName : string; begin result := FFileName; end; function TSourceConfig.GetIsHttp : Boolean; begin result := TStringUtils.StartsWith(LowerCase(FSource), 'http://') or TStringUtils.StartsWith(LowerCase(FSource), 'https://') end; function TSourceConfig.GetName : string; begin result := FName; end; function TSourceConfig.GetPassword : string; begin result := FPassword; end; function TSourceConfig.GetUserName : string; begin result := FUserName; end; function TSourceConfig.GetSource : string; begin result := FSource; end; function TSourceConfig.GetSourceType : TSourceType; begin result := FSourceType; end; function TSourceConfig.LoadFromJson(const jsonObj : TJsonObject) : boolean; var srcType : string; uri : IUri; begin result := true; FName := jsonObj.S['name']; FSource := jsonObj.S['source']; FUserName := jsonObj.S['userName']; FPassword := jsonObj.S['password']; srcType := jsonObj.S['type']; if FPassword <> '' then FPassword := DecryptString(FPassword); if jsonObj.Contains('enabled') then FEnabled := jsonObj.B['enabled']; if srcType <> '' then FSourceType := TEnumUtils.StringtoEnum<TSourceType>(srcType) else FSourceType := TSourceType.Folder; //source type was added later so we can differenciate between //remote source types like github and https servers if FSourceType = TSourceType.Folder then begin //it might not have been set before, so we need to figure it out. if TUriFactory.TryParse(FSource, false, uri) then begin if (uri.Scheme <> 'file') then begin if (uri.Scheme = 'http') or (uri.Scheme = 'https') then FSourceType := TSourceType.DPMServer else raise EArgumentOutOfRangeException.Create('Invalid Source uri scheme - only https or file supported. '); end; end; end; end; function TSourceConfig.SaveToJson(const parentObj : TJsonObject) : boolean; var sourceObj : TJsonObject; begin sourceObj := parentObj.A['packageSources'].AddObject; sourceObj.S['name'] := FName; sourceObj.S['source'] := FSource; if FUserName <> '' then sourceObj.S['userName'] := FUserName; sourceObj.S['type'] := TEnumUtils.EnumToString<TSourceType>(FSourceType); if FPassword <> '' then sourceObj.S['password'] := EncryptString(FPassword); sourceObj.B['enabled'] := FEnabled; result := true; end; procedure TSourceConfig.SetIsEnabled(const value : Boolean); begin FEnabled := value; end; procedure TSourceConfig.SetName(const value : string); begin FName := value; end; procedure TSourceConfig.SetPassword(const value : string); begin FPassword := value; end; procedure TSourceConfig.SetUserName(const value : string); begin FUserName := value; end; procedure TSourceConfig.SetSource(const value : string); begin FSource := value; end; procedure TSourceConfig.SetSourceType(const value : TSourceType); begin FSourceType := value; end; { TConfiguration } procedure TConfiguration.AddDefaultSources; var source : ISourceConfig; begin source := TSourceConfig.Create('DPM', 'https://delphi.dev/api/v1/index.json', TSourceType.DPMServer, '', '', true); FSources.Add(source); end; constructor TConfiguration.Create(const logger : ILogger); begin inherited Create; FLogger := logger; FSources := TCollections.CreateList<ISourceConfig>; end; function TConfiguration.GetFileName : string; begin result := FFileName; end; function TConfiguration.GetIsDefaultPackageCacheLocation : Boolean; begin result := SameText(FPackageCacheLocation, cDefaultPackageCache) or SameText(FPackageCacheLocation, TSystemUtils.ExpandEnvironmentStrings(cDefaultPackageCache)); end; function TConfiguration.GetPackageCacheLocation : string; begin result := FPackageCacheLocation; end; function TConfiguration.GetSourceByName(const name: string): ISourceConfig; var sourceConfig : ISourceConfig; begin result := nil; for sourceConfig in FSources do begin if SameText(sourceConfig.Name, name) then exit(sourceConfig); end; end; function TConfiguration.GetSources : IList<ISourceConfig>; begin result := FSources; end; function TConfiguration.LoadFromFile(const fileName : string) : boolean; var jsonObj : TJsonObject; begin result := false; try jsonObj := TJsonObject.ParseFromFile(fileName) as TJsonObject; try Result := LoadFromJson(jsonObj); FFileName := fileName; finally jsonObj.Free; end; except on e : Exception do begin FLogger.Error('Exception while loading config file [' + fileName + ']' + #13#10 + e.Message); exit; end; end; end; function TConfiguration.LoadFromJson(const jsonObj : TJsonObject) : boolean; var sourcesArray : TJsonArray; source : ISourceConfig; bResult : boolean; i : integer; begin result := true; FPackageCacheLocation := jsonObj['packageCacheLocation']; sourcesArray := jsonObj.A['packageSources']; bResult := false; for i := 0 to sourcesArray.Count - 1 do begin source := TSourceConfig.Create(FLogger); bResult := source.LoadFromJson(sourcesArray.O[i]); if bResult then begin if not FSources.Any( function(const item : ISourceConfig) : boolean begin result := SameText(item.Name, source.Name); end) then begin FSources.Add(source); end; end; end; if not FSources.Any( function(const item : ISourceConfig) : boolean begin result := SameText(item.Name, 'DPM') end) then begin AddDefaultSources; end; result := result and bResult; end; function TConfiguration.SaveToFile(const fileName : string) : boolean; var sFileName : string; jsonObj : TJsonObject; begin if fileName <> '' then sFileName := fileName else sFileName := FFileName; if sFileName = '' then begin FLogger.Error('No filename set for config file, unable to save'); exit(false); end; jsonObj := TJsonObject.Create; try try result := SaveToJson(jsonObj); if result then jsonObj.SaveToFile(sFileName, false); FFileName := sFileName; except on e : Exception do begin FLogger.Error('Exception while saving config to file [' + sFileName + ']' + #13#10 + e.Message); result := false; end; end; finally jsonObj.Free; end; end; function TConfiguration.SaveToJson(const parentObj : TJsonObject) : boolean; var i : integer; begin result := true; parentObj['packageCacheLocation'] := FPackageCacheLocation; for i := 0 to FSources.Count - 1 do result := FSources[i].SaveToJson(parentObj) and result; end; procedure TConfiguration.SetFileName(const value : string); begin FFileName := value; end; procedure TConfiguration.SetPackageCacheLocation(const value : string); begin FPackageCacheLocation := value; end; end.
{ publish with BSD Licence. Copyright (c) Terry Lao } unit iLBC_define; {$MODE Delphi} interface Const { general codec settings } FS = 8000.0; BLOCKL_20MS = 160 ; BLOCKL_30MS = 240 ; BLOCKL_MAX = 240 ; NSUB_20MS = 4 ; NSUB_30MS = 6 ; NSUB_MAX = 6 ; NASUB_20MS = 2 ; NASUB_30MS = 4 ; NASUB_MAX = 4 ; SUBL =40 ; STATE_LEN = 80; STATE_SHORT_LEN_30MS= 58; STATE_SHORT_LEN_20MS= 57; { LPC settings } LPC_FILTERORDER = 10 ; LPC_CHIRP_SYNTDENUM = 0.9025 ; LPC_CHIRP_WEIGHTDENUM = 0.4222 ; LPC_LOOKBACK = 60 ; LPC_N_20MS = 1 ; LPC_N_30MS = 2 ; LPC_N_MAX = 2 ; LPC_ASYMDIFF = 20 ; LPC_BW = 60.0 ; LPC_WN = 1.0001 ; LSF_NSPLIT = 3 ; LSF_NUMBER_OF_STEPS = 4 ; LPC_HALFORDER = (LPC_FILTERORDER div 2); { cb settings } CB_NSTAGES = 3 ; CB_EXPAND = 2 ; CB_MEML = 147 ; CB_FILTERLEN = 2*4 ; CB_HALFFILTERLEN = 4 ; CB_RESRANGE = 34 ; CB_MAXGAIN = 1.3 ; { enhancer } ENH_BLOCKL = 80; { block length } ENH_BLOCKL_HALF = (ENH_BLOCKL div 2); ENH_HL = 3; { 2*ENH_HL+1 is number blocks in said second sequence } ENH_SLOP = 2; { max difference estimated and correct pitch period } ENH_PLOCSL = 20; { pitch-estimates and pitch- locations buffer length } ENH_OVERHANG = 2; ENH_UPS0 = 4; { upsampling rate } ENH_FL0 = 3; { 2*FLO+1 is the length of each filter } ENH_VECTL = (ENH_BLOCKL+2*ENH_FL0); ENH_CORRDIM = (2*ENH_SLOP+1); ENH_NBLOCKS = (BLOCKL_MAX div ENH_BLOCKL); ENH_NBLOCKS_EXTRA = 5; ENH_NBLOCKS_TOT = 8; { ENH_NBLOCKS + ENH_NBLOCKS_EXTRA } ENH_BUFL = (ENH_NBLOCKS_TOT)*ENH_BLOCKL; ENH_ALPHA0 = 0.05; { Down sampling } FILTERORDER_DS = 7; DELAY_DS = 3 ; FACTOR_DS = 2; { bit stream defs } NO_OF_BYTES_20MS = 38 ; NO_OF_BYTES_30MS = 50 ; NO_OF_WORDS_20MS = 19 ; NO_OF_WORDS_30MS = 25 ; STATE_BITS = 3; BYTE_LEN = 8 ; ULP_CLASSES = 3; { help parameters } FLOAT_MAX = 1.0e37 ; EPS = 2.220446049250313e-016; PI = 3.14159265358979323846; MIN_SAMPLE = -32768 ; MAX_SAMPLE = 32767 ; TWO_PI = 6.283185307 ; PI2 = 0.159154943 ; Type { type definition encoder instance } piLBC_ULP_Inst_t=^iLBC_ULP_Inst_t; iLBC_ULP_Inst_t=record lsf_bits: array [0..5,0..ULP_CLASSES+1] of Integer; start_bits: array [0..ULP_CLASSES+1] of Integer; startfirst_bits:array [0..ULP_CLASSES+1] of Integer; scale_bits:array [0..ULP_CLASSES+1] of integer; state_bits:array [0..ULP_CLASSES+1] of integer; extra_cb_index:array [0..CB_NSTAGES-1,0..ULP_CLASSES+1] of integer; extra_cb_gain:array [0..CB_NSTAGES-1,0..ULP_CLASSES+1] of integer; cb_index:array [0..NSUB_MAX-1,0..CB_NSTAGES-1,0..ULP_CLASSES+1] of integer; cb_gain:array [0..NSUB_MAX-1,0..CB_NSTAGES-1,0..ULP_CLASSES+1] of integer; end; { type definition encoder instance } piLBC_Enc_Inst_t=^iLBC_Enc_Inst_t; iLBC_Enc_Inst_t=record { flag for frame size mode } mode:integer; { basic parameters for different frame sizes } blockl:integer; nsub:integer; nasub:integer; no_of_bytes, no_of_words:integer; lpc_n:integer; state_short_len:integer; ULP_inst:^iLBC_ULP_Inst_t; { analysis filter state } anaMem:array [0..LPC_FILTERORDER-1] of real; { old lsf parameters for interpolation } lsfold:array [0..LPC_FILTERORDER-1] of real; lsfdeqold:array [0..LPC_FILTERORDER-1] of real; { signal buffer for LP analysis } lpc_buffer:array [0..LPC_LOOKBACK + BLOCKL_MAX-1] of real; { state of input HP filter } hpimem:array [0..3] of real; end; { type definition decoder instance } piLBC_Dec_Inst_t=^iLBC_Dec_Inst_t; iLBC_Dec_Inst_t=record { flag for frame size mode } mode:integer; { basic parameters for different frame sizes } blockl:integer; nsub:integer; nasub:integer; no_of_bytes, no_of_words:integer; lpc_n:integer; state_short_len:integer; ULP_inst:^iLBC_ULP_Inst_t; { synthesis filter state } syntMem:array [0..LPC_FILTERORDER-1] of real; { old LSF for interpolation } lsfdeqold:array [0..LPC_FILTERORDER-1 ] of real; { pitch lag estimated in enhancer and used in PLC } last_lag:integer; { PLC state information } prevLag, consPLICount, prevPLI, prev_enh_pl:integer; prevLpc:array [0..LPC_FILTERORDER] of real; prevResidual:array [0..NSUB_MAX*SUBL-1] of real; per:real; seed:cardinal; { previous synthesis filter parameters } old_syntdenum:array [0..(LPC_FILTERORDER + 1)*NSUB_MAX-1] of real; { state of output HP filter } hpomem:array [0..3] of real; { enhancer state information } use_enhancer:integer; enh_buf:array [0..ENH_BUFL-1] of real; enh_period:array [0..ENH_NBLOCKS_TOT-1] of real; end; implementation end.
unit uSplitPreSale; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, PAIDETODOS, DBTables, DB, Grids, LblEffct, ExtCtrls, StdCtrls, ADODB, siComp, siLangRT, DBGrids, SMDBGrid, DateBox, Mask, SuperComboADO, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid, Variants; type TSplitPreSale = class(TFrmParent) dsPreSaleItem: TDataSource; quPreSaleItem: TADOQuery; btSplit: TButton; spSplit: TADOStoredProc; quUnMarkAll: TADOQuery; quPreSaleItemIDPreInventoryMov: TIntegerField; quPreSaleItemDocumentID: TIntegerField; quPreSaleItemMarked: TBooleanField; quPreSaleItemModel: TStringField; quPreSaleItemDescription: TStringField; quPreSaleItemSalesPerson: TStringField; quPreSaleItemMovDate: TDateTimeField; quPreSaleItemDiscount: TFloatField; quPreSaleItemTotal: TFloatField; Panel4: TPanel; Panel5: TPanel; Label1: TLabel; EditCustomer: TEdit; pnlDeliver: TPanel; grdPreSaleItem: TcxGrid; grdPreSaleItemDBTableView1: TcxGridDBTableView; grdPreSaleItemLevel1: TcxGridLevel; grdPreSaleItemDBTableView1Marked: TcxGridDBColumn; grdPreSaleItemDBTableView1Description: TcxGridDBColumn; grdPreSaleItemDBTableView1Qty: TcxGridDBColumn; grdPreSaleItemDBTableView1Total: TcxGridDBColumn; grdPreSaleItemDBTableView1QtyRealMov: TcxGridDBColumn; quTotalToDivide: TADOQuery; grdPreSaleItemDBTableView1Model: TcxGridDBColumn; Panel9: TPanel; pnlTitle6: TPanel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label34: TLabel; Label6: TLabel; Label7: TLabel; scoDeliverType: TSuperComboADO; edtDate: TDateBox; edtAddress: TEdit; memOBS: TMemo; quPreSaleItemIDModel: TIntegerField; quPreSaleItemNotVerifyQty: TBooleanField; quPreSaleItemQty: TFloatField; quPreSaleItemQtyRealMov: TFloatField; quTotalToDivideTotalRealMov: TFloatField; quTotalToDivideTotalQty: TFloatField; quPreSaleItemDepartment: TStringField; grdPreSaleItemDBTableView1DBColumn1: TcxGridDBColumn; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btSplitClick(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure quPreSaleItemQtyRealMovValidate(Sender: TField); procedure grdPreSaleItemDBTableView1MarkedPropertiesChange( Sender: TObject); procedure grdPreSaleItemDBTableView1FocusedItemChanged( Sender: TcxCustomGridTableView; APrevFocusedItem, AFocusedItem: TcxCustomGridTableItem); procedure quPreSaleItemQtyRealMovChange(Sender: TField); procedure dsPreSaleItemDataChange(Sender: TObject; Field: TField); procedure dsPreSaleItemStateChange(Sender: TObject); procedure grdPreSaleItemExit(Sender: TObject); procedure scoDeliverTypeChange(Sender: TObject); procedure edtDateChange(Sender: TObject); procedure edtAddressChange(Sender: TObject); procedure scoDeliverTypeSelectItem(Sender: TObject); private { Private declarations } MyIDCustomer: Integer; MyDocumentID: integer; bIsExchangeItem : Boolean; procedure PreSaleItemOpen; procedure PreSaleItemClose; procedure ConcileOption; procedure DoPost; function ValidateDivide: Boolean; function CanDivide: Boolean; function MovingAllItems: Boolean; public { Public declarations } procedure Start(DocumentID, IDCustomer: integer; Customer, Address: String); end; implementation uses uDM, uMsgBox, uMsgConstant, uDMGlobal, uSystemConst, uPassword, DateUtils, uNumericFunctions; {$R *.DFM} procedure TSplitPreSale.PreSaleItemOpen; begin with quPreSaleItem do begin if Active then Close; Parameters.ParambyName('DocumentID').Value := MyDocumentID; Open; end; end; procedure TSplitPreSale.PreSaleItemClose; begin quPreSaleItem.Close; end; procedure TSplitPreSale.Start(DocumentID, IDCustomer: integer; Customer, Address: String); begin ConcileOption; editCustomer.Text := Customer; MyIDCustomer := IDCustomer; edtAddress.Text := Address; MyDocumentID := DocumentID; lblSubMenu.Caption := lblSubMenu.Caption + ' #' +IntToStr(DocumentID); ShowModal; end; procedure TSplitPreSale.FormShow(Sender: TObject); begin inherited; PreSaleItemOpen; with quPreSaleItem do begin grdPreSaleItem.Enabled := not isEmpty; //btSplit.Enabled := (not isEmpty) and CanDivide; {if not isEmpty then grdPreSaleItem. := clWindow else grdPreSaleItem.ParentColor := True;} end; bIsExchangeItem := False; end; procedure TSplitPreSale.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; PreSaleItemClose; Action := caFree; end; procedure TSplitPreSale.btSplitClick(Sender: TObject); var nHold : Integer; sDelivers : String; begin DoPost; nHold := 0; inherited; case DM.fSystem.SrvParam[PARAM_SALE_SCREEN_TYPE] of 1: begin with spSplit do begin Parameters.ParambyName('@IDPreSale').Value := MyDocumentID; ExecProc; nHold := Parameters.ParambyName('@NewIDPreSale').Value; end; FormShow(nil); end; 2: begin if not ValidateDivide then Exit; DM.fPOS.DivideHold(MyDocumentID, StrToInt(scoDeliverType.LookUpValue), edtDate.Date ,edtAddress.Text, memOBS.Text, nHold); sDelivers := DM.fPOS.GetCustomerDeliverOpenHold(MyIDCustomer, MyDocumentID); if sDelivers <> '' then MsgBox(Format(MSG_INF_INVOICE_NOT_DELEVERED, [EditCustomer.Text, sDelivers]), vbInformation + vbOkOnly); end; end; FormShow(nil); //if nHold <> 0 then // MsgBox(MSG_INF_PART_NEW_HOLD_NUMBER +' '+ IntToStr(nHold), vbOkOnly + vbInformation); end; procedure TSplitPreSale.btCloseClick(Sender: TObject); begin inherited; with quUnMarkAll do begin Parameters.ParambyName('DocumentID').Value := MyDocumentID; ExecSQL; end; Close; end; procedure TSplitPreSale.quPreSaleItemQtyRealMovValidate(Sender: TField); begin inherited; if ((IsNegative(quPreSaleItemQtyRealMov.Value) <> IsNegative(quPreSaleItemQty.Value)) and (quPreSaleItemQtyRealMov.Value <> 0)) or (Abs(quPreSaleItemQtyRealMov.Value) > Abs(quPreSaleItemQty.Value)) then raise Exception.Create(MSG_INF_NOT_EQUAL_QTY); end; procedure TSplitPreSale.ConcileOption; begin case DM.fSystem.SrvParam[PARAM_SALE_SCREEN_TYPE] of 1: begin pnlDeliver.Visible := False; quPreSaleItemQtyRealMov.Visible := False; end; 2: begin pnlDeliver.Visible := True; quPreSaleItemQtyRealMov.Visible := True; end; else begin pnlDeliver.Visible := False; quPreSaleItemQtyRealMov.Visible := False; end; end; grdPreSaleItemDBTableView1QtyRealMov.Visible := quPreSaleItemQtyRealMov.Visible; grdPreSaleItemDBTableView1Marked.Options.Editing := not quPreSaleItemQtyRealMov.Visible; grdPreSaleItemDBTableView1Marked.Properties.ReadOnly := quPreSaleItemQtyRealMov.Visible; end; procedure TSplitPreSale.grdPreSaleItemDBTableView1MarkedPropertiesChange( Sender: TObject); begin inherited; DoPost; end; procedure TSplitPreSale.grdPreSaleItemDBTableView1FocusedItemChanged( Sender: TcxCustomGridTableView; APrevFocusedItem, AFocusedItem: TcxCustomGridTableItem); begin inherited; DoPost; end; procedure TSplitPreSale.DoPost; begin if quPreSaleItem.State = dsEdit then quPreSaleItem.Post; end; procedure TSplitPreSale.quPreSaleItemQtyRealMovChange(Sender: TField); begin inherited; if Abs(quPreSaleItemQtyRealMov.NewValue) > 0 then begin if not quPreSaleItemMarked.AsBoolean then quPreSaleItemMarked.AsBoolean := True; end else quPreSaleItemMarked.AsBoolean := False; end; function TSplitPreSale.ValidateDivide : Boolean; var i : Integer; fQtyDelivered : Double; bHasDelivery : Boolean; AQtyAvaiable: Double; begin Result := False; if MovingAllItems then Exit; if scoDeliverType.LookUpValue = '' then begin MsgBox(MSG_INF_DELIVER_TYPE_EMPTY, vbCritical + vbOKOnly); scoDeliverType.SetFocus; Exit; end; if Trim(edtDate.Text) = '' then begin MsgBox(MSG_CRT_NO_DATE, vbCritical + vbOKOnly); edtDate.SetFocus; Exit; end; if edtDate.Date < Date then begin MsgBox(MSG_CRT_DELIVER_DATE_SMALER, vbCritical + vbOkOnly); edtDate.SetFocus; Exit; end; if Trim(edtAddress.Text) = '' then begin MsgBox(MSG_INF_NOT_EMPTY_ADDRESS, vbCritical + vbOKOnly); edtAddress.SetFocus; Exit; end; //Horas para entregar if (DM.fSystem.SrvParam[PARAM_MARK_DELIVERY_HOUR] <> -1) and (not Password.HasFuncRight(55)) then if CompareDate(edtDate.Date, (Now+1)) = 0 then if (HourOf(Now) > DM.fSystem.SrvParam[PARAM_MARK_DELIVERY_HOUR]) then begin i := DM.fSystem.SrvParam[PARAM_MARK_DELIVERY_HOUR]; MsgBox(Format(MSG_CRT_MARK_DELIVERY_NEXTDAY, [i]), vbCritical + vbOkOnly); Exit; end; //Verifica pgto antes de entregar if (DM.fSystem.SrvParam[PARAM_SALE_SCREEN_TYPE] = CASHREG_TYPE_OFFICE) and (DM.fSystem.SrvParam[PARAM_CONFIRM_DELIVERY_AFTER_FINISH_SALE] = True) and (not bIsExchangeItem) and DM.fSystem.SrvParam[PARAM_VERIFY_PGTO_BEFORE_DELIVERY] = True then begin if DM.fPOS.HasPaymentPending(MyDocumentID) then begin MsgBox(MSG_INF_PAYMENT_NOT_RECEIVE, vbCritical + vbOkOnly); Exit; end; end; if (DM.fSystem.SrvParam[PARAM_SALE_SCREEN_TYPE] = 2) and (DM.fSystem.SrvParam[PARAM_CONFIRM_DELIVERY_AFTER_FINISH_SALE] = True) and (not bIsExchangeItem) then begin quPreSaleItem.DisableControls; quPreSaleItem.First; try while not quPreSaleItem.Eof do begin if quPreSaleItemMarked.AsBoolean and (not quPreSaleItemNotVerifyQty.AsBoolean) then if (quPreSaleItemQty.AsFloat >= 0) then begin //Verificar estoque if DM.fPOS.IsNegativeStoreDelivery(MyDocumentID, DM.fStore.IDStoreSale, quPreSaleItemIDModel.AsInteger, AQtyAvaiable ) then begin MsgBox(Format(MSG_CRT_INVENTORY_NEGATIVE, [quPreSaleItemModel.AsString]), vbCritical + vbOkOnly); Exit; end; if (AQtyAvaiable - quPreSaleItemQtyRealMov.AsFloat) < 0 then begin MsgBox(Format(MSG_CRT_UNAVAIlABLE_INVENTORY, [quPreSaleItemModel.AsString]), vbCritical + vbOkOnly); Exit; end; //Verificar entrega fQtyDelivered := DM.fPOS.QtyInDelivered(quPreSaleItemIDModel.AsInteger, DM.fStore.IDStoreSale, bHasDelivery); if (bHasDelivery) and (fQtyDelivered < quPreSaleItemQtyRealMov.AsFloat) then begin MsgBox(Format(MSG_CRT_MODEL_IS_IN_DELIVER, [quPreSaleItemModel.AsString]), vbCritical + vbOkOnly); Exit; end; //Validade last delivery if Password.HasFuncRight(87) then if not DM.fPOS.CanMarkDelivery(quPreSaleItemDocumentID.AsInteger, quPreSaleItemIDModel.AsInteger, quPreSaleItemMovDate.AsDateTime, AQtyAvaiable, quPreSaleItemQtyRealMov.AsFloat) then begin MsgBox(Format(MSG_CRT_CANNOT_MARK_DELIVER, [quPreSaleItemModel.AsString]), vbCritical + vbOkOnly); Exit; end; end; quPreSaleItem.Next; end; finally quPreSaleItem.EnableControls; end; end; Result := True end; function TSplitPreSale.CanDivide : Boolean; var sMaxDays : String; begin if (scoDeliverType.LookUpValue <> '') and (edtDate.Date <> null) then begin sMaxDays := DM.DescCodigo(['IDDeliverType'], [scoDeliverType.LookUpValue], 'DeliverType', 'MaxDeliverDelay'); if sMaxDays <> '' then begin if Trunc(edtDate.Date) > (Date + StrToInt(sMaxDays)) then begin MsgBox(MSG_INF_MAX_DELIVERY_DAYS1 + sMaxDays + MSG_INF_MAX_DELIVERY_DAYS2, vbCritical + vbOKOnly); Result := False; Exit; end; end; end; if DM.fSystem.SrvParam[PARAM_SALE_SCREEN_TYPE] = CASHREG_TYPE_OFFICE then begin Result := (scoDeliverType.LookUpValue <> '') and (Trim(edtDate.Text) <> '') and (Trim(edtAddress.Text) <> ''); if not Result then Exit; quTotalToDivide.Close; quTotalToDivide.Parameters.ParamByName('DocumentID').Value := MyDocumentID; try quTotalToDivide.Open; Result := (quTotalToDivideTotalRealMov.Value <> 0); finally quTotalToDivide.Close; end; end else begin Result := True; end; end; function TSplitPreSale.MovingAllItems : Boolean; begin Result := True; quTotalToDivide.Close; quTotalToDivide.Parameters.ParamByName('DocumentID').Value := MyDocumentID; try quTotalToDivide.Open; Result := (quTotalToDivideTotalRealMov.Value >= quTotalToDivideTotalQty.Value); if Result then MsgBox(MSG_INF_NOT_SPLIT_ALL_ITEMS, vbCritical + vbOKOnly); finally quTotalToDivide.Close; end; end; procedure TSplitPreSale.dsPreSaleItemDataChange(Sender: TObject; Field: TField); begin inherited; btSplit.Enabled := CanDivide; end; procedure TSplitPreSale.dsPreSaleItemStateChange(Sender: TObject); begin inherited; btSplit.Enabled := CanDivide; end; procedure TSplitPreSale.grdPreSaleItemExit(Sender: TObject); begin inherited; DoPost; end; procedure TSplitPreSale.scoDeliverTypeChange(Sender: TObject); begin inherited; btSplit.Enabled := CanDivide; end; procedure TSplitPreSale.edtDateChange(Sender: TObject); begin inherited; btSplit.Enabled := CanDivide; end; procedure TSplitPreSale.edtAddressChange(Sender: TObject); begin inherited; btSplit.Enabled := CanDivide; end; procedure TSplitPreSale.scoDeliverTypeSelectItem(Sender: TObject); var fIsExchange : Variant; begin inherited; fIsExchange := scoDeliverType.GetFieldByName('CanExchangeItem'); if fIsExchange <> Null then bIsExchangeItem := StrToBoolDef(fIsExchange, False) else bIsExchangeItem := False; end; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_BASERUNNER.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} unit PAXCOMP_BASERUNNER; interface uses {$I uses.def} {$ifdef DRTTI} RTTI, PAXCOMP_2010, PAXCOMP_2010REG, {$endif} SysUtils, Classes, TypInfo, PAXCOMP_CONSTANTS, PAXCOMP_TYPES, PAXCOMP_SYS, PAXCOMP_CLASSLST, PAXCOMP_CLASSFACT, PAXCOMP_TYPEINFO, PAXCOMP_OFFSET, PAXCOMP_RTI, PAXCOMP_PROGLIST, PAXCOMP_MAP, PAXCOMP_STDLIB, PAXCOMP_SYMBOL_REC, PAXCOMP_BASESYMBOL_TABLE, PAXCOMP_LOCALSYMBOL_TABLE, PAXCOMP_INVOKE, PAXCOMP_GC, PAXCOMP_BRIDGE, PaxInvoke; type TBaseRunner = class private fClassList: TClassList; fSearchPathList: TStringList; fRunMode: Integer; fIsEvent: Boolean; fInitCallStackCount: Integer; fIsRunning: Boolean; fProcessingExceptBlock: Boolean; fExceptionIsAvailableForHostApplication: Boolean; fHasError: Boolean; fInitializationProcessed: Boolean; function GetRootOwner: TObject; function GetDataPtr: PBytes; function GetRootSearchPathList: TStringList; function GetRunMode: Integer; procedure SetRunMode(value: Integer); function GetIsEvent: Boolean; procedure SetIsEvent(value: Boolean); function GetInitCallStackCount: Integer; procedure SetInitCallStackCount(value: Integer); function GetIsRunning: Boolean; procedure SetIsRunning(value: Boolean); function GetProcessingExceptBlock: Boolean; procedure SetProcessingExceptBlock(value: Boolean); function GetExceptionIsAvailableForHostApplication: Boolean; procedure SetExceptionIsAvailableForHostApplication(value: Boolean); function GetHasError: Boolean; procedure SetHasError(value: Boolean); protected gInstance: TObject; function GetCodePtr: PBytes; virtual; function GetProgramSize: Integer; virtual; abstract; function _VirtualAlloc(Address: Pointer; Size, flAllocType, flProtect: Cardinal): Pointer; virtual; procedure _VirtualFree(Address: Pointer; Size: Cardinal); virtual; procedure Protect; virtual; procedure UnProtect; virtual; procedure RunInternal; virtual; procedure RunExceptInitialization; virtual; function FireAddressEvent(MR: TMapRec): Pointer; virtual; public Owner: TObject; PCUOwner: TBaseRunner; Data: Pointer; Prog: Pointer; fDataSize: Integer; fCodeSize: Integer; fCurrException: Exception; fPrevException: Exception; fImageDataPtr: Integer; CurrExpr: String; IsHalted: Boolean; JS_Record: TJS_Record; PCULang: Byte; ExitCode: Integer; SuspendFinalization: Boolean; ExceptionRec: Pointer; PausedPCU: TBaseRunner; UseMapping: Boolean; Console: Boolean; ModeSEH: Boolean; PAX64: Boolean; InitializationIsProcessed: Boolean; {$IFNDEF PAXARM_DEVICE} EPoint: TInvoke; {$ENDIF} JS_Object: TObject; JS_Boolean: TObject; JS_String: TObject; JS_Number: TObject; JS_Date: TObject; JS_Function: TObject; JS_Array: TObject; JS_RegExp: TObject; JS_Math: TObject; JS_Error: TObject; {$IFDEF ARC} ContextList: TList<TObject>; {$ELSE} ContextList: TList; {$ENDIF} ProgTag: Integer; fGC: TGC; PassedClassRef: TClass; SavedClass: TClass; OnMapTableNamespace: TMapTableNamespaceEvent; OnMapTableVarAddress: TMapTableVarAddressEvent; OnMapTableProcAddress: TMapTableProcAddressEvent; OnMapTableClassRef: TMapTableClassRefEvent; OnLoadPCU: TLoadPCUEvent; OnException: TErrNotifyEvent; OnUnhandledException: TErrNotifyEvent; OnPause: TPauseNotifyEvent; OnPauseUpdated: TPauseNotifyEvent; OnHalt: THaltNotifyEvent; OnLoadProc: TLoadProcEvent; OnBeforeCallHost: TIdNotifyEvent; OnAfterCallHost: TIdNotifyEvent; OnCreateObject: TObjectNotifyEvent; OnAfterObjectCreation: TObjectNotifyEvent; OnDestroyObject: TObjectNotifyEvent; OnAfterObjectDestruction: TClassNotifyEvent; OnCreateHostObject: TObjectNotifyEvent; OnDestroyHostObject: TObjectNotifyEvent; OnPrint: TPrintEvent; OnPrintEx: TPrintExEvent; OnPrintClassTypeField: TPrintClassTypeFieldEvent; OnPrintClassTypeProp: TPrintClassTypePropEvent; OnCustomExceptionHelper: TCustomExceptionHelperEvent; OnSaveToStream: TStreamEvent; OnLoadFromStream: TStreamEvent; OnBeginProcNotifyEvent: TProcNotifyEvent; OnEndProcNotifyEvent: TProcNotifyEvent; OnVirtualObjectMethodCall: TVirtualObjectMethodCallEvent; OnVirtualObjectPutProperty: TVirtualObjectPutPropertyEvent; HostMapTable: TMapTable; ScriptMapTable: TMapTable; ProgClassFactory: TPaxClassFactory; MessageList: TMessageList; ExportList: TExportList; ProgTypeInfoList: TPaxTypeInfoList; OffsetList: TOffsetList; RunTimeModuleList: TRuntimeModuleList; DllList: TStringList; ProgList: TProgList; LocalSymbolTable: TProgSymbolTable; GlobalSym: TBaseSymbolTable; FinallyCount: Integer; ByteCodeGlobalEntryList: TIntegerDynArray; ByteCodeInterfaceSetupList: TIntegerList; constructor Create; virtual; destructor Destroy; override; procedure ClearCurrException; function GetRootGC: TGC; function GetDestructorAddress: Pointer; virtual; abstract; function NeedAllocAll: Boolean; virtual; function GetRootProg: TBaseRunner; procedure CreateClassFactory; procedure CreateGlobalJSObjects; procedure Deallocate; procedure Allocate(InitCodeSize, InitDataSize: Integer); procedure AllocateSimple(InitCodeSize, InitDataSize: Integer); procedure RegisterDefinitions(SymbolTable: TBaseSymbolTable); procedure ForceMappingEvents; procedure ForceMapping(SymbolTable: TBaseSymbolTable; Reassign: Boolean); procedure MapGlobal; procedure MapLocal; function HasAvailUnit(const FullName: String): Boolean; virtual; function LookUpAvailClass(const FullName: String): TClass; virtual; function LookUpAvailAddress(const FullName: String; OverCount: Integer): Pointer; virtual; {$IFDEF DRTTI} function LookUpAvailMethod(const FullName: String; OverCount: Integer): TRTTIMethod; {$ENDIF} procedure RegisterMember(LevelId: Integer; const Name: String; Address: Pointer); function RegisterNamespace(LevelId: Integer; const Name: String): Integer; function RegisterClassType(LevelId: Integer; C: TClass): Integer; {$IFNDEF PAXARM_DEVICE} procedure SetEntryPoint(EntryPoint: TPaxInvoke); virtual; abstract; procedure ResetEntryPoint(EntryPoint: TPaxInvoke); virtual; abstract; {$ENDIF} procedure SaveToStream(S: TStream); virtual; abstract; procedure LoadFromStream(S: TStream); virtual; abstract; procedure SaveToBuff(var Buff); procedure LoadFromBuff(var Buff); procedure SaveToFile(const Path: String); procedure LoadFromFile(const Path: String); procedure RebindEvents(AnInstance: TObject); virtual; procedure LoadDFMStream(Instance: TObject; S: TStream; const OnFindMethod: TFindMethodEvent = nil; const OnError: TReaderError = nil); procedure LoadDFMFile(Instance: TObject; const FileName: String; const OnFindMethod: TFindMethodEvent = nil; const OnError: TReaderError = nil); function CallFunc(const FullName: String; This: Pointer; const ParamList: array of OleVariant; OverCount: Integer = 0): OleVariant; virtual; abstract; function CallByteCode(InitN: Integer; This: Pointer; R_AX, R_CX, R_DX, R_8, R_9: IntPax; StackPtr: Pointer; ResultPtr: Pointer; var FT: Integer): Integer; virtual; procedure Run; virtual; abstract; procedure RunExtended; procedure Pause; virtual; abstract; procedure DiscardPause; virtual; abstract; procedure RemovePause; virtual; abstract; procedure ResetRun; virtual; abstract; function IsPaused: Boolean; virtual; abstract; function GetCallStackCount: Integer; virtual; abstract; function GetCallStackItem(I: Integer): Integer; virtual; abstract; function GetCallStackLineNumber(I: Integer): Integer; virtual; abstract; function GetCallStackModuleName(I: Integer): String; virtual; abstract; function GetCallStackModuleIndex(I: Integer): Integer; virtual; abstract; function GetCurrentSub: TMapRec; function GetCurrentFunctionFullName: String; procedure GetCurrentLocalVars(result: TStrings); procedure GetCurrentParams(result: TStrings); function Valid: Boolean; virtual; function GetIsRootProg: Boolean; procedure RunInitialization; virtual; procedure RunFinalization; virtual; procedure DiscardDebugMode; virtual; abstract; procedure RaiseError(const Message: string; params: array of Const); procedure SetGlobalSym(AGlobalSym: Pointer); virtual; function RegisterClass(C: TClass; const FullName: String; Offset: Integer = -1): TClassRec; function RegisterClassEx(C: TClass; const FullName: String; Offset: Integer; ClassIndex: Integer): TClassRec; procedure AssignEventHandlerRunner(MethodAddress: Pointer; Instance: TObject); virtual; abstract; procedure Reset; virtual; function CreateScriptObject(const ScriptClassName: String; const ParamList: array of const): TObject; virtual; abstract; procedure DestroyScriptObject(var X: TObject); function GetImageSize: Integer; function GetImageDataPtr: Integer; procedure CopyRootEvents; function GetResultPtr: Pointer; function GetByteCodeLine: Integer; virtual; procedure SetByteCodeLine(N: Integer); function GetSourceLine: Integer; function GetModuleName: String; function GetModuleIndex: Integer; function GetParamAddress(Offset: Integer): Pointer; overload; virtual; abstract; function GetLocalAddress(Offset: Integer): Pointer; overload; virtual; abstract; function GetParamAddress(StackFrameNumber, Offset: Integer): Pointer; overload; virtual; abstract; function GetLocalAddress(StackFrameNumber, Offset: Integer): Pointer; overload; virtual; abstract; procedure WrapMethodAddress(var Address: Pointer); function WrapGlobalAddress(var Address: Pointer): Integer; function GetAddress(Handle: Integer): Pointer; overload; function GetAddress(const FullName: String; var MR: TMapRec): Pointer; overload; function GetFieldAddress(X: TObject; const FieldName: String): Pointer; function LoadAddressEx(const FileName, ProcName: String; RunInit: Boolean; OverCount: Integer; var MR: TMapRec; var DestProg: Pointer): Pointer; virtual; function GetAddressEx(const FullName: String; OverCount: Integer; var MR: TMapRec): Pointer; function GetAddressExtended(const FullName: String; var MR: TMapRec): Pointer; overload; function GetAddressExtended(const FullName: String; OverCount: Integer; var MR: TMapRec): Pointer; overload; procedure SetAddress(Offset: Integer; P: Pointer); function SetHostAddress(const FullName: String; Address: Pointer): Boolean; procedure CopyRootBreakpoints(const UnitName: String); procedure InitMessageList; procedure CreateMapOffsets; function GetOffset(Shift: Integer): Integer; procedure SetupInterfaces(P: Pointer); function GetTypeInfo(const FullTypeName: String): PTypeInfo; function GetCallConv(const FullName: String): Integer; function GetRetSize(const FullName: String): Integer; function FileExists(const FileName: String; out FullPath: String): Boolean; procedure UnloadDlls; procedure UnloadPCU(const FullPath: String); procedure LoadPCU(const FileName: String; var DestProg: Pointer); function AddBreakpoint(const ModuleName: String; SourceLineNumber: Integer): TBreakpoint; function AddTempBreakpoint(const ModuleName: String; SourceLineNumber: Integer): TBreakpoint; function RemoveBreakpoint(const ModuleName: String; SourceLineNumber: Integer): Boolean; overload; function RemoveBreakpoint(const ModuleName: String): Boolean; overload; function HasBreakpoint(const ModuleName: String; SourceLineNumber: Integer): Boolean; procedure RemoveAllBreakpoints; function IsExecutableLine(const ModuleName: String; SourceLineNumber: Integer): Boolean; procedure SaveState(S: TStream); virtual; procedure LoadState(S: TStream); virtual; function GetInterfaceToObjectOffset(JumpN: Integer): Integer; virtual; function GetReturnFinalTypeId(InitSubN: Integer): Integer; virtual; property ClassList: TClassList read fClassList; property ResultPtr: Pointer read GetResultPtr; property DataPtr: PBytes read GetDataPtr; property DataSize: Integer read fDataSize write fDataSize; property CodePtr: PBytes read GetCodePtr; property IsRootProg: Boolean read GetIsRootProg; property RootSearchPathList: TStringList read GetRootSearchPathList; property RunMode: Integer read GetRunMode write SetRunMode; property IsRunning: Boolean read GetIsRunning write SetIsRunning; property CodeSize: Integer read fCodeSize write fCodeSize; property ProgramSize: Integer read GetProgramSize; property RootIsEvent: Boolean read GetIsEvent write SetIsEvent; property CurrException: Exception read fCurrException write fCurrException; property RootInitCallStackCount: Integer read GetInitCallStackCount write SetInitCallStackCount; property CurrN: Integer read GetByteCodeLine; property CurrS: Integer read GetSourceLine; property RootGC: TGC read GetRootGC; property RootOwner: TObject read GetRootOwner; property RootExceptionIsAvailableForHostApplication: Boolean read GetExceptionIsAvailableForHostApplication write SetExceptionIsAvailableForHostApplication; property ProcessingExceptBlock: Boolean read GetProcessingExceptBlock write SetProcessingExceptBlock; property HasError: Boolean read GetHasError write SetHasError; property InitializationProcessed: Boolean read fInitializationProcessed; end; TBaseRunnerClass = class of TBaseRunner; type TCreate_JSObjects = procedure(Prog: Pointer; R: TJS_Record); TEmitProc = procedure (kernel, prog: Pointer; context: Pointer = nil); TRegisterProc = procedure (st: TBaseSymbolTable); TAssignRunnerLib = procedure; var CrtJSObjects: TCreate_JSObjects = nil; CurrProg: TBaseRunner = nil; AssignRunnerLibProc: TAssignRunnerLib = nil; DefaultRunnerClass: TBaseRunnerClass; RegisterSEH: TRegisterProc = nil; dmp_procedure: procedure (sprog: Pointer = nil) = nil; dump_all_procedure: procedure(path: String; kernel, prog, sprog: Pointer); Address_Exit: Pointer = nil; Address_CondRaise: Pointer = nil; Address_LoadSeg: Pointer = nil; Address_CreateObject: Pointer = nil; Address_DestroyObject: Pointer = nil; Address_TryOn: Pointer = nil; Address_TryOff: Pointer = nil; Address_Raise: Pointer = nil; Address_Pause: Pointer = nil; Address_InitSub: Pointer = nil; Address_EndSub: Pointer = nil; Address_SetEventProp: Pointer = nil; Address_SetEventProp2: Pointer = nil; procedure dmp(sprog: Pointer = nil); procedure Dump_All(path: String; kernel, prog, sprog: Pointer); var CurrRunner: TBaseRunner; implementation procedure dmp(sprog: Pointer = nil); begin if Assigned(dmp_procedure) then dmp_procedure(sprog); end; procedure Dump_All(path: String; kernel, prog, sprog: Pointer); begin if Assigned(dump_all_procedure) then dump_all_procedure(path, kernel, prog, sprog); end; constructor TBaseRunner.Create; begin inherited; FindAvailTypes; GlobalSym := GlobalSymbolTable; fClassList := TClassList.Create; fSearchPathList := TStringList.Create; HostMapTable := TMapTable.Create; ScriptMapTable := TMapTable.Create; ProgClassFactory := TPaxClassFactory.Create; MessageList := TMessageList.Create; ExportList := TExportList.Create; ProgTypeInfoList := TPaxTypeInfoList.Create; OffsetList := TOffsetList.Create; RuntimeModuleList := TRuntimeModuleList.Create(Self); DllList := TStringList.Create; ProgList := TProgList.Create(Self); LocalSymbolTable := TProgSymbolTable.Create(GlobalSym); {$IFDEF ARC} ContextList := TList<TObject>.Create; {$ELSE} ContextList := TList.Create; {$ENDIF} fGC := TGC.Create; Data := nil; fDataSize := 0; fExceptionIsAvailableForHostApplication := true; ByteCodeInterfaceSetupList := TIntegerList.Create; end; destructor TBaseRunner.Destroy; begin FreeAndNil(fClassList); FreeAndNil(fSearchPathList); FreeAndNil(HostMapTable); FreeAndNil(ScriptMapTable); if ProgClassFactory <> nil then FreeAndNil(ProgClassFactory); FreeAndNil(MessageList); FreeAndNil(ExportList); FreeAndNil(ProgTypeInfoList); FreeAndNil(OffsetList); FreeAndNil(RuntimeModuleList); FreeAndNil(DllList); if ProgList <> nil then FreeAndNil(ProgList); FreeAndNil(LocalSymbolTable); FreeAndNil(ContextList); FreeAndNil(fGC); FreeAndNil(ByteCodeInterfaceSetupList); inherited; end; procedure TBaseRunner.Reset; begin fClassList.Clear; HostMapTable.Clear; ScriptMapTable.Clear; ProgClassFactory.Clear; MessageList.Clear; ExportList.Clear; ProgTypeInfoList.Clear; OffsetList.Clear; LocalSymbolTable.Reset; ContextList.Clear; if ProgList <> nil then ProgList.Clear; fGC.Clear; ByteCodeInterfaceSetupList.Clear; fInitializationProcessed := false; end; function TBaseRunner.RegisterClass(C: TClass; const FullName: String; Offset: Integer = -1): TClassRec; var P: Pointer; I: Integer; S: String; begin if (Offset = -1) or (Offset = 0) then begin S := C.ClassName; for I:=0 to fClassList.Count - 1 do if StrEql(fClassList.Names[I], S) then begin Offset := fClassList[I].Offset; break; end; if Offset = -1 then RaiseError(errCannotRegisterClass, [S]); end; P := ShiftPointer(DataPtr, Offset); Pointer(P^) := C; result := fClassList.AddClass(C, FullName, true, Offset); for I:=0 to result.PropInfos.Count - 1 do begin P := ShiftPointer(P, SizeOf(Pointer)); Pointer(P^) := result.PropInfos[I]; end; end; function TBaseRunner.RegisterClassEx(C: TClass; const FullName: String; Offset: Integer; ClassIndex: Integer): TClassRec; var P: Pointer; I: Integer; begin P := ShiftPointer(DataPtr, Offset); Pointer(P^) := C; result := fClassList.AddClassEx(C, FullName, true, Offset, ClassIndex); for I:=0 to result.PropInfos.Count - 1 do begin P := ShiftPointer(P, SizeOf(Pointer)); Pointer(P^) := result.PropInfos[I]; end; end; procedure TBaseRunner.RaiseError(const Message: string; params: array of Const); begin raise Exception.Create(Format(Message, params)); end; function TBaseRunner.GetDataPtr: PBytes; begin result := Data; end; procedure TBaseRunner.InitMessageList; var I: Integer; R: TMessageRec; MR: TMapRec; begin for I := 0 to MessageList.Count - 1 do begin R := MessageList[I]; R.Address := GetAddress(R.FullName, MR); R.Class_Name := ExtractClassName(R.FullName); R.Class_Name := ExtractName(R.Class_Name); end; for I := 0 to ProgClassFactory.Count - 1 do begin VmtDynamicTableSlot(ProgClassFactory[I].VMTPtr)^ := MessageList.CreateDmtTable(ExtractName(ProgClassFactory[I].FullClassName), ProgClassFactory[I].DmtTableSize); end; for I := 0 to ProgList.Count - 1 do TBaseRunner(ProgList[I].Prog).InitMessageList; end; procedure TBaseRunner.CreateMapOffsets; begin HostMapTable.CreateOffsets(OffsetList, true); ScriptMapTable.CreateOffsets(OffsetList, false); end; function TBaseRunner.GetOffset(Shift: Integer): Integer; begin if OffsetList.Count > 0 then begin if Shift <= 0 then begin result := Shift; Exit; end; result := OffsetList.GetOffset(Shift); end else result := Shift; end; function TBaseRunner.GetInterfaceToObjectOffset(JumpN: Integer): Integer; begin result := 0; end; function TBaseRunner.GetReturnFinalTypeId(InitSubN: Integer): Integer; begin result := 0; end; procedure TBaseRunner.SetupInterfaces(P: Pointer); var I, J, K, Index: Integer; ClassRec: TClassRec; IntfRec: TIntfRec; IntfMethodRec: TIntfMethodRec; A: Pointer; begin ByteCodeInterfaceSetupList.Clear; if P = nil then begin for I := 0 to ClassList.Count - 1 do begin ClassRec := ClassList[I]; for J := 0 to ClassRec.IntfList.Count - 1 do begin IntfRec := ClassRec.IntfList[J]; for K := 0 to IntfRec.IntfMethods.Count - 1 do begin IntfMethodRec := IntfRec.IntfMethods[K]; A := Pointer(IntfMethodRec.MethodOffset); Index := 0; if not NativeAddress(A) then begin WrapGlobalAddress(A); case K of 0: begin Index := ByteCodeInterfaceSetupList.Count; ByteCodeInterfaceSetupList.Add(IntfMethodRec.MethodOffset); end; 1: A := GetFakeAddRefAddress(Index); 2: A := GetFakeReleaseAddress(Index); end; end; IntfMethodRec.MethodOffset := IntPax(A); end; end; end; end; ClassList.SetupInterfaces(P); end; function TBaseRunner.GetTypeInfo(const FullTypeName: String): PTypeInfo; var R: TTypeInfoContainer; begin R := ProgTypeInfoList.LookupFullName(FullTypeName); if R = nil then result := nil else result := R.TypeInfoPtr; end; function TBaseRunner.GetCallConv(const FullName: String): Integer; var MapRec: TMapRec; begin result := ccREGISTER; MapRec := ScriptMapTable.Lookup(FullName); if MapRec <> nil then if MapRec.Kind in KindSUBS then begin result := MapRec.SubDesc.CallConv; Exit; end; MapRec := HostMapTable.Lookup(FullName); if MapRec <> nil then if MapRec.Kind in KindSUBS then result := MapRec.SubDesc.CallConv; end; function TBaseRunner.GetRetSize(const FullName: String): Integer; var MapRec: TMapRec; begin result := 0; MapRec := ScriptMapTable.Lookup(FullName); if MapRec <> nil then if MapRec.Kind in KindSUBS then begin result := MapRec.SubDesc.RetSize; Exit; end; MapRec := HostMapTable.Lookup(FullName); if MapRec <> nil then if MapRec.Kind in KindSUBS then result := MapRec.SubDesc.RetSize; end; procedure TBaseRunner.SaveToBuff(var Buff); var P: Pointer; S: TMemoryStream; begin P := @Buff; S := TMemoryStream.Create; try SaveToStream(S); S.Position := 0; S.Read(P^, S.Size); finally FreeAndNil(S); end; end; procedure TBaseRunner.LoadFromBuff(var Buff); var P: Pointer; temp: TMemoryStream; SZ: Integer; begin P := @Buff; temp := TMemoryStream.Create; try temp.Write(P^, SizeOf(Integer)); SZ := LongInt(P^); temp.Position := 0; temp.Write(P^, SZ); temp.Position := 0; LoadFromStream(temp); finally FreeAndNil(temp); end; end; procedure TBaseRunner.SaveToFile(const Path: String); var M: TMemoryStream; begin M := TMemoryStream.Create; try SaveToStream(M); M.Position := 0; M.SaveToFile(Path); finally FreeAndNil(M); end; end; procedure TBaseRunner.LoadFromFile(const Path: String); var M: TMemoryStream; begin M := TMemoryStream.Create; try M.LoadFromFile(Path); M.Position := 0; LoadFromStream(M); finally FreeAndNil(M); end; end; procedure TBaseRunner.RunInitialization; begin fInitializationProcessed := true; CurrRunner := Self; if fGC = RootGC then fGC.Clear; end; procedure TBaseRunner.RunFinalization; begin end; function TBaseRunner.GetRootProg: TBaseRunner; begin result := Self; while result.PCUOwner <> nil do result := result.PCUOwner; end; function TBaseRunner.GetIsRootProg: Boolean; begin result := PCUOwner = nil; end; function TBaseRunner.GetRootSearchPathList: TStringList; begin result := GetRootProg.fSearchPathList; end; function TBaseRunner.FileExists(const FileName: String; out FullPath: String): Boolean; var I: Integer; S: String; begin if SysUtils.FileExists(FileName) then begin result := true; FullPath := FileName; end else begin result := false; for I := 0 to RootSearchPathList.Count - 1 do begin S := RootSearchPathList[I] + FileName; if SysUtils.FileExists(S) then begin result := true; FullPath := S; Exit; end; end; FullPath := FileName; end; end; procedure TBaseRunner.CopyRootBreakpoints(const UnitName: String); var RP: TBaseRunner; I, L: Integer; begin RP := GetRootProg; for I := 0 to RP.RuntimeModuleList.BreakpointList.Count - 1 do if StrEql(UnitName, RP.RuntimeModuleList.BreakpointList[I].ModuleName) then begin L := RP.RuntimeModuleList.BreakpointList[I].SourceLine; AddBreakpoint(UnitName, L); end; end; procedure TBaseRunner.UnloadDlls; var H: Cardinal; begin while DllList.Count > 0 do begin H := Cardinal(DllList.Objects[0]); FreeLibrary(H); DllList.Delete(0); end; end; procedure TBaseRunner.CopyRootEvents; var RP: TBaseRunner; begin RP := GetRootProg; if Self <> RP then begin Owner := RP.Owner; OnException := RP.OnException; OnUnhandledException := RP.OnUnhandledException; OnPause := RP.OnPause; OnPauseUpdated := RP.OnPauseUpdated; OnHalt := RP.OnHalt; OnLoadProc := RP.OnLoadProc; OnCreateObject := RP.OnCreateObject; OnAfterObjectCreation := RP.OnAfterObjectCreation; OnDestroyObject := RP.OnDestroyObject; OnAfterObjectDestruction := RP.OnAfterObjectDestruction; OnMapTableNamespace := RP.OnMapTableNamespace; OnMapTableVarAddress := RP.OnMapTableVarAddress; OnMapTableProcAddress := RP.OnMapTableProcAddress; OnMapTableClassRef := RP.OnMapTableClassRef; OnLoadPCU := RP.OnLoadPCU; OnPrint := RP.OnPrint; OnCustomExceptionHelper := RP.OnCustomExceptionHelper; OnBeginProcNotifyEvent := RP.OnBeginProcNotifyEvent; OnEndProcNotifyEvent := RP.OnEndProcNotifyEvent; end; end; procedure TBaseRunner.SetAddress(Offset: Integer; P: Pointer); begin Move(P, DataPtr^[Offset], SizeOf(Pointer)); end; function TBaseRunner.SetHostAddress(const FullName: String; Address: Pointer): Boolean; var MR: TMapRec; P: Pointer; I: Integer; begin result := false; MR := HostMapTable.Lookup(FullName); if MR <> nil then if MR.Kind in KindSUBS + [KindVAR] then begin P := ShiftPointer(DataPtr, MR.Offset); Pointer(P^) := Address; result := true; end; for I:=0 to ProgList.Count - 1 do TBaseRunner(ProgList[I].Prog).SetHostAddress(FullName, Address); end; procedure TBaseRunner.UnloadPCU(const FullPath: String); var I: Integer; begin ProgList.RemoveProg(FullPath); for I := 0 to ProgList.Count - 1 do TBaseRunner(ProgList[I].Prog).UnloadPCU(FullPath); end; procedure TBaseRunner.LoadPCU(const FileName: String; var DestProg: Pointer); var P: TBaseRunner; UnitName, FullPath: String; ProgRec: TProgRec; InputStream: TStream; C: TBaseRunnerClass; begin DestProg := nil; FullPath := ''; UnitName := ExtractFullOwner(FileName); InputStream := nil; if Assigned(OnLoadPCU) then OnLoadPCU(Owner, UnitName, InputStream); if InputStream = nil then if not FileExists(FileName, FullPath) then begin RaiseError(errFileNotFound, [FileName]); end; C := TBaseRunnerClass(ClassType); P := C.Create; P.PCUOwner := Self; if InputStream <> nil then P.LoadFromStream(InputStream) else P.LoadFromFile(FullPath); ProgRec := TProgRec.Create; ProgRec.FullPath := FullPath; ProgRec.Prog := P; ProgList.Add(ProgRec); P.CopyRootEvents; end; function TBaseRunner.GetAddressExtended(const FullName: String; var MR: TMapRec): Pointer; var I: Integer; begin result := GetAddress(FullName, MR); if result <> nil then Exit; for I := 0 to ProgList.Count - 1 do begin result := TBaseRunner(ProgList[I].Prog).GetAddressExtended(FullName, MR); if result <> nil then Exit; end; end; function TBaseRunner.GetAddressExtended(const FullName: String; OverCount: Integer; var MR: TMapRec): Pointer; var I: Integer; begin result := GetAddressEx(FullName, OverCount, MR); if result <> nil then Exit; for I := 0 to ProgList.Count - 1 do begin result := TBaseRunner(ProgList[I].Prog).GetAddressExtended(FullName, OverCount, MR); if result <> nil then Exit; end; end; function TBaseRunner.AddBreakpoint(const ModuleName: String; SourceLineNumber: Integer): TBreakpoint; var I: Integer; P: TBaseRunner; begin for I := 0 to ProgList.Count - 1 do begin P := TBaseRunner(ProgList[I].Prog); result := P.AddBreakpoint(ModuleName, SourceLineNumber); if result <> nil then Exit; end; result := RunTimeModuleList.AddBreakpoint(ModuleName, SourceLineNumber); end; function TBaseRunner.AddTempBreakpoint(const ModuleName: String; SourceLineNumber: Integer): TBreakpoint; var I: Integer; P: TBaseRunner; begin for I := 0 to ProgList.Count - 1 do begin P := TBaseRunner(ProgList[I].Prog); result := P.AddTempBreakpoint(ModuleName, SourceLineNumber); if result <> nil then Exit; end; result := RunTimeModuleList.AddTempBreakpoint(ModuleName, SourceLineNumber); end; function TBaseRunner.RemoveBreakpoint(const ModuleName: String; SourceLineNumber: Integer): Boolean; var I: Integer; P: TBaseRunner; begin for I := 0 to ProgList.Count - 1 do begin P := TBaseRunner(ProgList[I].Prog); result := P.RemoveBreakpoint(ModuleName, SourceLineNumber); if result then Exit; end; result := RunTimeModuleList.RemoveBreakpoint(ModuleName, SourceLineNumber); end; function TBaseRunner.RemoveBreakpoint(const ModuleName: String): Boolean; var I: Integer; P: TBaseRunner; begin for I := 0 to ProgList.Count - 1 do begin P := TBaseRunner(ProgList[I].Prog); result := P.RemoveBreakpoint(ModuleName); if result then Exit; end; result := RunTimeModuleList.RemoveBreakpoint(ModuleName); end; function TBaseRunner.HasBreakpoint(const ModuleName: String; SourceLineNumber: Integer): Boolean; var I: Integer; P: TBaseRunner; begin for I := 0 to ProgList.Count - 1 do begin P := TBaseRunner(ProgList[I].Prog); result := P.HasBreakpoint(ModuleName, SourceLineNumber); if result then Exit; end; result := RunTimeModuleList.HasBreakpoint(ModuleName, SourceLineNumber); end; procedure TBaseRunner.RemoveAllBreakpoints; var I: Integer; P: TBaseRunner; begin for I := 0 to ProgList.Count - 1 do begin P := TBaseRunner(ProgList[I].Prog); P.RemoveAllBreakpoints; end; RunTimeModuleList.RemoveAllBreakpoints; end; function TBaseRunner.IsExecutableLine(const ModuleName: String; SourceLineNumber: Integer): Boolean; var I: Integer; P: TBaseRunner; begin for I := 0 to ProgList.Count - 1 do begin P := TBaseRunner(ProgList[I].Prog); result := P.IsExecutableLine(ModuleName, SourceLineNumber); if result then Exit; end; result := RunTimeModuleList.IsExecutableLine(ModuleName, SourceLineNumber); end; function TBaseRunner.GetByteCodeLine: Integer; var P: Pointer; begin P := ShiftPointer(Data, H_ByteCodePtr); result := LongInt(P^); end; procedure TBaseRunner.SetByteCodeLine(N: Integer); var P: Pointer; begin P := ShiftPointer(Data, H_ByteCodePtr); LongInt(P^) := N; end; function TBaseRunner.GetSourceLine: Integer; begin result := GetByteCodeLine; if result = - 1 then Exit; result := RunTimeModuleList.GetSourceLine(result); end; function TBaseRunner.GetModuleName: String; var ByteCodeLine: Integer; begin result := ''; ByteCodeLine := GetByteCodeLine; if ByteCodeLine = - 1 then Exit; result := RunTimeModuleList.GetModuleName(ByteCodeLine); end; function TBaseRunner.GetModuleIndex: Integer; var ByteCodeLine: Integer; begin result := -1; ByteCodeLine := GetByteCodeLine; if ByteCodeLine = - 1 then Exit; result := RunTimeModuleList.GetModuleIndex(ByteCodeLine); end; function TBaseRunner.GetRunMode: Integer; begin result := GetRootProg.fRunMode; end; procedure TBaseRunner.SetRunMode(value: Integer); begin GetRootProg.fRunMode := value; end; function TBaseRunner.GetCodePtr: PBytes; begin result := nil; end; function TBaseRunner.Valid: Boolean; begin result := (Data <> nil); end; function TBaseRunner.GetResultPtr: Pointer; begin result := Data; end; procedure TBaseRunner.CreateGlobalJSObjects; begin if Assigned(CrtJSObjects) then CrtJSObjects(Self, JS_Record); end; function TBaseRunner.GetImageSize: Integer; var S: TMemoryStream; begin S := TMemoryStream.Create; try SaveToStream(S); result := S.Size; finally FreeAndNil(S); end; end; function TBaseRunner.GetImageDataPtr: Integer; begin if fImageDataPtr = 0 then GetImageSize; result := fImageDataPtr; end; procedure TBaseRunner.DestroyScriptObject(var X: TObject); begin FreeAndNil(X); end; function TBaseRunner.GetFieldAddress(X: TObject; const FieldName: String): Pointer; var MapRec: TMapRec; MapFieldRec: TMapFieldRec; begin if IsPaxObject(X) then begin MapRec := ScriptMapTable.LookupType(X.ClassName); if MapRec <> nil then begin if MapRec.FieldList = nil then RaiseError(errInternalError, []); MapFieldRec := MapRec.FieldList.Lookup(FieldName); if MapFieldRec = nil then result := nil else result := ShiftPointer(X, MapFieldRec.FieldOffset); end else result := X.FieldAddress(FieldName); end else result := X.FieldAddress(FieldName); end; function TBaseRunner.GetIsEvent: Boolean; begin result := GetRootProg.fIsEvent; end; procedure TBaseRunner.SetIsEvent(value: Boolean); begin GetRootProg.fIsEvent := value; end; function TBaseRunner.GetCurrentSub: TMapRec; var N: Integer; begin N := GetByteCodeLine; result := ScriptMapTable.GetSub(N); end; function TBaseRunner.GetCurrentFunctionFullName: String; var MR: TMapRec; begin result := ''; MR := GetCurrentSub; if MR = nil then Exit; result := MR.FullName; end; procedure TBaseRunner.GetCurrentLocalVars(result: TStrings); var MR: TMapRec; I: Integer; begin MR := GetCurrentSub; if MR = nil then Exit; if MR.SubDesc.LocalVarList.Count = 0 then Exit; for I := 0 to MR.SubDesc.LocalVarList.Count - 1 do result.Add(MR.SubDesc.LocalVarList[I].LocalVarName); end; procedure TBaseRunner.GetCurrentParams(result: TStrings); var MR: TMapRec; I: Integer; begin MR := GetCurrentSub; if MR = nil then Exit; if MR.SubDesc.ParamList.Count = 0 then Exit; for I := 0 to MR.SubDesc.ParamList.Count - 1 do result.Add(MR.SubDesc.ParamList[I].ParamName); end; procedure TBaseRunner.SetGlobalSym(AGlobalSym: Pointer); begin GlobalSym := TBaseSymbolTable(AGlobalSym); if LocalSymbolTable <> nil then FreeAndNil(LocalSymbolTable); LocalSymbolTable := TProgSymbolTable.Create(GlobalSym); end; procedure TBaseRunner.RegisterMember(LevelId: Integer; const Name: String; Address: Pointer); begin if LocalSymbolTable.Card = -1 then LocalSymbolTable.Reset; LocalSymbolTable.RegisterMember(LevelId, Name, Address); end; function TBaseRunner.RegisterNamespace(LevelId: Integer; const Name: String): Integer; begin if LocalSymbolTable.Card = -1 then LocalSymbolTable.Reset; result := LocalSymbolTable.RegisterNamespace(LevelId, Name); end; function TBaseRunner.RegisterClassType(LevelId: Integer; C: TClass): Integer; begin if LocalSymbolTable.Card = -1 then LocalSymbolTable.Reset; result := LocalSymbolTable.RegisterClassType(LevelId, C); end; procedure TBaseRunner.MapGlobal; begin ForceMapping(GlobalSym, true); end; procedure TBaseRunner.MapLocal; begin ForceMapping(LocalSymbolTable, true); end; procedure TBaseRunner.ForceMapping(SymbolTable: TBaseSymbolTable; Reassign: Boolean); var IsGlobal: Boolean; I, J: Integer; MapRec: TMapRec; FullName: String; P: Pointer; ClsRef: TClass; begin IsGlobal := SymbolTable = GlobalSym; if HostMapTable.Count > 0 then begin for I:=0 to HostMapTable.Count - 1 do begin MapRec := HostMapTable[I]; if MapRec.Global <> IsGlobal then continue; if MapRec.TypedConst then continue; FullName := MapRec.FullName; J := SymbolTable.LookupFullNameEx(FullName, true, MapRec.SubDesc.OverCount); if J > 0 then begin if MapRec.Kind = KindVAR then begin P := SymbolTable[J].Address; if P <> nil then begin if Reassign then begin if Assigned(OnMapTableVarAddress) then OnMapTableVarAddress(Owner, FullName, MapRec.Global, P); if P = nil then RaiseError(errUnresolvedAddress, [FullName]); SymbolTable[J].Address := P; end; SetAddress(MapRec.Offset, P); end else begin P := nil; if Assigned(OnMapTableVarAddress) then OnMapTableVarAddress(Owner, FullName, MapRec.Global, P); if P = nil then RaiseError(errUnresolvedAddress, [FullName]); SetAddress(MapRec.Offset, P); end; end else if MapRec.Kind in KindSUBS then begin P := nil; if Assigned(OnMapTableProcAddress) then OnMapTableProcAddress(Owner, FullName, MapRec.SubDesc.OverCount, MapRec.Global, P) else P := SymbolTable[J].Address; if P = nil then P := LookupAvailAddress(FullName, MapRec.SubDesc.OverCount); if P = nil then RaiseError(errUnresolvedAddress, [FullName]); SetAddress(MapRec.Offset, P); end else if MapRec.Kind = KindTYPE then begin ClsRef := nil; if Assigned(OnMapTableClassRef) then OnMapTableClassRef(Owner, FullName, MapRec.Global, ClsRef) else ClsRef := TClass(IntPax(SymbolTable[J + 1].Value)); if ClsRef = nil then ClsRef := LookupAvailClass(FullName); if ClsRef = nil then RaiseError(errUnresolvedClassReference, [FullName]) else RegisterClassEx(ClsRef, MapRec.FullName, MapRec.Offset, MapRec.ClassIndex); end; end else begin if MapRec.Kind = KindVAR then begin if Assigned(OnMapTableVarAddress) then begin P := nil; OnMapTableVarAddress(Owner, FullName, MapRec.Global, P); if P = nil then RaiseError(errUnresolvedAddress, [FullName]); SetAddress(MapRec.Offset, P); end else RaiseError(errHostMemberIsNotDefined, [FullName]); end else if MapRec.Kind in KindSUBS then begin P := nil; if Assigned(OnMapTableProcAddress) then OnMapTableProcAddress(Owner, FullName, MapRec.SubDesc.OverCount, MapRec.Global, P); if P = nil then P := LookupAvailAddress(FullName, MapRec.SubDesc.OverCount); if P = nil then RaiseError(errUnresolvedAddress, [FullName]); SetAddress(MapRec.Offset, P); end else if MapRec.Kind = KindTYPE then begin ClsRef := nil; if Assigned(OnMapTableClassRef) then OnMapTableClassRef(Owner, FullName, MapRec.Global, ClsRef); if ClsRef = nil then ClsRef := LookupAvailClass(FullName); if ClsRef = nil then begin RaiseError(errUnresolvedClassReference, [FullName]); end else RegisterClassEx(ClsRef, MapRec.FullName, MapRec.Offset, MapRec.ClassIndex); end; end; end; end; for I:=0 to ProgList.Count - 1 do TBaseRunner(ProgList[I].Prog).ForceMapping(SymbolTable, Reassign); end; procedure TBaseRunner.ForceMappingEvents; var I, J, TypeId: Integer; MapRec: TMapRec; P: Pointer; ClsRef: TClass; L: TIntegerList; C: TClass; ClassRec: TClassRec; begin if not Assigned(OnMapTableProcAddress) then Exit; if not Assigned(OnMapTableClassRef) then Exit; L := TIntegerList.Create; try for I:=0 to HostMapTable.Count - 1 do begin MapRec := HostMapTable[I]; if MapRec.Kind in KindSUBS then begin P := nil; OnMapTableProcAddress(Owner, MapRec.FullName, MapRec.SubDesc.OverCount, MapRec.Global, P); if P = nil then P := LookupAvailAddress(MapRec.FullName, MapRec.SubDesc.OverCount); if P <> nil then begin J := GlobalSym.LookupFullNameEx(MapRec.FullName, true, MapRec.SubDesc.OverCount); if J > 0 then begin GlobalSym[J].Address := P; if GlobalSym[J].IsVirtual then if GlobalSym[J].MethodIndex = 0 then L.Add(J); end; SetAddress(MapRec.Offset, P); end; end else if MapRec.Kind = KindTYPE then begin ClsRef := nil; if Assigned(OnMapTableClassRef) then OnMapTableClassRef(Owner, MapRec.FullName, MapRec.Global, ClsRef); if ClsRef = nil then ClsRef := LookupAvailClass(MapRec.FullName); if ClsRef <> nil then begin J := GlobalSym.LookupFullName(MapRec.FullName, true); if J > 0 then begin GlobalSym[J].PClass := ClsRef; GlobalSym[J+1].Value := LongInt(ClsRef); end; ClassRec := ClassList.Lookup(MapRec.FullName); if ClassRec <> nil then ClassRec.PClass := ClsRef; end; end; end; for I:=0 to L.Count - 1 do begin J := L[I]; TypeId := GlobalSym[J].Level; C := GlobalSym[TypeId].PClass; if C = nil then RaiseError(errInternalErrorMethodIndex, []); GlobalSym[J].MethodIndex := VirtualMethodIndex(C, GlobalSym[J].Address) + 1; end; finally FreeAndNil(L); end; end; procedure TBaseRunner.RegisterDefinitions(SymbolTable: TBaseSymbolTable); var I, I1, Offset: Integer; J: IntPax; R, R1: TSymbolRec; FullName: String; IsGlobal: Boolean; MapRec: TMapRec; begin IsGlobal := SymbolTable = GlobalSym; TOffsetList_Sort(OffsetList); if UseMapping then begin if HostMapTable.Count > 0 then begin for I:=0 to HostMapTable.Count - 1 do begin MapRec := HostMapTable[I]; if MapRec.Kind <> kindNAMESPACE then continue; if MapRec.Global <> IsGlobal then continue; FullName := MapRec.FullName; J := SymbolTable.LookupFullName(FullName, true); if J = 0 then if Assigned(OnMapTableNamespace) then OnMapTableNamespace(Owner, FullName, MapRec.Global); end; end; end; if IsGlobal then I1 := 1 else I1 := FirstLocalId + 1; for I:=I1 to SymbolTable.Card do begin R := SymbolTable[I]; if R.Address <> nil then begin Offset := GetOffset(R.Shift); if Offset = -1 then continue; SetAddress(Offset, R.Address); end else if R.ClassIndex <> -1 then begin R1 := SymbolTable[I + 1]; // cls ref J := R1.Value; if J = 0 then ClassList.Add(R.FullName, R. Host) else begin Offset := GetOffset(R1.Shift); if Offset = -1 then continue; RegisterClass(TClass(J), R.FullName, Offset); end; end; end; end; function TBaseRunner._VirtualAlloc(Address: Pointer; Size, flAllocType, flProtect: Cardinal): Pointer; begin result := AllocMem(Size); end; procedure TBaseRunner._VirtualFree(Address: Pointer; Size: Cardinal); begin FreeMem(Address, Size); end; procedure TBaseRunner.Deallocate; begin if Data <> nil then begin FreeMem(Data, DataSize); Data := nil; end; if Prog <> nil then begin {$IFDEF PAXARM} FreeMem(Prog, fCodeSize); {$ELSE} _VirtualFree(Prog, fCodeSize); {$ENDIF} Prog := nil; end; ClearCurrException; fPrevException := nil; UnProtect; InitializationIsProcessed := false; end; procedure TBaseRunner.Allocate(InitCodeSize, InitDataSize: Integer); begin Deallocate; DataSize := InitDataSize; Data := AllocMem(DataSize); fCodeSize := InitCodeSize; {$IFDEF PAXARM} Prog := AllocMem(fCodeSize); {$ELSE} Prog := _VirtualAlloc(nil, fCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); {$ENDIF} Protect; SetAddress(H_SelfPtr, Self); SetAddress(H_ExceptionPtr, @ fCurrException); RegisterDefinitions(GlobalSym); end; procedure TBaseRunner.AllocateSimple(InitCodeSize, InitDataSize: Integer); begin Deallocate; DataSize := InitDataSize; Data := AllocMem(DataSize); fCodeSize := InitCodeSize; {$IFDEF PAXARM} Prog := AllocMem(fCodeSize); {$ELSE} Prog := _VirtualAlloc(nil, fCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); {$ENDIF} end; procedure TBaseRunner.Protect; begin end; procedure TBaseRunner.UnProtect; begin end; procedure TBaseRunner.ClearCurrException; begin if Assigned(CurrException) then begin {$IFNDEF ARC} CurrException.Free; {$ENDIF} CurrException := nil; end; end; procedure TBaseRunner.RunExtended; begin {$IFDEF PAXARM} if IsPaused then {$ELSE} if IsPaused or (EPoint <> nil) then {$ENDIF} begin RunInternal; Exit; end else begin RunInitialization; if Assigned(CrtJSObjects) then CrtJSObjects(Self, Self.JS_Record); end; if IsPaused then Exit; RunExceptInitialization; if not IsPaused then begin if not SuspendFinalization then begin InitializationIsProcessed := false; ProgList.RunFinalization; end; end; end; procedure TBaseRunner.RunInternal; begin Run; end; procedure TBaseRunner.RunExceptInitialization; begin Run; end; function TBaseRunner.FireAddressEvent(MR: TMapRec): Pointer; begin result := @TBaseRunner.FireAddressEvent; end; function TBaseRunner.GetAddress(Handle: Integer): Pointer; begin if Handle < 0 then begin result := ShiftPointer(CodePtr, - Handle); end else begin result := ShiftPointer(DataPtr, GetOffset(Handle)); end; end; function TBaseRunner.GetAddress(const FullName: String; var MR: TMapRec): Pointer; begin result := nil; MR := ScriptMapTable.Lookup(FullName); if MR <> nil then begin case MR.Kind of KindVAR, kindTYPE: result := ShiftPointer(DataPtr, MR.Offset); KindSUB, KindCONSTRUCTOR, KindDESTRUCTOR: begin if MR.IsExternal then result := nil else begin result := ShiftPointer(CodePtr, MR.Offset); end; end; end; Exit; end; MR := HostMapTable.Lookup(FullName); if MR <> nil then if MR.Kind in KindSUBS + [KindVAR] then begin result := ShiftPointer(DataPtr, MR.Offset); result := Pointer(result^); end; end; function TBaseRunner.GetAddressEx(const FullName: String; OverCount: Integer; var MR: TMapRec): Pointer; begin result := nil; if OverCount = 0 then begin result := GetAddress(FullName, MR); Exit; end; MR := ScriptMapTable.LookupEx(FullName, OverCount); if MR <> nil then begin case MR.Kind of KindVAR, kindTYPE: result := ShiftPointer(DataPtr, MR.Offset); KindSUB, KindCONSTRUCTOR, KindDESTRUCTOR: begin if MR.IsExternal then result := nil else begin result := ShiftPointer(CodePtr, MR.Offset); end; end; end; Exit; end; MR := HostMapTable.LookupEx(FullName, OverCount); if MR <> nil then if MR.Kind in KindSUBS + [KindVAR] then begin result := ShiftPointer(DataPtr, MR.Offset); result := Pointer(result^); Exit; end; end; function TBaseRunner.LoadAddressEx(const FileName, ProcName: String; RunInit: Boolean; OverCount: Integer; var MR: TMapRec; var DestProg: Pointer): Pointer; begin result := GetRootProg.ProgList.LoadAddress(FileName, ProcName, RunInit, OverCount, MR, DestProg); end; procedure TBaseRunner.CreateClassFactory; var I: Integer; ClassRec: TClassRec; C: TClass; S: String; P: Pointer; PaxInfo: PPaxInfo; MR: TMapRec; begin ProgClassFactory.Clear; for I:=0 to ClassList.Count - 1 do begin ClassRec := ClassList[I]; if ClassRec.Host then continue; S := ExtractName(ClassRec.FullName); C := ProgClassFactory.CreatePaxClass(ClassRec.FullName, ClassRec.InstSize, TObject, GetDestructorAddress); ClassRec.PClass := C; P := GetAddress(ClassRec.FullName, MR); if P <> nil then Pointer(P^) := C; PaxInfo := GetPaxInfo(ClassRec.PClass); if PaxInfo = nil then RaiseError(errInternalError, []); PaxInfo^.Prog := Self; PaxInfo^.ClassIndex := I; end; ProgClassFactory.SetupParents(Self, ClassList); ProgClassFactory.AddInheritedMethods; ProgClassFactory.AddOverridenMethods(Self, ScriptMapTable); ProgClassFactory.SetupStdVirtuals(ClassList, CodePtr); ProgTypeInfoList.AddToProgram(Self); end; function TBaseRunner.GetInitCallStackCount: Integer; begin result := GetRootProg.fInitCallStackCount; end; procedure TBaseRunner.SetInitCallStackCount(value: Integer); begin GetRootProg.fInitCallStackCount := value; end; function TBaseRunner.GetIsRunning: Boolean; begin result := fIsRunning; end; procedure TBaseRunner.SetIsRunning(value: Boolean); begin fIsRunning := value; end; function TBaseRunner.NeedAllocAll: Boolean; begin result := false; end; function TBaseRunner.GetRootGC: TGC; begin result := GetRootProg.fGC; end; function TBaseRunner.GetRootOwner: TObject; begin result := GetRootProg.Owner; end; procedure TBaseRunner.SaveState(S: TStream); begin end; procedure TBaseRunner.LoadState(S: TStream); begin end; function TBaseRunner.GetProcessingExceptBlock: Boolean; begin result := fProcessingExceptBlock; end; procedure TBaseRunner.SetProcessingExceptBlock(value: Boolean); begin fProcessingExceptBlock := value; end; function TBaseRunner.GetExceptionIsAvailableForHostApplication: Boolean; begin result := GetRootProg.fExceptionIsAvailableForHostApplication; end; procedure TBaseRunner.SetExceptionIsAvailableForHostApplication(value: Boolean); begin GetRootProg.fExceptionIsAvailableForHostApplication := value; end; function TBaseRunner.GetHasError: Boolean; begin result := GetRootProg.fHasError; end; procedure TBaseRunner.SetHasError(value: Boolean); begin GetRootProg.fHasError := value; end; {$IFDEF FPC} type TStreamOriginalFormat = (sofUnknown, sofBinary, sofText, sofUTF8Text); function TestStreamFormat(Stream: TStream): TStreamOriginalFormat; var Pos: Integer; Signature: Integer; begin Pos := Stream.Position; Signature := 0; Stream.Read(Signature, SizeOf(Signature)); Stream.Position := Pos; if (Byte(Signature) = $FF) or (Signature = Integer(FilerSignature)) or (Signature = 0) then Result := sofBinary // text format may begin with "object", "inherited", or whitespace else if AnsiChar(Signature) in ['o','O','i','I',' ',#13,#11,#9] then Result := sofText else if (Signature and $00FFFFFF) = $00BFBBEF then Result := sofUTF8Text else Result := sofUnknown; end; {$ENDIF} procedure TBaseRunner.LoadDFMFile(Instance: TObject; const FileName: String; const OnFindMethod: TFindMethodEvent = nil; const OnError: TReaderError = nil); var fs: TFileStream; ms: TMemoryStream; Reader: TReader; ptd: PTypeData; P: Pointer; MR: TMapRec; begin fs := TFileStream.Create(FileName, fmOpenRead); ms := TMemoryStream.Create; try Reader := nil; case TestStreamFormat(fs) of {$IFDEF UNIC} sofText, sofUTF8Text: {$ELSE} sofText: {$ENDIF} begin ObjectTextToBinary(fs, ms); ms.Position := 0; Reader := TReader.Create(ms, 4096 * 10); end; sofBinary: begin fs.ReadResHeader; Reader := TReader.Create(fs, 4096 * 10); end; else RaiseError(errUnknownStreamFormat, []); end; try gInstance := Instance; Reader.OnFindMethod := OnFindMethod; Reader.OnError := OnError; Reader.ReadRootComponent(Instance as TComponent); finally FreeAndNil(Reader); end; finally FreeAndNil(ms); FreeAndNil(fs); end; if not ModeSEH then RebindEvents(Instance); ptd := GetTypeData(Instance.ClassInfo); P := GetAddress(StringFromPShortString(@ptd^.UnitName) + '.' + Copy(Instance.ClassName, 2, Length(Instance.ClassName)), MR); if P <> nil then Pointer(P^) := Instance; end; procedure TBaseRunner.LoadDFMStream(Instance: TObject; S: TStream; const OnFindMethod: TFindMethodEvent = nil; const OnError: TReaderError = nil); var ms: TMemoryStream; Reader: TReader; ptd: PTypeData; P: Pointer; MR: TMapRec; begin ms := TMemoryStream.Create; try Reader := nil; case TestStreamFormat(s) of {$IFDEF UNIC} sofText, sofUTF8Text: {$ELSE} sofText: {$ENDIF} begin ObjectTextToBinary(s, ms); ms.Position := 0; Reader := TReader.Create(ms, 4096 * 10); end; sofBinary: begin s.ReadResHeader; Reader := TReader.Create(s, 4096 * 10); end; else RaiseError(errUnknownStreamFormat, []); end; try gInstance := Instance; Reader.OnFindMethod := OnFindMethod; Reader.OnError := OnError; Reader.ReadRootComponent(Instance as TComponent); finally FreeAndNil(Reader); end; finally FreeAndNil(ms); end; if not ModeSEH then RebindEvents(Instance); ptd := GetTypeData(Instance.ClassInfo); P := GetAddress(StringFromPShortString(@ptd^.UnitName) + '.' + Copy(Instance.ClassName, 2, Length(Instance.ClassName)), MR); if P <> nil then Pointer(P^) := Instance; end; procedure TBaseRunner.RebindEvents(AnInstance: TObject); begin end; function TBaseRunner.CallByteCode(InitN: Integer; This: Pointer; R_AX, R_CX, R_DX, R_8, R_9: IntPax; StackPtr: Pointer; ResultPtr: Pointer; var FT: Integer): Integer; begin result := 0; end; procedure TBaseRunner.WrapMethodAddress(var Address: Pointer); var I, N: integer; begin if Address <> nil then if not NativeAddress(Address) then begin N := IntPax(Address); I := ClassList.GetByteCodeMethodEntryIndex(N); if I = -1 then RaiseError(errInternalError, []); Address := GetFakeHandlerAddress(I); end; end; function TBaseRunner.WrapGlobalAddress(var Address: Pointer): Integer; var I, N: integer; begin result := -1; if Address <> nil then if not NativeAddress(Address) then begin N := IntPax(Address); for I := 0 to System.Length(ByteCodeGlobalEntryList) - 1 do if ByteCodeGlobalEntryList[I] = N then begin Address := GetFakeGlobalAddress(I); result := I; Exit; end; RaiseError(errInternalError, []); end; end; {$ifdef DRTTI} function TBaseRunner.HasAvailUnit(const FullName: String): Boolean; begin result := AvailUnitList.IndexOf(FullName) >= 0; end; function TBaseRunner.LookUpAvailClass(const FullName: String): TClass; var t: TRTTIType; I: Integer; begin result := nil; I := AvailTypeList.IndexOf(FullName); if I >= 0 then begin t := TRTTIType(AvailTypeList.Objects[I]); if t is TRttiInstanceType then result := (t as TRttiInstanceType).MetaclassType; end; end; function TBaseRunner.LookUpAvailAddress(const FullName: String; OverCount: Integer): Pointer; var m: TRTTIMethod; begin m := LookUpAvailMethod(FullName, OverCount); if m = nil then result := nil else result := m.CodeAddress; end; function TBaseRunner.LookUpAvailMethod(const FullName: String; OverCount: Integer): TRTTIMethod; var t: TRTTIType; I, K: Integer; TypeName, MethName: String; {$IFDEF DPULSAR} IndexedProp: TRTTIIndexedProperty; {$ENDIF} m: TRTTIMethod; begin result := nil; TypeName := ExtractFullOwner(FullName); MethName := ExtractName(FullName); I := AvailTypeList.IndexOf(TypeName); if I = -1 then I := AvailTypeList.IndexOf('System.' + TypeName); if I = -1 then Exit; t := TRTTIType(AvailTypeList.Objects[I]); K := 0; for m in t.GetDeclaredMethods do if CheckMethod(t, m) then if StrEql(m.Name, MethName) then begin if OverCount = 0 then begin result := m; Exit; end else begin Inc(K); if K = OverCount then Exit; end; end; {$IFDEF DPULSAR} for IndexedProp in t.GetDeclaredIndexedProperties do if CheckIndexedProperty(t, IndexedProp) then begin if IndexedProp.IsReadable then begin result := IndexedProp.ReadMethod; if StrEql(result.Name, MethName) then Exit; end; if IndexedProp.IsWritable then begin result := IndexedProp.WriteMethod; if StrEql(result.Name, MethName) then Exit; end; end; {$ENDIF} result := nil; end; {$else} function TBaseRunner.HasAvailUnit(const FullName: String): Boolean; begin result := false; end; function TBaseRunner.LookUpAvailClass(const FullName: String): TClass; begin result := nil; end; function TBaseRunner.LookUpAvailAddress(const FullName: String; OverCount: Integer): Pointer; begin result := nil; end; {$endif} end.
unit MixiPageObserver; interface uses SysUtils, Classes, Contnrs, MixiPage, MixiAPIToken, HttpLib, superxmlparser, superobject; const API_ENDPOINT = 'http://api.mixi-platform.com/2'; type TObserveUpdates = class private FMessage: String; FIsRead: Boolean; public constructor Create(sMessage: String); property Message: String read FMessage; property IsRead: Boolean read FIsRead write FIsRead; end; TObserveEntry = class private FPageId: Cardinal; FPage: TMixiPage; FFeeds: TObjectList; FUpdates: TObjectList; function CallPageAPI(token: TMixiAPIToken): ISuperObject; function CallFeedsAPI(token: TMixiAPIToken): ISuperObject; procedure AddUpdate(message: String); function GetFeedByContentUri(Uri: String): TMixiPageFeed; public constructor Create(pageId: Cardinal); destructor Destroy; override; procedure Initialize(token: TMixiAPIToken); procedure Synchronize(token: TMixiAPIToken); property PageId: Cardinal read FPageId; property Page: TMixiPage read FPage; property Feeds: TObjectList read FFeeds; property Updates: TObjectList read FUpdates; end; TMixiPageObserver = class private FObserveList: TObjectList; FUpdates: TObjectList; FTokenFactory: TMixiAPITokenFactory; FToken: TMixiAPIToken; function GetToken: TMixiAPIToken; public constructor Create(key, secret: String; redirect: String = ''); destructor Destroy; override; procedure Synchronize; procedure AddObserve(pageId: Cardinal); procedure RemoveObserve(pageId: Cardinal); property ObserveList: TObjectList read FObserveList; property Updates: TObjectList read FUpdates; end; implementation { TObserveUpdates } constructor TObserveUpdates.Create(sMessage: String); begin FMessage := sMessage; IsRead := False; end; { TObserveEntry } constructor TObserveEntry.Create(pageId: Cardinal); begin FPageId := pageId; FFeeds := TObjectList.Create; FUpdates := TObjectList.Create; end; destructor TObserveEntry.Destroy; begin FPage.Free; FFeeds.Free; FUpdates.Free; end; procedure TObserveEntry.Initialize(token: TMixiAPIToken); var i, mx: Integer; feedJson: ISuperObject; begin FPage := TMixiPage.Create(Self.CallPageAPI(token)); feedJson := CallFeedsAPI(token); mx := feedJson['entry'].AsArray.Length - 1; for i := 0 to mx do begin FFeeds.Add( TMixiPageFeed.Create(feedJson['entry'].AsArray.O[i]) ); end; end; procedure TObserveEntry.Synchronize(token: TMixiAPIToken); var i, mx: Integer; json, feedJson: ISuperObject; feed: TMixiPageFeed; begin FUpdates.Clear; //page json := CallPageAPI(token); if ( FPage.HasUpdates(json) ) then begin AddUpdate(FPage.GetUpdateMessage(json)); FPage.Update(json); end; //feeds json := CallFeedsAPI(token); mx := json['entry'].AsArray.Length - 1; for i := 0 to mx do begin feedJson := json['entry'].AsArray.O[i]; feed := GetFeedByContentUri(feedJson['contentUri'].AsString); if ( feed = nil ) then Continue; if feed.HasUpdates(feedJson) then AddUpdate(feed.GetUpdateMessage(feedJson)); end; FFeeds.Clear; for i := 0 to mx do begin feedJson := json['entry'].AsArray.O[i]; Feeds.Add( TMixiPageFeed.Create(feedJson) ); end; end; function TObserveEntry.CallPageAPI(token: TMixiAPIToken): ISuperObject; var endpoint, response: String; begin endpoint := Format( '%s/pages/%d?access_token=%s', [API_ENDPOINT, FPageId, token.AccessToken] ); response := UserAgent.Get(endpoint); Result := SO(Utf8ToAnsi(response)); end; function TObserveEntry.CallFeedsAPI(token: TMixiAPIToken): ISuperObject; var endpoint, response: String; json: ISuperObject; ua: TUserAgent; begin ua := TUserAgent.Create; try endpoint := Format( '%s/pages/%d/feeds?access_token=%s', [API_ENDPOINT, FPageId, token.AccessToken] ); response := ua.Get(endpoint); finally ua.Free; end; json := SO(Utf8ToAnsi(response)); Result := json; end; function TObserveEntry.GetFeedByContentUri(Uri: String): TMixiPageFeed; var i, mx: Integer; feed: TMixiPageFeed; begin Result := nil; mx := FFeeds.Count - 1; for i := 0 to mx do begin feed := TMixiPageFeed(FFeeds[i]); if ( feed.ContentUri = Uri ) then begin Result := feed; Exit; end; end; end; procedure TObserveEntry.AddUpdate(message: String); begin FUpdates.Add( TObserveUpdates.Create(message) ); end; { TMixiPageObserver } constructor TMixiPageObserver.Create(key, secret, redirect: String); begin FObserveList := TObjectList.Create; FTokenFactory := TMixiAPITokenFactory.Create(key, secret, redirect); FToken := nil; FUpdates := TObjectList.Create(False); end; destructor TMixiPageObserver.Destroy; begin FObserveList.Free; FTokenFactory.Free; FUpdates.Free; end; procedure TMixiPageObserver.Synchronize; var token: TMixiAPIToken; entry: TObserveEntry; i, mx: Integer; procedure CopyUpdates; var i, mx: Integer; begin mx := entry.Updates.Count - 1; for i := 0 to mx do FUpdates.Add(entry.Updates[i]); end; begin mx := FObserveList.Count - 1; FUpdates.Clear; for i := 0 to mx do begin token := GetToken; entry := TObserveEntry(FObserveList[i]); try entry.Synchronize(token); if entry.Updates.Count > 0 then CopyUpdates; except end; end; end; procedure TMixiPageObserver.AddObserve(pageId: Cardinal); var entry: TObserveEntry; begin entry := TObserveEntry.Create(pageId); entry.Initialize(GetToken); FObserveList.Add(entry); end; procedure TMixiPageObserver.RemoveObserve(pageId: Cardinal); var i, mx: Integer; begin mx := FObserveList.Count - 1; for i := 0 to mx do begin if TObserveEntry(FObserveList[i]).PageId = pageId then begin FObserveList.Delete(i); end; end; end; function TMixiPageObserver.GetToken: TMixiAPIToken; begin if FToken = nil then begin FToken := FTokenFactory.CreateClientCredentials; Result := FToken; Exit; end; if FToken.isExpired then begin if Not(FTokenFactory.RefreshToken(FToken)) then begin FToken := FTokenFactory.CreateClientCredentials; end; end; Result := FToken; end; end.
unit EditArtistController; interface uses Generics.Collections, Aurelius.Engine.ObjectManager, Artist; type TEditArtistController = class private FManager: TObjectManager; FArtist: TArtist; public constructor Create; destructor Destroy; override; procedure SaveArtist(Artist: TArtist); procedure Load(ArtistId: Variant); property Artist: TArtist read FArtist; end; implementation uses DBConnection; { TEditArtistController } constructor TEditArtistController.Create; begin FArtist := TArtist.Create; FManager := TDBConnection.GetInstance.CreateObjectManager; end; destructor TEditArtistController.Destroy; begin if not FManager.IsAttached(FArtist) then FArtist.Free; FManager.Free; inherited; end; procedure TEditArtistController.Load(ArtistId: Variant); begin if not FManager.IsAttached(FArtist) then FArtist.Free; FArtist := FManager.Find<TArtist>(ArtistId); end; procedure TEditArtistController.SaveArtist(Artist: TArtist); begin if not FManager.IsAttached(Artist) then FManager.SaveOrUpdate(Artist); FManager.Flush; end; end.
Unit HookObjects; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} Interface Uses {$IFDEF FPC} JwaWinSvc, {$ELSE} WinSvc, {$ENDIF} Windows, IRPMonDll, ComCtrls, Generics.Collections; Type EHookObjectOperation = ( hooNone, hooHook, hooUnhook, hooChange, hooStart, hooStop, hooWatchClass, hooUnwatchClass, hooWatchDriver, hooUnwatchDriver, hooLibraryInitialize, hooLibraryFinalize, hooMax ); EHookObjectOperationResult = ( hoorSuccess, hoorWarning, hoorError ); THookObjectOperations = Set Of EHookObjectOperation; TTaskOperationList = Class; TTaskObject = Class; TTaskObjectCompletionCallback = Function (AList:TTaskOperationList; AObject:TTaskObject; AOperation:EHookObjectOperation; AStatus:Cardinal; AContext:Pointer):Cardinal; TTaskObject = Class Private FName : WideString; FObjectType : WideString; FSupportedOperations : THookObjectOperations; FCompletionCallback : TTaskObjectCompletionCallback; FCompletionContext : Pointer; FTaskList : TTaskOperationList; Public Constructor Create(AType:WideString; AName:WideString; ASupportedOperations:THookObjectOperations = []); Reintroduce; Function Operation(AOperationType:EHookObjectOperation):Cardinal; Virtual; Abstract; Function FinishCompletion(AOperationType:EHookObjectOperation; AStatus:Cardinal):Cardinal; Procedure SetCompletionCallback(ACallback:TTaskObjectCompletionCallback; AContext:Pointer); Function OperationString(AOpType:EHookObjectOperation):WideString; Virtual; Function OperationResult(AOpType:EHookObjectOperation; AStatus:Cardinal):EHookObjectOperationResult; Virtual; Function StatusDescription(AOpType:EHookObjectOperation; AStatus:Cardinal):WideString; Virtual; Property SupportedOperations : THookObjectOperations Read FSupportedOperations; Property ObjectTpye : WideString Read FObjectType; Property Name : WideString Read FName; end; TDriverTaskObject = Class (TTaskObject) Private FInitInfo : IRPMON_INIT_INFO; FServiceName : WideString; FServiceBinary : WideString; FServiceDescription : WideString; FServiceDisplayName : WideString; FhSCM : SC_HANDLE; Function Install:Cardinal; Function Uninstall:Cardinal; Function Load:Cardinal; Function Unload:Cardinal; Public Constructor Create(Var AInitInfo:IRPMON_INIT_INFO; ASCHandle:SC_HANDLE; AServiceName:WideString; AServiceDisplayName:WideString = ''; AServiceDescription:WideString = ''; AFileName:WideString = ''); Reintroduce; Function Operation(AOperationType:EHookObjectOperation):Cardinal; Override; Function OperationString(AOpType:EHookObjectOperation):WideString; Override; Function OperationResult(AOpType:EHookObjectOperation; AStatus:Cardinal):EHookObjectOperationResult; Override; Property ServiceName : WideString Read FServiceName; Property ServiceBinary : WideString Read FServiceBinary; Property ServiceDisplayName : WideString Read FServiceDisplayName; Property ServiceDescription : WideString Read FServiceDescription; end; THookObject = Class (TTaskObject) Protected FAddress : Pointer; FObjectId : Pointer; FHooked : Boolean; FTreeNode : TTreeNode; Public Constructor Create(AType:WideString; AAddress:Pointer; AName:PWideChar; ASupportedOperations:THookObjectOperations = []); Reintroduce; Property Address : Pointer Read FAddress; Property ObjectId : Pointer Read FObjectId Write FObjectId; Property Hooked : Boolean Read FHooked Write FHooked; Property TreeNode : TTreeNode Read FTreenode Write FTreeNode; end; TDriverHookObject = Class (THookObject) Private FDeviceExtensionHook : Boolean; Function Unhook:Cardinal; Function Hook:Cardinal; Function Change:Cardinal; Function Start:Cardinal; Function Stop:Cardinal; Public NumberOfHookedDevices : Cardinal; Settings : DRIVER_MONITOR_SETTINGS; Constructor Create(AAddress:Pointer; AName:PWideChar); Reintroduce; Function Operation(AOperationType:EHookObjectOperation):Cardinal; Override; Property DeviceExtensionHook : Boolean Read FDeviceExtensionHook Write FDeviceExtensionHook; end; TDeviceHookObject = Class (THookObject) Private FDriverObject : Pointer; FAttachedDevice : Pointer; Function Unhook:Cardinal; Function Hook:Cardinal; Function Change:Cardinal; Public IRPSettings : TIRPSettings; FastIOSettings : TFastIoSettings; Constructor Create(AAddress:Pointer; ADriverObject:Pointer; AAttachedDevice:Pointer; AName:PWideChar); Reintroduce; Function Operation(AOperationType:EHookObjectOperation):Cardinal; Override; Property Driverobject : Pointer Read FDriverObject; Property AttachedDevice : Pointer Read FAttachedDevice; end; TTaskOperationList = Class Private FCount : Cardinal; FObjectList : TList<TTaskObject>; FOpList : TList<EHookObjectOperation>; Protected Function GetItem(AIndex:Integer):TPair<EHookObjectOperation, TTaskObject>; Public Constructor Create; Destructor Destroy; Override; Function Add(AOp:EHookObjectOperation; AObject:TTaskObject):TTaskOperationList; Procedure Clear; Property Items [AIndex:Integer] : TPair<EHookObjectOperation, TTaskObject> Read GetItem; Property Count : Cardinal Read FCount; end; Implementation Uses SysUtils; (** TTaskObject **) Constructor TTaskObject.Create(AType:WideString; AName:WideString; ASupportedOperations:THookObjectOperations = []); begin Inherited Create; FName := AName; FSupportedOperations := ASupportedOperations; FObjectType := AType; FCompletionCallback := Nil; FCompletionContext := Nil; FTaskList := Nil; end; Procedure TTaskObject.SetCompletionCallback(ACallback:TTaskObjectCompletionCallback; AContext:Pointer); begin FCompletionCallback := ACallback; FCompletionContext := AContext; end; Function TTaskObject.FinishCompletion(AOperationType:EHookObjectOperation; AStatus:Cardinal):Cardinal; begin Result := AStatus; If Assigned(FCompletionCallback) THen Result := FCompletionCallback(FTaskList, Self, AOperationType, AStatus, FCompletionContext); end; Function TTaskObject.OperationString(AOpType:EHookObjectOperation):WideString; begin Case AOpType Of hooNone: Result := 'None'; hooHook: Result := 'Hook'; hooUnhook: Result := 'Unhook'; hooChange: Result := 'Change'; hooStart: Result := 'Start'; hooStop: Result := 'Stop'; hooWatchClass: Result := 'WatchClass'; hooUnwatchClass: Result := 'UnwatchClass'; hooWatchDriver: Result := 'WatchDriver'; hooUnwatchDriver: Result := 'UnwatchDriver'; hooMax: Result := 'Max'; Else Result := Format('<unknown (%u)>', [Ord(AOpType)]); end; end; Function TTaskObject.OperationResult(AOpType:EHookObjectOperation; AStatus:Cardinal):EHookObjectOperationResult; begin Case AStatus Of 0 : Result := hoorSuccess; Else Result := hoorError; end; end; Function TTaskObject.StatusDescription(AOpType:EHookObjectOperation; AStatus:Cardinal):WideString; begin Result := SysErrorMessage(AStatus); end; (** THookObject **) Constructor THookObject.Create(AType:WideString; AAddress:Pointer; AName:PWideChar; ASupportedOperations:THookObjectOperations = []); Var n : WideString; begin n := ''; If Assigned(AName) THen begin SetLength(n, StrLen(AName)); CopyMemory(PWideChar(n), AName, StrLen(AName)*SizeOf(WideChar)); end; Inherited Create(AType, n, ASupportedOperations); FAddress := AAddress; FObjectId := Nil; FHooked := False; end; (** TDriverHookObject **) Constructor TDriverHookObject.Create(AAddress:Pointer; AName:PWideChar); begin Inherited Create('Driver', AAddress, AName, [hooHook, hooUnhook, hooChange, hooStart, hooStop]); NumberOfHookedDevices := 0; Settings.MonitorNewDevices := False; Settings.MonitorAddDevice := False; Settings.MonitorStartIo := False; Settings.MonitorFastIo := True; Settings.MonitorIRP := True; Settings.MonitorIRPCompletion := True; Settings.MonitorData := False; Settings.MonitorUnload := False; FillChar(Settings.IRPSettings, SizeOf(Settings.IRPSettings), Ord(True)); FillChar(Settings.FastIoSettings, SizeOf(Settings.FastIoSettings), Ord(True)); end; Function TDriverHookObject.Operation(AOperationType:EHookObjectOperation):Cardinal; begin Case AOperationType Of hooHook: Result := Hook; hooUnhook: Result := Unhook; hooChange: Result := Change; hooStart: Result := Start; hooStop: Result := Stop; Else Result := ERROR_NOT_SUPPORTED; end; Result := FinishCompletion(AOperationType, Result); end; Function TDriverHookObject.Unhook:Cardinal; Var h : THandle; begin Result := IRPMonDllOpenHookedDriver(FObjectId, h); If Result = ERROR_SUCCESS Then begin Result := IRPMonDllUnhookDriver(h); IRPMonDllCloseHookedDriverHandle(h); end; end; Function TDriverHookObject.Hook:Cardinal; Var h : THandle; begin Result := IRPMonDllHookDriver(PWideChar(FName), Settings, FDeviceExtensionHook, h, FObjectId); If Result = ERROR_SUCCESS Then IRPMonDllCloseHookedDriverHandle(h); end; Function TDriverHookObject.Change:Cardinal; Var h : THandle; begin Result := IRPMonDllOpenHookedDriver(FObjectId, h); If Result = ERROR_SUCCESS Then begin Result := IRPMonDllDriverSetInfo(h, Settings); IRPMonDllCloseHookedDriverHandle(h); end; end; Function TDriverHookObject.Start:Cardinal; Var h : THandle; begin Result := IRPMonDllOpenHookedDriver(FObjectId, h); If Result = ERROR_SUCCESS Then begin Result := IRPMonDllDriverStartMonitoring(h); IRPMonDllCloseHookedDriverHandle(h); end; end; Function TDriverHookObject.Stop:Cardinal; Var h : THandle; begin Result := IRPMonDllOpenHookedDriver(FObjectId, h); If Result = ERROR_SUCCESS Then begin Result := IRPMonDllDriverStopMonitoring(h); IRPMonDllCloseHookedDriverHandle(h); end; end; (** TDeviceHookObject **) Constructor TDeviceHookObject.Create(AAddress:Pointer; ADriverObject:Pointer; AAttachedDevice:Pointer; AName:PWideChar); begin Inherited Create('Device', AAddress, AName, [hooHook, hooUnhook, hooChange]); FDriverObject := ADriverObject; FAttachedDevice := AAttachedDevice; FillChar(IRPSettings, SizeOf(IRPSettings), Ord(True)); FillChar(FastIoSettings, SizeOf(FastIoSettings), Ord(True)); end; Function TDeviceHookObject.Operation(AOperationType:EHookObjectOperation):Cardinal; begin Case AOperationType Of hooHook: Result := Hook; hooUnhook: Result := Unhook; hooChange: Result := Change; Else Result := ERROR_NOT_SUPPORTED; end; Result := FinishCompletion(AOperationType, Result); end; Function TDeviceHookObject.Unhook:Cardinal; Var h : THandle; begin Result := IRPMonDllOpenHookedDevice(FObjectId, h); If Result = ERROR_SUCCESS Then begin Result := IRPMonDllUnhookDevice(h); IRPMonDllCloseHookedDeviceHandle(h); end; end; Function TDeviceHookObject.Hook:Cardinal; Var h : THandle; begin Result := IRPMonDllHookDeviceByAddress(FAddress, h, FObjectId); If Result = ERROR_SUCCESS Then begin Result := IRPMonDllHookedDeviceSetInfo(h, @IRPSettings, @FastIoSettings, True); If Result <> ERROR_SUCCESS Then IRPMonDllUnhookDevice(h); IRPMonDllCloseHookedDeviceHandle(h); end; end; Function TDeviceHookObject.Change:Cardinal; Var h : THandle; begin Result := IRPMonDllOpenHookedDevice(FObjectId, h); If Result = ERROR_SUCCESS Then begin Result := IRPMonDllHookedDeviceSetInfo(h, @IRPSettings, @FastIoSettings, True); IRPMonDllCloseHookedDeviceHandle(h); end; end; (** TDriverTaskObject **) Constructor TDriverTaskObject.Create(Var AInitInfo:IRPMON_INIT_INFO; ASCHandle:SC_HANDLE; AServiceName:WideString; AServiceDisplayName:WideString = ''; AServiceDescription:WideString = ''; AFileName:WideString = ''); begin Inherited Create('Driver', AServiceName, [hooHook, hooUnhook, hooStart, hooStop, hooLibraryInitialize, hooLibraryFinalize]); FInitInfo := AInitInfo; FServiceName := AServiceName; FServiceDisplayName := AServiceDisplayName; FServiceDescription := AServiceDescription; FServiceBinary := AFileName; FhSCM := ASCHandle; end; Function TDriverTaskObject.Operation(AOperationType:EHookObjectOperation):Cardinal; begin Result := ERROR_SUCCESS; Case AOperationType Of hooHook: Result := Install; hooStart : Result := Load; hooStop : Result := Unload; hooUnhook : Result := Uninstall; hooLibraryInitialize : Result := IRPMonDllInitialize(FInitInfo); hooLibraryFinalize : IRPMonDllFInalize; Else Result := ERROR_NOT_SUPPORTED; end; Result := FinishCompletion(AOperationType, Result); end; Function TDriverTaskObject.OperationString(AOpType:EHookObjectOperation):WideString; begin Result := ''; Case AOpType Of hooHook: Result := 'Install'; hooStart : Result := 'Load'; hooStop : Result := 'Unload'; hooUnhook : Result := 'Uninstall'; hooLibraryInitialize : Result := 'Connect'; hooLibraryFinalize : Result := 'Disconnect'; end; end; Function TDriverTaskObject.OperationResult(AOpType:EHookObjectOperation; AStatus:Cardinal):EHookObjectOperationResult; begin Result := Inherited OperationResult(AOpType, AStatus); Case AOpType Of hooHook : begin If AStatus = ERROR_SERVICE_EXISTS Then Result := hoorWarning; end; hooStart : begin If AStatus = ERROR_SERVICE_ALREADY_RUNNING Then Result := hoorWarning; end; end; end; Function TDriverTaskObject.Install:Cardinal; Var hService : THandle; sd : SERVICE_DESCRIPTIONW; begin Result := ERROR_SUCCESS; hService := CreateServiceW(FhSCM, PWideChar(FServiceName), PWideChar(FServiceDisplayName), SERVICE_CHANGE_CONFIG , SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, PWideChar(FServiceBinary), Nil, Nil, Nil, Nil, Nil); If hService <> 0 Then begin sd.lpDescription := PWideChar(FServiceDescription); If Not ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, @sd) Then begin Result := GetLastError; DeleteService(hService); end; CloseServiceHandle(hService); end Else Result := GetLastError; end; Function TDriverTaskObject.Uninstall:Cardinal; Var hService : THandle; begin Result := ERROR_SUCCESS; // $10000 is the DELETE access right hService := OpenServiceW(FhSCM, PWideChar(FServiceName), $10000); If hService <> 0 Then begin If Not DeleteService(hService) Then Result := GetLastError; CloseServiceHandle(hService); end Else Result := GetLastError; end; Function TDriverTaskObject.Load:Cardinal; Var hService : SC_HANDLE; dummy : PWideChar; begin Result := ERROR_SUCCESS; hService := OpenServiceW(FhSCM, PWideChar(FServiceName), SERVICE_START); If hService <> 0 Then begin dummy := Nil; {$IFDEF FPC} If Not StartServiceW(hService, 0, @dummy) Then {$ELSE} If Not StartServiceW(hService, 0, dummy) Then {$ENDIF} Result := GetLastError; CloseServiceHandle(hService); end Else Result := GetLastError; end; Function TDriverTaskObject.Unload:Cardinal; Var hService : THandle; ss : SERVICE_STATUS; begin Result := ERROR_SUCCESS; hService := OpenServiceW(FhSCM, PWideChar(FServiceName), SERVICE_STOP); If hService <> 0 Then begin If Not ControlService(hService, SERVICE_CONTROL_STOP, ss) Then Result := GetLastError; CloseServiceHandle(hService); end Else Result := GetLastError; end; (** TTaskOperationList **) Constructor TTaskOperationList.Create; begin Inherited Create; FOpList := TList<EHookObjectOperation>.Create; FObjectList := TList<TTaskObject>.Create; end; Destructor TTaskOperationList.Destroy; begin FObjectList.Free; FOpList.Free; Inherited Destroy; end; Procedure TTaskOperationList.Clear; begin FCount := 0; FOpList.Clear; FObjectList.Clear; end; Function TTaskOperationList.Add(AOp:EHookObjectOperation; AObject:TTaskObject):TTaskOperationList; begin If Not (AOp In AObject.SupportedOperations) Then Raise Exception.Create('Attempt to add an unsupported operation'); AObject.FTaskList := Self; FOpList.Add(AOp); FObjectList.Add(AObject); Inc(FCount); Result := Self; end; Function TTaskOperationList.GetItem(AIndex:Integer):TPair<EHookObjectOperation, TTaskObject>; begin Result.Key := FOpList[AIndex]; Result.Value := FObjectList[AIndex]; end; End.
unit uPreSale; interface uses SysUtils, Classes, uMsgBox, uMsgConstant, uNumericFunctions, Math; type TDiscountType = (tdtDesconto, tdtAcrescimo); TDiscountValueType = (dvtValor, dvtPerc); TDiscountKind = (dkNone, dkItem, dkInvoice); TPreSaleType = (tptInvoice, tptRefund, tptLayAway, tptExchange); TPreSaleItem = class; TBeforeAddPreSaleItem = procedure(var PSI: TPreSaleItem; var Sucess: Boolean) of object; TAfterAddPreSaleItem = procedure(PSI: TPreSaleItem; var Sucess: Boolean) of object; TBeforeDoInvoiceDiscount = procedure(ADiscountPerc: Currency; var AAccept: Boolean) of object; TPreSaleItemRequestRight = procedure(PSI: TPreSaleItem; var AAccept: Boolean) of object; TSellingItem = class IDModel: Integer; Model: String; CostPrice: Currency; SalePrice: Currency; Description: String; end; TSalesPersonInfo = class IDUser: Integer; UserName: String; IDCommission: Integer; IDCommissionType: Integer; end; TMediaInfo = class IDMedia: Integer; MediaName: String; end; TCustomerInfo = class IDCustomer: Integer; FirstName: String; LastName: String; Endereco: String; Cidade: String; Bairro: String; Zip: String; CPF: String; TelDDD: String; Telefone: String; Juridico: Boolean; IsNew: Boolean; Estado: String; CelDDD: String; Celelular: String; Email: String; WebSite: String; Identidate: String; OrgEmiss: String; ExpDate: TDateTime; BirthDate: TDateTime; CustCard: String; CMotorista: String; NomeJuridico: String; InscEstadual: String; InscMunicipal:String; Contato: String; OBS: String; StoreAccountLimit: Currency; Nonpayer: Boolean; end; TTouristGroup = class IDTouristGroup: Integer; TouristGroup: String; end; TCommissionGroup = class IDCommisionGroup: Integer; CommisionGroup: String; end; TPreSaleInfo = class private FCommissionGroup: TCommissionGroup; FCustomerInfo: TCustomerInfo; FMediaInfo: TMediaInfo; FTouristGroup: TTouristGroup; public property MediaInfo: TMediaInfo read FMediaInfo write FMediaInfo; property CustomerInfo: TCustomerInfo read FCustomerInfo write FCustomerInfo; property TouristGroup: TTouristGroup read FTouristGroup write FTouristGroup; property CommissionGroup: TCommissionGroup read FCommissionGroup write FCommissionGroup; constructor Create; destructor Destroy;override; procedure UnSet; end; TPreSaleItemSuggestion = class FModel: String; FDescription: String; FSalePrice: Currency; FOBS: String; end; TPreSaleItemSerial = class private FSerialNumber: String; FIdentificationNumber: String; public property SerialNumber: String read FSerialNumber write FSerialNumber; property IdentificationNumber: String read FIdentificationNumber write FIdentificationNumber; end; TPreSaleItemPrice = class private FIDVendorPrice: Integer; FIDDescriptionPrice: Integer; FSuggPrice: Currency; FSalePrice: Currency; public property IDVendorPrice: Integer read FIDVendorPrice write FIDVendorPrice; property IDDescriptionPrice: Integer read FIDDescriptionPrice write FIDDescriptionPrice; property SuggPrice: Currency read FSuggPrice write FSuggPrice; property SalePrice: Currency read FSalePrice write FSalePrice; end; TPreSaleItem = class private FIDCustomer: Integer; FIDModel: Integer; FIDStore: Integer; FQty: Double; FDiscount: Currency; FSale: Currency; FCost: Currency; FIDUser: Integer; FIDCommis: Integer; FMovDate: TDateTime; FDate: TDateTime; FManager: Boolean; FIDPreInvMov: Integer; FPercMaxDisc: Currency; FTaxValue : Currency; FDescription: String; FECFTaxIndex: String; FECFIndex: Integer; FModel: String; FImagePath: String; FBarCode: String; FRequestCustomer: Boolean; FPuppyTracker: Boolean; FCaseQty: Double; FPrinted: Boolean; FIDDepartment: Integer; FSerialNumbers: TList; FSuggPrice: Currency; FIDVendorPrice: Integer; FIDDescriptionPrice: Integer; FIDDocumentType: Integer; FDocumentNumber: String; FTotalInformed: Currency; FTotalizadorParcial: String; FUnidade: String; function GetSerialNumbers(Index: Integer): TPreSaleItemSerial; procedure SetSerialNumbers(Index: Integer; const Value: TPreSaleItemSerial); procedure ClearSerialItems; public property IDCustomer: Integer read FIDCustomer write FIDCustomer; property IDModel: Integer read FIDModel write FIDModel; property IDStore: Integer read FIDStore write FIDStore; property Qty: Double read FQty write FQty; property Discount: Currency read FDiscount write FDiscount; property Sale: Currency read FSale write FSale; property Cost: Currency read FCost write FCost; property IDUser: Integer read FIDUser write FIDUser; property IDCommis: Integer read FIDCommis write FIDCommis; property MovDate: TDateTime read FMovDate write FMovDate; property Date: TDateTime read FDate write FDate; property Manager: Boolean read FManager write FManager; property IDPreInvMov: Integer read FIDPreInvMov write FIDPreInvMov; property PercMaxDisc: Currency read FPercMaxDisc write FPercMaxDisc; property TaxValue: Currency read FTaxValue write FTaxValue; property Description: String read FDescription write FDescription; property ECFTaxIndex: String read FECFTaxIndex write FECFTaxIndex; property ECFIndex: Integer read FECFIndex write FECFIndex; property Model: String read FModel write FModel; property ImagePath: String read FImagePath write FImagePath; property BarCode: String read FBarCode write FBarCode; property PuppyTracker: Boolean read FPuppyTracker write FPuppyTracker; property RequestCustomer: Boolean read FRequestCustomer write FRequestCustomer; property CaseQty: Double read FCaseQty write FCaseQty; property Printed: Boolean read FPrinted write FPrinted; property IDDepartment: Integer read FIDDepartment write FIDDepartment; property IDDescriptionPrice: Integer read FIDDescriptionPrice write FIDDescriptionPrice; property IDVendorPrice: Integer read FIDVendorPrice write FIDVendorPrice; property SuggPrice: Currency read FSuggPrice write FSuggPrice; property DocumentNumber: String read FDocumentNumber write FDocumentNumber; property IDDocumentType: Integer read FIDDocumentType write FIDDocumentType; property TotalInformed: Currency read FTotalInformed write FTotalInformed; property TotalizadorParcial: String read FTotalizadorParcial write FTotalizadorParcial; property Unidade: String read FUnidade write FUnidade; property SerialNumbers[Index: Integer]: TPreSaleItemSerial read GetSerialNumbers write SetSerialNumbers; constructor Create; destructor Destroy; override; procedure AddSerialNumber(ASerialNumber, AIdentificationNumber: String); overload; procedure AddSerialNumber(APreSaleItemSerial: TPreSaleItemSerial); overload; end; TPreSale = class(TComponent) private FDeliverType: Integer; FIsLayaway: Boolean; FIDStore: Integer; FPreSaleDate: TDateTime; FInvObs: String; FIDPreSale: Integer; FPresaleMaxDisc: Currency; FItems: TList; FItemsSugg: TStringList; FSaleBelowCostPrice: Boolean; FBeforeAddPreSaleItem: TBeforeAddPreSaleItem; FAfterAddPreSaleItem: TAfterAddPreSaleItem; FInvoiceDiscount: Currency; FPreSaleInfo: TPreSaleInfo; FECFAddedItems: Integer; FIDOtherComiss: Integer; FCOO: String; FTaxExempt: Boolean; FPuppyTracker : Boolean; FSaleCode: String; FBeforeDoInvoiceDiscount: TBeforeDoInvoiceDiscount; FDiscountKind: TDiscountKind; FSerialECF: String; FPreSaleType: TPreSaleType; FRoundDecimalTo: Integer; FOnItemDiscount: TPreSaleItemRequestRight; FCouponOpened: Boolean; FImported: Boolean; FCCF: String; function GetItems(Index: Integer): TPreSaleItem; procedure SetItems(Index: Integer; const Value: TPreSaleItem); function GetSuggestItems(Index: Integer): TPreSaleItemSuggestion; function GetCount: Integer; function GetSuggestCount : Integer; procedure RemovePreSaleItem(Index: Integer); procedure UpdateValues; function GetDiscountTotal: Currency; function GetCostTotal: Currency; function GetSaleTotal: Currency; function GetTaxTotal: Currency; function GetRefundTotal: Currency; function TestDiscountAdd(PSI: TPreSaleItem): Boolean; function GetScaleDifference: Currency; protected { Protected declarations } public { Public declarations } property Items[Index: Integer]: TPreSaleItem read GetItems write SetItems; property SuggestItems[Index: Integer]: TPreSaleItemSuggestion read GetSuggestItems; property COO: String read FCOO write FCOO; property CCF: String read FCCF write FCCF; property DeliverType: Integer read FDeliverType write FDeliverType; property IsLayaway: Boolean read FIsLayaway write FIsLayaway; property IDStore: Integer read FIDStore write FIDStore; property PreSaleDate: TDateTime read FPreSaleDate write FPreSaleDate; property InvObs: String read FInvObs write FInvObs; property IDPreSale: Integer read FIDPreSale write FIDPreSale; property IDOtherComiss: Integer read FIDOtherComiss write FIDOtherComiss; property PresaleMaxDisc: Currency read FPresaleMaxDisc write FPresaleMaxDisc; property DiscountKind: TDiscountKind read FDiscountKind write FDiscountKind; property DiscountTotal: Currency read GetDiscountTotal; property SaleTotal: Currency read GetSaleTotal; property ScaleDifference: Currency read GetScaleDifference; property CostTotal: Currency read GetCostTotal; property RefundTotal: Currency read GetRefundTotal; property TaxTotal: Currency read GetTaxTotal; property TaxExempt: Boolean read FTaxExempt write FTaxExempt; property PuppyTracker: Boolean read FPuppyTracker write FPuppyTracker; property SaleBelowCostPrice: Boolean read FSaleBelowCostPrice write FSaleBelowCostPrice; property SerialECF: String read FSerialECF write FSerialECF; property RoundDecimalTo: Integer read FRoundDecimalTo write FRoundDecimalTo; property PreSaleType: TPreSaleType read FPreSaleType write FPreSaleType; property InvoiceDiscount: Currency read FInvoiceDiscount write FInvoiceDiscount; property PreSaleInfo: TPreSaleInfo read FPreSaleInfo write FPreSaleInfo; property Count: Integer read GetCount; property SuggestCount: Integer read GetSuggestCount; property ECFAddedItems: Integer read FECFAddedItems; property SaleCode: String read FSaleCode write FSaleCode; property CouponOpened: Boolean read FCouponOpened write FCouponOpened; property Imported: Boolean read FImported write FImported; constructor Create(AOwner: TComponent);override; destructor Destroy;override; function AddPreSaleItem(AIDCustomer, AIDModel, AIDStore, AIDUser, AIDCommis: Integer; ADiscount, ASale, ACost: Currency; AQty : Double; ATaxValue, APercMaxDisc: Currency; AMovDate, ADate: TDateTime; AResetDisc, AManager: Boolean; ADescription, AECFTaxIndex, AModel, AImagePath: String; APuppyTracker, ARequestCustomer: Boolean; ACaseQty: Double; AIDDepartment, AIDVendorPrice, AIDDescriptionPrice: Integer; ASuggPrice: Currency; ADocumentNumber: String; AIDDocumentType: Integer; ASerialNumber, AIdentificationNumber: String; ATotalInformed : Currency; ATotParcial, AUnidade: String): Boolean; function Add(PreSaleItem: TPreSaleItem): Integer; procedure Clear; procedure Delete(Index: Integer); procedure ResetDiscount; function DoDiscount(ADiscountType: TDiscountType; ADiscountValueType : TDiscountValueType; AValue: Currency): Boolean; function CalcDiscount(ADiscountType: TDiscountType; ADiscountValueType : TDiscountValueType; AValue: Currency): Currency; procedure ResetTax; function AddItemSuggestion(AModel, ADescription, AOBS : String; ASalePrice: Currency):Boolean; function PrintedCount: Integer; published property BeforeAddPreSaleItem: TBeforeAddPreSaleItem read FBeforeAddPreSaleItem write FBeforeAddPreSaleItem; property AfterAddPreSaleItem: TAfterAddPreSaleItem read FAfterAddPreSaleItem write FAfterAddPreSaleItem; property BeforeDoInvoiceDiscount: TBeforeDoInvoiceDiscount read FBeforeDoInvoiceDiscount write FBeforeDoInvoiceDiscount; property OnItemDiscount: TPreSaleItemRequestRight read FOnItemDiscount write FOnItemDiscount; end; procedure Register; implementation procedure Register; begin RegisterComponents('NewPower', [TPreSale]); end; { TPreSale } function TPreSale.Add(PreSaleItem: TPreSaleItem): Integer; begin Result := FItems.Add(PreSaleItem); if PreSaleItem.Discount <> 0 then FDiscountKind := dkItem; UpdateValues; end; function TPreSale.AddPreSaleItem(AIDCustomer, AIDModel, AIDStore, AIDUser, AIDCommis: Integer; ADiscount, ASale, ACost: Currency; AQty : Double; ATaxValue, APercMaxDisc: Currency; AMovDate, ADate: TDateTime; AResetDisc, AManager: Boolean; ADescription, AECFTaxIndex, AModel, AImagePath: String; APuppyTracker, ARequestCustomer: Boolean; ACaseQty: Double; AIDDepartment, AIDVendorPrice, AIDDescriptionPrice: Integer; ASuggPrice: Currency; ADocumentNumber: String; AIDDocumentType: Integer; ASerialNumber, AIdentificationNumber: String; ATotalInformed : Currency; ATotParcial, AUnidade: String): Boolean; var PreSaleItem : TPreSaleItem; begin Result := False; try PreSaleItem := TPreSaleItem.Create; with PreSaleItem do begin FIDCustomer := AIDCustomer; FIDModel := AIDModel; FIDStore := AIDStore; FQty := AQty; FDiscount := ADiscount; FSale := ASale; FCost := ACost; FTotalInformed := ATotalInformed; FIDUser := AIDUser; FIDCommis := AIDCommis; FMovDate := AMovDate; FDate := ADate; FManager := AManager; FTaxValue := ATaxValue; FPercMaxDisc := APercMaxDisc; FDescription := ADescription; FECFTaxIndex := AECFTaxIndex; FModel := AModel; FImagePath := AImagePath; FPuppyTracker := APuppyTracker; FRequestCustomer := ARequestCustomer; FCaseQty := ACaseQty; FPrinted := False; FIDDepartment := AIDDepartment; FIDVendorPrice := AIDVendorPrice; FIDDescriptionPrice := AIDDescriptionPrice; FSuggPrice := ASuggPrice; FDocumentNumber := ADocumentNumber; FIDDocumentType := AIDDocumentType; FTotalizadorParcial := ATotParcial; FUnidade := AUnidade; if ASerialNumber <> '' then AddSerialNumber(ASerialNumber, AIdentificationNumber); end; if not TestDiscountAdd(PreSaleItem) then Exit; if AResetDisc then ResetDiscount; if Assigned(FBeforeAddPreSaleItem) then FBeforeAddPreSaleItem(PreSaleItem, Result); if Result then begin Add(PreSaleItem); Inc(FECFAddedItems); PreSaleItem.ECFIndex := FECFAddedItems; if Assigned(FAfterAddPreSaleItem) then FAfterAddPreSaleItem(PreSaleItem, Result); end else FreeAndNil(PreSaleItem); except Result := False; end; UpdateValues; end; constructor TPreSale.Create(AOwner: TComponent); begin inherited Create(AOwner); if not (csDesigning in ComponentState) then begin FItems := TList.Create; FPreSaleInfo := TPreSaleInfo.Create; FItemsSugg := TStringList.Create; FIDPreSale := -1; FECFAddedItems := 0; FDiscountKind := dkNone; FPreSaleType := tptInvoice; end; end; procedure TPreSale.Delete(Index: Integer); begin RemovePreSaleItem(Index); FItems.Delete(Index); end; destructor TPreSale.Destroy; begin if not (csDesigning in ComponentState) then begin Clear; FreeAndNil(FItems); FreeAndNil(FPreSaleInfo); end; inherited Destroy; end; function TPreSale.GetCostTotal: Currency; var I: Integer; begin Result := 0; for I := 0 to FItems.Count - 1 do Result := Result + TruncDecimal(TPreSaleItem(FItems[I]).Cost * TPreSaleItem(FItems[I]).Qty, FRoundDecimalTo); end; function TPreSale.GetSuggestCount : Integer; begin Result := FItemsSugg.Count; end; function TPreSale.GetCount: Integer; begin Result := FItems.Count; end; function TPreSale.GetDiscountTotal: Currency; var I: Integer; begin Result := 0; for I := 0 to FItems.Count - 1 do Result := Result + TPreSaleItem(FItems[I]).Discount; end; function TPreSale.GetItems(Index: Integer): TPreSaleItem; begin Result := FItems[Index]; end; function TPreSale.GetSaleTotal: Currency; var I: Integer; begin Result := 0; for I := 0 to FItems.Count - 1 do if (TPreSaleItem(FItems[I]).FTotalInformed <> 0) then Result := Result + TruncDecimal(TPreSaleItem(FItems[I]).TotalInformed, FRoundDecimalTo) else Result := Result + TruncDecimal(TPreSaleItem(FItems[I]).Sale * TPreSaleItem(FItems[I]).Qty, FRoundDecimalTo); end; function TPreSale.GetTaxTotal: Currency; var I: Integer; begin Result := 0; for I := 0 to FItems.Count - 1 do Result := Result + (TPreSaleItem(FItems[I]).TaxValue); end; procedure TPreSale.RemovePreSaleItem(Index: Integer); var PreSaleItem: TPreSaleItem; begin PreSaleItem := FItems[Index]; FreeAndNil(PreSaleItem); end; procedure TPreSale.SetItems(Index: Integer; const Value: TPreSaleItem); begin FItems[Index] := Value; end; procedure TPreSale.UpdateValues; begin // Esta é uma procedure legal. Não sei pra que ela serve // mas ainda vou descobrir :-) end; procedure TPreSale.ResetDiscount; var I: Integer; begin for I := 0 to FItems.Count - 1 do TPreSaleItem(FItems[I]).Discount := 0; FDiscountKind := dkNone; end; procedure TPreSale.ResetTax; var I: Integer; begin for I := 0 to FItems.Count - 1 do TPreSaleItem(FItems[I]).TaxValue := 0; end; function TPreSale.TestDiscountAdd(PSI: TPreSaleItem): Boolean; var LucroItem, PercAplicado: Currency; begin case PreSaleType of tptInvoice, tptLayAway: begin if not FSaleBelowCostPrice then begin Result := not (PSI.Sale < PSI.Cost); if not Result then begin MsgBox(MSG_INF_NOT_SELL_BELLOW_COST, vbCritical + vbOKOnly); Exit; end; //Verificar mais tarde //LucroItem := TruncDecimal((PSI.Sale - PSI.Cost - (PSI.Sale * PSI.TaxValue / 100)) * PSI.Qty, FRoundDecimalTo) - PSI.Discount; //Result := (LucroItem >= 0); //if not Result then // Exit; end; // Atriubui a uma variavel currency, para nao haver erro na comparacao PercAplicado := 0; if PSI.Sale <> 0 then PercAplicado := (PSI.Discount / PSI.Sale * 100); Result := PSI.PercMaxDisc >= PercAplicado; if not Result then if Assigned(FOnItemDiscount) then FOnItemDiscount(PSI, Result); end; tptRefund, tptExchange: Result := True; else Result := False; end; end; procedure TPreSale.Clear; var I : integer; ItemSugg : TPreSaleItemSuggestion; begin while FItems.Count > 0 do Delete(0); for I := 0 to FItemsSugg.Count-1 do begin ItemSugg := TPreSaleItemSuggestion(FItemsSugg.Objects[I]); FreeAndNil(ItemSugg); end; FItemsSugg.Clear; FIDPreSale := -1; FPreSaleInfo.UnSet; FInvoiceDiscount := 0; FECFAddedItems := 0; FIDOtherComiss := 0; FCOO := ''; FCCF := ''; FInvObs := ''; FPuppyTracker := False; FDiscountKind := dkNone; FSerialECF := ''; FPreSaleType := tptInvoice; FImported := False; end; function TPreSale.CalcDiscount(ADiscountType: TDiscountType; ADiscountValueType : TDiscountValueType; AValue: Currency): Currency; var Fator : Integer; Falta, PercDiscount: Currency; ASaleTotal : Currency; AAccept : Boolean; begin Falta := 0; PercDiscount := 0; case ADiscountType of tdtDesconto: Fator := 1; tdtAcrescimo: Fator := -1; end; case ADiscountValueType of dvtPerc: begin PercDiscount := AValue; PercDiscount := (PercDiscount * Fator) / 100; Falta := (GetSaleTotal - DiscountTotal) * PercDiscount; if PercDiscount >= 1 then raise Exception.Create(MSG_INF_DISCOUNT_LIMT_REACHED); end; dvtValor: begin if PreSaleType = tptRefund Then Fator := Fator * -1; PercDiscount := (AValue / (GetSaleTotal - DiscountTotal)){ * 100}; Falta := AValue * Fator; ASaleTotal := (GetSaleTotal - DiscountTotal); if PreSaleType = tptRefund Then ASaleTotal := ABS(ASaleTotal); if Falta >= ASaleTotal then raise Exception.Create(MSG_INF_DISCOUNT_LIMT_REACHED); end; end; if Assigned(FBeforeDoInvoiceDiscount) then FBeforeDoInvoiceDiscount(PercDiscount * 100, AAccept); if not AAccept then raise Exception.Create(MSG_INF_INV_DISCOUNT_LIMT); FDiscountKind := dkInvoice; Falta := TruncDecimal(Falta, FRoundDecimalTo); Result := Falta; end; function TPreSale.DoDiscount(ADiscountType: TDiscountType; ADiscountValueType: TDiscountValueType; AValue: Currency): Boolean; var I, Fator : Integer; Falta, PercDiscount: Currency; AItem: TPreSaleItem; FaltaTotal: Currency; AAccept : Boolean; ASaleTotal, Retirar, DescontoMaximo: Currency; begin Result := True; try Falta := 0; PercDiscount := 0; Fator := 0; case ADiscountType of tdtDesconto: Fator := 1; tdtAcrescimo: Fator := -1; end; case ADiscountValueType of dvtPerc: begin PercDiscount := AValue; PercDiscount := (PercDiscount * Fator) / 100; Falta := GetSaleTotal * PercDiscount; if PercDiscount >= 1 then raise Exception.Create(MSG_INF_DISCOUNT_LIMT_REACHED); end; dvtValor: begin if PreSaleType = tptRefund Then Fator := Fator * -1; PercDiscount := (AValue / GetSaleTotal){ * 100}; Falta := AValue * Fator; ASaleTotal := GetSaleTotal; if PreSaleType = tptRefund Then ASaleTotal := ABS(ASaleTotal); if Falta >= ASaleTotal then raise Exception.Create(MSG_INF_DISCOUNT_LIMT_REACHED); end; end; AAccept := False; if Assigned(FBeforeDoInvoiceDiscount) then FBeforeDoInvoiceDiscount(PercDiscount * 100, AAccept); if not AAccept then raise Exception.Create(MSG_INF_INV_DISCOUNT_LIMT); Falta := TruncDecimal(Falta, FRoundDecimalTo); FaltaTotal := Falta; for I := 0 to GetCount - 1 do begin AItem := FItems[I]; if I = (GetCount - 1) then begin Retirar := Falta; if (ADiscountType = tdtAcrescimo) then DescontoMaximo := (AItem.Sale * AItem.Qty) * Fator else DescontoMaximo := (AItem.Sale * AItem.Qty) * AItem.PercMaxDisc * Fator / 100; DescontoMaximo := TruncDecimal(DescontoMaximo, FRoundDecimalTo); if Abs(Retirar) > Abs(DescontoMaximo) then AItem.Discount := DescontoMaximo else AItem.Discount := Retirar; end else begin Retirar := (AItem.Sale * AItem.Qty) * PercDiscount * Fator; Retirar := TruncDecimal(Retirar, FRoundDecimalTo); DescontoMaximo := (AItem.Sale * AItem.Qty) * AItem.PercMaxDisc * Fator / 100; DescontoMaximo := TruncDecimal(DescontoMaximo, FRoundDecimalTo); if Abs(Retirar) > Abs(DescontoMaximo) then AItem.Discount := DescontoMaximo else AItem.Discount := Retirar; end; Falta := Falta - Retirar; end; if AValue = 0 then FDiscountKind := dkNone else FDiscountKind := dkInvoice; case ADiscountValueType of dvtPerc: FInvoiceDiscount := GetSaleTotal * PercDiscount; dvtValor: FInvoiceDiscount := FaltaTotal; end; except on E: Exception do begin MsgBox(E.Message, vbCritical+vbOKOnly); Result := False; end; end; end; function TPreSale.AddItemSuggestion(AModel, ADescription, AOBS: String; ASalePrice: Currency): Boolean; var ItemSugg : TPreSaleItemSuggestion; begin Result := FItemsSugg.IndexOf(AModel)=-1; if Result then begin ItemSugg := TPreSaleItemSuggestion.Create; with ItemSugg do begin FModel := AModel; FDescription := ADescription; FOBS := AOBS; FSalePrice := ASalePrice; end; FItemsSugg.AddObject(AModel,ItemSugg); end; end; function TPreSale.GetSuggestItems(Index: Integer): TPreSaleItemSuggestion; begin Result := TPreSaleItemSuggestion(FItemsSugg.Objects[Index]); end; function TPreSale.PrintedCount: Integer; var I: Integer; begin Result := 0; for I := 0 to GetCount - 1 do begin if GetItems(I).Printed then Inc(Result); end; end; function TPreSale.GetRefundTotal: Currency; var I: Integer; begin Result := 0; for I := 0 to FItems.Count - 1 do if TPreSaleItem(FItems[I]).Qty < 0 then Result := Result + (TPreSaleItem(FItems[I]).Qty * TPreSaleItem(FItems[I]).FSale); end; function TPreSale.GetScaleDifference: Currency; var I: Integer; cScaleTotal, cSaleTotal : Currency; begin Result := 0; cScaleTotal := 0; cSaleTotal := 0; for I := 0 to FItems.Count - 1 do if (TPreSaleItem(FItems[I]).FTotalInformed <> 0) then cScaleTotal := cScaleTotal + TruncDecimal(TPreSaleItem(FItems[I]).TotalInformed, FRoundDecimalTo) else cScaleTotal := cScaleTotal + TruncDecimal(TPreSaleItem(FItems[I]).Sale * TPreSaleItem(FItems[I]).Qty, FRoundDecimalTo); for I := 0 to FItems.Count - 1 do cSaleTotal := cSaleTotal + TruncDecimal(TPreSaleItem(FItems[I]).Sale * TPreSaleItem(FItems[I]).Qty, FRoundDecimalTo); Result := (cSaleTotal - cScaleTotal); end; { TPreSaleInfo } constructor TPreSaleInfo.Create; begin inherited Create; FCommissionGroup := nil; FCustomerInfo := nil; FMediaInfo := nil; FTouristGroup := nil; end; destructor TPreSaleInfo.Destroy; begin UnSet; inherited Destroy; end; procedure TPreSaleInfo.UnSet; begin if FCommissionGroup <> nil then FreeAndNil(FCommissionGroup); if FCustomerInfo <> nil then FreeAndNil(FCustomerInfo); if FMediaInfo <> nil then FreeAndNil(FMediaInfo); if FTouristGroup <> nil then FreeAndNil(FTouristGroup); end; { TPreSaleItem } constructor TPreSaleItem.Create; begin inherited Create; FSerialNumbers := TList.Create; end; destructor TPreSaleItem.Destroy; begin ClearSerialItems; FSerialNumbers.Free; inherited Destroy; end; procedure TPreSaleItem.ClearSerialItems; var PIS: TPreSaleItemSerial; I : Integer; begin for I := 0 to FSerialNumbers.Count - 1 do begin PIS := TPreSaleItemSerial(FSerialNumbers[I]); if PIS <> nil then FreeAndNil(PIS); end; FSerialNumbers.Clear; end; function TPreSaleItem.GetSerialNumbers(Index: Integer): TPreSaleItemSerial; begin Result := TPreSaleItemSerial(FSerialNumbers[Index]); end; procedure TPreSaleItem.SetSerialNumbers(Index: Integer; const Value: TPreSaleItemSerial); begin FSerialNumbers[Index] := Value; end; procedure TPreSaleItem.AddSerialNumber(ASerialNumber, AIdentificationNumber: String); var PIS: TPreSaleItemSerial; begin PIS := TPreSaleItemSerial.Create; PIS.SerialNumber := ASerialNumber; PIS.IdentificationNumber := AIdentificationNumber; AddSerialNumber(PIS); end; procedure TPreSaleItem.AddSerialNumber(APreSaleItemSerial: TPreSaleItemSerial); begin FSerialNumbers.Add(APreSaleItemSerial); end; end.
unit uAddModifAdr3; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uAddModifForm, uInvisControl, uSpravControl, uFormControl, StdCtrls, Buttons, uFControl, uLabeledFControl, uCharControl, DB, FIBDataSet, pFIBDataSet, uAdr_DataModule, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, IBase, cxLookAndFeelPainters, cxButtons, ActnList, uAdressForm, cxCalendar, cxLabel, AdrSp_MainForm, Address_ZMessages; type TAddModifAdrForm3 = class(TForm) CBCountry: TcxLookupComboBox; CountryBtn: TcxButton; CountryLbl: TLabel; RegionBtn: TcxButton; RegionLbl: TLabel; CBDistrict: TcxLookupComboBox; DistrictBtn: TcxButton; DistrictLbl: TLabel; CBTown: TcxLookupComboBox; TownBtn: TcxButton; TownLbl: TLabel; CBStreet: TcxLookupComboBox; StreetBtn: TcxButton; StreetLbl: TLabel; CBArea: TcxLookupComboBox; AreaBtn: TcxButton; AreaLbl: TLabel; TEFlat: TcxTextEdit; TEHouse: TcxTextEdit; TEKorpus: TcxTextEdit; KorpusLbl: TLabel; HouseLbl: TLabel; FlatLbl: TLabel; ZipLbl: TLabel; AcceptBtn: TcxButton; CancelBtn: TcxButton; ActionList1: TActionList; AcceptAction: TAction; CancelAction: TAction; CBRegion: TcxLookupComboBox; MEZip: TcxMaskEdit; SearchBtn: TcxButton; DEBeg: TcxDateEdit; DEEnd: TcxDateEdit; DateLbl: TcxLabel; DateLbl2: TcxLabel; SearchPlaceBtn: TcxButton; procedure DistrictOpenSprav(Sender: TObject); procedure CountryOpenSprav(Sender: TObject); procedure RegionOpenSprav(Sender: TObject); procedure PlaceOpenSprav(Sender: TObject); procedure StreetOpenSprav(Sender: TObject); procedure AreaOpenSprav(Sender: TObject); procedure CBCountryPropertiesChange(Sender: TObject); procedure CBRegionPropertiesChange(Sender: TObject); procedure CBDistrictPropertiesChange(Sender: TObject); procedure CBTownPropertiesChange(Sender: TObject); procedure CancelActionExecute(Sender: TObject); procedure CBStreetPropertiesChange(Sender: TObject); procedure CBAreaPropertiesChange(Sender: TObject); procedure SearchBtnClick(Sender: TObject); procedure MEZipPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure MEZipRefresh; procedure MEZipExit(Sender: TObject); procedure MEZipKeyPress(Sender: TObject; var Key: Char); procedure CBStreetPropertiesCloseUp(Sender: TObject); procedure CBDistrictPropertiesCloseUp(Sender: TObject); procedure CBTownPropertiesCloseUp(Sender: TObject); procedure CBRegionPropertiesCloseUp(Sender: TObject); procedure AcceptActionExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CBRegionPropertiesEditValueChanged(Sender: TObject); procedure CBCountryPropertiesEditValueChanged(Sender: TObject); procedure CBCountryPropertiesCloseUp(Sender: TObject); procedure CBDistrictPropertiesEditValueChanged(Sender: TObject); procedure CBTownPropertiesEditValueChanged(Sender: TObject); procedure CBStreetPropertiesEditValueChanged(Sender: TObject); procedure CBAreaPropertiesEditValueChanged(Sender: TObject); procedure CBAreaPropertiesCloseUp(Sender: TObject); procedure SearchPlaceBtnClick(Sender: TObject); private { Private declarations } DM: TAdrDM; pForTownSelect:Boolean; pIsLocked:Boolean; function ModeIfLocked:FormMode; public pIdPlace:Integer; pFullName:String; pIdAddress:Integer; pIdPk:Integer; DBHandle:Integer; constructor Create(AOwner:TComponent; ADB_Handle:TISC_DB_HANDLE; ForTownSelect:Boolean=False; ShowDates:Boolean=False; AIdAddress:Integer=-1); reintroduce; end; implementation {$R *.dfm} uses RxMemDS, uUnivSprav, StdConvs, FIBDatabase, FIBQuery; function TAddModifAdrForm3.ModeIfLocked:FormMode; begin if pIsLocked then Result:=AdrSp_MainForm.fsmShow else Result:=AdrSp_MainForm.fsmSelect; end; constructor TAddModifAdrForm3.Create(AOwner:TComponent; ADB_Handle:TISC_DB_HANDLE; ForTownSelect:Boolean=False; ShowDates:Boolean=False; AIdAddress:Integer=-1); begin inherited Create(AOwner); DM := TAdrDM.Create(Self); DM.pFIBDB_Adr.Handle := ADB_Handle; DM.pFIBDB_Adr.DefaultTransaction.Active:=True; DBHandle:=Integer(DM.pFIBDB_Adr.Handle); pIsLocked:=False; //****************************************************************************** // Настраиваем поля ввода // Страна DM.pFIBDS_SelectCountry.Open; CBCountry.Properties.ListSource:=DM.DSourceCountry; CBCountry.Clear; // Область CBRegion.Properties.ListSource:=DM.DSourceRegion; CBRegion.Enabled:=False; RegionBtn.Enabled:=False; // Район области CBDistrict.Properties.ListSource:=DM.DSourceDistrict; DM.pFIBDS_SelectDistrict.Active; CBDistrict.Enabled:=False; DistrictBtn.Enabled:=False; // Город CBTown.Properties.ListSource:=DM.DSourcePlace; CBTown.Enabled:=False; TownBtn.Enabled:=False; // Улица CBStreet.Properties.ListSource:=DM.DSourceStreet; CBStreet.Enabled:=False; StreetBtn.Enabled:=False; // Район городской CBArea.Properties.ListSource:=DM.DSourceArea; CBArea.Enabled:=False; AreaBtn.Enabled:=False; //****************************************************************************** MEZipRefresh; //****************************************************************************** pForTownSelect:=ForTownSelect; //****************************************************************************** if ForTownSelect then begin pIdPlace:=AIdAddress; CBStreet.Hide; StreetLbl.Hide; StreetBtn.Hide; CBArea.Hide; AreaLbl.Hide; AreaBtn.Hide; MEZip.Hide; ZipLbl.Hide; TEHouse.Hide; HouseLbl.Hide; TEKorpus.Hide; KorpusLbl.Hide; TEFlat.Hide; FlatLbl.Hide; SearchBtn.Hide; AcceptBtn.Top:=CBTown.Top+CBTown.Height+10; CancelBtn.Top:=AcceptBtn.Top; Height:=AcceptBtn.Top+AcceptBtn.Height+40; if DM.DSetPlace.Active then DM.DSetPlace.Close; DM.DSetPlace.SQLs.SelectSQL.Text:='SELECT * FROM ADR_GET_BY_ID_PLACE('+IntToStr(pIdPlace)+')'; DM.DSetPlace.Open; CBCountry.EditValue:=DM.DSetPlace['ID_COUNTRY']; CBRegion.EditValue:=DM.DSetPlace['ID_REGION']; CBDistrict.EditValue:=DM.DSetPlace['ID_DISTRICT']; CBTown.EditValue:=DM.DSetPlace['ID_PLACE']; pFullName:=VarToStr(DM.DSetPlace['FULL_NAME']); end else begin pIdAddress:=AIdAddress; if ShowDates then begin DEBeg.Show; DEEnd.Show; DateLbl.Show; DateLbl2.Show; end else begin Height:=Height-30; AcceptBtn.Top:=AcceptBtn.Top-30; CancelBtn.Top:=AcceptBtn.Top; end; if pIdAddress>0 then begin if DM.pFIBDS_Id.Active then DM.pFIBDS_Id.Close; DM.pFIBDS_Id.SQLs.SelectSQL.Text:='SELECT * FROM ADR_ADRESS_SEL('+IntToStr(pIdAddress)+')'; DM.pFIBDS_Id.Open; CBCountry.EditValue:=DM.pFIBDS_Id['ID_COUNTRY']; CBRegion.EditValue:=DM.pFIBDS_Id['ID_REGION']; CBDistrict.EditValue:=DM.pFIBDS_Id['ID_DISTRICT']; CBTown.EditValue:=DM.pFIBDS_Id['ID_PLACE']; CBStreet.EditValue:=DM.pFIBDS_Id['ID_STREET']; CBArea.EditValue:=DM.pFIBDS_Id['ID_CITY_AREA']; pIdPk:=DM.pFIBDS_Id['ID_ADR_PK']; MEZip.Text:=VarToStr(DM.pFIBDS_Id['ZIPCODE']); TEKorpus.Text:=VarToStr(DM.pFIBDS_Id['KORPUS']); TEHouse.Text:=VarToStr(DM.pFIBDS_Id['HOUSE']); TEFlat.Text:=VarToStr(DM.pFIBDS_Id['FLAT']); DEBeg.Date:=VarToDateTime(DM.pFIBDS_Id['DATE_BEG']); DEEnd.Date:=VarToDateTime(DM.pFIBDS_Id['DATE_END']); pFullName:=VarToStr(DM.pFIBDS_Id['FULL_NAME']); if MEZip.Text='' then MEZipRefresh; end; end; end; procedure TAddModifAdrForm3.CountryOpenSprav(Sender: TObject); var Params:TSpParams; OutPut : TRxMemoryData; begin Params.FormCaption:='Довідник країн'; Params.ShowMode:=ModeIfLocked; Params.ShowButtons:=[AdrSp_MainForm.fbAdd,AdrSp_MainForm.fbDelete,AdrSp_MainForm.fbModif,AdrSp_MainForm.fbExit]; Params.AddFormClass:='TAdd_Country_Form'; Params.ModifFormClass:='TAdd_Country_Form'; Params.TableName:='adr_country_select'; Params.Fields:='Name_country,id_country'; Params.FieldsName:='Назва'; Params.KeyField:='id_country'; Params.ReturnFields:='Name_country,id_country'; Params.DeleteSQL:='execute procedure adr_country_d(:id_country);'; Params.DBHandle:=DBHandle; Params.NameForSearch:=CBCountry.EditText; OutPut:=TRxMemoryData.Create(self); if GetAdressesSp(Params,OutPut) then begin Refresh; if DM.pFIBDS_SelectCountry.Active then DM.pFIBDS_SelectCountry.Close; DM.pFIBDS_SelectCountry.Open; CBCountry.EditValue:=output['id_country']; end else begin Refresh; if OutPut.Filtered then begin if DM.pFIBDS_SelectCountry.Active then DM.pFIBDS_SelectCountry.Close; DM.pFIBDS_SelectCountry.Open; end; end; OutPut.Free; end; procedure TAddModifAdrForm3.RegionOpenSprav(Sender: TObject); var Params:TSpParams; OutPut:TRxMemoryData; begin Params.FormCaption:='Довідник регіонів'; Params.ShowMode:=ModeIfLocked; Params.ShowButtons:=[AdrSp_MainForm.fbAdd,AdrSp_MainForm.fbDelete,AdrSp_MainForm.fbModif,AdrSp_MainForm.fbExit]; Params.AddFormClass:='TAdd_Region_Form'; Params.ModifFormClass:='TAdd_Region_Form'; Params.TableName:='ADR_REGION_SELECT_SP('+IntToStr(CBCountry.EditValue)+');'; Params.Fields:='Name_region,NAME_TYPE,ZIP,id_region'; Params.FieldsName:='Назва регіона, Тип регіона, Індекси'; Params.KeyField:='id_region'; Params.ReturnFields:='Name_region,id_region'; Params.DeleteSQL:='execute procedure adr_region_d(:id_region);'; Params.DBHandle:=DBHandle; Params.NameForSearch:=CBRegion.EditText; Params.Additional:=VarArrayCreate([0,1],varVariant); Params.Additional[0]:=CBCountry.EditValue; Params.Additional[1]:=CBCountry.EditText; OutPut:=TRxMemoryData.Create(self); if GetAdressesSp(Params,OutPut) then begin Refresh; if DM.pFIBDS_SelectRegion.Active then DM.pFIBDS_SelectRegion.Close; DM.pFIBDS_SelectRegion.Open; CBRegion.EditValue:=output['id_region']; end else begin Refresh; if OutPut.Filtered then begin if DM.pFIBDS_SelectRegion.Active then DM.pFIBDS_SelectRegion.Close; DM.pFIBDS_SelectRegion.Open; end; end; OutPut.Free; end; procedure TAddModifAdrForm3.DistrictOpenSprav(Sender: TObject); var Params:TSpParams; OutPut : TRxMemoryData; begin Params.FormCaption:='Довідник районів'; Params.ShowMode:=ModeIfLocked; Params.ShowButtons:=[AdrSp_MainForm.fbAdd,AdrSp_MainForm.fbDelete,AdrSp_MainForm.fbModif,AdrSp_MainForm.fbExit]; Params.AddFormClass:='TAdd_District_Form'; Params.ModifFormClass:='TAdd_District_Form'; Params.TableName:='adr_district_select_SP('+IntToStr(CBRegion.EditValue)+');'; Params.Fields:='Name_district,NAME_TYPE,NAME_REGION,NAME_COUNTRY,ZIP,id_district'; Params.FieldsName:='Район, Тип района, Регіон, Країна, Індекси'; Params.KeyField:='id_district'; Params.ReturnFields:='Name_district,id_district'; Params.DeleteSQL:='execute procedure adr_district_d(:id_district);'; Params.DBHandle:=DBHandle; Params.NameForSearch:=CBDistrict.EditText; Params.Additional:=VarArrayCreate([0,1],varVariant); Params.Additional[0]:=CBRegion.EditValue; Params.Additional[1]:=CBRegion.EditText; OutPut:=TRxMemoryData.Create(self); if GetAdressesSp(Params,OutPut) then begin Refresh; if DM.pFIBDS_SelectDistrict.Active then DM.pFIBDS_SelectDistrict.Close; DM.pFIBDS_SelectDistrict.Open; CBDistrict.EditValue:=output['id_district']; end else begin Refresh; if OutPut.Filtered then begin if DM.pFIBDS_SelectDistrict.Active then DM.pFIBDS_SelectDistrict.Close; DM.pFIBDS_SelectDistrict.Open; end; end; OutPut.Free; end; procedure TAddModifAdrForm3.PlaceOpenSprav(Sender: TObject); var Params:TSpParams; OutPut : TRxMemoryData; id_distr: string; begin if not VarIsNull(CBDistrict.EditValue) then id_distr:=IntToStr(CBDistrict.EditValue) else id_distr:='null'; Params.FormCaption:='Довідник населених пунктів'; Params.ShowMode:=ModeIfLocked; Params.ShowButtons:=[AdrSp_MainForm.fbAdd,AdrSp_MainForm.fbDelete,AdrSp_MainForm.fbModif,AdrSp_MainForm.fbExit]; Params.AddFormClass:='TAdd_Place_Form'; Params.ModifFormClass:='TAdd_Place_Form'; Params.TableName:='ADR_PLACE_SELECT_SP('+IntToStr(CBRegion.EditValue)+','+id_distr+')'; Params.Fields:='Name_place_SP,NAME_TYPE,NAME_DISTRICT,NAME_REGION,NAME_COUNTRY,ZIP,id_place'; Params.FieldsName:='Населений пункт, Тип ,Район, Регіон, Країна, Індекси'; Params.KeyField:='id_place'; Params.ReturnFields:='Name_place,id_place'; Params.DeleteSQL:='execute procedure adr_place_d(:id_place);'; Params.DBHandle:=DBHandle; Params.NameForSearch:=CBTown.EditText; Params.Additional:=VarArrayCreate([0,3],varVariant); Params.Additional[0]:=CBRegion.EditValue; Params.Additional[1]:=CBRegion.EditText; Params.Additional[2]:=CBDistrict.EditValue; Params.Additional[3]:=CBDistrict.EditText; OutPut:=TRxMemoryData.Create(self); if GetAdressesSp(Params,OutPut) then begin Refresh; if DM.pFIBDS_SelectPlace.Active then DM.pFIBDS_SelectPlace.Close; DM.pFIBDS_SelectPlace.Open; CBTown.EditValue:=output['id_place']; end else begin Refresh; if OutPut.Filtered then begin if DM.pFIBDS_SelectPlace.Active then DM.pFIBDS_SelectPlace.Close; DM.pFIBDS_SelectPlace.Open; end; end; OutPut.Free; end; procedure TAddModifAdrForm3.StreetOpenSprav(Sender: TObject); var Params:TSpParams; OutPut : TRxMemoryData; begin Params.FormCaption:='Довідник вулиць'; Params.ShowMode:=AdrSp_MainForm.fsmSelect; Params.ShowButtons:=[AdrSp_MainForm.fbAdd,AdrSp_MainForm.fbDelete,AdrSp_MainForm.fbModif,AdrSp_MainForm.fbExit]; Params.AddFormClass:='TAdd_Street_Form'; Params.ModifFormClass:='TAdd_Street_Form'; Params.TableName:='ADR_STREET_SELECT_SP('+IntToStr(CBTown.EditValue)+');'; Params.Fields:='Name_street_SP,NAME_TYPE,NAME_PLACE,NAME_DISTRICT,NAME_REGION,NAME_COUNTRY,id_street'; Params.FieldsName:='Вулиця, Тип, Населений пункт, Район, Регіон, Країна'; Params.KeyField:='id_street'; Params.ReturnFields:='Name_street,id_street'; Params.DeleteSQL:='execute procedure adr_street_d(:id_street);'; Params.DBHandle:=DBHandle; Params.NameForSearch:=CBStreet.EditText; Params.Additional:=VarArrayCreate([0,1],varVariant); Params.Additional[0]:=CBTown.EditValue; Params.Additional[1]:=CBTown.EditText; OutPut:=TRxMemoryData.Create(self); if GetAdressesSp(Params,OutPut) then begin Refresh; if DM.pFIBDS_SelectStreet.Active then DM.pFIBDS_SelectStreet.Close; DM.pFIBDS_SelectStreet.Open; CBStreet.EditValue:=output['id_street']; end else begin Refresh; if OutPut.Filtered then begin if DM.pFIBDS_SelectStreet.Active then DM.pFIBDS_SelectStreet.Close; DM.pFIBDS_SelectStreet.Open; end; end; OutPut.Free; end; procedure TAddModifAdrForm3.AreaOpenSprav(Sender: TObject); var Params:TSpParams; OutPut : TRxMemoryData; begin Params.FormCaption:='Довідник міських районів'; Params.ShowMode:=AdrSp_MainForm.fsmSelect; Params.ShowButtons:=[AdrSp_MainForm.fbAdd,AdrSp_MainForm.fbDelete,AdrSp_MainForm.fbModif,AdrSp_MainForm.fbExit]; Params.AddFormClass:='TAddCityArea'; Params.ModifFormClass:='TAddCityArea'; Params.TableName:='ADR_CITY_AREA_SELECT_SP('+IntToStr(CBTown.EditValue)+');'; Params.Fields:='Name_city_area,NAME_PLACE,NAME_DISTRICT,NAME_REGION,NAME_COUNTRY,id_city_area'; Params.FieldsName:='Район, Населений пункт, Район, Регіон, Країна'; Params.KeyField:='id_city_area'; Params.ReturnFields:='Name_city_area,id_city_area'; Params.DeleteSQL:='execute procedure adr_city_area_d(:id_city_area);'; Params.DBHandle:=DBHandle; Params.NameForSearch:=CBArea.EditText; Params.Additional:=VarArrayCreate([0,1],varVariant); Params.Additional[0]:=CBTown.EditValue; Params.Additional[1]:=CBTown.EditText; OutPut:=TRxMemoryData.Create(self); if GetAdressesSp(Params,OutPut) then begin Refresh; if DM.pFIBDS_SelectArea.Active then DM.pFIBDS_SelectArea.Close; DM.pFIBDS_SelectArea.Open; CBArea.EditValue:=output['id_city_area']; end else begin Refresh; if OutPut.Filtered then begin if DM.pFIBDS_SelectArea.Active then DM.pFIBDS_SelectArea.Close; DM.pFIBDS_SelectArea.Open; end; end; OutPut.Free; end; procedure TAddModifAdrForm3.CBCountryPropertiesChange( Sender: TObject); begin if CBCountry.Text='' then CBCountryPropertiesEditValueChanged(Self); end; procedure TAddModifAdrForm3.CBRegionPropertiesChange( Sender: TObject); begin if CBRegion.Text='' then CBRegionPropertiesEditValueChanged(Self); end; procedure TAddModifAdrForm3.CBDistrictPropertiesChange( Sender: TObject); begin if CBDistrict.Text='' then CBDistrictPropertiesEditValueChanged(Self); end; procedure TAddModifAdrForm3.CBTownPropertiesChange( Sender: TObject); begin if CBTown.Text='' then CBTownPropertiesEditValueChanged(Self); end; procedure TAddModifAdrForm3.CancelActionExecute(Sender: TObject); begin DM.pFIBDB_Adr.DefaultTransaction.Active:=False; ModalResult:=mrCancel; end; procedure TAddModifAdrForm3.CBStreetPropertiesChange(Sender: TObject); begin if CBStreet.Text='' then CBStreetPropertiesEditValueChanged(Self); end; procedure TAddModifAdrForm3.CBAreaPropertiesChange(Sender: TObject); begin if CBArea.Text='' then CBTownPropertiesEditValueChanged(Self); end; procedure TAddModifAdrForm3.SearchBtnClick(Sender: TObject); var StrZip:String; begin StrZip:=MEZip.Text; if StrZip='*****' then Exit; pIsLocked:=not pIsLocked; MEZip.Properties.ReadOnly:=pIsLocked; if pIsLocked then begin SearchBtn.Caption:='Відмінити результати пошуку'; Delete(StrZip,Pos('*',StrZip),Length(StrZip)-Pos('*',StrZip)+1); if DM.DSetSearch.Active then DM.DSetSearch.Close; DM.DSetSearch.SQLs.SelectSQL.Text:='SELECT * FROM ADR_GET_BY_ZIP('''+StrZip+''')'; DM.DSetSearch.Open; //****************************************************************************** CBCountry.EditValue := DM.DSetSearch['ID_COUNTRY']; DM.pFIBDS_SelectCountry.Filtered:=True; if not VarIsNull(DM.DSetSearch['ID_STREET']) then begin // Блокируем данные, чтобы выбирать можно было только среди рез-тов поиска DM.pFIBDS_SelectRegion.Filtered:=True; DM.pFIBDS_SelectDistrict.Filtered:=True; DM.pFIBDS_SelectPlace.Filtered:=True; CBRegion.EditValue := DM.DSetSearch['ID_REGION']; CBDistrict.EditValue := DM.DSetSearch['ID_DISTRICT']; CBTown.EditValue := DM.DSetSearch['ID_PLACE']; // CBStreet.EditValue := DM.DSetSearch['ID_STREET']; DM.pFIBDS_SelectStreet.Filtered:=True; CBStreet.DroppedDown:=True; // DM.DSetSearch.Close; end else begin if not VarIsNull(DM.DSetSearch['ID_PLACE']) then begin CBRegion.EditValue := DM.DSetSearch['ID_REGION']; DM.pFIBDS_SelectRegion.Filtered:=True; DM.pFIBDS_SelectDistrict.Filtered:=True; if DM.pFIBDS_SelectDistrict.VisibleRecordCount>1 then CBDistrict.DroppedDown:=True else begin CBDistrict.EditValue := DM.DSetSearch['ID_DISTRICT']; CBDistrictPropertiesCloseUp(Self); end; end else begin if not VarIsNull(DM.DSetSearch['ID_REGION']) then begin DM.pFIBDS_SelectRegion.Filtered:=True; CBRegion.DroppedDown:=True; end; end; end; { CountryBtn.Enabled:=False; RegionBtn.Enabled:=False; DistrictBtn.Enabled:=False; TownBtn.Enabled:=False; StreetBtn.Enabled:=False; AreaBtn.Enabled:=False; } end else begin SearchBtn.Caption:='Пошук за індексом'; { CountryBtn.Enabled:=True; RegionBtn.Enabled:=True; DistrictBtn.Enabled:=True; TownBtn.Enabled:=True; StreetBtn.Enabled:=True; AreaBtn.Enabled:=True;} DM.pFIBDS_SelectCountry.Filtered:=False; DM.pFIBDS_SelectRegion.Filtered:=False; DM.pFIBDS_SelectDistrict.Filtered:=False; DM.pFIBDS_SelectPlace.Filtered:=False; DM.pFIBDS_SelectStreet.Filtered:=False; DM.DSetSearch.Close; end; end; procedure TAddModifAdrForm3.MEZipPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin MEZipRefresh; Error:=False; end; procedure TAddModifAdrForm3.MEZipRefresh; var Str:String; i:Integer; begin Str:=MEZip.EditText; Delete(Str,Pos('*',Str),Length(Str)-Pos('*',Str)+1); for i:=5 downto Length(Str)+1 do Str:=Str+'*'; MEZip.Text:=Str; end; procedure TAddModifAdrForm3.MEZipExit(Sender: TObject); begin MEZipRefresh; end; procedure TAddModifAdrForm3.MEZipKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then MEZipRefresh; end; procedure TAddModifAdrForm3.CBStreetPropertiesCloseUp(Sender: TObject); begin DM.pFIBDS_SelectStreet.Filtered:=False; CBStreetPropertiesEditValueChanged(Self); end; procedure TAddModifAdrForm3.CBDistrictPropertiesCloseUp(Sender: TObject); begin CBDistrictPropertiesEditValueChanged(Self); if DM.DSetSearch.Active then begin DM.pFIBDS_SelectPlace.Filtered:=True; if DM.pFIBDS_SelectPlace.VisibleRecordCount>1 then CBTown.DroppedDown:=True else begin CBTown.EditValue := DM.DSetSearch['ID_PLACE']; CBTownPropertiesCloseUp(Self); end; end; end; procedure TAddModifAdrForm3.CBTownPropertiesCloseUp(Sender: TObject); begin CBTownPropertiesEditValueChanged(Self); end; procedure TAddModifAdrForm3.CBRegionPropertiesCloseUp(Sender: TObject); begin CBRegionPropertiesEditValueChanged(Self); end; procedure TAddModifAdrForm3.AcceptActionExecute(Sender: TObject); begin if {VarIsNull(CBCountry.EditValue)} CBCountry.EditText='' then begin MessageDlg('Не всі необхідні поля заповнено!',mtError,[mbOk],-1); CBCountry.SetFocus; Exit; end; if {VarIsNull(CBRegion.EditValue)} CBRegion.EditText='' then begin MessageDlg('Не всі необхідні поля заповнено!',mtError,[mbOk],-1); CBRegion.SetFocus; Exit; end; if {VarIsNull(CBTown.EditValue)} CBTown.EditText='' then begin MessageDlg('Не всі необхідні поля заповнено!',mtError,[mbOk],-1); CBTown.SetFocus; Exit; end; if {VarIsNull(CBStreet.EditValue)} (CBStreet.EditText='') and not pForTownSelect then begin MessageDlg('Не всі необхідні поля заповнено!',mtError,[mbOk],-1); CBStreet.SetFocus; Exit; end; if not pForTownSelect then try if not pIsLocked then begin DM.StProcAddress.StoredProcName:='ADR_ZIP_STREET_IN_PLACE'; DM.StProcAddress.Transaction.StartTransaction; DM.StProcAddress.Prepare; DM.StProcAddress.ParamByName('ID_STREET').AsInteger:=CBStreet.EditValue; if Pos('*',MEZip.Text)=0 then DM.StProcAddress.ParamByName('ZIP_CODE').AsInteger:=StrToInt(MEZip.EditText); DM.StProcAddress.ExecProc; if DM.StProcAddress.ParamByName('ZIP_IN_RANGE').AsInteger=0 then if ZShowMessage('Увага','Вказаний індекс не належить діапазону індексів обраного населеного пункта. Його не буде збережено. Продовжити?',mtWarning,[mbOK,mbNo])=mrOk then MEZip.Text:='******' else Exit; end; DM.StProcAddress.StoredProcName:='ADR_ADRESS_MAIN_IUM'; DM.StProcAddress.Transaction.StartTransaction; DM.StProcAddress.Prepare; DM.StProcAddress.ParamByName('ID_ADR').AsInteger:=pIdAddress; if Pos('*',MEZip.Text)=0 then DM.StProcAddress.ParamByName('ZIPCODE').AsString:=MEZip.EditText; if CBArea.EditText<>'' then DM.StProcAddress.ParamByName('ID_CITY_AREA').AsInteger:=CBArea.EditValue; if CBStreet.EditText<>'' then DM.StProcAddress.ParamByName('ID_STREET').AsInteger:=CBStreet.EditValue; DM.StProcAddress.ParamByName('KORPUS').AsString:=TEKorpus.Text; DM.StProcAddress.ParamByName('HOUSE').AsString:=TEHouse.Text; DM.StProcAddress.ParamByName('FLAT').AsString:=TEFlat.Text; if DEBeg.Visible and DEEnd.Visible then begin DM.StProcAddress.ParamByName('DATE_BEG').AsDate:=DEBeg.Date; DM.StProcAddress.ParamByName('DATE_END').AsDate:=DEEnd.Date; end; DM.StProcAddress.ParamByName('ID_ADR_PK').AsInteger:=pIdPk; DM.StProcAddress.ParamByName('IS_MODIF').AsInteger:=0; DM.StProcAddress.ExecProc; pIdAddress:=DM.StProcAddress.ParamByName('ID_ADRESS').AsInteger; DM.StProcAddress.Transaction.Commit; DM.StProcAddress.StoredProcName:='ADR_ADRESS_SEL'; DM.StProcAddress.Transaction.StartTransaction; DM.StProcAddress.Prepare; DM.StProcAddress.ParamByName('ID_ADRESS').AsInteger:=pIdAddress; DM.StProcAddress.ExecProc; pFullName:=DM.StProcAddress.ParamByName('FULL_NAME').AsString; DM.StProcAddress.Transaction.Rollback; ModalResult:=mrOk; except on e:Exception do begin DM.StProcAddress.Transaction.Rollback; MessageDlg(E.Message,mtError,[mbOk],-1); end; end else begin pIdPlace:=CBTown.EditValue; if DM.DSetPlace.Active then DM.DSetPlace.Close; DM.DSetPlace.SQLs.SelectSQL.Text:='SELECT * FROM ADR_GET_BY_ID_PLACE('+IntToStr(pIdPlace)+')'; DM.DSetPlace.Open; pFullName:=VarToStr(DM.DSetPlace['FULL_NAME']); ModalResult:=mrOk; end; end; procedure TAddModifAdrForm3.FormClose(Sender: TObject; var Action: TCloseAction); begin DM.pFIBDB_Adr.DefaultTransaction.Active:=False; DM.Free; end; procedure TAddModifAdrForm3.CBRegionPropertiesEditValueChanged( Sender: TObject); begin CBDistrict.Enabled:=not(CBRegion.Text=''); DistrictBtn.Enabled:=not(CBRegion.Text=''); CBTown.Enabled:=not(CBRegion.Text=''); TownBtn.Enabled:=not(CBRegion.Text=''); if (DM.pFIBDS_SelectRegion.Active) and (CBRegion.EditText<>'') then begin DM.pFIBDS_SelectRegion.Locate('NAME_REGION',CBRegion.EditText,[]); CBRegion.EditValue:=DM.pFIBDS_SelectRegion['ID_REGION']; end else begin CBRegion.EditValue:=Null; CBDistrict.EditText:=''; CBTown.EditText:=''; end; end; procedure TAddModifAdrForm3.CBCountryPropertiesEditValueChanged( Sender: TObject); begin CBRegion.Enabled:=not(CBCountry.Text=''); RegionBtn.Enabled:=not(CBCountry.Text=''); {Меняем не по ID, а по названию, т.к. оно уникально на каждом уровне и пользователь не может вводить своё в поле поиска, при поиске по идентификатору и при вводе названия с клавиатуры EditValue не изменяется} if (DM.pFIBDS_SelectCountry.Active) and (CBCountry.EditText<>'') then begin DM.pFIBDS_SelectCountry.Locate('NAME_COUNTRY',CBCountry.EditText,[]); CBCountry.EditValue:=DM.pFIBDS_SelectCountry['ID_COUNTRY']; end else begin CBCountry.EditValue:=Null; CBRegion.EditText:=''; end; end; procedure TAddModifAdrForm3.CBCountryPropertiesCloseUp(Sender: TObject); begin CBCountryPropertiesEditValueChanged(Self); end; procedure TAddModifAdrForm3.CBDistrictPropertiesEditValueChanged( Sender: TObject); begin if (DM.pFIBDS_SelectDistrict.Active) and (CBDistrict.EditText<>'') then begin DM.pFIBDS_SelectDistrict.Locate('NAME_DISTRICT',CBDistrict.EditText,[]); CBDistrict.EditValue:=DM.pFIBDS_SelectDistrict['ID_DISTRICT']; end else CBDistrict.EditValue:=Null; if DM.pFIBDS_SelectPlace.Active then DM.pFIBDS_SelectPlace.Close; DM.pFIBDS_SelectPlace.ParamByName('ID_DISTRICT').AsVariant:=CBDistrict.EditValue; DM.pFIBDS_SelectPlace.Open; end; procedure TAddModifAdrForm3.CBTownPropertiesEditValueChanged( Sender: TObject); begin CBStreet.Enabled:=not(CBTown.Text=''); StreetBtn.Enabled:=not(CBTown.Text=''); CBArea.Enabled:=not(CBTown.Text=''); AreaBtn.Enabled:=not(CBTown.Text=''); if (not DM.pFIBDS_SelectPlace.Active) or (CBTown.EditText='') then begin CBTown.EditValue:=Null; CBStreet.EditText:=''; CBArea.EditText:=''; end else begin DM.pFIBDS_SelectPlace.Locate('NAME_PLACE',CBTown.EditText,[]); CBTown.EditValue:=DM.pFIBDS_SelectPlace['ID_PLACE']; end; end; procedure TAddModifAdrForm3.CBStreetPropertiesEditValueChanged( Sender: TObject); begin if (not DM.pFIBDS_SelectStreet.Active) or (CBStreet.EditText='') then CBStreet.EditValue:=Null else begin DM.pFIBDS_SelectStreet.Locate('NAME_STREET',CBStreet.EditText,[]); CBStreet.EditValue:=DM.pFIBDS_SelectStreet['ID_STREET']; end; end; procedure TAddModifAdrForm3.CBAreaPropertiesEditValueChanged( Sender: TObject); begin if (not DM.pFIBDS_SelectArea.Active) or (CBArea.EditText='') then CBArea.EditValue:=Null else begin DM.pFIBDS_SelectArea.Locate('NAME_CITY_AREA',CBArea.EditText,[]); CBArea.EditValue:=DM.pFIBDS_SelectArea['ID_CITY_AREA']; end; end; procedure TAddModifAdrForm3.CBAreaPropertiesCloseUp(Sender: TObject); begin CBAreaPropertiesEditValueChanged(Self); end; //************************************************************************ // изменить процедуру - изменить Params и т.д. // //************************************************************************ procedure TAddModifAdrForm3.SearchPlaceBtnClick(Sender: TObject); var Params:TSpParams; OutPut : TRxMemoryData; SearchString: string; begin SearchString:='NULL'; Params.FormCaption:='Довідник населених пунктів'; Params.ShowMode:=AdrSp_MainForm.fsmSearchPlaceMode; Params.ShowButtons:=[AdrSp_MainForm.fbAdd,AdrSp_MainForm.fbDelete,AdrSp_MainForm.fbModif,AdrSp_MainForm.fbExit]; Params.AddFormClass:='TAdd_Place_Form'; Params.ModifFormClass:='TAdd_Place_Form'; Params.TableName:='ADR_PLACE_SELECT_SP_BY_NAME('+SearchString+')'; Params.Fields:='Name_place_SP,NAME_TYPE,NAME_DISTRICT,NAME_REGION,NAME_COUNTRY,ZIP,id_place'; Params.FieldsName:='Населений пункт, Тип ,Район, Регіон, Країна, Індекси'; Params.KeyField:='id_place'; Params.ReturnFields:='Name_place,id_country,id_region,id_district,id_place'; Params.DeleteSQL:='execute procedure adr_place_d(:id_place);'; Params.DBHandle:=DBHandle; Params.NameForSearch := CBCountry.EditText; { Params.NameForSearch:=CBTown.EditText; Params.Additional:=VarArrayCreate([0,3],varVariant); Params.Additional[0]:=CBRegion.EditValue; Params.Additional[1]:=CBRegion.EditText; Params.Additional[2]:=CBDistrict.EditValue; Params.Additional[3]:=CBDistrict.EditText; *} OutPut:=TRxMemoryData.Create(self); if GetAdressesSp(Params,OutPut) then begin // Область CBRegion.Properties.ListSource:=DM.DSourceRegion; CBRegion.Enabled:=True; RegionBtn.Enabled:=True; // Район области CBDistrict.Properties.ListSource:=DM.DSourceDistrict; DM.pFIBDS_SelectDistrict.Active; CBDistrict.Enabled:=True; DistrictBtn.Enabled:=True; // Город CBTown.Properties.ListSource:=DM.DSourcePlace; CBTown.Enabled:=True; TownBtn.Enabled:=True; // Улица CBStreet.Properties.ListSource:=DM.DSourceStreet; CBStreet.Enabled:=True; StreetBtn.Enabled:=True; // Район городской CBArea.Properties.ListSource:=DM.DSourceArea; CBArea.Enabled:=True; AreaBtn.Enabled:=True; // Refresh; if DM.pFIBDS_SelectCountry.Active then DM.pFIBDS_SelectCountry.Close; DM.pFIBDS_SelectCountry.Open; CBCountry.EditValue:=output['id_country']; // Refresh; if DM.pFIBDS_SelectRegion.Active then DM.pFIBDS_SelectRegion.Close; DM.pFIBDS_SelectRegion.Open; CBRegion.EditValue:=output['id_region']; // Refresh; if DM.pFIBDS_SelectDistrict.Active then DM.pFIBDS_SelectDistrict.Close; DM.pFIBDS_SelectDistrict.Open; CBDistrict.EditValue:=output['id_district']; //Refresh; if DM.pFIBDS_SelectPlace.Active then DM.pFIBDS_SelectPlace.Close; DM.pFIBDS_SelectPlace.Open; CBTown.EditValue := output['id_place']; end else begin Refresh; if OutPut.Filtered then begin if DM.pFIBDS_SelectPlace.Active then DM.pFIBDS_SelectPlace.Close; DM.pFIBDS_SelectPlace.Open; end; end; OutPut.Free; end; //************************************************************************ initialization RegisterClass(TAddModifAdrForm3); end.
namespace Calculator.iOS; interface uses UIKit, Calculator.Engine; type [IBObject] RootViewController = private class(UIViewController) [IBOutlet] var edValue: weak UITextField; public method init: InstanceType; override; method viewDidLoad; override; method didReceiveMemoryWarning; override; [IBAction] method pressBackButton(sender: id); [IBAction] method pressExitButton(sender: id); [IBAction] method pressEvaluateButton(sender: id); [IBAction] method pressCharButton(sender: id); end; implementation method RootViewController.init: instancetype; begin inherited initWithNibName("RootViewController") bundle(nil); title := 'Calculator.iOS'; end; method RootViewController.viewDidLoad; begin inherited viewDidLoad(); // Do any additional setup after loading the view. end; method RootViewController.didReceiveMemoryWarning; begin inherited didReceiveMemoryWarning(); // Dispose of any resources that can be recreated. end; method RootViewController.pressBackButton(sender: id); begin var s := edValue.text; if s.length > 0 then begin s := s.substringToIndex(s.length - 1); edValue.text := s; end; end; method RootViewController.pressExitButton(sender: id); begin self.dismissViewControllerAnimated(true) completion(nil); end; method RootViewController.pressEvaluateButton(sender: id); begin try var eval := new Evaluator(); edValue.text := '' + eval.Evaluate(edValue.text); except on e: EvaluatorError do begin var alert := UIAlertController.alertControllerWithTitle("Calculator!") message("Error evaluation: "+e.reason) preferredStyle(UIAlertControllerStyle.Alert); presentViewController(alert) animated (true) completion(nil); end; end; end; method RootViewController.pressCharButton(sender: id); begin edValue.text := (UIButton(sender)).titleLabel.text; end; end.
unit o_lpUserlist; interface uses SysUtils, Classes, Contnrs, o_lpBaseList, o_lpUser; type Tlp_UserList = class(Tlp_BaseList) private function getUser(Index: Integer): Tlp_User; public constructor Create; override; destructor Destroy; override; function Add: Tlp_User; property Item[Index: Integer]: Tlp_User read getUser; end; implementation { Tlp_UserList } constructor Tlp_UserList.Create; begin inherited; end; destructor Tlp_UserList.Destroy; begin inherited; end; function Tlp_UserList.getUser(Index: Integer): Tlp_User; begin Result := nil; if Index > fList.Count -1 then exit; Result := Tlp_User(fList[Index]); end; function Tlp_UserList.Add: Tlp_User; begin Result := Tlp_User.Create; fList.Add(Result); end; end.
unit DSA.Tree.Heap; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Rtti, DSA.List_Stack_Queue.ArrayList, DSA.Interfaces.Comparer, DSA.Utils; type THeapkind = (Min, Max); { THeap } generic THeap<T, TComparer> = class private type TArr_T = specialize TArray<T>; TArrayList_T = specialize TArrayList<T>; ICmp_T = specialize IDSA_Comparer<T>; var __data: specialize TArrayList<T>; __comparer: specialize IDSA_Comparer<T>; __heapKind: THeapkind; /// <summary> 返回完全二叉树的数组表示中,一个索引所表示的元素的父亲节点的索引 </summary> function __parent(index: integer): integer; /// <summary> 返回完全二叉树的数组表示中,一个索引所表示的元素的左孩子节点的索引 </summary> function __leftChild(index: integer): integer; /// <summary> 返回完全二叉树的数组表示中,一个索引所表示的元素的右孩子节点的索引 </summary> function __rightChild(index: integer): integer; /// <summary> 交换索引为 i , j 的节点元素 </summary> procedure __swap(i: integer; j: integer); /// <summary> 元素上浮过程 </summary> procedure __shiftUp(k: integer); /// <summary> 元素下沉过程 </summary> procedure __shiftDown(k: integer); public constructor Create(capacity: integer = 10; heapKind: THeapkind = THeapkind.Min); overload; constructor Create(const arr: TArr_T; heapKind: THeapkind = THeapkind.Min); overload; constructor Create(const arr: TArr_T; cmp: ICmp_T; heapKind: THeapkind = THeapkind.Min); overload; destructor Destroy; override; /// <summary> 返回堆中元素个数 </summary> function Size: integer; /// <summary> 返回天所布尔值,表示堆中是否为空 </summary> function IsEmpty: boolean; /// <summary> 向堆中添加元素 </summary> procedure Add(e: T); /// <summary> 返回堆中的第一个元素的值 </summary> function FindFirst: T; /// <summary> 取出堆中第一个元素 </summary> function ExtractFirst: T; /// <summary> 设置比较器 </summary> procedure SetComparer(c: ICmp_T); end; procedure Main; implementation type THeap_int = specialize THeap<integer, TComparer_int>; procedure Main; var n: integer; maxHeap, minHeap: THeap_int; i: integer; arr: TArray_int; begin n := 10; Randomize; maxHeap := THeap_int.Create(n, THeapkind.Max); for i := 0 to n - 1 do maxHeap.Add(Random(1000)); SetLength(arr, n); for i := 0 to n - 1 do arr[i] := maxHeap.ExtractFirst; for i := 1 to n - 1 do if (arr[i - 1] < arr[i]) then raise Exception.Create('Error'); Writeln('Test MaxHeap completed.'); TDSAUtils.DrawLine; minHeap := THeap_int.Create(n, THeapkind.Min); for i := 0 to n - 1 do minHeap.Add(Random(1000)); SetLength(arr, n); for i := 0 to n - 1 do arr[i] := minHeap.ExtractFirst; for i := 1 to n - 1 do if (arr[i - 1] > arr[i]) then raise Exception.Create('Error'); Writeln('Test MinHeap completed.'); end; { THeap } procedure THeap.Add(e: T); begin __data.AddLast(e); __shiftUp(__data.GetSize - 1); end; constructor THeap.Create(capacity: integer; heapKind: THeapkind); begin __comparer := TComparer.Default; __data := TArrayList_T.Create(capacity); __heapKind := heapKind; end; constructor THeap.Create(const arr: TArr_T; cmp: ICmp_T; heapKind: THeapkind); var i: integer; begin __comparer := cmp; __data := TArrayList_T.Create(arr); __heapKind := heapKind; // heapify for i := __parent(__data.GetSize - 1) downto 0 do begin __shiftDown(i); end; end; constructor THeap.Create(const arr: TArr_T; heapKind: THeapkind = THeapkind.Min); begin Self.Create(arr, TComparer.Default, heapKind); end; destructor THeap.Destroy; begin FreeAndNil(__comparer); FreeAndNil(__data); inherited; end; function THeap.ExtractFirst: T; var ret: T; begin ret := FindFirst; __swap(0, __data.GetSize - 1); __data.RemoveLast; __shiftDown(0); Result := ret; end; procedure THeap.SetComparer(c: ICmp_T); begin __comparer := c; end; function THeap.FindFirst: T; begin if __data.GetSize = 0 then raise Exception.Create('Can not findFirst when heap is empty.'); Result := __data.Get(0); end; function THeap.IsEmpty: boolean; begin Result := __data.IsEmpty; end; function THeap.Size: integer; begin Result := __data.GetSize; end; function THeap.__leftChild(index: integer): integer; begin Result := index * 2 + 1; end; function THeap.__parent(index: integer): integer; begin if index = 0 then raise Exception.Create('index-0 doesn''t have parent.'); Result := (index - 1) div 2; end; function THeap.__rightChild(index: integer): integer; begin Result := index * 2 + 2; end; procedure THeap.__shiftDown(k: integer); var j: integer; begin case __heapKind of THeapkind.Min: while __leftChild(k) < __data.GetSize do begin j := __leftChild(k); if ((j + 1) < __data.GetSize) and (__comparer.Compare(__data.Get(j + 1), __data.Get(j)) < 0) then j := __rightChild(k); // __data[j] 是 leftChild 和 rightChild 中的最小值 if __comparer.Compare(__data[k], __data[j]) <= 0 then Break; __swap(k, j); k := j; end; THeapkind.Max: while __leftChild(k) < __data.GetSize do begin j := __leftChild(k); if ((j + 1) < __data.GetSize) and (__comparer.Compare(__data.Get(j + 1), __data.Get(j)) > 0) then j := __rightChild(k); // __data[j] 是 leftChild 和 rightChild 中的最大值 if __comparer.Compare(__data[k], __data[j]) >= 0 then Break; __swap(k, j); k := j; end; end; end; procedure THeap.__shiftUp(k: integer); begin case __heapKind of THeapkind.Min: while (k > 0) and (__comparer.Compare(__data.Get(__parent(k)), __data.Get(k)) > 0) do begin __swap(k, __parent(k)); k := __parent(k); end; THeapkind.Max: while (k > 0) and (__comparer.Compare(__data.Get(__parent(k)), __data.Get(k)) < 0) do begin __swap(k, __parent(k)); k := __parent(k); end; end; end; procedure THeap.__swap(i: integer; j: integer); var temp: T; begin if (i < 0) or (i >= Size) or (j < 0) or (j >= Size) then raise Exception.Create('index is illegal.'); temp := __data[i]; __data[i] := __data[j]; __data[j] := temp; end; end.
unit ActivationUtils; interface uses Windows, Messages, Classes, SysUtils, Forms, Graphics, Menus, ExtCtrls, Registry, Dialogs, Controls, Variants, DBClient, IdHashMessageDigest, ShellAPI, TLHelp32, IdSMTP, IdMessage, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL; function SendEmail(sender_email, receiver, subject, msg : string ): boolean; function KillTask(ExeFileName: string): Integer; function MD5(const text_str : string) : string; function GetHDDSerial : string; function Check_Registration(EXE_FILE : string) : Boolean; function GetRegistryValue(KeyName, ValueName: string): string; function CreateUniqTimeString : string; function RegistSystemID(AppNameStr : string) : string; implementation function SendEmail(sender_email, receiver, subject, msg : string ): boolean; var IdSSLIOHandlerSocketOpenSSL: TIdSSLIOHandlerSocketOpenSSL; IdSMTP: TIdSMTP; IdMsg: TIdMessage; begin IdSSLIOHandlerSocketOpenSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil); try IdSSLIOHandlerSocketOpenSSL.Destination := 'smtp.gmail.com:587'; IdSSLIOHandlerSocketOpenSSL.Host := 'smtp.gmail.com'; IdSSLIOHandlerSocketOpenSSL.Port := 587; IdSSLIOHandlerSocketOpenSSL.DefaultPort := 0; IdSSLIOHandlerSocketOpenSSL.SSLOptions.Method := sslvTLSv1; IdSSLIOHandlerSocketOpenSSL.SSLOptions.Mode := sslmUnassigned; IdSSLIOHandlerSocketOpenSSL.SSLOptions.VerifyMode := []; IdSSLIOHandlerSocketOpenSSL.SSLOptions.VerifyDepth := 0; IdSMTP := TIdSMTP.Create(nil); try IdSMTP.IOHandler := IdSSLIOHandlerSocketOpenSSL; IdSMTP.Host := 'smtp.gmail.com'; IdSMTP.Port := 587; IdSMTP.UseTLS := utUseExplicitTLS; IdSMTP.Username := 'ccnplaza@gmail.com'; IdSMTP.Password := '@Choe3415'; IdSMTP.Connect; try IdMsg := TIdMessage.Create; try IdMsg.From.Address := sender_email; //'ccnplaza@gmail.com'; IdMsg.Recipients.EMailAddresses := receiver; //'ccnplaza@daum.net'; IdMsg.ContentType := 'text/HTML; charset=euc-kr'; IdMsg.ContentTransferEncoding := '8bit'; IdMsg.Subject := subject; //'액티베이션 요청메일'; IdMsg.Body.Text := msg; //'액티베이션 요청합니다.'; IdSMTP.Send(IdMsg); Result := True; finally IdMsg.Free; end; finally IdSMTP.Disconnect; end; finally IdSMTP.Free; end; finally IdSSLIOHandlerSocketOpenSSL.Free; end; end; function KillTask(ExeFileName: string): Integer; const PROCESS_TERMINATE = $0001; var ContinueLoop: BOOL; FSnapshotHandle: THandle; FProcessEntry32: TProcessEntry32; begin Result := 0; FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); FProcessEntry32.dwSize := SizeOf(FProcessEntry32); ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32); while Integer(ContinueLoop) <> 0 do begin if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeFileName))) then Result := Integer(TerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0), FProcessEntry32.th32ProcessID), 0)); ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32); end; CloseHandle(FSnapshotHandle); end; function MD5(const text_str : string) : string; var idmd5 : TIdHashMessageDigest5; begin idmd5 := TIdHashMessageDigest5.Create; try Result := idmd5.HashStringAsHex(text_str); finally idmd5.Free; end; end; function GetHDDSerial : string; var vGet: TGetDiskSerial; HDDID : string; begin vGet:= TGetDiskSerial.Create(nil); vGet.RegCode:= 'J8B8U-DYYXX-A2Y8T-UV3WP-7SKGS'; try HDDID := vGet.SerialNumber; if HDDID = '' then Result := '' else Result := HDDID; finally FreeAndNil(vGet); end; end; function Check_Registration(EXE_FILE : string) : Boolean; var mdStr, HID, HDDID, Reg2_value : string; begin HDDID := GetHDDSerial; HID := MD5('CCNSOFT' + UpperCase(EXE_FILE) + HDDID); mdStr := 'CCNSoftware\' + UpperCase(EXE_FILE); Reg2_value := GetRegistryValue(mdStr, ''); if CompareStr(HID, Reg2_value) <> 0 then begin Result := False; end else begin Result:= True; end; end; function GetRegistryValue(KeyName, ValueName: string): string; var Registry: TRegistry; regVal : string; begin Registry := TRegistry.Create(KEY_READ); try Registry.RootKey := HKEY_CURRENT_USER; if Registry.OpenKey(KeyName, False) then regVal := Registry.ReadString(ValueName) else regVal := ''; Result := regVal; finally Registry.Free; end; end; function CreateUniqTimeString : string; begin result := FormatDateTime('yyyymmddhhnnsszzz', now); end; function RegistSystemID(AppNameStr : string) : string; var readReg, saveReg: TRegistry; guid : TGUID; strGUID, RegKey, RegValue : string; begin readReg := TRegistry.Create(KEY_READ); readReg.RootKey := HKEY_CURRENT_USER; RegKey := MD5('CCNSOFT.' + AppNameStr); RegKey := 'CLSID\' + '{' + Copy(RegKey, 1, 8) + '-' + Copy(RegKey, 9, 4) + '-' + Copy(RegKey, 13, 4) + '-' + Copy(RegKey, 17, 4) + '-' + Copy(RegKey, 21, 12) + '}'; if readReg.OpenKey(RegKey, False) then begin RegValue := readReg.ReadString(''); if (RegValue = '') or (Length(RegValue) <> 38) then begin CreateGUID(guid); strGUID := GuidtoString(guid); saveReg := TRegistry.Create(KEY_WRITE); saveReg.RootKey := HKEY_CURRENT_USER; saveReg.CreateKey(RegKey); saveReg.OpenKey(RegKey, True); RegValue := strGUID; saveReg.WriteString('', RegValue); end; end else begin CreateGUID(guid); strGUID := GuidtoString(guid); saveReg := TRegistry.Create(KEY_WRITE); saveReg.RootKey := HKEY_CURRENT_USER; saveReg.CreateKey(RegKey); saveReg.OpenKey(RegKey, True); RegValue := strGUID; saveReg.WriteString('', RegValue); end; Result := RegValue; end; end.
unit uSelectForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridTableView, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridDBTableView, cxGrid, uSearchFrame, ActnList; type TSelectForm = class(TForm) Panel1: TPanel; RefreshButton: TSpeedButton; CancelButton: TSpeedButton; SelectButton: TSpeedButton; Grid: TcxGrid; TableView: TcxGridDBTableView; GridLevel1: TcxGridLevel; StyleRepository: TcxStyleRepository; stBackground: TcxStyle; stContent: TcxStyle; stContentEven: TcxStyle; stContentOdd: TcxStyle; stFilterBox: TcxStyle; stFooter: TcxStyle; stGroup: TcxStyle; stGroupByBox: TcxStyle; stHeader: TcxStyle; stInactive: TcxStyle; stIncSearch: TcxStyle; stIndicator: TcxStyle; stPreview: TcxStyle; stSelection: TcxStyle; stHotTrack: TcxStyle; qizzStyle: TcxGridTableViewStyleSheet; SearchFrame: TfmSearch; ActionList1: TActionList; SelectAction: TAction; QuitAction: TAction; RefreshAction: TAction; SelectSource: TDataSource; ShowId: TAction; procedure QuitActionExecute(Sender: TObject); procedure SelectActionExecute(Sender: TObject); procedure RefreshActionExecute(Sender: TObject); procedure GridDblClick(Sender: TObject); procedure TableViewDblClick(Sender: TObject); procedure TableViewKeyPress(Sender: TObject; var Key: Char); procedure TableViewCellClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); procedure TableViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ShowIdExecute(Sender: TObject); private Data: TDataSet; public constructor Create(AOwner: TComponent; DataSet: TDataSet); reintroduce; end; function qSelect(DataSet: TDataSet; Caption: String = 'Âèá³ð...'): Boolean; var SelectForm: TSelectForm; implementation {$R *.dfm} function qSelect(DataSet: TDataSet; Caption: String = 'Âèá³ð...'): Boolean; var form: TSelectForm; begin form := TSelectForm.Create(Application.MainForm, DataSet); form.Caption := Caption; Result := form.ShowModal = mrOk; form.Free; end; constructor TSelectForm.Create(AOwner: TComponent; DataSet: TDataSet); begin inherited Create(AOwner); Data := DataSet; if not Data.Active then begin Data.Close; Data.Open; end; SearchFrame.Prepare(Data); SelectSource.DataSet := Data; TableView.DataController.CreateAllItems; end; procedure TSelectForm.QuitActionExecute(Sender: TObject); begin Close; end; procedure TSelectForm.SelectActionExecute(Sender: TObject); begin if not Data.IsEmpty then ModalResult := mrOk; end; procedure TSelectForm.RefreshActionExecute(Sender: TObject); begin TableView.DataController.DataSet.Close; TableView.DataController.DataSet.Open; end; procedure TSelectForm.GridDblClick(Sender: TObject); begin SelectAction.Execute; end; procedure TSelectForm.TableViewDblClick(Sender: TObject); begin SelectAction.Execute; end; procedure TSelectForm.TableViewKeyPress(Sender: TObject; var Key: Char); begin if ord(Key) > 31 then SearchFrame.SearchEdit.Text := SearchFrame.SearchEdit.Text + Key; end; procedure TSelectForm.TableViewCellClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin SearchFrame.SearchEdit.Text := ''; end; procedure TSelectForm.TableViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_BACK then SearchFrame.SearchEdit.Text := ''; end; procedure TSelectForm.ShowIdExecute(Sender: TObject); var text : string; i : integer; begin text:=''; for i:=1 to SelectSource.DataSet.Fields.Count do text:=text + SelectSource.DataSet.Fields[i-1].FieldName + ' : ' + SelectSource.DataSet.Fields[i-1].DisplayText + #13; ShowMessage(text); end; end.
unit GLDMaterialPickerForm; interface uses Windows, Classes, Controls, Forms, Dialogs, StdCtrls, Buttons, DesignIntf, GL, GLDObjects, GLDMaterial; type TGLDMaterialPickerForm = class(TForm) LB_Materials: TListBox; BB_Ok: TBitBtn; BB_Cancel: TBitBtn; procedure FormCreate(Sender: TObject); procedure LB_MaterialsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BitBtnClick(Sender: TObject); private FOldMaterial: TGLDMaterial; FMaterialOwner: TGLDEditableObject; FMaterials: TGLDMaterialList; FDesigner: Pointer; FCloseMode: GLubyte; procedure SetMaterialOwner(Value: TGLDEditableObject); procedure SetMaterials(Value: TGLDMaterialList); public property MaterialOwner: TGLDEditableObject read FMaterialOwner write SetMaterialOwner; property SourceMaterialList: TGLDMaterialList read FMaterials write SetMaterials; property Designer: Pointer read FDesigner write FDesigner; end; function GLDGetMaterialPickerForm: TGLDMaterialPickerForm; procedure GLDReleaseMaterialPickerForm; implementation {$R *.dfm} uses GLDConst; var vMaterialPickerForm: TGLDMaterialPickerForm = nil; function GLDGetMaterialPickerForm: TGLDMaterialPickerForm; begin if not Assigned(vMaterialPickerForm) then vMaterialPickerForm := TGLDMaterialPickerForm.Create(nil); Result := vMaterialPickerForm; end; procedure GLDReleaseMaterialPickerForm; begin if Assigned(vMaterialPickerForm) then vMaterialPickerForm.Free; vMaterialPickerForm := nil; end; procedure TGLDMaterialPickerForm.FormCreate(Sender: TObject); begin FCloseMode := GLD_CLOSEMODE_CANCEL; FMaterialOwner := nil; FMaterials := nil; FDesigner := nil; LB_Materials.Clear; end; procedure TGLDMaterialPickerForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if FCloseMode = GLD_CLOSEMODE_CANCEL then if Assigned(FMaterialOwner) then FMaterialOwner.Material := FOldMaterial; end; procedure TGLDMaterialPickerForm.SetMaterialOwner(Value: TGLDEditableObject); begin FMaterialOwner := Value; if Assigned(FMaterialOwner) then FOldMaterial := FMaterialOwner.Material else FOldMaterial := nil; end; procedure TGLDMaterialPickerForm.SetMaterials(Value: TGLDMaterialList); var i: GLuint; begin FMaterials := Value; LB_Materials.Clear; if FMaterials <> nil then begin if FMaterials.Count > 0 then for i := 1 to FMaterials.Count do LB_Materials.AddItem(FMaterials[i].Name, FMaterials[i]); end; end; procedure TGLDMaterialPickerForm.LB_MaterialsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Index: GLint; begin Index := LB_Materials.ItemAtPos(Point(X, Y), True); if (Index <> -1) and Assigned(FMaterialOwner) and Assigned(FMaterials) then begin FMaterialOwner.Material := FMaterials[Index + 1]; if Assigned(FDesigner) then IDesigner(FDesigner).Modified; end; end; procedure TGLDMaterialPickerForm.BitBtnClick(Sender: TObject); begin FCloseMode := TBitBtn(Sender).Tag; Close; end; initialization finalization GLDReleaseMaterialPickerForm; end.
unit SearchProcessor; interface uses SysUtils, Classes, ParseMap, StringSupport, EncodeSupport, AdvObjects, DateAndTime, FHIRResources, FHIRLang, FHIRConstants, FHIRComponents, FHIRTypes, FHIRIndexManagers, FHIRDataStore, FHIRUtilities; const SEARCH_PARAM_NAME_ID = 'search-id'; HISTORY_PARAM_NAME_ID = 'history-id'; SEARCH_PARAM_NAME_OFFSET = 'search-offset'; SEARCH_PARAM_NAME_TEXT = '_text'; SEARCH_PARAM_NAME_COUNT = '_count'; SEARCH_PARAM_NAME_SORT = 'search-sort'; SEARCH_PARAM_NAME_SUMMARY = '_summary'; SEARCH_PAGE_DEFAULT = 50; SEARCH_PAGE_LIMIT = 1000; SUMMARY_SEARCH_PAGE_LIMIT = 10000; type TDateOperation = (dopEqual, dopLess, dopLessEqual, dopGreater, dopGreaterEqual); TSearchProcessor = class (TAdvObject) private FLink: String; FSort: String; FFilter: String; FTypeKey: integer; FCompartmentId: String; FCompartments: String; FParams: TParseMap; FType: TFHIRResourceType; FBaseURL: String; FWantSummary: boolean; FIndexer: TFhirIndexManager; FLang: String; FRepository: TFHIRDataStore; Function ProcessParam(types : TFHIRResourceTypeSet; name : String; value : String; nested : boolean; var bFirst : Boolean; var bHandled : Boolean) : String; procedure SetIndexer(const Value: TFhirIndexManager); procedure SetRepository(const Value: TFHIRDataStore); function SchemeForName(name: String): string; procedure SplitByCommas(value: String; list: TStringList); function findPrefix(var value: String; subst: String): boolean; procedure checkDateFormat(s : string); public procedure Build; //procedure TFhirOperation.ProcessDefaultSearch(typekey : integer; aType : TFHIRResourceType; params : TParseMap; baseURL, compartments, compartmentId : String; id, key : string; var link, sql : String; var total : Integer; var wantSummary : boolean); // inbound property typekey : integer read FTypeKey write FTypeKey; property type_ : TFHIRResourceType read FType write FType; property compartmentId : String read FCompartmentId write FCompartmentId; property compartments : String read FCompartments write FCompartments; property baseURL : String read FBaseURL write FBaseURL; property lang : String read FLang write FLang; property params : TParseMap read FParams write FParams; property indexer : TFhirIndexManager read FIndexer write SetIndexer; property repository : TFHIRDataStore read FRepository write SetRepository; // outbound property link : String read FLink write FLink; property sort : String read FSort write FSort; property filter : String read FFilter write FFilter; property wantSummary : boolean read FWantSummary write FWantSummary; end; implementation { TSearchProcessor } procedure TSearchProcessor.Build; var first : boolean; handled : boolean; i, j : integer; ix : TFhirIndex; ts : TStringList; begin if typekey = 0 then filter := 'Ids.MasterResourceKey is null' else filter := 'Ids.MasterResourceKey is null and Ids.ResourceTypeKey = '+inttostr(typekey); if (compartmentId <> '') then filter := filter +' and Ids.ResourceKey in (select ResourceKey from Compartments where CompartmentType = 1 and Id = '''+compartmentId+''')'; if (compartments <> '') then filter := filter +' and Ids.ResourceKey in (select ResourceKey from Compartments where CompartmentType = 1 and Id in ('+compartments+'))'; link := ''; first := false; ts := TStringList.create; try for i := 0 to params.Count - 1 do begin ts.Clear; ts.assign(params.List(i)); for j := ts.count - 1 downto 0 do if ts[j] = '' then ts.delete(j); for j := 0 to ts.count - 1 do begin handled := false; filter := filter + processParam([type_], params.VarName(i), ts[j], false, first, handled); if handled then link := link + '&'+params.VarName(i)+'='+EncodeMIME(ts[j]); end; end; finally ts.free; end; if params.VarExists(SEARCH_PARAM_NAME_SORT) and (params.Value[SEARCH_PARAM_NAME_SORT] <> '_id') then begin ix := FIndexer.Indexes.getByName(type_, params.Value[SEARCH_PARAM_NAME_SORT]); if (ix = nil) then Raise Exception.create(StringFormat(GetFhirMessage('MSG_SORT_UNKNOWN', lang), [params.Value[SEARCH_PARAM_NAME_SORT]])); sort :='(SELECT Min(Value) FROM IndexEntries WHERE IndexEntries.ResourceKey = Ids.ResourceKey and IndexKey = '+inttostr(ix.Key)+')'; link := link+'&'+SEARCH_PARAM_NAME_SORT+'='+ix.Name; end else begin sort := 'Id'; link := link+'&'+SEARCH_PARAM_NAME_SORT+'=_id'; end; end; Function TSearchProcessor.processParam(types : TFHIRResourceTypeSet; name : String; value : String; nested : boolean; var bFirst : Boolean; var bHandled : Boolean) : String; var key, i : integer; left, right, op, modifier : String; f, dummy : Boolean; ts : TStringList; pfx, sfx : String; date : TDateAndTime; a : TFHIRResourceType; type_ : TFhirSearchParamType; parts : TArray<string>; dop : TDateOperation; begin date := nil; result := ''; op := ''; bHandled := false; if (value = '') then exit; if (name = '_include') or (name = '_reverseInclude') then bHandled := true else if (name = '_summary') and (value = 'true') then begin bHandled := true; wantSummary := true; end else if (name = '_text') then begin result := '(IndexKey = '+inttostr(FIndexer.NarrativeIndex)+' and CONTAINS(Xhtml, '''+SQLWrapString(value)+'''))'; end else if pos('.', name) > 0 then begin StringSplit(name, '.', left, right); if (pos(':', left) > 0) then begin StringSplit(left, ':', left, modifier); if not StringArrayExistsInSensitive(CODES_TFHIRResourceType, modifier) then raise Exception.create(StringFormat(GetFhirMessage('MSG_UNKNOWN_TYPE', lang), [modifier])); a := TFHIRResourceType(StringArrayIndexOfSensitive(CODES_TFHIRResourceType, modifier)); types := [a]; end else modifier := ''; key := FIndexer.GetKeyByName(types, left); if key = 0 then raise Exception.create(StringFormat(GetFhirMessage('MSG_PARAM_CHAINED', lang), [left])); f := true; if modifier <> '' then result := result + '(IndexKey = '+inttostr(Key)+' /*'+left+'*/ and target in (select ResourceKey from IndexEntries where (ResourceKey in (select ResourceKey from Ids where ResourceTypeKey = '+inttostr(FRepository.ResConfig[a].key)+')) and ('+processParam(FIndexer.GetTargetsByName(types, left), right, lowercase(value), true, f, bHandled)+')))' else result := result + '(IndexKey = '+inttostr(Key)+' /*'+left+'*/ and target in (select ResourceKey from IndexEntries where '+processParam(FIndexer.GetTargetsByName(types, left), right, lowercase(value), true, f, bHandled)+'))'; bHandled := true; end else begin //remove the modifier: if (pos(':', name) > 0) then StringSplit(name, ':', name, modifier); if name = 'originalId' then begin bHandled := true; if modifier <> '' then raise exception.create('modifier "'+modifier+'" not handled on originalId'); result := '(originalId = '''+sqlwrapString(value)+''')'; end else if (name = '_tag') or (name = 'profile') or (name = '_security') then begin bHandled := true; if modifier = 'partial' then result := '(MostRecent in (Select ResourceVersionKey from VersionTags where TagKey in (Select TagKey from Tags where SchemeUri = '''+SchemeForName(name)+''' and TermUri like '''+SQLWrapString(value)+'%'')))' else if modifier = 'text' then result := '(MostRecent in (Select ResourceVersionKey from VersionTags where Label like ''%'+SQLWrapString(value)+'%''))' else if modifier = '' then result := '(MostRecent in (Select ResourceVersionKey from VersionTags where TagKey = '''+intToStr(FRepository.KeyForTag(SchemeForName(name), value))+'''))' else raise exception.create('modifier "'+modifier+'" not handled on tag'); end else begin key := FIndexer.GetKeyByName(types, name); if key > 0 then begin type_ := FIndexer.GetTypeByName(types, name); if modifier = 'missing' then begin bHandled := true; if StrToBoolDef(value, false) then result := result + '((Select count(*) from IndexEntries where IndexKey = '+inttostr(Key)+' /*'+name+'*/ and IndexEntries.ResourceKey = Ids.ResourceKey) = 0)' else result := result + '((Select count(*) from IndexEntries where IndexKey = '+inttostr(Key)+' /*'+name+'*/ and IndexEntries.ResourceKey = Ids.ResourceKey) > 0)'; end else begin ts := TStringlist.create; try SplitByCommas(value, ts); if (ts.count > 1) then result := '('; for i := 0 to ts.count - 1 do begin if i > 0 then result := result +') or ('; value := ts[i]; if i > 0 then result := result + op; bHandled := true; case type_ of SearchParamTypeDate: begin if modifier <> '' then raise exception.create(StringFormat(GetFhirMessage('MSG_PARAM_UNKNOWN', lang), [name+':'+modifier])); dop := dopEqual; if findPrefix(value, '<=') then dop := dopLessEqual else if findPrefix(value, '<') then dop := dopLess else if findPrefix(value, '>=') then dop := dopGreaterEqual else if findPrefix(value, '>') then dop := dopGreater; CheckDateFormat(value); date := TDateAndTime.CreateXML(value); try case dop of dopEqual: result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and Value >= '''+date.AsUTCDateTimeMinHL7+''' and Value2 <= '''+date.AsUTCDateTimeMaxHL7+''')'; dopLess: result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and Value <= '''+date.AsUTCDateTimeMinHL7+''')'; dopLessEqual: result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and Value <= '''+date.AsUTCDateTimeMaxHL7+''')'; dopGreater: result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and Value2 >= '''+date.AsUTCDateTimeMaxHL7+''')'; dopGreaterEqual: result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and Value2 >= '''+date.AsUTCDateTimeMinHL7+''')'; end; finally date.free; date := nil; end; end; SearchParamTypeString: begin value := lowercase(value); if name = 'phonetic' then value := EncodeNYSIIS(value); if (modifier = 'partial') or (modifier = '') then begin pfx := 'like ''%'; sfx := '%'''; end else if (modifier = 'exact') then begin pfx := '= '''; sfx := ''''; end else raise exception.create(StringFormat(GetFhirMessage('MSG_PARAM_UNKNOWN', lang), [modifier])); result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and Value '+pfx+sqlwrapString(lowercase(RemoveAccents(value)))+sfx+')'; end; SearchParamTypeToken: begin value := lowercase(value); // _id is a special case if (name = '_id') then result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and Value = '''+sqlwrapString(value)+''')' else if modifier = 'text' then result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and Value2 like ''%'+sqlwrapString(lowercase(RemoveAccents(value)))+'%'')' else if value.Contains('|') then begin StringSplit(value, '|', left, right); result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and SpaceKey = (Select SpaceKey from Spaces where Space = '''+sqlwrapstring(left)+''') and Value = '''+sqlwrapString(right)+''')'; end else result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and Value = '''+sqlwrapString(value)+''')' // // ! // // _id is a special case // if (name = '_id') or (FIndexer.GetTypeByName(types, name) = SearchParamTypeToken) then // result := result + '(IndexKey = '+inttostr(Key)+' and Value = '''+sqlwrapString(value)+''')' // else // else if (modifier = 'code') or ((modifier = '') and (pos('/', value) > 0)) then // begin // StringSplitRight(value, '/', left, right); // result := result + '(IndexKey = '+inttostr(Key)+' and SpaceKey = (Select SpaceKey from Spaces where Space = '''+sqlwrapstring(left)+''') and Value = '''+sqlwrapString(right)+''')'; // end // else if modifier = 'anyns' then // result := result + '(IndexKey = '+inttostr(Key)+' and Value = '''+sqlwrapString(value)+''')' // else // raise exception.create(StringFormat(GetFhirMessage('MSG_PARAM_UNKNOWN', lang), [modifier])) end; SearchParamTypeReference : begin // _id is a special case if (name = '_id') or (FIndexer.GetTypeByName(types, name) = SearchParamTypeToken) then result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and Value = '''+sqlwrapString(value)+''')' else if modifier = 'text' then result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and Value2 like ''%'+sqlwrapString(lowercase(RemoveAccents(value)))+'%'')' else if (modifier = 'anyns') or (modifier = '') then begin if IsId(value) then result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and Value = '''+sqlwrapString(value)+''')' else if value.StartsWith(baseUrl) then begin parts := value.Substring(baseURL.Length).Split(['/']); if Length(parts) = 2 then begin result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and SpaceKey = (Select SpaceKey from Spaces where Space = '''+sqlwrapstring(parts[0])+''') and Value = '''+sqlwrapString(parts[1])+''')' end else raise exception.create(StringFormat(GetFhirMessage('MSG_PARAM_UNKNOWN', lang), [name])) end else raise exception.create(StringFormat(GetFhirMessage('MSG_PARAM_UNKNOWN', lang), [modifier])) end else begin if IsId(value) then result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and SpaceKey = (Select SpaceKey from Spaces where Space = '''+sqlwrapstring(modifier)+''') and Value = '''+sqlwrapString(value)+''')' else if value.StartsWith(baseUrl) then begin parts := value.Substring(baseURL.Length).Split(['/']); if Length(parts) = 2 then begin result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and SpaceKey = (Select SpaceKey from Spaces where Space = '''+sqlwrapstring(parts[0])+''') and SpaceKey = (Select SpaceKey from Spaces where Space = '''+sqlwrapstring(modifier)+''') and Value = '''+sqlwrapString(parts[1])+''')' end else raise exception.create(StringFormat(GetFhirMessage('MSG_PARAM_UNKNOWN', lang), [name])) end else raise exception.create(StringFormat(GetFhirMessage('MSG_PARAM_UNKNOWN', lang), [modifier])) end end; SearchParamTypeQuantity : raise exception.create('not done yet: type = '+CODES_TFhirSearchParamType[type_]); else raise exception.create('not done yet: type = '+CODES_TFhirSearchParamType[type_]); end; { todo: renable for quantity with right words etc + ucum else if (right = 'before') or (right = 'after') then begin bHandled := true; if (right = 'before') then op := '<=' else if (right = 'after') then op := '>=' else op := '='; result := result + '(IndexKey = '+inttostr(Key)+' /*'+name+'*/ and Value '+op+' '''+sqlwrapString(value)+''')'; end } end; if ts.count > 1 then result := result + ')'; finally ts.free; end; end; end; end; end; if result <> '' then begin if not nested and (name <> 'tag') then result := 'Ids.ResourceKey in (select ResourceKey from IndexEntries where '+result+')'; if not bfirst then result := ' and '+result; end; bfirst := bfirst and (result = ''); end; procedure TSearchProcessor.SetIndexer(const Value: TFhirIndexManager); begin FIndexer := Value; end; procedure TSearchProcessor.SetRepository(const Value: TFHIRDataStore); begin FRepository := Value; end; function TSearchProcessor.SchemeForName(name : String) : string; begin if name = '_tag' then result := 'http://hl7.org/fhir/tag' else if result = '_profile' then result :='http://hl7.org/fhir/tag/profile' else result := 'http://hl7.org/fhir/tag/security'; end; procedure TSearchProcessor.SplitByCommas(value : String; list : TStringList); var s : String; begin for s in value.Split([',']) do list.add(s); end; function TSearchProcessor.findPrefix(var value : String; subst : String) : boolean; begin result := value.StartsWith(subst); if result then value := value.Substring(subst.Length); end; procedure TSearchProcessor.checkDateFormat(s: string); var ok : boolean; begin ok := false; if (length(s) = 4) and StringIsCardinal16(s) then ok := true else if (length(s) = 7) and (s[5] = '-') and StringIsCardinal16(copy(s, 1, 4)) and StringIsCardinal16(copy(s, 5, 2)) then ok := true else if (length(s) = 10) and (s[5] = '-') and (s[8] = '-') and StringIsCardinal16(copy(s, 1, 4)) and StringIsCardinal16(copy(s, 6, 2)) and StringIsCardinal16(copy(s, 9, 2)) then ok := true else if (length(s) > 11) and (s[5] = '-') and (s[8] = '-') and (s[11] = 'T') and StringIsCardinal16(copy(s, 1, 4)) and StringIsCardinal16(copy(s, 6, 2)) and StringIsCardinal16(copy(s, 9, 2)) then begin if (length(s) = 16) and (s[14] = ':') and StringIsCardinal16(copy(s, 12, 2)) and StringIsCardinal16(copy(s, 15, 2)) then ok := true else if (length(s) = 19) and (s[14] = ':') and (s[17] = ':') and StringIsCardinal16(copy(s, 12, 2)) and StringIsCardinal16(copy(s, 15, 2)) and StringIsCardinal16(copy(s, 18, 2)) then ok := true; end; if not ok then raise exception.create(StringFormat(GetFhirMessage('MSG_DATE_FORMAT', lang), [s])); end; end.
unit uSubVendorHistory; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentSub, siComp, siLangRT, Grids, DBGrids, SMDBGrid, DB, ADODB; type TSubVendorHistory = class(TParentSub) dsVendorHistory: TDataSource; quVendorHistory: TADOQuery; quVendorHistoryLastDate: TDateTimeField; quVendorHistoryModelID: TIntegerField; quVendorHistoryModel: TStringField; quVendorHistoryDescription: TStringField; quVendorHistoryCostPrice: TFloatField; quVendorHistoryFreight: TFloatField; quVendorHistoryOtherCost: TFloatField; quVendorHistoryTotal: TFloatField; grdModelFrameVendorHistory: TSMDBGrid; quVendorHistoryQty: TFloatField; procedure FormDestroy(Sender: TObject); private { Private declarations } fIDStore : Integer; fIDVendor : Integer; protected procedure AfterSetParam; override; public { Public declarations } procedure DataSetRefresh; procedure DataSetOpen; override; procedure DataSetClose; override; end; implementation uses uDM, uParamFunctions, uDMGlobal; {$R *.dfm} procedure TSubVendorHistory.DataSetRefresh; begin DataSetClose; DataSetOpen; end; procedure TSubVendorHistory.DataSetOpen; begin with quVendorHistory do if not Active then begin Parameters.ParambyName('IDStore').Value := fIDStore; if fIDVendor <> 0 then Parameters.ParambyName('IDFornecedor').Value := fIDVendor else Parameters.ParambyName('IDFornecedor').Value := Null; Open; end; end; procedure TSubVendorHistory.DataSetClose; begin with quVendorHistory do if Active then Close; end; procedure TSubVendorHistory.AfterSetParam; begin fIDStore := StrToIntDef(ParseParam(FParam, 'IDStore'),0); fIDVendor := StrToIntDef(ParseParam(FParam, 'IDVendor'),0); DataSetRefresh; end; procedure TSubVendorHistory.FormDestroy(Sender: TObject); begin DataSetClose; inherited; end; initialization RegisterClass(TSubVendorHistory); end.
unit FGKX_EditCord; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,Dialog_View, Mask, RzEdit,Class_CORD_IN_GKZF,Class_TYPE_IN_GKZF, Uni,UniConnct, RzCmboBx, RzButton, RzRadChk; type TDialogEditCordEditMode=(decemAddx,decemEdit); TFGKXEditCord = class(TDialogView) Btnx_Mrok: TButton; Btnx_Quit: TButton; Edit_Code: TRzEdit; Edit_Name: TRzEdit; Labl_1: TLabel; Labl_2: TLabel; Labl_3: TLabel; Comb_TYPE: TRzComboBox; Labl_4: TLabel; Edit_RULE: TRzEdit; Chkb_Dash: TRzCheckBox; Chkb_Attr: TRzCheckBox; Labl_5: TLabel; Edit_Memo: TRzEdit; procedure Btnx_MrokClick(Sender: TObject); procedure Edit_RULEKeyPress(Sender: TObject; var Key: Char); procedure Edit_CodeKeyPress(Sender: TObject; var Key: Char); private FEditMode:TDialogEditCordEditMode; FRealCord:TCORD; protected procedure SetInitialize;override; procedure SetCommParams;override; procedure SetGridParams;override; procedure SetComboItems;override; procedure TryFreeAndNil;override; public function CheckLicit:Boolean; procedure SaveItDB; procedure UpdateDB; procedure InsertDB; end; var FGKXEditCord: TFGKXEditCord; function ViewEditCord(AEditMode:TDialogEditCordEditMode; ACord:TCORD):Integer; implementation uses Class_KzUtils,Class_AppUtil; {$R *.dfm} function ViewEditCord(AEditMode:TDialogEditCordEditMode; ACord:TCORD):Integer; begin try FGKXEditCord:=TFGKXEditCord.Create(nil); FGKXEditCord.FEditMode:=AEditMode; FGKXEditCord.FRealCord:=ACord; Result:=FGKXEditCord.ShowModal; finally FreeAndNil(FGKXEditCord); end; end; { TDialogEditCord } function TFGKXEditCord.CheckLicit: Boolean; begin Result:=False; if Trim(Edit_CODE.Text)='' then begin ShowMessage('请填写分组名称.'); Exit; end; if Trim(Edit_Name.Text)='' then begin ShowMessage('请填写分组名称.'); Exit; end; if Trim(Edit_RULE.Text)='' then begin ShowMessage('请填写编码规则.'); Exit; end; if Comb_Type.ItemIndex=-1 then begin ShowMessage('请选择应用场所.'); Exit; end; Result:=True; end; procedure TFGKXEditCord.InsertDB; var UniConnct:TUniConnection; begin if FRealCord=nil then begin FRealCord:=TCORD.Create; end; FRealCord.UNITLINK:='-1'; FRealCord.CORDIDEX:=-1; FRealCord.CORDCODE:=Trim(Edit_Code.Text); FRealCord.CORDNAME:=Trim(Edit_Name.Text); FRealCord.CORDTYPE:=Trim(Comb_Type.Text); FRealCord.CODERULE:=Trim(Edit_RULE.Text); FRealCord.CORDMEMO:=Trim(Edit_Memo.Text); FRealCord.WITHDASH:=TKzUtils.IfThen(Chkb_Dash.Checked,1,0); FRealCord.WITHATTR:=TKzUtils.IfThen(Chkb_Attr.Checked,1,0); try UniConnct:=UniConnctEx.GetConnection(CONST_MARK_GKZF); //-> FRealCord.CORDIDEX:=FRealCord.GetNextIdex(UniConnct); FRealCord.InsertDB(UniConnct); ModalResult:=mrOk; //-< finally FreeAndNil(UniConnct); FreeAndNil(FRealCord); end; end; procedure TFGKXEditCord.SaveItDB; begin if not CheckLicit then Exit; case FEditMode of decemAddx:InsertDB; decemEdit:UpdateDB; end; end; procedure TFGKXEditCord.SetComboItems; begin inherited; with Comb_Type do begin Items.Clear; Items.Add('<空>'); Items.Add('凭证:记账类型'); Items.Add('凭证:单据类型'); Items.Add('凭证:单位信息'); Items.Add('凭证:资金性质'); Items.Add('凭证:功能分类'); Items.Add('凭证:经济分类'); Items.Add('凭证:项目分类'); Items.Add('凭证:预算项目'); Items.Add('凭证:指标来源'); Items.Add('凭证:支付类型'); Items.Add('凭证:结算类型'); Items.Add('凭证:金额'); Items.Add('凭证:摘要'); {Items.Add(Class_AppUtil.CONST_CORD_TYPE_SECT); Items.Add(Class_AppUtil.CONST_CORD_TYPE_CARD);} Style:=csDropDownList; ItemIndex:=0; DropDownCount:=Items.Count; end; end; procedure TFGKXEditCord.SetCommParams; begin inherited; Caption:='凭证元素'; Btnx_Quit.Caption:='取消'; Btnx_Mrok.Caption:='确定'; Btnx_Quit.ModalResult:=mrCancel; end; procedure TFGKXEditCord.SetGridParams; begin inherited; end; procedure TFGKXEditCord.SetInitialize; var NumbA:Integer; UniConnct:TUniConnection; begin inherited; if FEditMode=decemAddx then begin try UniConnct:=UniConnctEx.GetConnection(CONST_MARK_GKZF); //-> NumbA:=TCORD.CheckField('CORD_IDEX','GKX_CORD',[],UniConnct); Edit_Code.Text:=TKzUtils.TryFormatCode(NumbA,2,'0'); //-< finally FreeAndNil(UniConnct); end; end else if FEditMode=decemEdit then begin if FRealCord<>nil then begin Edit_Code.Text:=FRealCord.CORDCODE; Edit_Name.Text:=FRealCord.CORDNAME; Edit_RULE.Text:=FRealCord.CODERULE; Edit_Memo.Text:=FRealCord.CORDMEMO; Chkb_Dash.Checked:=FRealCord.WITHDASH=1; Comb_Type.ItemIndex:=Comb_Type.IndexOf(FRealCord.CORDTYPE); try UniConnct:=UniConnctEx.GetConnection(CONST_MARK_GKZF); //-> NumbA:=TCORD.CheckCount('CORD_IDEX','GKX_TYPE',['UNIT_LINK',FRealCord.UNITLINK,'CORD_IDEX',FRealCord.CORDIDEX],UniConnct); Chkb_Dash.Enabled:=not (NumbA>=1); //-< finally FreeAndNil(UniConnct); end; end; end; end; procedure TFGKXEditCord.TryFreeAndNil; begin inherited; if FRealCord=nil then begin FreeAndNil(FRealCord); end; end; procedure TFGKXEditCord.UpdateDB; var UniConnct:TUniConnection; begin try UniConnct:=UniConnctEx.GetConnection(CONST_MARK_GKZF); //-> FRealCord.CORDNAME:=Trim(Edit_Name.Text); FRealCord.CORDTYPE:=Trim(Comb_TYPE.Text); FRealCord.CODERULE:=Trim(Edit_RULE.Text); FRealCord.CORDMEMO:=Trim(Edit_Memo.Text); FRealCord.WITHDASH:=TKzUtils.IfThen(Chkb_Dash.Checked,1,0); FRealCord.WITHATTR:=TKzUtils.IfThen(Chkb_Attr.Checked,1,0); FRealCord.UpdateDB(UniConnct); ModalResult:=mrOk; //-< finally FreeAndNil(UniConnct); end; end; procedure TFGKXEditCord.Btnx_MrokClick(Sender: TObject); begin SaveItDB; end; procedure TFGKXEditCord.Edit_RULEKeyPress(Sender: TObject; var Key: Char); begin if not (key in ['0'..'9','.',#8, #13,'-']) then begin key := chr(0); end; end; procedure TFGKXEditCord.Edit_CodeKeyPress(Sender: TObject; var Key: Char); begin if not (key in ['0'..'9','.',#8, #13,'-']) then begin key := chr(0); end; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, Menus; type { TForm1 } TForm1 = class(TForm) MainMenu1: TMainMenu; Memo1: TMemo; MenuItem1: TMenuItem; MenuItem10: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; MenuItem6: TMenuItem; MenuItem7: TMenuItem; MenuItem8: TMenuItem; MenuItem9: TMenuItem; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; procedure FormCreate(Sender: TObject); procedure MenuItem10Click(Sender: TObject); procedure MenuItem2Click(Sender: TObject); procedure MenuItem3Click(Sender: TObject); procedure MenuItem4Click(Sender: TObject); procedure MenuItem5Click(Sender: TObject); procedure MenuItem6Click(Sender: TObject); procedure MenuItem7Click(Sender: TObject); procedure MenuItem9Click(Sender: TObject); private public end; var Form1: TForm1; implementation {$R *.lfm} {Глобальные переменные} // Спецификация файла - его полное имя, которое ВИДНО ВО ВСЕХ процедурах var sf: string; { TForm1 } {Особые действия при открытии} procedure TForm1.FormCreate(Sender: TObject); begin sf := ''; // Никакого файла мы ещё не открывали // Каталоги для сохраненияи и открытия по умочанию (Папка проекта) OpenDialog1.InitialDir:=''; SaveDialog1.InitialDir:=''; end; {Создать} procedure TForm1.MenuItem2Click(Sender: TObject); begin Memo1.Clear; // Очищаем текстовый редактор, что равносильно изменению в Memo1 Memo1.Modified:= False; // Но мы же ничего не поменяли, надо это указать sf:=''; // А у файла нет ещё имени Form1.Caption:= 'Form1'; // Заголовок окна end; {Открыть} procedure TForm1.MenuItem3Click(Sender: TObject); begin // Перед тем как открыть новый файл, нодо проверить вдруг есть несохранённые // изменения в старом - УЖЕ открытом(новом пустом) файле If Memo1.Modified then case MessageDlg('Текст был изменён' + #13 + 'Сохранить его?', mtConfirmation,[mbYes, mbNo, mbCancel],0) of mrYes : MenuItem5Click(self); // Да -> сохраняем старый файл mrNo : ; mrCancel: Exit; end; // Если диалог открытия файла завершился нормально, // То есть его не закрыли и не нажали cancel // То есть юзер выбрал нужный ему файл и нажал ОК If openDialog1.Execute then begin sf:=OpenDialog1.FileName; // Извлекаем имя файла из этого диалога Memo1.Lines.LoadFromFile(sf); // Выводим его в Memo1 Memo1.Modified:=False; // Что равносильно его изменению, но мы же не изменяли файл Form1.Caption:='Form1 ' + sf; // В заголовок окна выводим имя файла end; end; {Закрыть} procedure TForm1.MenuItem4Click(Sender: TObject); begin // Стандартных диалог сохранения файла // Если Memo1 было изменено if Memo1.Modified then // Стандартное окно Сообщения case MessageDlg('Данные о студентах были изменены' + #13 + 'Сохранить их?', mtConfirmation,[mbYes, mbNo, mbCancel],0) of mrYes: MenuItem5Click(self); // Сохраняем файл mrNo:; // Ничего не делаем mrCancel: Exit; // Выходим из окна сообщения, и возвращаемся к редактированию текста(действия ниже выполняться не будут) end; // Если мы не вишли через 'Cancel', то совершаем стандартные действия Memo1.Clear; // Очищаем окно редактора Memo1.Modified:= False; sf:=''; Form1.Caption:= 'Form1'; end; {Сохранить как} procedure TForm1.MenuItem6Click(Sender: TObject); begin // Если диалог сохранения прошёл хорошо if SaveDialog1.Execute then begin sf:= SaveDialog1.FileName; // Извлекаем имя файла Memo1.Lines.SaveToFile(sf); // Cохраняем содержимое редактора в файл с именем sf Memo1.Modified := False; // Содержимое в редакторе соответсвует файлу на диске Form1.Caption:= 'Form1 ' + sf; // Устанавливаем заголовок приложения с именем файла end; end; {Сохранить} procedure TForm1.MenuItem5Click(Sender: TObject); begin // Исли имя файла не задано, то вызываем Окно 'сохранить как' if sf = '' then MenuItem6Click(self) else // Иначе, то есть имя файла уже установлено begin Memo1.Lines.SaveToFile(sf); // Сразу сохраняем его на диск Memo1.Modified:= False; // Содержание устанавливаем не изменённым, тк сохранили всё на диск end; end; {Выход} procedure TForm1.MenuItem7Click(Sender: TObject); begin // Сообщение: Сохранить ли изменённый файл if Memo1.Modified then case MessageDlg('Файл был изменён' + #13 + 'Сохранить его?', mtConfirmation,[mbYes, mbNo, mbCancel],0) of mrYes : MenuItem5Click(self); // Да -> сохраняем открытый файл mrNo : ; mrCancel: Exit; end; // Закрываем приложение close; end; // Обработка {Обработка 1} procedure TForm1.MenuItem9Click(Sender: TObject); begin end; {Обработка 2} procedure TForm1.MenuItem10Click(Sender: TObject); begin end; end.