text
stringlengths
14
6.51M
unit SSCollapsePanelGroup; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, contnrs, Forms, Dialogs, ExtCtrls; type TSSCollapsePanel = class(TCustomPanel) private fcollapsed: Boolean; procedure setcollapsed(value: Boolean); public property Collapsed: boolean read fcollapsed write setcollapsed; published end; TSSCollapsePanelGroup = class(TCustomPanel) private // fpanels:TObjectList; procedure LayoutPanels; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public procedure Loaded; override; function GetChildOwner: TComponent; override; procedure WriteState(Writer: TWriter); override; procedure ReadState(Reader: TReader); override; procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; procedure AddPanel; constructor Create(aOwner: TComponent); override; destructor destroy; override; published property Align; end; implementation procedure TSSCollapsePanel.setcollapsed(value: Boolean); begin fcollapsed := value; end; procedure TSSCollapsePanelGroup.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; LayoutPanels; end; procedure TSSCollapsePanelGroup.Loaded; var i: integer; begin for i := 0 to controlcount - 1 do controls[i].parent := self; inherited; LayoutPanels; end; procedure TSSCollapsePanelGroup.LayoutPanels; var y, t1: integer; panel: TSSCollapsePanel; begin if controlcount = 0 then exit; //dont resize y := 0; for t1 := 0 to controlcount - 1 do inc(y, TSSCollapsePanel(controls[t1]).Height); if (csDesigning in ComponentState) then y := y + 50; //Give the designer something to hold on to! height := y; y := 0; for t1 := 0 to controlcount - 1 do begin panel := TSSCollapsePanel(controls[t1]); panel.left := 0; panel.width := ClientWidth; panel.top := y; inc(y, panel.Height); end; end; procedure TSSCollapsePanelGroup.WriteState(Writer: TWriter); begin if writer.Ancestor = nil then inherited WriteState(writer); end; procedure TSSCollapsePanelGroup.ReadState(Reader: TReader); var i: integer; begin for i := controlcount - 1 downto 0 do controls[i].free; inherited; end; function TSSCollapsePanelGroup.GetChildOwner: TComponent; begin //set the child owner to the form as they are streamed in if owner = nil then result := self else result := owner; end; procedure TSSCollapsePanelGroup.GetChildren(Proc: TGetChildProc; Root: TComponent); var t1: integer; begin //Our children should be "owned" by us, even though they are really owned by the form for t1 := 0 to ControlCount - 1 do Proc(Controls[t1]); end; procedure TSSCollapsePanelGroup.AddPanel; var panel: TSSCollapsePanel; t1: integer; begin panel := TSSCollapsePanel.Create(parent); //Form should own our children {Note: from 0 to count. That's one more number than the amount of panels we\ are holding. Guarantees that there is a gap in this range.} for t1 := 0 to ControlCount do if FindComponent('Panel' + inttostr(t1)) = nil then begin panel.name := 'Panel' + inttostr(t1); break; end; if panel.Name = '' then begin panel.Free; //we have failed in our mission... erase all evidence! end else begin panel.parent := self; //but they are our graphical children LayoutPanels; end; end; constructor TSSCollapsePanelGroup.Create(aOwner: TComponent); begin inherited; ControlStyle := ControlStyle - [csAcceptsControls]; //we only want self managed panels on us end; destructor TSSCollapsePanelGroup.destroy; begin inherited; end; end.
unit AT.Windows.Clipboard; interface var CF_HTML: Integer; CF_RTF: Integer; implementation uses Winapi.Windows; initialization CF_HTML := RegisterClipboardFormat('HTML Format'); CF_RTF := RegisterClipboardFormat('Rich Text Format'); end.
{$ifdef license} (* Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder 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 HOLDER 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. *) {$endif} unit cwIO.Buffer.Standard; {$ifdef fpc} {$mode delphiunicode} {$endif} interface uses cwUnicode , cwIO ; type TBuffer = class( TInterfacedObject, IBuffer, IUnicodeBuffer ) private fAlign16: boolean; fActualDataWhenAligned: pointer; fData: pointer; fSize: nativeuint; private //- IBuffer -// procedure FillMem( const value: uint8 ); function LoadFromStream( const Stream: IStream; const Bytes: nativeuint ): nativeuint; function SaveToStream( const Stream: IStream; const Bytes: nativeuint ): nativeuint; procedure Assign( const Buffer: IBuffer ); procedure InsertData( const Buffer: Pointer; const Offset: nativeuint; const Bytes: nativeuint ); function AppendData( const Buffer: Pointer; const Bytes: nativeuint ): pointer; overload; function AppendData( const Buffer: pointer ): pointer; overload; procedure ExtractData( const Buffer: Pointer; const Offset: nativeuint; const Bytes: nativeuint ); function getDataPointer: pointer; function getSize: nativeuint; function getByte( const idx: nativeuint ): uint8; procedure setByte( const idx: nativeuint; const value: uint8 ); procedure setSize( const aSize: nativeuint ); private //- IUnicodeBuffer -// function ReadBOM( const Format: TUnicodeFormat ): boolean; procedure WriteBOM( const Format: TUnicodeFormat ); function DetermineUnicodeFormat: TUnicodeFormat; function WriteString( const aString: string; const Format: TUnicodeFormat; ZeroTerm: boolean = FALSE ): nativeuint; function ReadString( const Format: TUnicodeFormat; const ZeroTerm: boolean = False; const Max: int32 = -1 ): string; function getAsString: string; procedure setAsString( const value: string ); procedure AllocateBuffer( const NewSize: nativeuint ); procedure DeallocateBuffer; procedure ResizeBuffer( const NewSize: nativeuint ); public constructor Create( const aSize: nativeuint = 0; const Align16: boolean = FALSE ); overload; destructor Destroy; override; end; implementation uses cwUnicode.Standard , cwHeap , cwHeap.Standard , cwStatus ; procedure TBuffer.AllocateBuffer(const NewSize: nativeuint); begin if (fSize>0) then begin DeallocateBuffer; end; if NewSize>0 then begin fSize := NewSize; if fAlign16 then begin fActualDataWhenAligned := Heap.Allocate(fSize+$0F); {$ifdef CPU64} {$hints off}fData := pointer(((nativeuint(fActualDataWhenAligned) and $FFFFFFFFFFFFFFF0)+$0F));{$hints on} {$else} {$hints off}fData := pointer(((nativeuint(fActualDataWhenAligned) and $FFFFFFF0)+$0F));{$hints on} {$endif} end; fData := Heap.Allocate(fSize); end; end; procedure TBuffer.DeallocateBuffer; begin if (fSize>0) then begin if assigned(fData) then begin if fAlign16 then begin Heap.Deallocate(fActualDataWhenAligned); end else begin Heap.Deallocate(fData); end; end; fSize := 0; fData := nil; end; end; function TBuffer.getDataPointer: pointer; begin Result := fData; end; function TBuffer.getSize: nativeuint; begin Result := fSize; end; function TBuffer.ReadBOM(const Format: TUnicodeFormat): boolean; var BomSize: uint8; begin BomSize := 0; // Determine BOM size. case Format of TUnicodeFormat.utfUnknown: BomSize := 0; TUnicodeFormat.utfANSI: BomSize := 0; TUnicodeFormat.utf8: BomSize := 3; TUnicodeFormat.utf16LE: BomSize := 2; TUnicodeFormat.utf16BE: BomSize := 2; TUnicodeFormat.utf32LE: BomSize := 4; TUnicodeFormat.utf32BE: BomSize := 4; end; if BomSize>0 then begin Result := Unicode.DecodeBOM(fData^,Format,BomSize); end else begin Result := False; end; end; function TBuffer.ReadString(const Format: TUnicodeFormat; const ZeroTerm: boolean; const Max: int32): string; var TotalSize: nativeuint; bytecount: uint8; ptr: pointer; CH: uint32; CP: TUnicodeCodePoint; S: string; StopOnError: boolean; begin CH:=0; if fSize=0 then begin Result := ''; Exit; end; // This must happen one 'character' (code-point) at a time. S := ''; bytecount := 0; CP := 0; TotalSize := 0; ptr := fData; StopOnError := False; while (TotalSize<GetSize) and ((Max<0) or (Length(S)<Max)) and (not StopOnError) do begin // decode the character from the buffer. Move(ptr^,CH,sizeof(CH)); {$warnings off} case Format of TUnicodeFormat.utfANSI: begin bytecount := sizeof(uint8); if not Unicode.AnsiDecode(CH,CP) then begin StopOnError := True; Continue; end; end; TUnicodeFormat.utf8: begin if Unicode.UTF8CharacterLength(CH, bytecount) then begin if not Unicode.UTF8Decode(CH, CP) then begin StopOnError := True; Continue; end; end else begin StopOnError := True; Continue; end; end; TUnicodeFormat.utf16LE: begin if Unicode.UTF16LECharacterLength(CH, bytecount) then begin if not Unicode.UTF16LEDecode(CH, CP) then begin StopOnError := True; Continue; end; end else begin StopOnError := True; Continue; end; end; TUnicodeFormat.utf16BE: begin if Unicode.UTF16BECharacterLength(CH,bytecount) then begin if not Unicode.UTF16BEDecode(CH, CP) then begin StopOnError := True; Continue; end; end else begin StopOnError := True; Continue; end; end; TUnicodeFormat.utf32LE: begin bytecount := sizeof(uint32); if not Unicode.UTF32LEDecode(CH, CP) then begin StopOnError := True; Continue; end; end; TUnicodeFormat.utf32BE: begin bytecount := sizeof(uint32); if not Unicode.UTF32BEDecode(CH,CP) then begin StopOnError := True; Continue; end; end; end; {$warnings on} // Warns that not all cases are covered, utfUnknown does not need to be covered if (CP=0) and (ZeroTerm) then begin Break; // drop the loop end; Unicode.EncodeCodepointToString(CP,S); {$ifdef fpc} {$hints off} {$endif} ptr := pointer(nativeuint(ptr)+bytecount); {$ifdef fpc} {$hints on} {$endif} TotalSize := TotalSize + bytecount; end; Result := S; end; procedure TBuffer.ResizeBuffer(const NewSize: nativeuint); var fNewBuffer: pointer; begin if NewSize=fSize then begin Exit; end else if fSize=0 then begin AllocateBuffer(NewSize); end else if NewSize=0 then begin DeallocateBuffer; end else begin // Create the new buffer and copy old data to it. fNewBuffer := Heap.Allocate(NewSize); FillChar(fNewBuffer^,NewSize,0); if NewSize>fSize then begin Move(fData^,fNewBuffer^,fSize); end else begin Move(fData^,fNewBuffer^,NewSize); end; DeallocateBuffer; fData := fNewBuffer; fSize := NewSize; end; end; procedure TBuffer.setAsString(const value: string); begin SetSize( Length(value) * 4 ); // max length of utf16 character is 32-bit, therefore 4-bytes, 4*characters in string should be sufficient. SetSize( WriteString(value,TUnicodeFormat.utf16LE) ); end; procedure TBuffer.setByte(const idx: nativeuint; const value: uint8); var ptr: ^uint8; begin if (idx<fSize) then begin {$ifdef fpc} {$hints off} {$endif} ptr := pointer(nativeuint(fData)+idx); {$ifdef fpc} {$hints on} {$endif} ptr^ := value; end; end; function TBuffer.LoadFromStream(const Stream: IStream; const Bytes: nativeuint): nativeuint; begin if getSize<=Bytes then begin Stream.Read(getDataPointer,getSize); Result := getSize; end else begin Stream.Read(getDataPointer,Bytes); Result := Bytes; end; end; function TBuffer.SaveToStream( const Stream: IStream; const Bytes: nativeuint ): nativeuint; begin if Bytes>getSize then begin Stream.Write(getDataPointer,getSize); Result := getSize; end else begin Stream.Write(getDataPointer,Bytes); Result := Bytes; end; end; procedure TBuffer.setSize( const aSize: nativeuint ); begin if fSize=aSize then Exit; ResizeBuffer(aSize); end; procedure TBuffer.WriteBOM( const Format: TUnicodeFormat ); var size: uint8; begin size := 0; Unicode.EncodeBOM(fData^,Format,size); end; function TBuffer.WriteString( const aString: string; const Format: TUnicodeFormat; ZeroTerm: boolean = FALSE ): nativeuint; var ptr: ^char; CH: uint32; StrLen: int32; CP: TUnicodeCodepoint; Cursor: int32; L: uint8; begin CP := 0; CH := 0; L := 0; Result := 0; // Loop each character StrLen := Length(aString); {$ifdef NEXTGEN} {$ifndef LINUX} StrLen := Pred(Length(aString)); {$endif} {$endif} //- Pass one, measure string length. Cursor := 1; {$ifdef NEXTGEN} {$ifndef LINUX} Cursor := 0; {$endif} {$endif} //- Pass one, measure string length. while (Cursor<=StrLen) do begin Unicode.DecodeCodepointFromString(CP,aString,Cursor); case Format of TUnicodeFormat.utfUnknown: begin TStatus(stCannotEncodeUnknownUnicodeFormat).Raize(['TBuffer.WriteString']); end; TUnicodeFormat.utfANSI: begin L := 1; end; TUnicodeFormat.utf8: begin Unicode.UTF8Encode(CP,CH,L); end; TUnicodeFormat.utf16LE: begin Unicode.UTF16LEEncode(CP,CH,L); end; TUnicodeFormat.utf16BE: begin Unicode.UTF16BEEncode(CP,CH,L); end; TUnicodeFormat.utf32LE: begin Unicode.UTF32LEEncode(CP,CH,L); end; TUnicodeFormat.utf32BE: begin Unicode.UTF32BEEncode(CP,CH,L); end; end; Result := Result + L; end; if ZeroTerm then begin inc(Result); end; //- Set buffer size. Self.AllocateBuffer(Result); //- Pass two, put data into buffer Cursor := 1; {$ifdef NEXTGEN} {$ifndef LINUX} Cursor := 0; {$endif} {$endif} ptr := fData; while (Cursor<=StrLen) do begin Unicode.DecodeCodepointFromString(CP,aString,Cursor); {$warnings off} case Format of TUnicodeFormat.utfANSI: begin Unicode.ANSIEncode(CP,CH,L); end; TUnicodeFormat.utf8: begin Unicode.UTF8Encode(CP,CH,L); end; TUnicodeFormat.utf16LE: begin Unicode.UTF16LEEncode(CP,CH,L); end; TUnicodeFormat.utf16BE: begin Unicode.UTF16BEEncode(CP,CH,L); end; TUnicodeFormat.utf32LE: begin Unicode.UTF32LEEncode(CP,CH,L); end; TUnicodeFormat.utf32BE: begin Unicode.UTF32BEEncode(CP,CH,L); end; end; {$warnings on} // warns that not all cases are covered, cases such as uftUnknown do not need to be covered Move(CH,ptr^,L); {$ifdef fpc} {$hints off} {$endif} ptr := pointer(nativeuint(pointer(Ptr)) + L); {$ifdef fpc} {$hints on} {$endif} end; if ZeroTerm then begin uint8(pointer(ptr)^) := 0; end; end; constructor TBuffer.Create( const aSize: nativeuint = 0; const Align16: boolean = FALSE ); begin inherited Create; fData := nil; fSize := aSize; fAlign16 := Align16; //- Dependencies //- Allocate an initial amount. AllocateBuffer(fSize); end; destructor TBuffer.Destroy; begin DeallocateBuffer; inherited Destroy; end; function TBuffer.DetermineUnicodeFormat: TUnicodeFormat; begin Result := TUnicodeFormat.utfUnknown; if ReadBOM(TUnicodeFormat.utf32LE) then begin Result := TUnicodeFormat.utf32LE; end else if ReadBOM(TUnicodeFormat.utf32BE) then begin Result := TUnicodeFormat.utf32BE; end else if ReadBOM(TUnicodeFormat.utf16LE) then begin Result := TUnicodeFormat.utf16LE end else if ReadBOM(TUnicodeFormat.utf16BE) then begin Result := TUnicodeFormat.utf16BE; end else if ReadBOM(TUnicodeFormat.utf8) then begin Result := TUnicodeFormat.utf8; end; end; function TBuffer.AppendData(const Buffer: pointer): pointer; var count: nativeuint; measurePtr: ^uint8; begin // First measure the buffer. count := 0; measurePtr := Buffer; while measurePtr^<>0 do begin inc(count); inc(measurePtr); end; Result := AppendData(Buffer,succ(Count)); end; procedure TBuffer.Assign(const Buffer: IBuffer); begin if Buffer.Size=0 then begin fSize := 0; Exit; end; SetSize( Buffer.Size ); Move(Buffer.getDataPointer^,fData^,fSize); end; procedure TBuffer.InsertData( const Buffer: Pointer; const Offset: nativeuint; const Bytes: nativeuint ); var DataPtr: pointer; begin {$ifdef fpc} {$hints off} {$endif} DataPtr := pointer(nativeuint(fData) + Offset ); {$ifdef fpc} {$hints on} {$endif} Move(Buffer^,DataPtr^,Bytes); end; function TBuffer.AppendData( const Buffer: Pointer; const Bytes: nativeuint ): pointer; var Target: NativeInt; TargetPtr: Pointer; OldSize: Longword; begin Result := nil; if bytes>0 then begin OldSize := fSize; SetSize( OldSize + Bytes ); {$HINTS OFF} Target := NativeInt(fData); {$HINTS ON} inc(Target,OldSize); {$HINTS OFF} TargetPtr := Pointer(Target); {$HINTS ON} Move(Buffer^,TargetPtr^,Bytes); Result := TargetPtr; end; end; procedure TBuffer.ExtractData( const Buffer: Pointer; const Offset: nativeuint; const Bytes: nativeuint ); var DataPtr: pointer; begin if not assigned(Buffer) then begin exit; end; if Bytes=0 then begin exit; end; {$ifdef fpc} {$hints off} {$endif} DataPtr := pointer(nativeuint(fData) + Offset); {$ifdef fpc} {$hints on} {$endif} if Bytes>(fSize-Offset) then begin Move(DataPtr^,Buffer^,(fSize-Offset)); end else begin Move(DataPtr^,Buffer^,Bytes); end; end; procedure TBuffer.FillMem(const value: uint8); begin FillChar(getDataPointer^,getSize,value); end; function TBuffer.getAsString: string; begin Result := ReadString(TUnicodeFormat.utf16LE); end; function TBuffer.getByte(const idx: nativeuint): uint8; var ptr: ^uint8; begin if (idx<fSize) then begin {$ifdef fpc} {$hints off} {$endif} ptr := pointer(nativeuint(fData)+idx); {$ifdef fpc} {$hints on} {$endif} Result := ptr^; end else begin Result := 0; end; end; end.
unit Gt04; { ULGT04.DPR================================================================= File: GT04.PAS Library Call Demonstrated: cbGetBoardName() Purpose: Prints a list of all boards installed in the system. Prints a list of all supported boards. Other Library Calls: cbErrHandling(), cbGetConfig() Special Requirements: --- (c) Copyright 1995 - 2002, Measurement Computing Corp. All rights reserved. =========================================================================== } interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, cbw; type TfrmBoards = class(TForm) cmdQuit: TButton; MemoData: TMemo; cmdList: TButton; procedure cmdQuitClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cmdListClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmBoards: TfrmBoards; implementation {$R *.DFM} var ULStat: Integer; NumBoards: Integer; ErrReporting: Integer; ErrHandling: Integer; InfoType: Integer; DevNum: Integer; ConfigItem: Integer; BoardName: PChar; NullString: array [0..BOARDNAMELEN] of Char; RevLevel: Single; ConfigVal: Integer; { String arguments in the Universal Library (and most DLLs) expect a null terminated string. This can be accomplished in Delphi by setting up an array of type Char and assigning a pointer (BoardName) to it. The array must be dimensioned to at least the length of the longest message. } procedure TfrmBoards.FormCreate(Sender: TObject); var BoardNum: Integer; begin {declare Revision Level} RevLevel:= CURRENTREVNUM; ULStat := cbDeclareRevision(RevLevel); { set up internal error handling for the Universal Library } ErrReporting := DONTPRINT; {set Universal Library ignore all errors} ErrHandling := DONTSTOP; ULStat := cbErrHandling(ErrReporting, ErrHandling); BoardName := @NullString; {assign a pointer to the Char array} MemoData.Text := 'List of Installed Boards:'; frmBoards.MemoData.Lines.Add (' '); { Get the number of boards installed in system } InfoType := GLOBALINFO; BoardNum := 0; DevNum := 0; ConfigItem := GINUMBOARDS; cbGetConfig (InfoType, BoardNum, DevNum, ConfigItem, ConfigVal); NumBoards := ConfigVal; for BoardNum := 0 to NumBoards -1 do begin { Get board name of each board using board number } cbGetBoardName (BoardNum, BoardName); frmBoards.MemoData.Lines.Add (StrPas(BoardName)); end; end; procedure TfrmBoards.cmdListClick(Sender: TObject); begin MemoData.Text := 'List of supported boards:'; frmBoards.MemoData.Lines.Add (' '); { Get the first board type in list of supported boards (the first string in the list of names is "Not Installed") } cbGetBoardName (GETFIRST, BoardName); frmBoards.MemoData.Lines.Add (StrPas(BoardName)); while StrLen(BoardName) > 0 do begin { Get each consecutive board type in list } cbGetBoardName (GETNEXT, BoardName); frmBoards.MemoData.Lines.Add (StrPas(BoardName)); end; end; procedure TfrmBoards.cmdQuitClick(Sender: TObject); begin Close; end; end.
unit Icon2Base64; interface uses Winapi.Windows, System.Classes, System.SysUtils, Soap.EncdDecd, Vcl.Graphics, System.IOUtils, ArrayEx; const WCMN: string = 'WCmnUI_UIItemBmp'; type TIcon2Base64 = class class function GetBase64(fileName: string; width: Integer = 16; height: Integer = 16): string; end; type TIconDirEntry = packed record bWidth: Byte; bHeight: Byte; bColorCount: Byte; bReserved: Byte; wPlanes: Word; wBitCount: Word; dwBytesInRes: DWord; dwImageOffset: DWord; end; TIcondir = packed record idReserved: Word; idType: Word; idCount: Word; IdEntries: array[1..20] of TIconDirEntry; end; implementation class function TIcon2Base64.GetBase64(fileName: string; width, height: Integer): string; var fs: TFileStream; b: TBytes; bw: TBinaryWriter; tp: Integer; ss: TStringStream; bmp1: TBitmap; img: TWICImage; begin img := TWICImage.Create; img.LoadFromFile(fileName); bmp1 := TBitmap.Create; bmp1.PixelFormat := pf8bit; bmp1.Width := width; bmp1.Height := height; bmp1.Canvas.Brush.Color := TColor($c3c3c3); bmp1.Canvas.FillRect(bmp1.Canvas.ClipRect); SetStretchBltMode(bmp1.Canvas.Handle, HALFTONE); bmp1.Canvas.StretchDraw(Rect(0, 0, bmp1.Width, bmp1.Height), img); bmp1.SaveToFile(Format('%s_%dx%d.bmp', [fileName, width, height])); fs := TFileStream.Create(Format('%s_%dx%d.bmp', [fileName, width, height]), fmOpenRead); SetLength(b, fs.Size); fs.ReadBuffer(b, fs.Size); fs.Free; bw := TBinaryWriter.Create(TMemoryStream.Create); bw.Write($FF); bw.Write($FF); bw.Write(Integer($00100001)); bw.Write(BytesOf(WCMN)); bw.Write(Integer(0)); bw.Write(0); bw.Write(0); tp := bw.BaseStream.Position; bw.Write(b); bw.Seek(tp, TSeekOrigin.soBeginning); bw.Write(SmallInt(0)); bw.Write($28); bw.Write(0); bw.Write(SmallInt(0)); bw.Write(0); bw.Write(4); bw.Write(SmallInt(0)); bw.Write(Integer(width * height)); //bw.Seek(20, TSeekOrigin.soCurrent); bw.BaseStream.Position := bw.BaseStream.Size; bw.Write(Integer($00F0F0F0)); bw.Write(Integer($00A0A0A0)); bw.Write(Integer($00F0F0F0)); bw.Write(Integer(0)); ss := TStringStream.Create; bw.BaseStream.Seek(0, TSeekOrigin.soBeginning); EncodeStream(bw.BaseStream, ss); bw.Free; Result := Format('%s', [ss.DataString]); ss.Free; bmp1 := nil; img := nil; DeleteFile(Format('%s_%dx%d.bmp', [fileName, width, height])); end; end.
PROGRAM AverageScore(INPUT, OUTPUT); CONST NumberOfScores = 4; ClassSize = 4; MaxScore = 100; MinScore = 0; VAR WhichScore: 0 .. NumberOfScores; Student: 0 .. ClassSize; Ave, TotalScore, ClassTotal, NextScore: INTEGER; Ch: CHAR; NameStudentFile: TEXT; IsOverflow: BOOLEAN; BEGIN {AverageScore} ClassTotal := 0; WRITELN('Student averages:'); Student := 0; IsOverflow := FALSE; WHILE (Student < ClassSize) AND (NOT IsOverflow) DO BEGIN WRITELN(OUTPUT, 'Enter the student''s grade soname and number'); REWRITE(NameStudentFile); READ(INPUT, Ch); IF Ch = ' ' THEN BEGIN WHILE NOT EOLN(INPUT) AND (Ch = ' ') DO READ(INPUT, Ch); WRITE(NameStudentFile, Ch) END ELSE WRITE(NameStudentFile, Ch); WHILE (NOT EOLN(INPUT)) AND (Ch <> ' ') DO BEGIN READ(INPUT, Ch); IF Ch <> ' ' THEN WRITE(NameStudentFile, Ch) END; TotalScore := 0; WhichScore := 0; WHILE (WhichScore < ClassSize) AND (NOT IsOverflow) DO BEGIN IF NOT EOLN(INPUT) THEN READ(NextScore); IsOverflow := (NextScore < MinScore) OR (NextScore > MaxScore); IF NOT IsOverflow THEN BEGIN TotalScore := TotalScore + NextScore; WhichScore := WhichScore + 1 END END; READLN(INPUT); IF NOT IsOverflow THEN BEGIN TotalScore := TotalScore * 10; Ave := TotalScore DIV NumberOfScores; WRITE(OUTPUT, 'Average rating of the '); RESET(NameStudentFile); WHILE NOT EOLN(NameStudentFile) DO BEGIN READ(NameStudentFile, Ch); WRITE(OUTPUT, Ch) END; IF Ave MOD 10 >= 5 THEN WRITELN(OUTPUT, ': is ', Ave DIV 10 + 1) ELSE WRITELN(OUTPUT, ': is ', Ave DIV 10); ClassTotal := ClassTotal + TotalScore; Student := Student + 1 END; END; WRITELN; IF IsOverflow THEN WRITELN(OUTPUT, 'NOT CORRECT DATA') ELSE BEGIN WRITELN(OUTPUT, 'Class average:'); ClassTotal := ClassTotal DIV ((ClassSize - 1) * NumberOfScores); WRITELN(OUTPUT, ClassTotal DIV 10, '.', ClassTotal MOD 10:1) END; END. {AverageScore}
(*--------------------------------------------------------*) (* Exercise 7 (BSP. 3. Quadratwurzel Verbesserung) *) (* Developer: Neuhold Michael *) (* Date: 25.11.2018 *) (* Verson: 2.0 *) (* better programming style *) (*--------------------------------------------------------*) PROGRAM Quadratwurzel; CONST max = 50; (* input of the start number and the precision *) PROCEDURE ReadNumberAndPrecision(VAR x,e: REAL); BEGIN WriteLn('Bitte den Wert für x eingaben:'); ReadLn(x); WriteLn('Bitte den Wert für e eingaben:'); ReadLn(e); END; (* One step of the newton formular *) FUNCTION ValueOfYn(x: REAL; VAR y0: REAL): REAL; BEGIN ValueOfYn := 0.5 * (y0 + (x/y0)); END; (* can the loop be leaved *) FUNCTION BooleanOfExit(yn,y0,e: REAL; i: INTEGER): BOOLEAN; BEGIN BooleanOfExit := (abs(yn-y0) < e) OR (i >= max); END; (* loop *) FUNCTION ValueOfNewtonCalc(x,e: REAL): REAL; VAR i: INTEGER; y0,yn: REAL; BEGIN i := 0; yn := 1; REPEAT y0 := yn; yn := ValueOfYn(x,y0); i := i + 1; UNTIL BooleanOfExit(yn,y0,e,i); ValueOfNewtonCalc := yn; END; VAR x,e: REAL; BEGIN ReadNumberAndPrecision(x,e); IF (x >= 0) AND (e > 0) THEN BEGIN WriteLn('Näherungswert:'); WriteLn(ValueOfNewtonCalc(x,e):10:6); END ELSE WriteLn('Error!'); END.
unit UTextEditForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls; type TNamedHandler = record Name: string; Handler: procedure of object; end; TNamedHandlers = array of TNamedHandler; TFoundStringHandler = procedure( const AFindText: string; ARow, ACol: integer; var AContinueAfterEndOfPattern: boolean) of object; TfrmTextEditor = class(TForm) pnEdit: TPanel; pnFind: TPanel; edFindText: TEdit; edReplaceBy: TEdit; btnReplace: TButton; lblFind: TLabel; lblReplaceBy: TLabel; cbReplaceSpecDelphi: TCheckBox; cbFindSpecDelphi: TCheckBox; btnExecute: TButton; lblTextLength: TLabel; cbChangeMethod: TComboBox; pnViews: TPanel; pnResult: TPanel; lblEditor: TLabel; lblResult: TLabel; lblMethod: TLabel; edArg1: TEdit; edArg2: TEdit; lblArg1: TLabel; lblArg2: TLabel; Label1: TLabel; edSpacesInTab: TEdit; Button1: TButton; lblArg3: TLabel; edArg3: TEdit; memEdit: TRichEdit; memResult: TRichEdit; edFuncName: TEdit; lmlFuncName: TLabel; procedure btnReplaceClick(Sender: TObject); procedure memEditChange(Sender: TObject); procedure btnExecuteClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure memEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edSpacesInTabKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Button1Click(Sender: TObject); procedure Button1KeyPress(Sender: TObject; var Key: Char); private { Private declarations } FHandlers: TNamedHandlers; FPatternIndex: integer; FLastRow: integer; FLastCol: integer; FRowStringForResult: string; FLettersCount: integer; function ConvertDelphiCodeToString(const ACode: string): string; function GetHandlers: TNamedHandlers; procedure UpdateTextLengthLabel; procedure FindAndHandleAllPatterns( const AFindText: string; AFoundStringHandler: TFoundStringHandler); procedure AppendIndexAndAddToResult( const AFindText: string; ARow, ACol: integer; var AContinueAfterEndOfPattern: boolean); procedure DeleteSubstrAndAddToResult( const AFindText: string; ARow, ACol: integer; var AContinueAfterEndOfPattern: boolean); function HexStrToStr(const AHexStr: string): string; //Handlers procedure ClearLineBreaksBetweenXMLCells; procedure ConvertFromDelphiStringCode; procedure ConvertToDelphiStringCode; procedure ReplaceEditBreakLinesByCodeBreakLines; procedure FindAllSubStrings; procedure GenerateAllFuncCombinations; procedure GenerateCirclingText; procedure AppendIndexForSearchWord; procedure DeleteSubstrAfterFoundWord; procedure FormatSQL; procedure FormatXMLByTabs; procedure FormatXMLTextByTabs; procedure HexTextToText; procedure HexTextToTextInXMLNode; procedure SortStringList; procedure ReplaceTabsBySpaces; procedure ToLowerCase; procedure GetMask; procedure CalcIntegerHash; procedure FormatNowByMask; procedure SortBlocksStartWith; procedure TrimWriteTptTabs; procedure ExecStringFunction; procedure InverseByteOrderHex; procedure ConvertNumberToBase; procedure ReturnDIV; procedure ReturnMOD; public { Public declarations } end; var frmTextEditor: TfrmTextEditor; implementation {$R *.dfm} uses StrUtils, Types, UBHashTable, UFunctionTextGenerator, UUtils, UTypes; procedure TfrmTextEditor.AppendIndexAndAddToResult( const AFindText: string; ARow, ACol: integer; var AContinueAfterEndOfPattern: boolean); var src: string; lastSrc: string; begin AContinueAfterEndOfPattern := true; src := memEdit.Lines[ARow]; if FLastRow <> ARow then begin if FLastRow <> -1 then begin lastSrc := memEdit.Lines[FLastRow]; memResult.Lines.Add( FRowStringForResult + Copy(lastSrc, FLastCol + Length(AFindText), Length(lastSrc))); end; FRowStringForResult := Copy(src, 1, ACol - 1); FLastRow := ARow; end else begin FRowStringForResult := FRowStringForResult + Copy( src, FLastCol + Length(AFindText), ACol - FLastCol - Length(AFindText)); end; FLastCol := ACol; FRowStringForResult := FRowStringForResult + AFindText + IntToStr(FPatternIndex); Inc(FPatternIndex); end; procedure TfrmTextEditor.AppendIndexForSearchWord; var lastSrc: string; begin if not TryStrToInt(edArg2.Text, FPatternIndex) then Exit; memResult.Clear; FLastRow := -1; FLastCol := -1; FRowStringForResult := ''; FindAndHandleAllPatterns(edArg1.Text, AppendIndexAndAddToResult); if FLastRow <> -1 then begin lastSrc := memEdit.Lines[FLastRow]; memResult.Lines.Add( FRowStringForResult + Copy(lastSrc, FLastCol + Length(edArg1.Text), Length(lastSrc))); end; end; procedure TfrmTextEditor.btnExecuteClick(Sender: TObject); begin FHandlers[cbChangeMethod.ItemIndex].Handler; end; procedure TfrmTextEditor.btnReplaceClick(Sender: TObject); var txt: string; fintTxt: string; replaceTxt: string; begin txt := memEdit.Lines.Text; fintTxt := edFindText.Text; replaceTxt := edReplaceBy.Text; if cbFindSpecDelphi.Checked then fintTxt := ConvertDelphiCodeToString(fintTxt); if cbReplaceSpecDelphi.Checked then replaceTxt := ConvertDelphiCodeToString(replaceTxt); memEdit.Lines.Text := StringReplace(txt, fintTxt, replaceTxt, [rfReplaceAll]); end; procedure TfrmTextEditor.Button1Click(Sender: TObject); begin memEdit.SelText := memResult.Text; memEdit.SetFocus; memEdit.SelStart := 0; memEdit.SelLength := Length(memResult.Text) - 1; end; procedure TfrmTextEditor.Button1KeyPress(Sender: TObject; var Key: Char); begin if Key = #9 then begin (Sender as TMemo).SelStart := 0; (Sender as TMemo).SelLength := 200; end; end; function LookupValuesAsArray(const ALookupValues: string): TStringDynArray; var sl: TStringList; i: integer; begin Result := nil; sl := TStringList.Create; try sl.Delimiter := ','; sl.QuoteChar := '"'; sl.StrictDelimiter := true; sl.DelimitedText := ALookupValues; SetLength(Result, sl.Count); for i := 0 to sl.Count - 1 do Result[i] := sl[i]; finally sl.Free; end; end; procedure TfrmTextEditor.CalcIntegerHash; var st: integer; fn: integer; i: integer; numStr: string; sum: double; k: integer; num: integer; begin if (not TryStrToInt(edArg1.Text, st)) or (not TryStrToInt(edArg2.Text, fn)) then begin memResult.Lines.Text := 'Non-integer Args!'; Exit; end; sum := 0; for i := 0 to memEdit.Lines.Count - 1 do begin numStr := Copy(memEdit.Lines[i], st, fn - st + 1); for k := 1 to Length(numStr) do begin if not TryStrToInt(numStr[k], num) then begin memResult.Lines.Text := 'Non-integer character in range!'; Exit; end; sum := sum + num; end; end; memResult.Lines.Text := FloatToStr(sum); end; procedure TfrmTextEditor.ClearLineBreaksBetweenXMLCells; var newSL: TStringList; i, k: integer; s: string; begin newSL := TStringList.Create; try for i := 0 to memEdit.Lines.Count - 1 do begin k := Pos('<tr>', memEdit.Lines[i]); if k > 0 then s := memEdit.Lines[i] else begin k := Pos('<td>', memEdit.Lines[i]); if k > 0 then s := s + Copy(memEdit.Lines[i], k, Length(memEdit.Lines[i])) else begin k := Pos('</tr>', memEdit.Lines[i]); if k > 0 then begin s := s + '</tr>'; newSL.Add(s); s := ''; end else newSL.Add(memEdit.Lines[i]); end; end; end; memEdit.Lines.Text := newSL.Text; finally newSL.Free; end; end; function TfrmTextEditor.ConvertDelphiCodeToString(const ACode: string): string; var i: integer; len: integer; isString: boolean; isSpec: boolean; codeStr: string; aposBegin: boolean; begin Result := ''; len := Length(ACode); i := 1; isString := false; isSpec := false; aposBegin := false; codeStr := ''; while i <= len do begin if isSpec then begin if ACode[i] in ['0'..'9'] then codeStr := codeStr + ACode[i] else begin Result := Result + Chr(StrToInt(codeStr)); codeStr := ''; isSpec := false; end; end; if not isSpec then begin if ACode[i] = '''' then begin if isString then if not aposBegin then aposBegin := true else begin Result := Result + ''''; aposBegin := false; end else isString := true; //isString := not isString; end else if aposBegin then begin isString := false; aposBegin := false; end else if isString then Result := Result + ACode[i]; if (not isString) and (ACode[i] = '#') then isSpec := true; end; Inc(i); end; if codeStr <> '' then Result := Result + Chr(StrToInt(codeStr)); end; procedure TfrmTextEditor.ConvertFromDelphiStringCode; var i: integer; s: string; ps: integer; prefix: string; pLen: integer; ident: string; new: string; cPos: integer; begin memResult.Clear; prefix := edArg1.Text; pLen := Length(prefix); for i := 0 to memEdit.Lines.Count - 1 do begin s := memEdit.Lines[i]; ps := Pos('''', s); if ps > 0 then System.Delete(s, ps, 1); ps := LastPos(''' +', s); if ps > 0 then System.Delete(s, ps, 3) else begin ps := LastPos('''', s); if ps > 0 then System.Delete(s, ps, 1) end; s := StringReplace(s, ''' + ', '', [rfReplaceAll]); s := StringReplace(s, ' + ''', '', [rfReplaceAll]); s := StringReplace(s, '''''', '''', [rfReplaceAll]); while true do begin ps := Pos(prefix, s); if ps = 0 then break; ident := NextIdent(s, ps, cPos); new := Copy(ident, pLen + 1, MaxInt); new := StringReplace(new, '_', '', [rfReplaceAll]); s := StringReplace(s, ident, new, [rfReplaceAll]); end; memResult.Lines.Add(s); end; end; procedure TfrmTextEditor.ConvertNumberToBase; var srcBase: integer; dstBase: integer; srcStr: string; number: TSNumber; begin srcBase := StrToIntDef(edArg1.Text, 2); dstBase := StrToIntDef(edArg2.Text, 10); srcStr := Trim(memEdit.Lines.Text); number := TSNumber.Create(srcBase, srcStr); number.ConvertTo(dstBase); memResult.Lines.Text := number.AsString; end; procedure TfrmTextEditor.ConvertToDelphiStringCode; var i: integer; s: string; begin memResult.Clear; for i := 0 to memEdit.Lines.Count - 1 do begin s := '''' + StringReplace(memEdit.Lines[i], '''', '''''', [rfReplaceAll]) + ''' +'; memResult.Lines.Add(s); end; end; procedure TfrmTextEditor.DeleteSubstrAfterFoundWord; var lastSrc: string; begin if not TryStrToInt(edArg2.Text, FLettersCount) then Exit; memResult.Clear; FLastRow := -1; FLastCol := -1; FRowStringForResult := ''; FindAndHandleAllPatterns(edArg1.Text, DeleteSubstrAndAddToResult); if FLastRow <> -1 then begin lastSrc := memEdit.Lines[FLastRow]; memResult.Lines.Add( FRowStringForResult + Copy( lastSrc, FLastCol + Length(edArg1.Text) + FLettersCount, Length(lastSrc))); end; end; procedure TfrmTextEditor.DeleteSubstrAndAddToResult( const AFindText: string; ARow, ACol: integer; var AContinueAfterEndOfPattern: boolean); var src: string; lastSrc: string; st: integer; begin AContinueAfterEndOfPattern := true; src := memEdit.Lines[ARow]; if FLastRow <> ARow then begin if FLastRow <> -1 then begin lastSrc := memEdit.Lines[FLastRow]; memResult.Lines.Add( FRowStringForResult + Copy( lastSrc, FLastCol + Length(AFindText) + FLettersCount, Length(lastSrc) )); end; FRowStringForResult := Copy(src, 1, ACol - 1); FLastRow := ARow; end else begin st := FLastCol + Length(AFindText) + FLettersCount; FRowStringForResult := FRowStringForResult + Copy(src, st, ACol - st); end; FLastCol := ACol; FRowStringForResult := FRowStringForResult + AFindText; end; procedure TfrmTextEditor.edSpacesInTabKeyDown( Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = []) or (Shift = [ssShift]) then if (not (Chr(Key) in ['0'..'9'])) or (Shift = [ssShift]) then Key := 0; end; procedure TfrmTextEditor.ExecStringFunction; var funcName: string; function isFunc(const AFuncName: string): boolean; begin Result := SameText(funcName, AFuncName); end; var src: string; res: string; begin funcName := edFuncName.Text; src := memEdit.Lines.Text; res := ''; if isFunc('LowerCase') then res := LowerCase(src) else if isFunc('UpperCase') then res := UpperCase(src); memResult.Lines.Text := res; end; procedure TfrmTextEditor.FindAndHandleAllPatterns( const AFindText: string; AFoundStringHandler: TFoundStringHandler); var i, k: integer; txt: string; lastPos: integer; continueAfterEndOfPattern: boolean; begin continueAfterEndOfPattern := false; for i := 0 to memEdit.Lines.Count - 1 do begin lastPos := 0; k := 1; while k > 0 do begin txt := Copy(memEdit.Lines[i], lastPos + 1, Length(memEdit.Lines[i])); k := Pos(AFindText, txt); if k > 0 then begin lastPos := lastPos + k; AFoundStringHandler(AFindText, i, lastPos, continueAfterEndOfPattern); if continueAfterEndOfPattern then lastPos := lastPos + Length(AFindText) - 1; end; end; end; end; procedure TfrmTextEditor.FindAllSubStrings; procedure findAllPatterns1(const AFindText: string); var i, k: integer; txt: string; lastPos: integer; was: boolean; begin was := false; for i := 0 to memEdit.Lines.Count - 1 do begin lastPos := 0; k := 1; while k > 0 do begin txt := Copy(memEdit.Lines[i], lastPos + 1, Length(memEdit.Lines[i])); k := Pos(AFindText, txt); if k > 0 then begin if not was then begin memResult.Lines.Add('Entries for "' + AFindText + '":'); was := true; end; lastPos := lastPos + k; memResult.Lines.Add( Format(#9'(%d:%d): %s', [i + 1, lastPos, memEdit.Lines[i]])); end; end; end; end; var txt: string; fintTxt: string; i, j: integer; curFindText: string; textParts: IBHashTable; begin txt := memEdit.Lines.Text; fintTxt := edFindText.Text; memResult.Clear; textParts := TBHashTable.Create; for i := 1 to Length(fintTxt) do begin for j := Length(fintTxt) downto i do begin curFindText := Copy(fintTxt, i, j - i + 1); if not textParts.Exists(curFindText) then begin findAllPatterns1(curFindText); textParts[curFindText] := 1; end; end; end; end; procedure TfrmTextEditor.FormatNowByMask; begin memResult.Lines.Text := FormatDateTime(memEdit.Lines.Text, Now); end; procedure TfrmTextEditor.FormatSQL; var sql: string; res: string; ident: string; cPos: integer; lPos: integer; begin memResult.Clear; sql := memEdit.Text; res := ''; lPos := 1; ident := NextIdent(sql, lPos, cPos); while ident <> '' do begin res := res + Copy(sql, lPos, cPos - lPos); if MatchText( ident, ['SELECT', 'FROM', 'WHERE', 'GROUP', 'UNION', 'ORDER', 'HAVING'] ) then res := res + #13#10; res := res + ident; lPos := cPos + Length(ident); ident := NextIdent(sql, lPos, cPos); end; res := res + Copy(sql, lPos, MaxInt); memResult.Text := res; end; procedure TfrmTextEditor.FormatXMLByTabs; var depth: integer; effDepth: integer; tags: TStringList; i, k, j: integer; tag: string; s: string; readTag: boolean; tagBegun: boolean; closingTag: boolean; tagContinue: boolean; bk, ek: integer; begin memResult.Clear; depth := 0; tags := TStringList.Create; try for i := 0 to memEdit.Lines.Count - 1 do begin s := memEdit.Lines[i]; k := Pos('<?xml', s); if k > 0 then effDepth := depth else begin j := 1; readTag := false; tagBegun := false; closingTag := false; tagContinue := false; bk := Pos('<', s); ek := Pos('</', s); if (bk > 0) and (bk <> ek) and (ek > 0) then effDepth := depth else if (bk > 0) and (bk <> ek) then begin effDepth := depth; Inc(depth); end else if ek > 0 then begin Dec(depth); effDepth := depth; end else effDepth := depth; end; memResult.Lines.Add(StringOfChar(#9, effDepth) + s); end; finally tags.Free; end; end; procedure TfrmTextEditor.FormatXMLTextByTabs; var depth: integer; effDepth: integer; tags: TStringList; i, k, j: integer; tag: string; s: string; readTag: boolean; tagBegun: boolean; closingTag: boolean; tagContinue: boolean; bk, ek: integer; xml: string; st: integer; begin memResult.Clear; depth := 0; tags := TStringList.Create; try xml := memEdit.Lines.Text; st := Pos('<?xml', xml); if st = 0 then st := 1 else st := Pos('>', xml) + 1; while true do begin end; for i := 0 to memEdit.Lines.Count - 1 do begin s := memEdit.Lines[i]; k := Pos('<?xml', s); if k > 0 then effDepth := depth else begin j := 1; readTag := false; tagBegun := false; closingTag := false; tagContinue := false; bk := Pos('<', s); ek := Pos('</', s); if (bk > 0) and (bk <> ek) and (ek > 0) then effDepth := depth else if (bk > 0) and (bk <> ek) then begin effDepth := depth; Inc(depth); end else if ek > 0 then begin Dec(depth); effDepth := depth; end else effDepth := depth; end; memResult.Lines.Add(StringOfChar(#9, effDepth) + s); end; finally tags.Free; end; end; procedure TfrmTextEditor.FormCreate(Sender: TObject); var i: integer; begin inherited; FHandlers := GetHandlers; cbChangeMethod.Clear; for i := Low(FHandlers) to High(FHandlers) do cbChangeMethod.AddItem(FHandlers[i].Name, nil); cbChangeMethod.ItemIndex := 0; UpdateTextLengthLabel; end; procedure TfrmTextEditor.GenerateAllFuncCombinations; var func: TFuncArg; begin func.Name := 'JOIN'; SetLength(Func.Args, 3); func.Args[0].Name := 'VAL'; SetLength(Func.Args[0].Args, 2); func.Args[0].Args[0].Name := 'VAL'; SetLength(Func.Args[0].Args[0].Args, 1); func.Args[0].Args[0].Args[0].Name := 'word_id'; func.Args[0].Args[1].Name := 'VAL'; SetLength(Func.Args[0].Args[1].Args, 1); func.Args[0].Args[1].Args[0].Name := 'word_id'; func.Args[1].Name := 'VAL'; SetLength(Func.Args[1].Args, 2); func.Args[1].Args[0].Name := 'VAL'; SetLength(Func.Args[1].Args[0].Args, 1); func.Args[1].Args[0].Args[0].Name := 'word_id'; func.Args[1].Args[1].Name := 'VAL'; SetLength(Func.Args[1].Args[1].Args, 1); func.Args[1].Args[1].Args[0].Name := 'word_id'; func.Args[2].Name := 'VAL'; SetLength(Func.Args[2].Args, 2); func.Args[2].Args[0].Name := 'VAL'; SetLength(Func.Args[2].Args[0].Args, 1); func.Args[2].Args[0].Args[0].Name := 'word_id'; func.Args[2].Args[1].Name := 'VAL'; SetLength(Func.Args[2].Args[1].Args, 1); func.Args[2].Args[1].Args[0].Name := 'word_id'; memResult.Clear; //AddAllCombinationsForFunction(func, memResult.Lines); end; procedure TfrmTextEditor.GenerateCirclingText; var i, j: integer; n: integer; c: char; s: string; sn: integer; cn: integer; spn: integer; yn: integer; begin memEdit.Clear; if edArg1.Text <> '' then c := edArg1.Text[1] else c := '1'; n := StrToIntDef(edArg2.Text, 0); memEdit.Font.Size := StrToIntDef(edArg3.Text, 8); sn := ((n + 1) * n);// div 2; s := ''; spn := 0; memEdit.Lines.Add(StringOfChar(c, sn) + StringOfChar(c, sn)); for i := n downto 0 do begin spn := spn + i; cn := sn - spn; s := StringOfChar(c, cn) + StringOfChar(' ', spn) + StringOfChar(' ', spn) + StringOfChar(c, cn); memEdit.Lines.Add(s); end; yn := 0; for i := 0 to n do begin cn := sn - spn; yn := yn + i; for j := 1 to i do begin s := StringOfChar(c, cn) + StringOfChar(' ', spn) + StringOfChar(' ', spn) + StringOfChar(c, cn); memEdit.Lines.Add(s); end; Inc(spn); end; { for i := 1 to n do begin s := s + StringOfChar(c, i); memEdit.Lines.Add(s); end; } end; function TfrmTextEditor.GetHandlers: TNamedHandlers; begin SetLength(Result, 25); Result[0].Name := 'Clear <br/> between XML cells'; Result[0].Handler := ClearLineBreaksBetweenXMLCells; Result[1].Name := 'Replace #32#10 by #10'; Result[1].Handler := ReplaceEditBreakLinesByCodeBreakLines; Result[2].Name := 'Find all substrings'; Result[2].Handler := FindAllSubStrings; Result[3].Name := 'Generate all func combinations (not work yet)'; Result[3].Handler := GenerateAllFuncCombinations; Result[4].Name := 'Append index for find word'; Result[4].Handler := AppendIndexForSearchWord; Result[5].Name := 'Delete substring after found words'; Result[5].Handler := DeleteSubstrAfterFoundWord; Result[6].Name := 'Format XML By Tabs'; Result[6].Handler := FormatXMLByTabs; Result[7].Name := 'Hex text to readable text'; Result[7].Handler := HexTextToText; Result[8].Name := 'Format SQL'; Result[8].Handler := FormatSQL; Result[9].Name := 'Generate circling text'; Result[9].Handler := GenerateCirclingText; Result[10].Name := 'Convert to delphi string code'; Result[10].Handler := ConvertToDelphiStringCode; Result[11].Name := 'Convert from delphi string code'; Result[11].Handler := ConvertFromDelphiStringCode; Result[12].Name := 'Sort string list'; Result[12].Handler := SortStringList; Result[13].Name := 'Replace TABs by spaces'; Result[13].Handler := ReplaceTabsBySpaces; Result[14].Name := 'To lower case'; Result[14].Handler := ToLowerCase; Result[15].Name := 'Get mask'; Result[15].Handler := GetMask; Result[16].Name := 'Calc integer hash'; Result[16].Handler := CalcIntegerHash; Result[17].Name := 'Format current date time by Mask'; Result[17].Handler := FormatNowByMask; Result[18].Name := 'Sort blocks which start with substring'; Result[18].Handler := SortBlocksStartWith; Result[19].Name := 'Trim write tabs in tpt'; Result[19].Handler := TrimWriteTptTabs; Result[20].Name := 'Exec string function'; Result[20].Handler := ExecStringFunction; Result[21].Name := 'Inverse byte order (HEX format)'; Result[21].Handler := InverseByteOrderHex; Result[22].Name := 'Convert Number To Base'; Result[22].Handler := ConvertNumberToBase; Result[23].Name := 'Return DIV'; Result[23].Handler := ReturnDIV; Result[24].Name := 'Return MOD'; Result[24].Handler := ReturnMOD; end; procedure TfrmTextEditor.GetMask; var s: string; res: string; i, j: integer; begin res := ''; if memEdit.Lines.Count > 0 then res := memEdit.Lines[0]; for i := 1 to memEdit.Lines.Count - 1 do begin s := memEdit.Lines[i]; for j := 1 to Length(res) do begin if res[j] <> s[j] then res[j] := '*'; end; end; memResult.Lines.Text := res; end; function TfrmTextEditor.HexStrToStr(const AHexStr: string): string; const CODE_MAPPER: array ['A'..'F'] of integer = (10, 11, 12, 13, 14, 15); function hexCharToInt(AChar: char): integer; begin if not TryStrToInt(AChar, Result) then Result := CODE_MAPPER[UpperCase(AChar)[1]]; end; function tryHexStrToChar(const AHexStr: string): boolean; begin Result := false; end; var code: integer; i: integer; begin i := 1; Result := ''; while i <= Length(AHexStr) do begin code := hexCharToInt(AHexStr[i]) * 16 + hexCharToInt(AHexStr[i + 1]); Result := Result + Chr(code); Inc(i, 2); end; end; procedure TfrmTextEditor.HexTextToText; begin memResult.Lines.Text := HexStrToStr(memEdit.Lines.Text); end; procedure TfrmTextEditor.HexTextToTextInXMLNode; var src: string; tagStart: string; tagEnd: string; st: integer; fn: integer; hexStr: string; begin if edArg1.Text = '' then Exit; src := memEdit.Lines.Text; tagStart := '<' + edArg1.Text + '>'; tagEnd := '</' + edArg1.Text + '>'; st := 1; while true do begin st := PosEx(tagStart, src, st); if st > 0 then begin fn := PosEx(tagStart, src, st); if fn > 0 then begin //TODO: end else break; end else break; end; end; procedure TfrmTextEditor.InverseByteOrderHex; procedure exchangeChars(var AStr: string; AIdx1, AIdx2: integer); var t: char; begin t := AStr[AIdx1]; AStr[AIdx1] := AStr[AIdx2]; AStr[AIdx2] := t; end; var line: string; i: integer; begin if memEdit.Lines.Count = 0 then Exit; line := memEdit.Lines[0]; if Length(line) mod 2 <> 0 then Exit; for i := 0 to Length(line) div 4 - 1 do begin exchangeChars(line, i * 2 + 1, Length(line) - i * 2 - 1); exchangeChars(line, i * 2 + 2, Length(line) - i * 2); end; memResult.Lines.Text := line; end; procedure TfrmTextEditor.memEditChange(Sender: TObject); begin UpdateTextLengthLabel; end; { qqwertyui qwert qwert jdfhjgfjh fjhkgjhkgkh fjhkfghkg fgjhgkhgk fghgh } procedure TfrmTextEditor.memEditKeyDown( Sender: TObject; var Key: Word; Shift: TShiftState); function deleteTabOrSpaces(const AStr: string): string; var tp: integer; i: integer; spInTab: integer; begin Result := AStr; if AStr = '' then Exit; tp := Pos(#9, AStr); if (tp > 0) and (Copy(AStr, 1, tp - 1) = StringOfChar(' ', tp - 1)) then begin Result := StringOfChar(' ', tp - 1) + Copy(AStr, tp + 1, Length(AStr)); end else begin spInTab := StrToIntDef(edSpacesInTab.Text, 1); i := 0; while i < spInTab do begin if AStr[i + 1] = ' ' then Inc(i) else break; end; Result := Copy(AStr, i + 1, Length(AStr)); end; end; var lines: TStringList; i: integer; //edit: TMemo; edit: TRichEdit; selStart: integer; begin edit := Sender as TRichEdit; if (Key = VK_TAB) and (edit.SelText <> '') then begin selStart := edit.SelStart; lines := TStringList.Create; try lines.Text := edit.SelText; for i := 0 to lines.Count - 1 do if Shift = [ssShift] then begin lines[i] := deleteTabOrSpaces(lines[i]); end else if Shift = [] then lines[i] := #9 + lines[i]; //edit.sel edit.SelText := lines.Text; edit.SelStart := selStart; edit.SelLength := Length(lines.Text); Key := 0; finally lines.Free; end; end; if (Chr(Key) = 'A') and (Shift = [ssCtrl])then begin edit.SelectAll; // := 0; //edit.SelLength := Length(edit.Text); Key := 0; end; end; procedure TfrmTextEditor.ReplaceEditBreakLinesByCodeBreakLines; begin memEdit.Lines.Text := StringReplace(memEdit.Lines.Text, #13#10, #10, [rfReplaceAll]); end; procedure TfrmTextEditor.ReplaceTabsBySpaces; var spCount: integer; spaces: string; begin spCount := StrToIntDef(edSpacesInTab.Text, 0); spaces := StringOfChar(' ', spCount); memResult.Lines.Text := StringReplace(memEdit.Lines.Text, #9, spaces, [rfReplaceAll]); end; procedure TfrmTextEditor.ReturnDIV; var num: integer; divider: integer; begin num := StrToIntDef(Trim(memEdit.Lines.Text), 0); divider := StrToIntDef(edArg1.Text, 1); memResult.Lines.Text := IntToStr(num div divider); end; procedure TfrmTextEditor.ReturnMOD; var num: integer; divider: integer; begin num := StrToIntDef(Trim(memEdit.Lines.Text), 0); divider := StrToIntDef(edArg1.Text, 1); memResult.Lines.Text := IntToStr(num mod divider); end; procedure TfrmTextEditor.SortBlocksStartWith; function getBlock( const ASource, ASubStr: string; AFrom: integer; out ABlock: string): integer; var ps: integer; begin ps := PosEx(ASubStr, ASource, AFrom); // if True then end; var source: string; findTxt: string; sl: TStringList; ps: integer; next: integer; block: string; firstBlock: string; res: string; begin source := memEdit.Lines.Text; findTxt := edFindText.Text; sl := TStringList.Create; try firstBlock := ''; ps := PosEx(findTxt, source, 1); if ps > 0 then firstBlock := Copy(source, 1, ps - 1); //next := 1; while ps > 0 do begin //ps := PosEx(findTxt, source, next); next := PosEx(findTxt, source, ps + 1); if next > 0 then begin block := Copy(source, ps, next - ps); sl.Add(block); ps := next; end else begin block := Copy(source, ps, System.MaxInt); sl.Add(block); Break; end; end; sl.Sort; res := firstBlock; for block in sl do res := res + block; memResult.Lines.Text := res; finally sl.Free; end; end; procedure TfrmTextEditor.SortStringList; var sl: TStringList; begin sl := TStringList.Create; try sl.Assign(memEdit.Lines); sl.CaseSensitive := true; sl.Sort; memResult.Lines.Assign(sl); finally sl.Free; end; end; procedure TfrmTextEditor.ToLowerCase; var st, fn: integer; s: string; begin st := StrToIntDef(edArg1.Text, 1); fn := StrToIntDef(edArg2.Text, MaxInt); s := memEdit.Lines.Text; memResult.Lines.Text := Copy(s, 1, st - 1) + LowerCase(Copy(s, st, fn - st + 1)); if fn <> MaxInt then memResult.Lines.Text := memResult.Lines.Text + Copy(s, fn + 1, MaxInt); end; procedure TfrmTextEditor.TrimWriteTptTabs; var i: integer; s: string; isTable: boolean; j: integer; line: TStringList; colCount: integer; begin memResult.Clear; isTable := false; line := TStringList.Create; try line.Delimiter := #9; line.StrictDelimiter := true; for i := 0 to memEdit.Lines.Count - 1 do begin s := memEdit.Lines[i]; if isTable then isTable := (Pos('[', s) <> 1); if not isTable then begin for j := Length(s) downto 1 do if s[j] = #9 then System.Delete(s, j, 1) else Break; end else begin line.DelimitedText := s; for j := line.Count - 1 downto colCount do line.Delete(j); s := line.DelimitedText; end; memResult.Lines.Add(s); if not isTable then begin isTable := (s <> '') and (Pos('//', s) <> 1) and (Pos('[', s) <> 1) and (Pos('=', s) = 0); if isTable then begin line.DelimitedText := s; colCount := line.Count; end; end; end; finally line.Free; end; end; procedure TfrmTextEditor.UpdateTextLengthLabel; begin lblTextLength.Caption := 'Length: ' + IntToStr(Length(memEdit.Lines.Text)); end; end.
unit Constants; interface uses ClassesRTTI; const { Classes supported in the database. } TPersistentClasses: array [0..3] of TClass = (CModel, CAddress, CContact, CCustomer); strDBPersistence = 'PERSISTENCE.GDB'; // Sql strings constants strCreateTable = 'create table '; strDropTable = 'drop table '; strPrimaryKey = ' not null primary key'; strInsert = 'insert into '; strValues = ' values '; strUpdate = 'update '; strSet = 'set '; strWhere = 'where '; strSelect = 'select '; strFrom = 'from '; strAnd = ' and '; strDeleteFrom = 'delete from '; strId = 'Id'; strReferences = 'references '; strConstraint = 'constraint '; strDropConstraint = 'drop constraint '; strAlterTable = 'alter table '; // Foreign Key actions strNoDeleteNoUpdate = 'on delete no action on update no action'; strDeleteCascadeUpdateCascade = 'on delete cascade on update cascade'; strNoDeleteUpdateCascade = 'on delete no action on update cascade'; strDeleteCascadeNoUpdate = 'on delete cascade on update no action'; // Special characters strOpenParenthesis = '('; strEndParenthesis = ')'; strEndQuery = ');'; strSpace = ' '; strComma = ', '; strSemiColon = ';'; strEqual = ' = '; strDot = '.'; // Prefixs strPrimaryKeyPrefix = 'prky'; strFK = 'fk'; strReferenceDNoActionUNoAction = 'dnun'; // Delete no action Update No Action strReferenceDCascadeUCascade = 'dcuc'; // Delete cascade Update cascade strReferenceDNoActionUCascade = 'dnuc'; // Delete no action Update Cascade strReferenceDCascadeUNoAction = 'dcun'; // Delete Cascade Update No Action // Prefix long PrefixLong = 4; // Property types ptInteger = 'integer'; ptString15 = 'string15'; ptString30 = 'string30'; ptString50 = 'string50'; ptPKeyInteger = 'pkInteger'; ptDouble = 'double'; // Interbase field types itInteger = 'integer'; itSmallInt = 'smallint'; itChar = 'char'; itVarChar = 'varchar(255)'; itVarChar15 = 'varchar(15)'; itVarChar30 = 'varchar(30)'; itVarChar50 = 'varchar(50)'; itNumeric = 'numeric'; itDate = 'date'; // Error codes when saving ecInsertion = -2; ecUpdate = -3; // Messages strReconstruct = 'You have to re-construct the database'; strNoConnection = 'It wasn''' + 't posible to connect to data base'; strSaveFirst = 'The customer must be previously saved'; strCreateTableError = 'Table creation Error. Probably tables have already been created'; strCommitCreateTableError = 'Table creation Error: Commit'; strParentPropListError = 'Error creating parent property list'; strSingletonCreationError = 'It has been tried to create more than one instance of provider'; implementation end.
PROGRAM Sortmeas(input,output); {Measures effeciency of various sorting routines} CONST sortlim = 1001; (* to accomodate up to 1000 records for sorting *) TYPE ET = integer; RecordType = RECORD key : ET; position: 0..sortlim END; SortArray = ARRAY [0..sortlim] OF RecordType; VAR A,B,C,D,E,F,G : SortArray; First,Last : integer; CmpCnt,SwtCnt,AsgCnt: integer; (********************************************************************) FUNCTION Init(var A: SortArray): integer; {fills the array from STDIN and returns the numbers of items as it's value} VAR Count: integer; BEGIN {Init} Count := 0; WHILE NOT EOF DO BEGIN {while} WHILE NOT EOLN DO BEGIN {while} Count := Count + 1; Read(A[Count].Key); A[Count].Position := Count; END; {while} READLN; END; {while} Init := Count; A[0].Position := 0; A[Sortlim].Position := 1001; END; {Init} (********************************************************************) PROCEDURE Print(A: Sortarray; First,Last: integer); {prints the array} VAR I: Integer; BEGIN {Print} FOR I := First TO Last DO BEGIN {For} Write(A[I].Key); Writeln(A[I].Position); END; {FOR} END; {PRINT} (*****************************************************************************) FUNCTION GT(Parm1,Parm2: ET): Boolean; {returns true if parm1>parm2} BEGIN {GT} GT := (Parm1 > Parm2); CmpCnt := CmpCnt + 2; END; {GT} (*****************************************************************************) FUNCTION LT(Parm1,Parm2: ET): Boolean; {returns true if parm1<parm2} BEGIN {LT} LT := (Parm1 < Parm2); CmpCnt := CmpCnt + 1; END; {LT} (*****************************************************************************) FUNCTION EQ(Parm1,Parm2: ET): Boolean; {returns true if parm1=PArm2} BEGIN {EQ} EQ := (Parm1 = Parm2); CmpCnt := CmpCnt + 1; END; {EQ} (*****************************************************************************) FUNCTION GE(Parm1,Parm2: ET): Boolean; {returns true if parm1>=parm2} BEGIN {GE} GE := (Parm1 >= Parm2); CmpCnt := CmpCnt + 1; END; {GE} (*****************************************************************************) FUNCTION LE(Parm1,Parm2: ET): Boolean; {returns true if parm1<=parm2} BEGIN {LE} LE := (Parm1 <= Parm2); CmpCnt := CmpCnt + 1; END; {LE} (*****************************************************************************) PROCEDURE Report(Srt,Len: integer); {prints a reports giving details of test} BEGIN {Report} IF Srt = 1 THEN BEGIN Writeln; Writeln('Method',' ','List Length',' ','Switches',' ','Assignments', ' ','Compares',' ','Assign+Compare',' ','Stable'); Write('-------------------------------------------------------'); Writeln('------------------------'); END; {if} CASE Srt OF 1 : Writeln('Bubble',' ',Len,' ',SwtCnt,' ',AsgCnt,' ', CmpCnt,' ',AsgCnt+CmpCnt); 2 : Writeln('Insert',' ',Len,' ',SwtCnt,' ',AsgCnt,' ', CmpCnt,' ',AsgCnt+CmpCnt); 3 : Writeln('Select',' ',Len,' ',SwtCnt,' ',AsgCnt,' ', CmpCnt,' ',AsgCnt+CmpCnt); 4 : Writeln('Heap ',' ',Len,' ',SwtCnt,' ',AsgCnt,' ', CmpCnt,' ',AsgCnt+CmpCnt); 5 : Writeln('Quick-R ',' ',Len,' ',SwtCnt,' ',AsgCnt,' ', CmpCnt,' ',AsgCnt+CmpCnt); 6 : Writeln('Quick -NR',' ',Len,' ',SwtCnt,' ',AsgCnt,' ', CmpCnt,' ',AsgCnt+CmpCnt); 7 : Writeln('AQuick - R',' ',Len,' ',SwtCnt,' ',AsgCnt,' ', CmpCnt,' ',AsgCnt+CmpCnt); 8 : Writeln('AQuick -NR',' ',Len,' ',SwtCnt,' ',AsgCnt,' ', CmpCnt,' ',AsgCnt+CmpCnt); 9 : Writeln('Shell',' ',Len,' ',SwtCnt,' ',AsgCnt,' ', CmpCnt,' ',AsgCnt+CmpCnt); END; {case} END; {report} (* ------------------------------------------------------------------------- *) (* Utility for almost all the sorts given below *) PROCEDURE Switch ( VAR item1, item2 : RecordType ); (* interchanges the values stored in item1 and item2 *) VAR temp : RecordType; BEGIN (* Switch *) temp := item1; item1 := item2; item2 := temp; AsgCnt := AsgCnt + 3; SwtCnt := SwtCnt + 1; END (* Switch *); (* ------------------------------------------------------------------------- *) (* BubbleSort *) PROCEDURE BubbleSort(VAR A : SortArray; first, last: integer); (* exchanges consecutive pairs of elements of A systematically and switches those that are not yet in order; it stops when no switches are done in a given pass or the last pass has been done *) VAR pass, pos, sw : integer; BEGIN (* BubbleSort *) pass := first; AsgCnt := AsgCnt + 1; REPEAT sw := 0; AsgCnt := AsgCnt + 1; Pos := First; AsgCnt := AsgCnt + 1; WHILE LE(Pos,Last+First-1) DO BEGIN {while} IF GT(A[pos].key,A[Pos+1].key) THEN BEGIN Switch( A[pos],A[pos+1] ); sw := sw+1; AsgCnt := AsgCnt + 1; END; Pos := Pos + 1; AsgCnt := AsgCnt + 1; END; {while} pass := pass+1; AsgCnt := AsgCnt + 1; UNTIL EQ(SW,0) OR GE(Pass,Last); END (* BubbleSort *); (* ------------------------------------------------------------------------- *) (* InsertSort *) PROCEDURE InsertSort(VAR A : SortArray; first, last: integer); (* with A[first] to A[pass-1] in place, it finds the right place for A[pass] relative to A[first]..A[pass-1]; it starts its search at the spot whose index is pass and goes down to the spot whose index is first; it slides the A[j]'s to the right as it goes so as to make room for the one to be inserted at the right spot *) VAR pass, pos : integer; temp : RecordType; BEGIN (* InsertSort *) A[0] := A[first-1];(* temporary storage so as not to lose A[first-1] *); AsgCnt := AsgCnt + 1; Pass := First + 1; AsgCnt := AsgCnt + 1; WHILE LE(Pass,Last) DO BEGIN temp := A[pass]; AsgCnt := AsgCnt + 1; A[first-1] := temp; AsgCnt := AsgCnt + 1; pos := pass-1; AsgCnt := AsgCnt + 1; WHILE LT(Temp.Key,A[Pos].Key) DO BEGIN (* find the right spot *) A[pos+1] := A[pos]; (* slide down while searching *) pos := pos-1; AsgCnt := AsgCnt + 2; END (* WHILE *); A[pos+1] := temp;(* put value in right spot *); A[first-1] := A[0];(* restore the value *) AsgCnt := AsgCnt + 2; Pass := Pass + 1; AsgCnt := AsgCnt + 1; END (* FOR pass *) END (* InsertSort *); (* ------------------------------------------------------------------------- *) (* SelectSort *) PROCEDURE SelectSort( VAR A : SortArray; first, last: integer); (* For each value of pass (going from first to last-1) this sort assigns to minplc the index of the item with the smallest key in the set of elements A[pos]..A[last] and then exchanges A[pass] with A[pos] *) VAR pass, minplc, pos : integer; BEGIN (* SelectSort *) Pass := First; AsgCnt := AsgCnt + 1; WHILE LE(Pass,Last-1) DO BEGIN minplc := pass+1; (* minplc is position of the current AsgCnt := AsgCnt + 1; smallest key during the search *) Pos := Pass + 2; AsgCnt := AsgCnt + 1; WHILE LE(Pos,Last) DO BEGIN IF LT(A[Pos].Key,A[Minplc].Key) THEN BEGIN minplc := Pos; AsgCnt := AsgCnt + 1; END; {if} Pos := Pos + 1; AsgCnt := AsgCnt + 1; END; {While} IF LT(A[Minplc].Key,A[Pass].Key) THEN Switch( A[minplc], A[pass] ); Pass := Pass + 1; AsgCnt := AsgCnt + 1; END (* FOR pass *) END (* SelectSort *); (* ------------------------------------------------------------------------- *) (* Heap Sort *) PROCEDURE PushDown ( VAR A : SortArray; sortstart, tmpstart, tmpfinish : integer ); (* This is the work horse in HeapSort : it essentially pushes A[tmpstart] down the tree consisting of all items from A[sortstart]..A[tmpfinish] until the partially ordered tree property is restored in A[tmpstart]..A[tmpfinish] *) VAR r : integer; (* holds coded current position of item *) BEGIN (* PushDown *) r := tmpstart-sortstart+1; AsgCnt := AsgCnt + 1; WHILE LE(R,((TmpFinish-SortStart+1) DIV 2)) DO BEGIN {while} IF EQ(R,((Tmpfinish-SortStart+1) DIV 2)) AND EQ(((Tmpfinish-SortStart+1) MOD 2),0) THEN (* A[sortstart-1 + r] has one child at place sortstart-1 + 2*r *) BEGIN IF LT(A[Sortstart-1+R].Key,A[SortStart-1+2*R].Key) THEN Switch( A[sortstart-1+r], A[sortstart-1+2*r] ); r := tmpfinish-sortstart+1 (* stop loop *); AsgCnt := AsgCnt + 1; END ELSE (* every parent has two children *) IF LT(A[sortstart-1 + r].key,A[sortstart-1 + 2*r].key) THEN IF LT(A[sortstart-1 + 2*r].key,A[sortstart-1 + 2*r+1].key) THEN (* exchange value of parent and right child *) BEGIN Switch( A[sortstart-1 + r], A[sortstart-1 + 2*r+1] ); r := 2*r+1; (* move on down *); AsgCnt := AsgCnt + 1; END ELSE (* exchange value of parent with leftchild *) BEGIN Switch( A[sortstart-1 + r], A[sortstart-1 + 2*r] ); r := 2*r; (* move on down *) AsgCnt := AsgCnt + 1; END ELSE IF LT(A[sortstart-1 + r].key,A[sortstart-1 + 2*r+1].key) THEN (* exchange value of parent and right child *) BEGIN Switch( A[sortstart-1 + r], A[sortstart-1 + 2*r+1] ); r := 2*r+1; AsgCnt := AsgCnt + 1; END ELSE (* A[sortstart-1 + r] doesn't violate the partially order tree prop *) BEGIN {else} r := tmpfinish-sortstart+1; AsgCnt := AsgCnt + 1; END; {else} END (* WHILE *) END (* PushDown *); PROCEDURE HeapSort( VAR A : SortArray; first, last: integer ); (* sorts A[first]..A[last] into non-decreasing order by pushing down the items not in the partial ordering of the tree in a systematic way.*) VAR pos : integer; (* a cursor into A *) BEGIN (* HeapSort *) Pos := (First-1) + ((Last-First+1) DIV 2); AsgCnt := AsgCnt + 1; WHILE GE(Pos,First) DO BEGIN {While} PushDown (A, first, pos, last); Pos := Pos - 1; AsgCnt := AsgCnt + 1; END; {while} Pos := Last; AsgCnt := AsgCnt + 1; WHILE GE(Pos,First+1) DO BEGIN Switch (A[first], A[pos]) (* removes minimum from the heap *); PushDown (A, first, first, pos-1); Pos := Pos - 1; AsgCnt := AsgCnt + 1; END (* FOR pos *) END (* HeapSort *); (* ------------------------------------------------------------------------- *) (* Recursive and Non Recursive QuickSort *) PROCEDURE partition( VAR A : sortarray; lo, hi : integer; VAR pivloc : integer); (* returns in A the items from A[lo] to A[hi] rearranged as follows: if lo<=i< pivloc, then A[i].key<A[pivloc].key; and if pivloc<=i<=hi, then A[pivloc].key>=A[i].key; thus the list from position lo to position hi is divided into two parts all in left part (coming before the pivloc spot) are smaller than all in right part. The place designated pivloc is a dividing value *) VAR piv : integer; (* key value *) i, lastsmall : integer; (* index values *) BEGIN (* partition *) (* pick middle as pivot and put in lo spot *) switch(A[lo], A[(lo+hi) DIV 2]); piv := A[lo].key; AsgCnt := AsgCnt + 1; (* keep track of last item in left half as things are rearranged *) lastsmall := lo; AsgCnt := AsgCnt + 1; I := Lo + 1; AsgCnt := AsgCnt + 1; WHILE LE (I,Hi) DO BEGIN {while} IF LT(A[i].key,piv) THEN BEGIN lastsmall := lastsmall+1; AsgCnt := AsgCnt + 1; switch(A[lastsmall], A[i]) END; I := I + 1; AsgCnt := AsgCnt + 1; END; {While} (* put pivot in lastsmall position *) switch(A[lo], A[lastsmall]); pivloc := lastsmall; AsgCnt := AsgCnt + 1; END (* partition *); (* recursive version *) PROCEDURE quicksort( VAR A : sortarray; first, last : integer ); (* partition the list into two halves and then call quicksort one each half to get job done *) VAR pivloc : integer; BEGIN (* quicksort *) IF LT(first,last) THEN BEGIN partition(A, first, last, pivloc); quicksort(A, first, pivloc-1); quicksort(A, pivloc+1, last) END END (* quicksort *); (*------------------------------------------------------------------------*) (* nonrecursive version of quicksort *) PROCEDURE nrquicksort ( VAR A : sortarray ; first, last : integer ); (* implements a non recursive version of quicksort with a pair of stacks that keep track of the boundaries for the partitioned sets *) CONST maxstack = 1; TYPE stacktype = ARRAY [1..maxstack] OF 0..sortlim; VAR pivloc : integer; lostack, histack : stacktype; nstack : integer; (* error : boolean; *) BEGIN nstack := 0; (* error := false; *) AsgCnt := AsgCnt + 1; REPEAT IF GT(nstack,0) THEN (* pop off the next two boundaries for partitioning *) BEGIN first := lostack[nstack]; last := histack[nstack]; nstack := nstack-1; AsgCnt := AsgCnt + 3; END; WHILE LT(first,last) (* AND (NOT error) *) DO BEGIN partition (A, first, last, pivloc); (* overflow check has been omitted since the two stacks are big enough even in worst cases IF GE(nstack,maxstack) THEN BEGIN error := true; writeln('sort terminated, stack overflow'); AsgCnt := AsgCnt + 1; END ELSE *) IF LT((pivloc-first),(last-pivloc)) THEN (* push larger sublist boundaries onto stack and do smaller list *) BEGIN nstack := nstack+1; lostack[nstack] := pivloc+1; histack[nstack] := last; last := pivloc-1; AsgCnt := AsgCnt + 4; END ELSE BEGIN nstack := nstack+1; lostack[nstack] := first; histack[nstack] := pivloc-1; first := pivloc+1; AsgCnt := AsgCnt + 4; END END (* WHILE *) UNTIL EQ(nstack,0) (* OR error *) END (* nrquicksort *); (*--------------------------------------------------------------------------*) (* alternate recursive quicksort *) FUNCTION Pivot ( VAR A : SortArray; i, j : integer ) : integer; (* returns the subscript of an array element in A[i]..A[j] whose key is the larger of the two leftmost different keys, unless all the keys of these elements are the same, in which case it returns the value of 0 *) VAR k : integer; BEGIN (* Pivot *) k := i+1; AsgCnt := AsgCnt + 1; WHILE LE(k,j) AND EQ(A[k].key,A[i].key) DO BEGIN k := k+1; AsgCnt := AsgCnt + 1; END; {while} IF EQ(k,j+1) THEN Pivot := 0 (* all keys were the same in this range *) ELSE IF GT(A[k].key,A[i].key) THEN Pivot := k ELSE (* A[k].key<A[i].key *) Pivot := i; AsgCnt := AsgCnt + 1 {for the nested if's} END (* Pivot *); FUNCTION PartitionBoundary( VAR A : SortArray; i, j, piv : integer ) : integer; (* let divider = A[piv].key at start; rearranges A[i]..A[j] so that all the A[t]'s with A[t].key<divider are on the left and all the A[t]'s with A[t].key>=divider are on the right & then returns the index of the array element that is at the boundary of the two halves of the array. *) VAR left, right : integer; BEGIN (* PartitionBoundary *) left := i; right := j; A[0] := A[piv]; AsgCnt := AsgCnt + 3; REPEAT Switch( A[left], A[right] ); WHILE LT(A[left].key,A[0].key) DO BEGIN left := left+1; AsgCnt := AsgCnt + 1; END; {while} WHILE GE(A[right].key,A[0].key) DO BEGIN right := right-1; AsgCnt := AsgCnt + 1; END; {while} UNTIL GT(left,right); PartitionBoundary := left; AsgCnt := AsgCnt + 1; END (* PartitionBoundary *); PROCEDURE AltQuickSort( VAR A : SortArray; first, last: integer); (* Sorts A from A[first] to A[last] by the partition method; calls itself recursively on each part of the partition that results. *) VAR pivindex, k : integer; BEGIN (* AltQuickSort *) pivindex := Pivot( A, first, last ); AsgCnt := AsgCnt + 1; IF NOT EQ(pivindex,0) THEN (* there are still parts of the partition to sort *) BEGIN k := PartitionBoundary( A, first, last, pivindex ); AsgCnt := AsgCnt + 1; AltQuickSort( A, first, k-1 ); (* do the left part of the partition *) AltQuickSort( A, k, last ); (* do the right part of the partition *) END END (* AltQuickSort *); (* ------------------------------------------------------------------------ *) (* Non recursive version of AltQuickSort *) PROCEDURE NrAltQuickSort( VAR A : sortarray; first, last: integer); (* Sorts A from A[first] to A[last] by the partition method; uses two stacks to keep track of ends of partitioned sets *) CONST maxstack = 1; TYPE stacktype = array [1..maxstack] OF integer; VAR pivindex, k : integer; nstack : 0..maxstack; lostack, histack : stacktype; BEGIN (* NrAltQuickSort *) nstack := 0; AsgCnt := AsgCnt + 1; REPEAT IF GT(nstack,0) THEN (* pop both stacks *) BEGIN first := lostack[nstack]; last := histack[nstack]; nstack := nstack-1; AsgCnt := AsgCnt + 3; END; pivindex := Pivot( A, first, last ); AsgCnt := AsgCnt + 1; WHILE NOT EQ(pivindex,0) DO BEGIN k := PartitionBoundary( A, first, last, pivindex ); AsgCnt := AsgCnt + 1; IF LT((k-1-first),(last-k)) THEN BEGIN nstack := nstack+1; lostack[nstack] := k; histack[nstack] := last; last := k-1; AsgCnt := AsgCnt + 4; END ELSE BEGIN nstack := nstack+1; lostack[nstack] := first; histack[nstack] := k-1; first := k; AsgCnt := AsgCnt + 4; END; pivindex := Pivot( A, first, last ); AsgCnt := AsgCnt + 1; END (* WHILE *) UNTIL EQ(nstack,0) END (* NrAltQuickSort *); (*---------------------------------------------------------------------------*) (* Shell Sort *) PROCEDURE ShellSort( VAR A : SortArray; first, last: integer); (* In each pass this sort switches successive pairs of items in A that are out of order, whose subscripts are incr apart and then cuts incr in half; it continues this process until incr reaches 0 *) VAR i, j, incr : integer; BEGIN (* ShellSort *) incr := (last-first+1) DIV 2; AsgCnt := AsgCnt + 1; WHILE GT(incr,0) DO BEGIN I := Incr + First; WHILE LE(I,Last) DO BEGIN j := i-incr; AsgCnt := AsgCnt + 1; WHILE GT(j,first-1) DO IF GT(A[j].key,A[j+incr].key) THEN BEGIN Switch( A[j], A[j+incr] ); j := j-incr; AsgCnt := AsgCnt + 1; END (* if two items are out of order *) ELSE BEGIN j := first-1; (* forces end of inner WHILE loop: no more to do *) AsgCnt := AsgCnt + 1; END; I := I + 1; END (* FOR i *); incr := ( incr DIV 2 ); AsgCnt := AsgCnt + 1; END (* WHILE *) END (* ShellSort *); (*--------------------------- MAIN ---------------------------------------*) BEGIN {SortMeas} AsgCnt := 0; SwtCnt := 0; CmpCnt := 0; Last := Init(A); B := A; C := A; D := A; e := a; f := a; g := a; First := 1; BubbleSort(A,First,Last); Report(A,First,Last); First := 1; asgcnt := 0;swtcnt:=0;cmpcnt:=0; InsertSort(b,First,Last); Writeln; Print(b,First,Last); Writeln(' Compares Switches Assign'); Writeln('Ins ',cmpcnt,' ',swtcnt,' ',asgcnt); First := 1; asgcnt:=0;swtcnt:=0;cmpcnt:=0; SelectSort(c,First,Last); Writeln; Print(C,First,Last); Writeln(' Compares Switches Assign'); Writeln('Sel ',cmpcnt,' ',swtcnt,' ',asgcnt); First := 1; asgcnt:=0;swtcnt:=0;cmpcnt:=0; HeapSort(D,First,Last); Writeln; Print(D,First,Last); Writeln(' Compares Switches Assign'); Writeln('Heap ',cmpcnt,' ',swtcnt,' ',asgcnt); First := 1; asgcnt:=0;swtcnt:=0;cmpcnt:=0; QuickSort(e,First,Last); Writeln; Print(e,First,Last); Writeln(' Compares Switches Assign'); Writeln('Quick ',cmpcnt,' ',swtcnt,' ',asgcnt); First := 1; asgcnt:=0;swtcnt:=0;cmpcnt:=0; AltQuickSort(f,First,Last); Writeln; Print(f,First,Last); Writeln(' Compares Switches Assign'); Writeln('aQuick ',cmpcnt,' ',swtcnt,' ',asgcnt); First := 1; asgcnt:=0;swtcnt:=0;cmpcnt:=0; ShellSort(g,First,Last); Writeln; Print(g,First,Last); Writeln(' Compares Switches Assign'); Writeln('shell ',cmpcnt,' ',swtcnt,' ',asgcnt); report(9,last); END. 
{***************************************************************************} { } { Delphi.Mocks } { } { Copyright (C) 2011 Vincent Parrett } { } { http://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 Delphi.Mocks.MethodData; {$I 'Delphi.Mocks.inc'} interface uses System.Rtti, System.SysUtils, System.Generics.Collections, Delphi.Mocks, Delphi.Mocks.Interfaces, Delphi.Mocks.ParamMatcher; type TSetupMethodDataParameters = record BehaviorMustBeDefined : boolean; AllowRedefineBehaviorDefinitions: boolean; IsStub: boolean; class function Create(const AIsStub: boolean; const ABehaviorMustBeDefined, AAllowRedefineBehaviorDefinitions: boolean): TSetupMethodDataParameters; static; end; TMethodData = class(TInterfacedObject,IMethodData) private FTypeName : string; FMethodName : string; FBehaviors : TList<IBehavior>; FReturnDefault : TValue; FExpectations : TList<IExpectation>; FSetupParameters: TSetupMethodDataParameters; FAutoMocker : IAutoMock; procedure MockNoBehaviourRecordHit(const Args: TArray<TValue>; const AExpectationHitCtr : Integer; const returnType : TRttiType; out Result : TValue); protected //Behaviors procedure WillReturnDefault(const returnValue : TValue); procedure WillReturnWhen(const Args: TArray<TValue>; const returnValue : TValue; const matchers : TArray<IMatcher>); procedure WillRaiseAlways(const exceptionClass : ExceptClass; const message : string); procedure WillRaiseWhen(const exceptionClass : ExceptClass; const message : string;const Args: TArray<TValue>; const matchers : TArray<IMatcher>); procedure WillExecute(const func : TExecuteFunc); procedure WillExecuteWhen(const func : TExecuteFunc; const Args: TArray<TValue>; const matchers : TArray<IMatcher>); function FindBehavior(const behaviorType : TBehaviorType; const Args: TArray<TValue>) : IBehavior; overload; function FindBehavior(const behaviorType : TBehaviorType) : IBehavior; overload; function FindBestBehavior(const Args: TArray<TValue>) : IBehavior; procedure RecordHit(const Args: TArray<TValue>; const returnType : TRttiType; const method : TRttiMethod; out Result : TValue); //Expectations function FindExpectation(const expectationType : TExpectationType; const Args: TArray<TValue>) : IExpectation;overload; function FindExpectation(const expectationTypes : TExpectationTypes) : IExpectation;overload; procedure OnceWhen(const Args : TArray<TValue>; const matchers : TArray<IMatcher>); procedure Once; procedure NeverWhen(const Args : TArray<TValue>; const matchers : TArray<IMatcher>); procedure Never; procedure AtLeastOnceWhen(const Args : TArray<TValue>; const matchers : TArray<IMatcher>); procedure AtLeastOnce; procedure AtLeastWhen(const times : Cardinal; const Args : TArray<TValue>; const matchers : TArray<IMatcher>); procedure AtLeast(const times : Cardinal); procedure AtMostWhen(const times : Cardinal; const Args : TArray<TValue>; const matchers : TArray<IMatcher>); procedure AtMost(const times : Cardinal); procedure BetweenWhen(const a,b : Cardinal; const Args : TArray<TValue>; const matchers : TArray<IMatcher>); procedure Between(const a,b : Cardinal); procedure ExactlyWhen(const times : Cardinal; const Args : TArray<TValue>; const matchers : TArray<IMatcher>); procedure Exactly(const times : Cardinal); procedure BeforeWhen(const ABeforeMethodName : string ; const Args : TArray<TValue>; const matchers : TArray<IMatcher>); procedure Before(const ABeforeMethodName : string); procedure AfterWhen(const AAfterMethodName : string;const Args : TArray<TValue>; const matchers : TArray<IMatcher>); procedure After(const AAfterMethodName : string); function Verify(var report : string) : boolean; procedure ResetCalls; procedure ClearExpectations; public constructor Create(const ATypeName : string; const AMethodName : string; const ASetupParameters: TSetupMethodDataParameters; const AAutoMocker : IAutoMock = nil); destructor Destroy;override; end; {$IFNDEF DELPHI_XE_UP} ENotImplemented = class(Exception); {$ENDIF} implementation uses System.TypInfo, Delphi.Mocks.Utils, Delphi.Mocks.Behavior, Delphi.Mocks.Expectation, Delphi.Mocks.Helpers; { TMethodData } procedure TMethodData.ClearExpectations; begin FExpectations.Clear; end; constructor TMethodData.Create(const ATypeName : string; const AMethodName : string; const ASetupParameters: TSetupMethodDataParameters; const AAutoMocker : IAutoMock = nil); begin FTypeName := ATypeName; FMethodName := AMethodName; FBehaviors := TList<IBehavior>.Create; FExpectations := TList<IExpectation>.Create; FReturnDefault := TValue.Empty; FSetupParameters := ASetupParameters; FAutoMocker := AAutoMocker; end; destructor TMethodData.Destroy; begin FBehaviors.Free; FExpectations.Free; inherited; end; procedure TMethodData.Exactly(const times: Cardinal); var expectation : IExpectation; begin expectation := FindExpectation([TExpectationType.Exactly,TExpectationType.ExactlyWhen]); if (expectation <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockException.Create(Format('[%s] already defines Expectation Exactly for method [%s]', [FTypeName, FMethodName])) else if expectation <> nil then FExpectations.Remove(expectation); expectation := TExpectation.CreateExactly(FMethodName,times); FExpectations.Add(expectation); end; procedure TMethodData.ExactlyWhen(const times: Cardinal; const Args: TArray<TValue>; const matchers : TArray<IMatcher>); var expectation : IExpectation; begin expectation := FindExpectation(TExpectationType.ExactlyWhen,Args); if (expectation <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockException.Create(Format('[%s] already defines Expectation Exactly for method [%s] with args.', [FTypeName, FMethodName])) else if expectation <> nil then FExpectations.Remove(expectation); expectation := TExpectation.CreateExactlyWhen(FMethodName, times, Args, matchers); FExpectations.Add(expectation); end; function TMethodData.FindBehavior(const behaviorType: TBehaviorType; const Args: TArray<TValue>): IBehavior; var behavior : IBehavior; begin result := nil; for behavior in FBehaviors do begin if behavior.BehaviorType = behaviorType then begin if behavior.Match(Args) then begin result := behavior; exit; end; end; end; end; function TMethodData.FindBehavior(const behaviorType: TBehaviorType): IBehavior; var behavior : IBehavior; begin result := nil; for behavior in FBehaviors do begin if behavior.BehaviorType = behaviorType then begin result := behavior; exit; end; end; end; function TMethodData.FindBestBehavior(const Args: TArray<TValue>): IBehavior; begin //First see if we have an always throws; result := FindBehavior(TBehaviorType.WillRaiseAlways); if Result <> nil then exit; result := FindBehavior(TBehaviorType.WillRaise, Args); if Result <> nil then exit; //then find an always execute result := FindBehavior(TBehaviorType.WillExecute); if Result <> nil then exit; result := FindBehavior(TBehaviorType.WillExecuteWhen,Args); if Result <> nil then exit; result := FindBehavior(TBehaviorType.WillReturn,Args); if Result <> nil then exit; result := FindBehavior(TBehaviorType.ReturnDefault,Args); if Result <> nil then exit; result := nil; end; function TMethodData.FindExpectation(const expectationType : TExpectationType; const Args: TArray<TValue>): IExpectation; var expectation : IExpectation; begin result := nil; for expectation in FExpectations do begin if expectation.ExpectationType = expectationType then begin if expectation.Match(Args) then begin result := expectation; exit; end; end; end; end; function TMethodData.FindExpectation(const expectationTypes : TExpectationTypes): IExpectation; var expectation : IExpectation; begin result := nil; for expectation in FExpectations do begin if expectation.ExpectationType in expectationTypes then begin result := expectation; exit; end; end; end; procedure TMethodData.MockNoBehaviourRecordHit(const Args: TArray<TValue>; const AExpectationHitCtr : Integer; const returnType: TRttiType; out Result: TValue); var behavior : IBehavior; mock : IProxy; begin Result := TValue.Empty; //If auto mocking has been turned on and this return type is either a class or interface, mock it. if FAutoMocker <> nil then begin //TODO: Add more options for how to handle properties and procedures. if returnType = nil then Exit; case returnType.TypeKind of tkClass, tkRecord, tkInterface: begin mock := FAutoMocker.Mock(returnType.Handle); result := TValue.From<IProxy>(mock); //Add a behaviour to return the value next time. behavior := TBehavior.CreateWillReturnWhen(Args, Result, TArray<IMatcher>.Create()); FBehaviors.Add(behavior); end else Result := FReturnDefault; end; Exit; end; //If we have no return type defined, and the default return type is empty if (returnType <> nil) and (FReturnDefault.IsEmpty) and (not FSetupParameters.IsStub) then //Say we didn't have a default return value raise EMockException.Create(Format('[%s] has no default return value or return type was defined for method [%s]', [FTypeName, FMethodName])); //If we have either a return type, or a default return value then check whether behaviour must be defined. if FSetupParameters.BehaviorMustBeDefined and (AExpectationHitCtr = 0) and (FReturnDefault.IsEmpty) then //If we must have default behaviour defined, and there was nothing defined raise a mock exception. raise EMockException.Create(Format('[%s] has no behaviour or expectation defined for method [%s]', [FTypeName, FMethodName])); Result := FReturnDefault; end; procedure TMethodData.After(const AAfterMethodName: string); begin raise ENotImplemented.Create('After not implented'); end; procedure TMethodData.AfterWhen(const AAfterMethodName: string; const Args: TArray<TValue>; const matchers : TArray<IMatcher>); begin raise ENotImplemented.Create('AfterWhen not implented'); end; procedure TMethodData.AtLeast(const times: Cardinal); var expectation : IExpectation; begin expectation := FindExpectation([TExpectationType.AtLeast,TExpectationType.AtLeastOnce,TExpectationType.AtLeastOnceWhen,TExpectationType.AtLeastWhen]); if (expectation <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockException.Create(Format('[%s] already defines Expectation At Least for method [%s]', [FTypeName, FMethodName])) else if expectation <> nil then FExpectations.Remove(expectation); expectation := TExpectation.CreateAtLeast(FMethodName,times); FExpectations.Add(expectation); end; procedure TMethodData.AtLeastOnce; var expectation : IExpectation; begin expectation := FindExpectation([TExpectationType.AtLeast,TExpectationType.AtLeastOnce,TExpectationType.AtLeastOnceWhen,TExpectationType.AtLeastWhen]); if (expectation <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockException.Create(Format('[%s] already defines Expectation At Least Once for method [%s]', [FTypeName, FMethodName])) else if expectation <> nil then FExpectations.Remove(expectation); expectation := TExpectation.CreateAtLeastOnce(FMethodName); FExpectations.Add(expectation); end; procedure TMethodData.AtLeastOnceWhen(const Args: TArray<TValue>; const matchers : TArray<IMatcher>); var expectation : IExpectation; begin expectation := FindExpectation(TExpectationType.AtLeastOnceWhen,Args); if (expectation <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockException.Create(Format('[%s] already defines Expectation At Least Once When for method [%s]', [FTypeName, FMethodName])) else if expectation <> nil then FExpectations.Remove(expectation); expectation := TExpectation.CreateAtLeastOnceWhen(FMethodName, Args, matchers); FExpectations.Add(expectation); end; procedure TMethodData.AtLeastWhen(const times: Cardinal; const Args: TArray<TValue>; const matchers : TArray<IMatcher>); var expectation : IExpectation; begin expectation := FindExpectation(TExpectationType.AtLeastWhen,Args); if (expectation <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockException.Create(Format('[%s] already defines Expectation At Least When for method [%s]', [FTypeName, FMethodName])) else if expectation <> nil then FExpectations.Remove(expectation); expectation := TExpectation.CreateAtLeastWhen(FMethodName, times, Args, matchers); FExpectations.Add(expectation); end; procedure TMethodData.AtMost(const times: Cardinal); var expectation : IExpectation; begin expectation := FindExpectation([TExpectationType.AtMost,TExpectationType.AtMostWhen]); if (expectation <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockException.Create(Format('[%s] already defines Expectation At Most for method [%s]', [FTypeName, FMethodName])) else if expectation <> nil then FExpectations.Remove(expectation); expectation := TExpectation.CreateAtMost(FMethodName, times); FExpectations.Add(expectation); end; procedure TMethodData.AtMostWhen(const times: Cardinal; const Args: TArray<TValue>; const matchers : TArray<IMatcher>); var expectation : IExpectation; begin expectation := FindExpectation(TExpectationType.AtMostWhen,Args); if (expectation <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockException.Create(Format('[%s] already defines Expectation At Most When for method [%s]', [FTypeName, FMethodName])) else if expectation <> nil then FExpectations.Remove(expectation); expectation := TExpectation.CreateAtMostWhen(FMethodName, times, Args, matchers); FExpectations.Add(expectation); end; procedure TMethodData.Before(const ABeforeMethodName: string); begin raise ENotImplemented.Create('Before not implented'); end; procedure TMethodData.BeforeWhen(const ABeforeMethodName: string; const Args: TArray<TValue>; const matchers : TArray<IMatcher>); begin raise ENotImplemented.Create('BeforeWhen not implented'); end; procedure TMethodData.Between(const a, b: Cardinal); var expectation : IExpectation; begin expectation := FindExpectation([TExpectationType.Between,TExpectationType.BetweenWhen]); if (expectation <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockException.Create(Format('[%s] already defines Expectation Between for method [%s]', [FTypeName, FMethodName])) else if expectation <> nil then FExpectations.Remove(expectation); expectation := TExpectation.CreateBetween(FMethodName,a,b); FExpectations.Add(expectation); end; procedure TMethodData.BetweenWhen(const a, b: Cardinal;const Args: TArray<TValue>; const matchers : TArray<IMatcher>); var expectation : IExpectation; begin expectation := FindExpectation(TExpectationType.BetweenWhen,Args); if (expectation <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockException.Create(Format('[%s] already defines Expectation Between When for method [%s]', [FTypeName, FMethodName])) else if expectation <> nil then FExpectations.Remove(expectation); expectation := TExpectation.CreateBetweenWhen(FMethodName, a, b, Args, matchers); FExpectations.Add(expectation); end; procedure TMethodData.Never; var expectation : IExpectation; begin expectation := FindExpectation([TExpectationType.Never ,TExpectationType.NeverWhen]); if (expectation <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockException.Create(Format('[%s] already defines Expectation Never for method [%s]', [FTypeName, FMethodName])) else if expectation <> nil then FExpectations.Remove(expectation); expectation := TExpectation.CreateNever(FMethodName); FExpectations.Add(expectation); end; procedure TMethodData.NeverWhen(const Args: TArray<TValue>; const matchers : TArray<IMatcher>); var expectation : IExpectation; begin expectation := FindExpectation(TExpectationType.NeverWhen,Args); if (expectation <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockException.Create(Format('[%s] already defines Expectation Never When for method [%s]', [FTypeName, FMethodName])) else if expectation <> nil then FExpectations.Remove(expectation); expectation := TExpectation.CreateNeverWhen(FMethodName, Args, matchers); FExpectations.Add(expectation); end; procedure TMethodData.Once; var expectation : IExpectation; begin expectation := FindExpectation([TExpectationType.Once,TExpectationType.OnceWhen]); if (expectation <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockException.Create(Format('[%s] already defines Expectation Once for method [%s]', [FTypeName, FMethodName])) else if expectation <> nil then FExpectations.Remove(expectation); expectation := TExpectation.CreateOnce(FMethodName); FExpectations.Add(expectation); end; procedure TMethodData.OnceWhen(const Args: TArray<TValue>; const matchers : TArray<IMatcher>); var expectation : IExpectation; begin expectation := FindExpectation(TExpectationType.OnceWhen,Args); if (expectation <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockException.Create(Format('[%s] already defines Expectation Once When for method [%s]', [FTypeName, FMethodName])) else if expectation <> nil then FExpectations.Remove(expectation); expectation := TExpectation.CreateOnceWhen(FMethodName, Args, matchers); FExpectations.Add(expectation); end; procedure TMethodData.RecordHit(const Args: TArray<TValue>; const returnType : TRttiType; const method : TRttiMethod; out Result: TValue); var behavior : IBehavior; expectation : IExpectation; expectationHitCtr: integer; returnValue : TValue; begin expectationHitCtr := 0; for expectation in FExpectations do begin if expectation.Match(Args) then begin expectation.RecordHit; inc(expectationHitCtr); end; end; behavior := FindBestBehavior(Args); if behavior <> nil then returnValue := behavior.Execute(Args, returnType) else begin if FSetupParameters.IsStub or (method = nil) or method.IsAbstract or (not method.IsVirtual) then MockNoBehaviourRecordHit(Args, expectationHitCtr, returnType, returnValue); // else // if (method = nil) or method.IsAbstract or (not method.IsVirtual) then // MockNoBehaviourRecordHit(Args, expectationHitCtr, returnType, returnValue); end; if returnType <> nil then Result := returnValue; end; procedure TMethodData.ResetCalls; var expectation : IExpectation; begin for expectation in FExpectations do begin expectation.ResetCalls; end; end; function TMethodData.Verify(var report : string) : boolean; var expectation : IExpectation; begin result := true; report := ''; for expectation in FExpectations do begin if not expectation.ExpectationMet then begin result := False; if report <> '' then report := report + #13#10 + ' ' else report := ' '; report := report + expectation.Report; end; end; if not result then report := ' Method : ' + FMethodName + #13#10 + report; end; //Behaviors procedure TMethodData.WillExecute(const func: TExecuteFunc); var behavior : IBehavior; begin behavior := FindBehavior(TBehaviorType.WillExecute); if (behavior <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockSetupException.Create(Format('[%s] already defines WillExecute for method [%s]', [FTypeName, FMethodName])) else if behavior <> nil then FBehaviors.Remove(behavior); behavior := TBehavior.CreateWillExecute(func); FBehaviors.Add(behavior); end; procedure TMethodData.WillExecuteWhen(const func: TExecuteFunc;const Args: TArray<TValue>; const matchers : TArray<IMatcher>); var behavior : IBehavior; begin behavior := FindBehavior(TBehaviorType.WillExecuteWhen,Args); if (behavior <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockSetupException.Create(Format('[%s] already defines WillExecute When for method [%s]', [FTypeName, FMethodName])) else if behavior <> nil then FBehaviors.Remove(behavior); behavior := TBehavior.CreateWillExecuteWhen(Args, func, matchers); FBehaviors.Add(behavior); end; procedure TMethodData.WillRaiseAlways(const exceptionClass: ExceptClass; const message : string); var behavior : IBehavior; begin behavior := FindBehavior(TBehaviorType.WillRaiseAlways); if (behavior <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockSetupException.Create(Format('[%s] already defines Will Raise Always for method [%s]', [FTypeName, FMethodName])) else if behavior <> nil then FBehaviors.Remove(behavior); behavior := TBehavior.CreateWillRaise(exceptionClass, message); FBehaviors.Add(behavior); end; procedure TMethodData.WillRaiseWhen(const exceptionClass: ExceptClass; const message : string; const Args: TArray<TValue>; const matchers : TArray<IMatcher>); var behavior : IBehavior; begin behavior := FindBehavior(TBehaviorType.WillRaise,Args); if (behavior <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockSetupException.Create(Format('[%s] already defines Will Raise When for method [%s]', [FTypeName, FMethodName])) else if behavior <> nil then FBehaviors.Remove(behavior); behavior := TBehavior.CreateWillRaiseWhen(Args,exceptionClass, message, matchers); FBehaviors.Add(behavior); end; procedure TMethodData.WillReturnDefault(const returnValue: TValue); begin if (not FReturnDefault.IsEmpty) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockSetupException.Create(Format('[%s] already defines Will Return Default for method [%s]', [FTypeName, FMethodName])); FReturnDefault := returnValue; end; procedure TMethodData.WillReturnWhen(const Args: TArray<TValue>; const returnValue: TValue; const matchers : TArray<IMatcher>); var behavior : IBehavior; begin behavior := FindBehavior(TBehaviorType.WillReturn,Args); if (behavior <> nil) AND (not FSetupParameters.AllowRedefineBehaviorDefinitions) then raise EMockSetupException.Create(Format('[%s] already defines Will Return When for method [%s]', [FTypeName, FMethodName])) else if behavior <> nil then FBehaviors.Remove(behavior); behavior := TBehavior.CreateWillReturnWhen(Args, returnValue, matchers); FBehaviors.Add(behavior); end; { TSetupMethodDataParameters } class function TSetupMethodDataParameters.Create(const AIsStub: boolean; const ABehaviorMustBeDefined, AAllowRedefineBehaviorDefinitions: boolean): TSetupMethodDataParameters; begin result.IsStub := AIsStub; result.BehaviorMustBeDefined := ABehaviorMustBeDefined; result.AllowRedefineBehaviorDefinitions := AAllowRedefineBehaviorDefinitions; end; end.
unit Project87.Scenes.Game; interface uses QuadEngine, QCore.Input, QEngine.Camera, QEngine.Texture, QGame.Scene, Strope.Math, Project87.Types.GameObject, Project87.Types.Starmap, Project87.Types.HeroInterface, Project87.Resources, Project87.Hero; type TGameScene = class sealed (TScene) strict private FMainCamera: IQuadCamera; FInterface: THeroInterface; FUnavailableBuffer: IQuadTexture; FUnavailableShader: IQuadShader; FUnCenter: array [0..1] of Single; FUnRadius, FNeedUnRadius: Single; FUnRatio: array [0..1] of Single; FHero: THero; FObjectManager: TObjectManager; FResource: TGameResources; FStartAnimation: Single; FShowMap: Single; FSystemResult: TStarSystemResult; FHeroShip: THeroShip; procedure SetupShader; procedure UpdateStartAnimation(const ADelta: Double); procedure ShowLocalMap; procedure PrepareConstrainData; procedure DrawConstrain; procedure BackToMap; public constructor Create(const AName: string); destructor Destroy; override; procedure OnInitialize(AParameter: TObject = nil); override; procedure OnUpdate(const ADelta: Double); override; procedure OnDraw(const ALayer: Integer); override; function OnKeyUp(AKey: TKeyButton): Boolean; override; end; implementation uses Math, SysUtils, QEngine.Core, QGame.Game, QGame.Resources, Project87.Asteroid, Project87.Fluid, Project87.BaseUnit, Project87.BaseEnemy, Project87.BigEnemy, Project87.SmallEnemy, Project87.Types.SystemGenerator, QApplication.Application, Project87.Types.StarFon; {$REGION ' TGameScene '} constructor TGameScene.Create(const AName: string); begin inherited Create(AName); FObjectManager := TObjectManager.GetInstance; FResource := TGameResources.Create; FMainCamera := TheEngine.CreateCamera; FHero := THero.GetInstance; FInterface := THeroInterface.Create(FHero); FUnavailableBuffer := (TheResourceManager.GetResource('Image', 'UnavailableBuffer') as TTextureResource).Texture; SetupShader; end; destructor TGameScene.Destroy; begin FreeAndNil(FObjectManager); FreeAndNil(FResource); inherited; end; procedure TGameScene.SetupShader; begin TheDevice.CreateShader(FUnavailableShader); FUnavailableShader.LoadPixelShader('..\data\shd\unavailable.bin'); FUnavailableShader.BindVariableToPS(1, @FUnRadius, 1); FUnavailableShader.BindVariableToPS(2, @FUnRatio, 1); FUnavailableShader.BindVariableToPS(3, @FUnCenter, 1); FNeedUnRadius := 1; FUnRadius := FNeedUnRadius; FUnCenter[0] := 0.5; FUnCenter[1] := 0.5; FUnRatio[0] := TheEngine.CurrentResolution.X / TheEngine.CurrentResolution.Y; FUnRatio[1] := 1; end; procedure TGameScene.OnInitialize(AParameter: TObject); var UnitSide: TLifeFraction; begin TheEngine.Camera := FMainCamera; FStartAnimation := 1; FShowMap := 1; TObjectManager.GetInstance.ClearObjects(); FHeroShip := THeroShip.CreateUnit(ZeroVectorF, Random(360), lfGreen); if (AParameter is TStarSystem) then TSystemGenerator.GenerateSystem(FHeroShip, TStarSystem(AParameter)); if (AParameter is TStarSystem) then begin case (AParameter as TStarSystem).Size of ssSmall: FNeedUnRadius := 1.1 * 3300 * 0.6 / FMainCamera.Resolution.Y; ssMedium: FNeedUnRadius := 1.1 * 3300 * 1 / FMainCamera.Resolution.Y; ssBig: FNeedUnRadius := 1.1 * 3300 * 1.3 / FMainCamera.Resolution.Y; end; FUnRadius := FNeedUnRadius; end; end; procedure TGameScene.OnUpdate(const ADelta: Double); begin THero.GetInstance.UpdateTransPower(3 * ADelta); UpdateStartAnimation(ADelta); ShowLocalMap(); FObjectManager.OnUpdate(ADelta); end; procedure TGameScene.OnDraw(const ALayer: Integer); var I: Integer; begin TheEngine.Camera := nil; TheRender.Rectangle(0, 0, TheEngine.CurrentResolution.X, TheEngine.CurrentResolution.Y, $FF000000); TheRender.SetBlendMode(qbmSrcAlpha); TStarFon.Instance.Draw; DrawConstrain; TheEngine.Camera := FMainCamera; FObjectManager.OnDraw; //Передавай камеру как-нибудь по другому в апдейт. FInterface.OnDraw; TheEngine.Camera := FMainCamera; end; function TGameScene.OnKeyUp(AKey: Word): Boolean; var I: Word; AEnemies: array [0..LIFEFRACTION_COUNT - 1] of Single; AResources: Project87.Types.StarMap.TResources; begin Result := False; if AKey = KB_E then THero.GetInstance.RecoveryHealth; if (AKey = KB_BACKSPACE) or (AKey = KB_ESC) then BackToMap; if THero.GetInstance.IsDead and (AKey = KB_SPACE) then BackToMap; end; procedure TGameScene.UpdateStartAnimation(const ADelta: Double); begin if (FStartAnimation > 0) then begin FStartAnimation := FStartAnimation - ADelta * 2; FMainCamera.Scale := Vec2F( 1 - FStartAnimation * FStartAnimation * 0.8, 1 - FStartAnimation * FStartAnimation * 0.8); if (FStartAnimation <= 0) then begin FStartAnimation := 0; FMainCamera.Scale := Vec2F(1, 1); end; end; end; procedure TGameScene.ShowLocalMap; begin if (TheControlState.Keyboard.IsKeyPressed[KB_TAB]) then begin if (FShowMap > 0.1) then begin FShowMap := FShowMap * 0.85; if FShowMap < 0.1 then FShowMap := 0.1; FMainCamera.Scale := Vec2F(FShowMap, FShowMap); end; end else if (FShowMap < 1) then begin FShowMap := FShowMap * 1.1; if FShowMap > 1 then FShowMap := 1; FMainCamera.Scale := Vec2F(FShowMap, FShowMap); end; end; procedure TGameScene.PrepareConstrainData; var ACenter: TVectorF; begin ACenter := FMainCamera.GetScreenPos(ZeroVectorF); ACenter := ACenter.ComponentwiseDivide(FMainCamera.Resolution); FUnCenter[0] := ACenter.X; FUnCenter[1] := ACenter.Y; FUnRadius := FNeedUnRadius * FMainCamera.Scale.X; end; procedure TGameScene.DrawConstrain; begin PrepareConstrainData; FUnavailableShader.SetShaderState(True); TheEngine.Camera := nil; FUnavailableBuffer.Draw(0, 0, $18FF6060); FUnavailableShader.SetShaderState(False); end; procedure TGameScene.BackToMap; var I: Word; AEnemies: Project87.Types.StarMap.TEnemies; AResources: Project87.Types.StarMap.TResources; begin THero.GetInstance.RebornPlayer; AEnemies := TSystemGenerator.GetLastEnemies; AResources := TSystemGenerator.GetRemainingResources; FSystemResult := TStarSystemResult.Create(AEnemies, AResources); TheSceneManager.MakeCurrent('StarMap'); TheSceneManager.OnInitialize(FSystemResult); FSystemResult := nil; end; {$ENDREGION} end.
program bob4; {$IFNDEF HASAMIGA} {$FATAL This source is compatible with Amiga, AROS and MorphOS only !} {$ENDIF} {$MODE OBJFPC}{$H+}{$HINTS ON} {$UNITPATH ../../../Base/CHelpers} {$UNITPATH ../../../Base/Trinity} {$UNITPATH ../../../Base/Sugar} {$IFDEF AMIGA} {$UNITPATH ../../../Sys/Amiga} {$ENDIF} {$IFDEF AROS} {$UNITPATH ../../../Sys/AROS} {$ENDIF} {$IFDEF MORPHOS} {$UNITPATH ../../../Sys/MorphOS} {$ENDIF} { =========================================================================== Project : bob4 Topic : Example of how to implement drag and drop Author : Thomas Rapp Source : http://thomas-rapp.homepage.t-online.de/examples/bob4.c =========================================================================== This example was originally written in c by Thomas Rapp. The original examples are available online and published at Thomas Rapp's website (http://thomas-rapp.homepage.t-online.de/examples) The c-sources were converted to Free Pascal, and (variable) names and comments were translated from German into English as much as possible. Free Pascal sources were adjusted in order to support the following targets out of the box: - Amiga-m68k, AROS-i386 and MorphOS-ppc In order to accomplish that goal, some use of support units is used that aids compilation in a more or less uniform way. Conversion to Free Pascal and translation was done by Magorium in 2015, with kind permission from Thomas Rapp to be able to publish. =========================================================================== Unless otherwise noted, you must consider these examples to be copyrighted by their respective owner(s) =========================================================================== } //*-------------------------------------------------------------------------*/ //* System Includes */ //*-------------------------------------------------------------------------*/ Uses Exec, AmigaDOS, AGraphics, CyberGraphics, Intuition, inputEvent, Utility, {$IFDEF AMIGA} systemvartags, {$ENDIF} CHelpers, Trinity; function ifthen(val: Boolean; const iftrue: Integer; const iffalse: Integer = 0): Integer; overload; begin if val then result := iftrue else result := iffalse; end; //*-------------------------------------------------------------------------*/ //* Constants and macros */ //*-------------------------------------------------------------------------*/ const WINX = 80; WINY = 40; WINW = 200; WINH = 100; BOBW = 80; BOBH = 40; BOBMINX = 40; BOBMINY = 20; BOBMAXX = (BOBMINX + BOBW - 1); BOBMAXY = (BOBMINY + BOBH - 1); //*-------------------------------------------------------------------------*/ //* Type definitions */ //*-------------------------------------------------------------------------*/ Type Pbob = ^Tbob; Tbob = record rp : PRastPort; x : SmallInt; y : SmallInt; w : SmallInt; h : SmallInt; bm : PBitMap; backx : SmallInt; backy : SmallInt; backw : SmallInt; backh : SmallInt; back : PBitMap; end; //*-------------------------------------------------------------------------*/ //* Global variables */ //*-------------------------------------------------------------------------*/ //*-------------------------------------------------------------------------*/ //* Prototypes */ //*-------------------------------------------------------------------------*/ //*-------------------------------------------------------------------------*/ //* */ //*-------------------------------------------------------------------------*/ procedure cut_bob(bob: Pbob; rp: PRastPort; x: LongInt; y: LongInt); var temprp : TRastPort; begin if assigned(bob) then begin InitRastPort(@temprp); temprp.BitMap := bob^.bm; ClipBlit(rp, x, y, @temprp, 0, 0, bob^.w, bob^.h, $C0); end; end; //*-------------------------------------------------------------------------*/ //* */ //*-------------------------------------------------------------------------*/ procedure remove_bob(bob: Pbob); begin if assigned(bob) then if assigned(bob^.rp) then begin BltBitMap(bob^.back, bob^.backx, bob^.backy, bob^.rp^.BitMap, bob^.x + bob^.backx, bob^.y + bob^.backy, bob^.backw, bob^.backh, $C0, $FF, nil); bob^.rp := nil; end; end; //*-------------------------------------------------------------------------*/ //* */ //*-------------------------------------------------------------------------*/ procedure add_bob(rp: PRastPort; bob: Pbob); var scrw, scrh, x, y: LongInt; begin if assigned(bob) then begin if assigned(bob^.rp) then remove_bob(bob); bob^.rp := rp; bob^.backw := bob^.w; bob^.backh := bob^.h; scrw := GetBitMapAttr(rp^.BitMap, BMA_WIDTH); scrh := GetBitMapAttr(rp^.BitMap, BMA_HEIGHT); if ((bob^.x + bob^.backw) > scrw) then bob^.backw := scrw - bob^.x; if ((bob^.y + bob^.backh) > scrh) then bob^.backh := scrh - bob^.y; bob^.backx := 0; bob^.backy := 0; if (bob^.x < 0) then begin bob^.backx := -bob^.x; bob^.backw := bob^.backw - bob^.backx; end; if (bob^.y < 0) then begin bob^.backy := -bob^.y; bob^.backh := bob^.backh - bob^.backy; end; x := bob^.x + bob^.backx; y := bob^.y + bob^.backy; BltBitMap(rp^.BitMap, x, y, bob^.back , bob^.backx, bob^.backy, bob^.backw, bob^.backh, $C0, $ff, nil); BltBitMap(bob^.bm , bob^.backx, bob^.backy, rp^.BitMap, x, y, bob^.backw, bob^.backh, $C0, $ff, nil); end; end; //*-------------------------------------------------------------------------*/ //* */ //*-------------------------------------------------------------------------*/ procedure move_bob(bob: Pbob; x: LongInt; y: LongInt); var rp : PRastPort = nil; begin if assigned(bob) then begin if SetAndTest(rp, bob^.rp) then remove_bob(bob); bob^.x := x; bob^.y := y; if assigned(rp) then add_bob(rp, bob); end; end; //*-------------------------------------------------------------------------*/ //* */ //*-------------------------------------------------------------------------*/ procedure free_bob(bob: Pbob); begin if assigned(bob) then begin if assigned(bob^.rp) then remove_bob(bob); if assigned(bob^.bm) then FreeBitMap(bob^.bm); if assigned(bob^.back) then FreeBitMap(bob^.back); ExecFreeMem(bob, sizeof(Tbob)); end; end; //*-------------------------------------------------------------------------*/ //* */ //*-------------------------------------------------------------------------*/ function new_bob(w: LongInt; h: LongInt; d: LongInt): Pbob; var bob : Pbob; begin bob := ExecAllocMem(sizeof(Tbob), MEMF_CLEAR); if assigned(bob) then begin bob^.w := w; bob^.h := h; if (d > 8) then d := 24; bob^.bm := AllocBitMap(w, h, d, ifthen(d = 24, BMF_SPECIALFMT or SHIFT_PIXFMT(PIXFMT_RGB24), 0), nil); bob^.back := AllocBitMap(w, h, d, ifthen(d = 24, BMF_SPECIALFMT or SHIFT_PIXFMT(PIXFMT_RGB24), 0), nil); if ((not assigned(bob^.bm)) or (not assigned(bob^.back))) then begin free_bob(bob); bob := nil; end; end; result := (bob); end; //*-------------------------------------------------------------------------*/ //* Main routine */ //*-------------------------------------------------------------------------*/ function main(argc: integer; argv: PPChar): integer; type targs = record pubscreen : PChar; end; var rdargs : pRDArgs; args : TArgs; scr : pScreen; win : pWindow; port : PMsgPort; mess : pIntuiMessage; cont : boolean; rp : PRastPort; i : Longint; bob : Pbob; diffx : LongInt = 0; diffy : LongInt = 0; begin args := Default(TArgs); if SetAndTest(rdargs, ReadArgs('PUBSCREEN/K', PLONG(@args), nil)) then begin if SetAndTest(scr, LockPubScreen(args.pubscreen)) then begin if SetAndTest(win, OpenWindowTags( nil, [ TAG_(WA_CustomScreen) , TAG_(scr), TAG_(WA_Width) , WINW, TAG_(WA_Height) , WINH, TAG_(WA_Left) , WINX, TAG_(WA_Top) , WINY, TAG_(WA_Flags) , TAG_(WFLG_CLOSEGADGET or WFLG_DRAGBAR or WFLG_DEPTHGADGET or WFLG_REPORTMOUSE or WFLG_RMBTRAP or WFLG_GIMMEZEROZERO or WFLG_ACTIVATE), TAG_(WA_IDCMP) , TAG_(IDCMP_CLOSEWINDOW or IDCMP_MOUSEMOVE or IDCMP_MOUSEBUTTONS), TAG_END ])) then begin rp := win^.RPort; for i := 0 to Pred(BOBW) do begin SetAPen(rp, (i and 3) + 1); GfxMove(rp, i + BOBMINX, BOBMINY); Draw(rp, BOBMAXX - i, BOBMAXY); end; for i := 0 to Pred(BOBH) do begin SetAPen(rp, (i and 3) + 1); GfxMove(rp, BOBMAXX, i + BOBMINY); Draw(rp, BOBMINX, BOBMAXY - i); end; bob := new_bob(BOBW, BOBH, GetBitMapAttr(scr^.RastPort.BitMap, BMA_DEPTH)); cut_bob(bob, rp, BOBMINX,BOBMINY); RectFill(rp, BOBMINX, BOBMINY, BOBMAXX, BOBMAXY); rp := @scr^.RastPort; port := win^.UserPort; cont := TRUE; while (cont) do begin WaitPort(port); while SetAndTest(mess, PIntuiMessage(GetMsg(port))) do begin case (mess^.IClass) of IDCMP_CLOSEWINDOW: cont := FALSE; IDCMP_MOUSEMOVE: move_bob(bob, scr^.MouseX - diffx, scr^.MouseY - diffy); IDCMP_MOUSEBUTTONS: begin if (mess^.Code = IECODE_LBUTTON) then begin if ( (win^.GZZMouseX >= BOBMINX) and (win^.GZZMouseX <= BOBMAXX) and (win^.GZZMouseY >= BOBMINY) and (win^.GZZMouseY <= BOBMAXY)) then begin diffx := scr^.MouseX - win^.LeftEdge - win^.BorderLeft - BOBMINX; diffy := scr^.MouseY - win^.TopEdge - win^.BorderTop - BOBMINY; move_bob(bob, scr^.MouseX - diffx, scr^.MouseY - diffy); add_bob(@scr^.RastPort, bob); end; end else remove_bob(bob); end; end; ReplyMsg(pMessage(mess)); end; end; remove_bob(bob); free_bob(bob); CloseWindow(win); end; UnlockPubScreen(nil, scr); end; FreeArgs(rdargs); end else PrintFault(IoErr(), nil); result := (0); end; //*-------------------------------------------------------------------------*/ //* End of original source text */ //*-------------------------------------------------------------------------*/ Function OpenLibs: boolean; begin Result := False; {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} GfxBase := OpenLibrary(GRAPHICSNAME, 0); if not assigned(GfxBase) then Exit; {$ENDIF} {$IF DEFINED(MORPHOS)} IntuitionBase := OpenLibrary(INTUITIONNAME, 0); if not assigned(IntuitionBase) then Exit; {$ENDIF} Result := True; end; Procedure CloseLibs; begin {$IF DEFINED(MORPHOS)} if assigned(IntuitionBase) then CloseLibrary(pLibrary(IntuitionBase)); {$ENDIF} {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} if assigned(GfxBase) then CloseLibrary(pLibrary(GfxBase)); {$ENDIF} end; begin WriteLn('enter'); if OpenLibs then ExitCode := Main(ArgC, ArgV) else ExitCode := RETURN_FAIL; CloseLibs; WriteLn('leave'); end.
// ****************************************************************** // // Program Name : AT Software_DNA Library // Program Version: 1.00 // Platform(s) : OS X, Win32, Win64 // Framework : FireMonkey // // Filenames : AT.DNA.FMX.Dlg.RequestEval.pas/.fmx // File Version : 1.20 // Date Created : 04-MAY-2016 // Author : Matthew S. Vesperman // // Description: // // Evaluation request dialog for Software_DNA - FireMonkey version for // cross-platform. // // Revision History: // // v1.00 : Initial version // v1.10 : 02-JUN-2016 // + text field trimming // v1.20 : 02-JUL-2016 // * Implemented resource strings // // ****************************************************************** // // COPYRIGHT © 2015 - PRESENT Angelic Technology // ALL RIGHTS RESERVED WORLDWIDE // // ****************************************************************** unit AT.DNA.FMX.Dlg.RequestEval; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, AT.DNA.FMX.Dlg.Base, System.ImageList, FMX.ImgList, FMX.Objects, FMX.Layouts, FMX.Controls.Presentation, FMX.Edit; type /// <summary> /// Request Evaluation dialog for Software_DNA. /// </summary> /// <remarks> /// When the dialog box's OK button is clicked the dialog box /// validates the email address the user has input. /// </remarks> TDNARequestEvalDlg = class(TDNABaseDlg) txtConfirmEmail: TEdit; ClearEditButton1: TClearEditButton; lblConfirmEmail: TLabel; txtEmail: TEdit; ClearEditButton2: TClearEditButton; lblEmail: TLabel; strict private /// <summary> /// EmailAddress property getter. /// </summary> /// <seealso cref="EmailAddress" /> function GetEmailAddress: String; /// <summary> /// EmailAddress property setter. /// </summary> /// <seealso cref="EmailAddress" /> procedure SetEmailAddress(const Value: String); strict protected procedure InitControls; override; procedure InitFields; override; procedure InitMacControls; override; function ValidateFields: Boolean; override; published /// <summary> /// Gets/Sets the email address field of the dialog box. /// </summary> property EmailAddress: String read GetEmailAddress write SetEmailAddress; end; var DNARequestEvalDlg: TDNARequestEvalDlg; implementation {$R *.fmx} uses AT.XPlatform.Internet, AT.DNA.ResourceStrings; function TDNARequestEvalDlg.GetEmailAddress: String; begin //Return the email address... Result := txtEmail.Text.Trim; end; procedure TDNARequestEvalDlg.InitControls; begin inherited InitControls; //call inherited... txtEmail.SetFocus; //Set the focus to the email address field... end; procedure TDNARequestEvalDlg.InitFields; begin inherited InitFields; //call inherited... //Init the email address field to empty string... EmailAddress := EmptyStr; end; procedure TDNARequestEvalDlg.InitMacControls; begin //Only called on Mac OS X platform... inherited InitMacControls; //call inherited... btnOK.Text := 'Send'; //Change OK button caption to Send... end; procedure TDNARequestEvalDlg.SetEmailAddress(const Value: String); begin //Set both the email and confirm email fields to Value... txtEmail.Text := Value.Trim; txtConfirmEmail.Text := Value.Trim; end; function TDNARequestEvalDlg.ValidateFields: Boolean; var AEmail, AConfirmEmail: String; begin //Check if email control is empty... AEmail := txtEmail.Text.Trim; if (AEmail.IsEmpty) then begin //Email control is blank so inform user... MessageDlg(rstrValEmailEmpty, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0, TMsgDlgBtn.mbOK); txtEmail.SetFocus; //Set focus to email control Exit(False); //Validation failure... end; //Ensure email address is valid... if (NOT CheckEmailFormat(AEmail)) then begin //Invalid email address, inform user... MessageDlg(rstrValEmailInvalid, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0, TMsgDlgBtn.mbOK); txtEmail.SetFocus; //Set focus to email control... Exit(False); //Validation failure... end; //Check if confirm email control is empty... AConfirmEmail := txtConfirmEmail.Text.Trim; if (AConfirmEmail.IsEmpty) then begin //Confirm email control is blank, inform user... MessageDlg(rstrValEmailConfirmEmpty, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0, TMsgDlgBtn.mbOK); txtConfirmEmail.SetFocus; //Set focus to confirm email control.. Exit(False); //Validation failure... end; //Ensure confirm email address is valid... if (NOT CheckEmailFormat(AConfirmEmail)) then begin //Invalid confirm email address, inform user... MessageDlg(rstrValEmailConfirmInvalid, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0, TMsgDlgBtn.mbOK); txtConfirmEmail.SetFocus; //Set focus to confirm email control.. Exit(False); //Validation failure... end; //Ensure email and confirm email values are the same... //NOT case-sensitive... if (CompareText(AEmail, AConfirmEmail) <> 0) then begin //Email addresses do NOT match, inform user... MessageDlg(rstrValEmailMismatch, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0, TMsgDlgBtn.mbOK); txtConfirmEmail.SetFocus; //Set focus to confirm email control.. Exit(False); //Validation failure... end; //Call inherited... Result := inherited ValidateFields; end; end.
unit radiogroup; {$mode delphi} interface uses Classes, SysUtils, And_jni, AndroidWidget, systryparent; type TOnCheckedChanged = procedure(Sender: TObject; checkedIndex: integer; checkedCaption: string) of Object; TRGOrientation = (rgHorizontal, rgVertical); {Draft Component code by "Lazarus Android Module Wizard" [12/25/2015 22:08:35]} {https://github.com/jmpessoa/lazandroidmodulewizard} {jVisualControl template} jRadioGroup = class(jVisualControl) private FOrientation: TRGOrientation; FOnCheckedChanged: TOnCheckedChanged; FCheckedIndex: integer; FItems: TStrings; procedure SetVisible(Value: Boolean); procedure SetColor(Value: TARGBColorBridge); //background public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; override; procedure Refresh; procedure UpdateLayout; override; function jCreate(): jObject; procedure jFree(); procedure SetViewParent(_viewgroup: jObject); override; procedure RemoveFromViewParent(); override; function GetView(): jObject; override; procedure SetLParamWidth(_w: integer); procedure SetLParamHeight(_h: integer); procedure SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); procedure AddLParamsAnchorRule(_rule: integer); procedure AddLParamsParentRule(_rule: integer); procedure SetLayoutAll(_idAnchor: integer); procedure ClearLayout(); procedure Check(_id: integer); procedure ClearCheck(); function GetCheckedRadioButtonId(): integer; function GetChildCount(): integer; procedure SetOrientation(_orientation: TRGOrientation); procedure CheckRadioButtonByCaption(_caption: string); procedure CheckRadioButtonByIndex(_index: integer); function GetChekedRadioButtonCaption(): string; function GetChekedRadioButtonIndex(): integer; function IsChekedRadioButtonByCaption(_caption: string): boolean; function IsChekedRadioButtonById(_id: integer): boolean; function IsChekedRadioButtonByIndex(_index: integer): boolean; procedure SetRoundCorner(); procedure SetRadiusRoundCorner(_radius: integer); procedure SetItems(Value: TStrings); procedure Add(_radioTitle: string); overload; procedure Add(_radioTitle: string; _color: TARGBColorBridge); overload; procedure GenEvent_CheckedChanged(Sender: TObject; checkedIndex: integer; checkedCaption: string); property CheckedIndex: integer read GetChekedRadioButtonIndex write CheckRadioButtonByIndex; published property Orientation: TRGOrientation read FOrientation write SetOrientation; property BackgroundColor: TARGBColorBridge read FColor write SetColor; property OnCheckedChanged: TOnCheckedChanged read FOnCheckedChanged write FOnCheckedChanged; property Items: TStrings read FItems write SetItems; end; function jRadioGroup_jCreate(env: PJNIEnv;_Self: int64; this: jObject; _orientation: integer): jObject; procedure jRadioGroup_jFree(env: PJNIEnv; _jradiogroup: JObject); procedure jRadioGroup_SetViewParent(env: PJNIEnv; _jradiogroup: JObject; _viewgroup: jObject); procedure jRadioGroup_RemoveFromViewParent(env: PJNIEnv; _jradiogroup: JObject); function jRadioGroup_GetView(env: PJNIEnv; _jradiogroup: JObject): jObject; procedure jRadioGroup_SetLParamWidth(env: PJNIEnv; _jradiogroup: JObject; _w: integer); procedure jRadioGroup_SetLParamHeight(env: PJNIEnv; _jradiogroup: JObject; _h: integer); procedure jRadioGroup_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jradiogroup: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); procedure jRadioGroup_AddLParamsAnchorRule(env: PJNIEnv; _jradiogroup: JObject; _rule: integer); procedure jRadioGroup_AddLParamsParentRule(env: PJNIEnv; _jradiogroup: JObject; _rule: integer); procedure jRadioGroup_SetLayoutAll(env: PJNIEnv; _jradiogroup: JObject; _idAnchor: integer); procedure jRadioGroup_ClearLayoutAll(env: PJNIEnv; _jradiogroup: JObject); procedure jRadioGroup_SetId(env: PJNIEnv; _jradiogroup: JObject; _id: integer); procedure jRadioGroup_Check(env: PJNIEnv; _jradiogroup: JObject; _id: integer); procedure jRadioGroup_ClearCheck(env: PJNIEnv; _jradiogroup: JObject); function jRadioGroup_GetCheckedRadioButtonId(env: PJNIEnv; _jradiogroup: JObject): integer; function jRadioGroup_GetChildCount(env: PJNIEnv; _jradiogroup: JObject): integer; procedure jRadioGroup_SetOrientation(env: PJNIEnv; _jradiogroup: JObject; _orientation: integer); procedure jRadioGroup_CheckRadioButtonByCaption(env: PJNIEnv; _jradiogroup: JObject; _caption: string); procedure jRadioGroup_CheckRadioButtonByIndex(env: PJNIEnv; _jradiogroup: JObject; _index: integer); function jRadioGroup_GetChekedRadioButtonCaption(env: PJNIEnv; _jradiogroup: JObject): string; function jRadioGroup_GetChekedRadioButtonIndex(env: PJNIEnv; _jradiogroup: JObject): integer; function jRadioGroup_IsChekedRadioButtonByCaption(env: PJNIEnv; _jradiogroup: JObject; _caption: string): boolean; function jRadioGroup_IsChekedRadioButtonById(env: PJNIEnv; _jradiogroup: JObject; _id: integer): boolean; function jRadioGroup_IsChekedRadioButtonByIndex(env: PJNIEnv; _jradiogroup: JObject; _index: integer): boolean; procedure jRadioGroup_SetRoundCorner(env: PJNIEnv; _jradiogroup: JObject); procedure jRadioGroup_SetRadiusRoundCorner(env: PJNIEnv; _jradiogroup: JObject; _radius: integer); procedure jRadioGroup_Add(env: PJNIEnv; _jradiogroup: JObject; _radioTitle: string); overload; procedure jRadioGroup_Add(env: PJNIEnv; _jradiogroup: JObject; _radioTitle: string; _color: integer); overload; implementation {--------- jRadioGroup --------------} constructor jRadioGroup.Create(AOwner: TComponent); begin inherited Create(AOwner); if gapp <> nil then FId := gapp.GetNewId(); FMarginLeft := 10; FMarginTop := 10; FMarginBottom := 10; FMarginRight := 10; FHeight := 96; //?? FWidth := 96; //?? FLParamWidth := lpWrapContent;//lpMatchParent; //lpWrapContent FLParamHeight := lpWrapContent; //lpMatchParent FAcceptChildrenAtDesignTime:= True; //your code here.... FOrientation:= rgVertical; FCheckedIndex:= -1; FItems:= TStringList.Create; end; destructor jRadioGroup.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jFree(); FjObject:= nil; end; end; //you others free code here...' FItems.Free; inherited Destroy; end; procedure jRadioGroup.Init; var rToP: TPositionRelativeToParent; rToA: TPositionRelativeToAnchorID; i: integer; begin if not FInitialized then begin inherited Init; //set default ViewParent/FjPRLayout as jForm.View! //your code here: set/initialize create params.... FjObject := jCreate(); if FjObject = nil then exit; if FParent <> nil then sysTryNewParent( FjPRLayout, FParent); FjPRLayoutHome:= FjPRLayout; jRadioGroup_SetViewParent(gApp.jni.jEnv, FjObject, FjPRLayout); jRadioGroup_SetId(gApp.jni.jEnv, FjObject, Self.Id); end; jRadioGroup_setLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject , FMarginLeft,FMarginTop,FMarginRight,FMarginBottom, sysGetLayoutParams( FWidth, FLParamWidth, Self.Parent, sdW, fmarginLeft + fmarginRight ), sysGetLayoutParams( FHeight, FLParamHeight, Self.Parent, sdH, fMargintop + fMarginbottom )); for rToA := raAbove to raAlignRight do begin if rToA in FPositionRelativeToAnchor then begin jRadioGroup_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToAnchor(rToA)); end; end; for rToP := rpBottom to rpCenterVertical do begin if rToP in FPositionRelativeToParent then begin jRadioGroup_AddLParamsParentRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToParent(rToP)); end; end; if Self.Anchor <> nil then Self.AnchorId:= Self.Anchor.Id else Self.AnchorId:= -1; //dummy jRadioGroup_SetLayoutAll(gApp.jni.jEnv, FjObject, Self.AnchorId); if not FInitialized then begin FInitialized:= True; if FColor <> colbrDefault then View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor)); for i:= 0 to FItems.Count-1 do begin if FItems.Strings[i] <> '' then jRadioGroup_Add(gApp.jni.jEnv, FjObject , FItems.Strings[i]); end; View_SetVisible(gApp.jni.jEnv, FjObject, FVisible); end; end; procedure jRadioGroup.SetColor(Value: TARGBColorBridge); begin FColor:= Value; if (FInitialized = True) and (FColor <> colbrDefault) then View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor)); end; procedure jRadioGroup.SetVisible(Value : Boolean); begin FVisible:= Value; if FInitialized then View_SetVisible(gApp.jni.jEnv, FjObject, FVisible); end; procedure jRadioGroup.UpdateLayout; begin if not FInitialized then exit; ClearLayout(); inherited UpdateLayout; init; end; procedure jRadioGroup.Refresh; begin if FInitialized then View_Invalidate(gApp.jni.jEnv, FjObject); end; //Event : Java -> Pascal procedure jRadioGroup.GenEvent_CheckedChanged(Sender: TObject; checkedIndex: integer; checkedCaption: string); begin if Assigned(FOnCheckedChanged) then FOnCheckedChanged(Sender, checkedIndex, checkedCaption); end; function jRadioGroup.jCreate(): jObject; begin Result:= jRadioGroup_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis, Ord(FOrientation)); end; procedure jRadioGroup.jFree(); begin //in designing component state: set value here... if FInitialized then jRadioGroup_jFree(gApp.jni.jEnv, FjObject); end; procedure jRadioGroup.SetViewParent(_viewgroup: jObject); begin //in designing component state: set value here... FjPRLayout:= _viewgroup; // <<-------------- if FInitialized then jRadioGroup_SetViewParent(gApp.jni.jEnv, FjObject, _viewgroup); end; procedure jRadioGroup.RemoveFromViewParent(); begin //in designing component state: set value here... if FInitialized then jRadioGroup_RemoveFromViewParent(gApp.jni.jEnv, FjObject); end; function jRadioGroup.GetView(): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jRadioGroup_GetView(gApp.jni.jEnv, FjObject); end; procedure jRadioGroup.SetLParamWidth(_w: integer); begin //in designing component state: set value here... if FInitialized then jRadioGroup_SetLParamWidth(gApp.jni.jEnv, FjObject, _w); end; procedure jRadioGroup.SetLParamHeight(_h: integer); begin //in designing component state: set value here... if FInitialized then jRadioGroup_SetLParamHeight(gApp.jni.jEnv, FjObject, _h); end; procedure jRadioGroup.SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); begin //in designing component state: set value here... if FInitialized then jRadioGroup_SetLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject, _left ,_top ,_right ,_bottom ,_w ,_h); end; procedure jRadioGroup.AddLParamsAnchorRule(_rule: integer); begin //in designing component state: set value here... if FInitialized then jRadioGroup_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, _rule); end; procedure jRadioGroup.AddLParamsParentRule(_rule: integer); begin //in designing component state: set value here... if FInitialized then jRadioGroup_AddLParamsParentRule(gApp.jni.jEnv, FjObject, _rule); end; procedure jRadioGroup.SetLayoutAll(_idAnchor: integer); begin //in designing component state: set value here... if FInitialized then jRadioGroup_SetLayoutAll(gApp.jni.jEnv, FjObject, _idAnchor); end; procedure jRadioGroup.ClearLayout(); var rToP: TPositionRelativeToParent; rToA: TPositionRelativeToAnchorID; begin //in designing component state: set value here... if FInitialized then begin jRadioGroup_clearLayoutAll(gApp.jni.jEnv, FjObject); for rToP := rpBottom to rpCenterVertical do if rToP in FPositionRelativeToParent then jRadioGroup_addlParamsParentRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToParent(rToP)); for rToA := raAbove to raAlignRight do if rToA in FPositionRelativeToAnchor then jRadioGroup_addlParamsAnchorRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToAnchor(rToA)); end; end; procedure jRadioGroup.Check(_id: integer); begin //in designing component state: set value here... if FInitialized then jRadioGroup_Check(gApp.jni.jEnv, FjObject, _id); end; procedure jRadioGroup.ClearCheck(); begin //in designing component state: set value here... if FInitialized then jRadioGroup_ClearCheck(gApp.jni.jEnv, FjObject); end; function jRadioGroup.GetCheckedRadioButtonId(): integer; begin //in designing component state: result value here... if FInitialized then Result:= jRadioGroup_GetCheckedRadioButtonId(gApp.jni.jEnv, FjObject); end; function jRadioGroup.GetChildCount(): integer; begin //in designing component state: result value here... if FInitialized then Result:= jRadioGroup_GetChildCount(gApp.jni.jEnv, FjObject); end; procedure jRadioGroup.SetOrientation(_orientation: TRGOrientation); begin //in designing component state: set value here... FOrientation:= _orientation; if FInitialized then jRadioGroup_SetOrientation(gApp.jni.jEnv, FjObject, Ord(_orientation)); end; procedure jRadioGroup.CheckRadioButtonByCaption(_caption: string); begin //in designing component state: set value here... if FInitialized then jRadioGroup_CheckRadioButtonByCaption(gApp.jni.jEnv, FjObject, _caption); end; procedure jRadioGroup.CheckRadioButtonByIndex(_index: integer); begin //in designing component state: set value here... FCheckedIndex:= _index; if FInitialized then jRadioGroup_CheckRadioButtonByIndex(gApp.jni.jEnv, FjObject, _index); end; function jRadioGroup.GetChekedRadioButtonCaption(): string; begin //in designing component state: result value here... if FInitialized then Result:= jRadioGroup_GetChekedRadioButtonCaption(gApp.jni.jEnv, FjObject); end; function jRadioGroup.GetChekedRadioButtonIndex(): integer; begin //in designing component state: result value here... Result:= FCheckedIndex; if FInitialized then Result:= jRadioGroup_GetChekedRadioButtonIndex(gApp.jni.jEnv, FjObject); end; function jRadioGroup.IsChekedRadioButtonByCaption(_caption: string): boolean; begin //in designing component state: result value here... if FInitialized then Result:= jRadioGroup_IsChekedRadioButtonByCaption(gApp.jni.jEnv, FjObject, _caption); end; function jRadioGroup.IsChekedRadioButtonById(_id: integer): boolean; begin //in designing component state: result value here... if FInitialized then Result:= jRadioGroup_IsChekedRadioButtonById(gApp.jni.jEnv, FjObject, _id); end; function jRadioGroup.IsChekedRadioButtonByIndex(_index: integer): boolean; begin //in designing component state: result value here... if FInitialized then Result:= jRadioGroup_IsChekedRadioButtonByIndex(gApp.jni.jEnv, FjObject, _index); end; procedure jRadioGroup.SetRoundCorner(); begin //in designing component state: set value here... if FInitialized then jRadioGroup_SetRoundCorner(gApp.jni.jEnv, FjObject); end; procedure jRadioGroup.SetRadiusRoundCorner(_radius: integer); begin //in designing component state: set value here... if FInitialized then jRadioGroup_SetRadiusRoundCorner(gApp.jni.jEnv, FjObject, _radius); end; procedure jRadioGroup.SetItems(Value: TStrings); var i: integer; begin FItems.Assign(Value); if FInitialized then begin for i:= 0 to FItems.Count - 1 do begin if FItems.Strings[i] <> '' then jRadioGroup_Add(gApp.jni.jEnv, FjObject , FItems.Strings[i]); end; end; end; procedure jRadioGroup.Add(_radioTitle: string); begin //in designing component state: set value here... if FInitialized then jRadioGroup_Add(gApp.jni.jEnv, FjObject, _radioTitle); end; procedure jRadioGroup.Add(_radioTitle: string; _color: TARGBColorBridge); begin //in designing component state: set value here... if FInitialized then jRadioGroup_Add(gApp.jni.jEnv, FjObject, _radioTitle ,GetARGB(FCustomColor, _color)); end; {-------- jRadioGroup_JNI_Bridge ----------} function jRadioGroup_jCreate(env: PJNIEnv;_Self: int64; this: jObject; _orientation: integer): jObject; var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].j:= _Self; jParams[1].i:= _orientation; jCls:= Get_gjClass(env); jMethod:= env^.GetMethodID(env, jCls, 'jRadioGroup_jCreate', '(JI)Ljava/lang/Object;'); Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams); Result:= env^.NewGlobalRef(env, Result); end; (* //Please, you need insert: public java.lang.Object jRadioGroup_jCreate(long _Self, int _orientation) { return (java.lang.Object)(new jRadioGroup(this,_Self,_orientation)); } //to end of "public class Controls" in "Controls.java" *) procedure jRadioGroup_jFree(env: PJNIEnv; _jradiogroup: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V'); env^.CallVoidMethod(env, _jradiogroup, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_SetViewParent(env: PJNIEnv; _jradiogroup: JObject; _viewgroup: jObject); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= _viewgroup; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'SetViewParent', '(Landroid/view/ViewGroup;)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_RemoveFromViewParent(env: PJNIEnv; _jradiogroup: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'RemoveFromViewParent', '()V'); env^.CallVoidMethod(env, _jradiogroup, jMethod); env^.DeleteLocalRef(env, jCls); end; function jRadioGroup_GetView(env: PJNIEnv; _jradiogroup: JObject): jObject; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'GetView', '()Landroid/widget/RadioGroup;'); Result:= env^.CallObjectMethod(env, _jradiogroup, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_SetLParamWidth(env: PJNIEnv; _jradiogroup: JObject; _w: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _w; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'SetLParamWidth', '(I)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_SetLParamHeight(env: PJNIEnv; _jradiogroup: JObject; _h: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _h; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'SetLParamHeight', '(I)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jradiogroup: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); var jParams: array[0..5] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _left; jParams[1].i:= _top; jParams[2].i:= _right; jParams[3].i:= _bottom; jParams[4].i:= _w; jParams[5].i:= _h; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'SetLeftTopRightBottomWidthHeight', '(IIIIII)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_AddLParamsAnchorRule(env: PJNIEnv; _jradiogroup: JObject; _rule: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _rule; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsAnchorRule', '(I)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_AddLParamsParentRule(env: PJNIEnv; _jradiogroup: JObject; _rule: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _rule; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsParentRule', '(I)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_SetLayoutAll(env: PJNIEnv; _jradiogroup: JObject; _idAnchor: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _idAnchor; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'SetLayoutAll', '(I)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_ClearLayoutAll(env: PJNIEnv; _jradiogroup: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'ClearLayoutAll', '()V'); env^.CallVoidMethod(env, _jradiogroup, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_SetId(env: PJNIEnv; _jradiogroup: JObject; _id: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _id; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'setId', '(I)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_Check(env: PJNIEnv; _jradiogroup: JObject; _id: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _id; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'Check', '(I)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_ClearCheck(env: PJNIEnv; _jradiogroup: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'ClearCheck', '()V'); env^.CallVoidMethod(env, _jradiogroup, jMethod); env^.DeleteLocalRef(env, jCls); end; function jRadioGroup_GetCheckedRadioButtonId(env: PJNIEnv; _jradiogroup: JObject): integer; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'GetCheckedRadioButtonId', '()I'); Result:= env^.CallIntMethod(env, _jradiogroup, jMethod); env^.DeleteLocalRef(env, jCls); end; function jRadioGroup_GetChildCount(env: PJNIEnv; _jradiogroup: JObject): integer; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'GetChildCount', '()I'); Result:= env^.CallIntMethod(env, _jradiogroup, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_SetOrientation(env: PJNIEnv; _jradiogroup: JObject; _orientation: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _orientation; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'SetOrientation', '(I)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_CheckRadioButtonByCaption(env: PJNIEnv; _jradiogroup: JObject; _caption: string); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_caption)); jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'CheckRadioButtonByCaption', '(Ljava/lang/String;)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_CheckRadioButtonByIndex(env: PJNIEnv; _jradiogroup: JObject; _index: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _index; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'CheckRadioButtonByIndex', '(I)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; function jRadioGroup_GetChekedRadioButtonCaption(env: PJNIEnv; _jradiogroup: JObject): string; var jStr: JString; jBoo: JBoolean; jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'GetChekedRadioButtonCaption', '()Ljava/lang/String;'); jStr:= env^.CallObjectMethod(env, _jradiogroup, jMethod); case jStr = nil of True : Result:= ''; False: begin jBoo:= JNI_False; Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo)); end; end; env^.DeleteLocalRef(env, jCls); end; function jRadioGroup_GetChekedRadioButtonIndex(env: PJNIEnv; _jradiogroup: JObject): integer; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'GetChekedRadioButtonIndex', '()I'); Result:= env^.CallIntMethod(env, _jradiogroup, jMethod); env^.DeleteLocalRef(env, jCls); end; function jRadioGroup_IsChekedRadioButtonByCaption(env: PJNIEnv; _jradiogroup: JObject; _caption: string): boolean; var jBoo: JBoolean; jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_caption)); jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'IsChekedRadioButtonByCaption', '(Ljava/lang/String;)Z'); jBoo:= env^.CallBooleanMethodA(env, _jradiogroup, jMethod, @jParams); Result:= boolean(jBoo); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; function jRadioGroup_IsChekedRadioButtonById(env: PJNIEnv; _jradiogroup: JObject; _id: integer): boolean; var jBoo: JBoolean; jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _id; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'IsChekedRadioButtonById', '(I)Z'); jBoo:= env^.CallBooleanMethodA(env, _jradiogroup, jMethod, @jParams); Result:= boolean(jBoo); env^.DeleteLocalRef(env, jCls); end; function jRadioGroup_IsChekedRadioButtonByIndex(env: PJNIEnv; _jradiogroup: JObject; _index: integer): boolean; var jBoo: JBoolean; jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _index; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'IsChekedRadioButtonByIndex', '(I)Z'); jBoo:= env^.CallBooleanMethodA(env, _jradiogroup, jMethod, @jParams); Result:= boolean(jBoo); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_SetRoundCorner(env: PJNIEnv; _jradiogroup: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'SetRoundCorner', '()V'); env^.CallVoidMethod(env, _jradiogroup, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_SetRadiusRoundCorner(env: PJNIEnv; _jradiogroup: JObject; _radius: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _radius; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'SetRadiusRoundCorner', '(I)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_Add(env: PJNIEnv; _jradiogroup: JObject; _radioTitle: string); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_radioTitle)); jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'Add', '(Ljava/lang/String;)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; procedure jRadioGroup_Add(env: PJNIEnv; _jradiogroup: JObject; _radioTitle: string; _color: integer); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_radioTitle)); jParams[1].i:= _color; jCls:= env^.GetObjectClass(env, _jradiogroup); jMethod:= env^.GetMethodID(env, jCls, 'Add', '(Ljava/lang/String;I)V'); env^.CallVoidMethodA(env, _jradiogroup, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; end.
(* Name: UfrmKeyboardFonts Copyright: Copyright (C) SIL International. Documentation: Description: Create Date: 3 Aug 2015 Modified Date: 24 Aug 2015 Authors: mcdurdin Related Files: Dependencies: Bugs: Todo: Notes: History: 03 Aug 2015 - mcdurdin - I4820 - Keyboard fonts dialog box has incorrect control types 24 Aug 2015 - mcdurdin - I4872 - OSK font and Touch Layout font should be the same in Developer *) unit UfrmKeyboardFonts; // I4820 // I4872 interface uses System.UITypes, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UfrmTike, Vcl.StdCtrls, KeyboardFonts, scFontCombobox; type TKeyboardFontControl = record CaptionLabel: TLabel; NameCombo: TSCFontComboBox; SizeEdit: TEdit; end; TfrmKeyboardFonts = class(TTikeForm) lblDevEnv: TLabel; fcbCode: TscFontComboBox; editCodeSize: TEdit; lblCodeFont: TLabel; lblDevEnvName: TLabel; lblDevEnvSize: TLabel; fcbChar: TscFontComboBox; editCharSize: TEdit; lblCharFont: TLabel; fcbOSK: TscFontComboBox; editOSKSize: TEdit; lblOSKFont: TLabel; editTouchLayoutPhoneSize: TEdit; lblTouchLayoutPhoneFont: TLabel; editTouchLayoutTabletSize: TEdit; lblTouchLayoutTabletFont: TLabel; editTouchLayoutDesktopSize: TEdit; lblTouchLayoutDesktopFont: TLabel; cmdOK: TButton; cmdCancel: TButton; lblProp: TLabel; lblPropName: TLabel; lblPropSize: TLabel; lblOSKFontSize: TLabel; lblTextEditorFontSize: TLabel; lblDebuggerFontSize: TLabel; lblTouchLayoutPhoneFontSize: TLabel; Label1: TLabel; Label2: TLabel; fcbTouchLayoutPhone: TscFontComboBox; fcbTouchLayoutTablet: TscFontComboBox; fcbTouchLayoutDesktop: TscFontComboBox; procedure FormCreate(Sender: TObject); procedure cmdOKClick(Sender: TObject); private FControls: array[TKeyboardFont] of TKeyboardFontControl; function GetFontInfo(Index: TKeyboardFont): TKeyboardFontInfo; procedure SetFontInfo(Index: TKeyboardFont; const Value: TKeyboardFontInfo); public { Public declarations } property FontInfo[Index: TKeyboardFont]: TKeyboardFontInfo read GetFontInfo write SetFontInfo; end; implementation {$R *.dfm} procedure TfrmKeyboardFonts.cmdOKClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TfrmKeyboardFonts.FormCreate(Sender: TObject); begin inherited; // Note: filename and path not currently used FControls[kfontCode].CaptionLabel := lblCodeFont; FControls[kfontCode].NameCombo := fcbCode; FControls[kfontCode].SizeEdit := editCodeSize; FControls[kfontChar].CaptionLabel := lblCharFont; FControls[kfontChar].NameCombo := fcbChar; FControls[kfontChar].SizeEdit := editCharSize; FControls[kfontOSK].CaptionLabel := lblOSKFont; FControls[kfontOSK].NameCombo := fcbOSK; FControls[kfontOSK].SizeEdit := editOSKSize; FControls[kfontTouchLayoutPhone].CaptionLabel := lblTouchLayoutPhoneFont; FControls[kfontTouchLayoutPhone].NameCombo := fcbTouchLayoutPhone; FControls[kfontTouchLayoutPhone].SizeEdit := editTouchLayoutPhoneSize; FControls[kfontTouchLayoutTablet].CaptionLabel := lblTouchLayoutTabletFont; FControls[kfontTouchLayoutTablet].NameCombo := fcbTouchLayoutTablet; FControls[kfontTouchLayoutTablet].SizeEdit := editTouchLayoutTabletSize; FControls[kfontTouchLayoutDesktop].CaptionLabel := lblTouchLayoutDesktopFont; FControls[kfontTouchLayoutDesktop].NameCombo := fcbTouchLayoutDesktop; FControls[kfontTouchLayoutDesktop].SizeEdit := editTouchLayoutDesktopSize; end; function TfrmKeyboardFonts.GetFontInfo(Index: TKeyboardFont): TKeyboardFontInfo; begin Result.Name := FControls[Index].NameCombo.FontName; // I4820 Result.Size := FControls[Index].SizeEdit.Text; Result.Enabled := FControls[Index].NameCombo.Enabled; //Result.Filename := IncludeTrailingPathDelimiter(FControls[Index].PathEdit.Text) + FControls[Index].FilenameEdit.Text; end; procedure TfrmKeyboardFonts.SetFontInfo(Index: TKeyboardFont; const Value: TKeyboardFontInfo); begin FControls[Index].NameCombo.Enabled := Value.Enabled; FControls[Index].SizeEdit.Enabled := Value.Enabled; FControls[Index].CaptionLabel.Enabled := Value.Enabled; if Value.Enabled then begin FControls[Index].NameCombo.FontName := Value.Name; // I4820 FControls[Index].SizeEdit.Text := Value.Size; end; end; end.
unit UWPDF2; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls, Grids_ts, TSGrid, WPPDFR2, UGlobals, UForms; type TWPDFConfig2 = class(TAdvancedForm) StatusBar1: TStatusBar; PageControl: TPageControl; general: TTabSheet; Advanced: TTabSheet; security: TTabSheet; PrListGrid: TtsGrid; Panel1: TPanel; btnCreatePDF: TButton; btnCancel: TButton; cbxThumbnails: TCheckBox; CompressionGroup: TRadioGroup; cbxEncrypt: TCheckBox; FontEmbedGroup: TRadioGroup; cbxBookmarks: TCheckBox; LabelViewPSW: TLabel; edtUserPSW: TEdit; cbxViewOnly: TCheckBox; cbxAllowPrint: TCheckBox; cbxAllowCopy: TCheckBox; cbxAllowChange: TCheckBox; LabelNotReqed: TLabel; PDFSaveDialog: TSaveDialog; edtAuthor: TEdit; Label4: TLabel; Label5: TLabel; edtSubject: TEdit; cbxLaunchPDF: TCheckBox; procedure btnCreatePDFClick(Sender: TObject); procedure cbxEncryptClick(Sender: TObject); procedure cbxViewOnlyClick(Sender: TObject); procedure cbxNotViewOnlyClick(Sender: TObject); procedure PrListGridClickCell(Sender: TObject; DataColDown, DataRowDown, DataColUp, DataRowUp: Integer; DownPos, UpPos: TtsClickPosition); private FDoc: TComponent; FPDFExport: TWPPDFPrinter; FShowAdvanced: Boolean; FOptions: Integer; FPgSettingChanged: Boolean; protected Procedure SetShowAdvanced(value: Boolean); public PgSpec: Array of PagePrintSpecRec; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SetOptions(Value: Integer); procedure SetConfiguration; procedure GetConfiguration; property ShowAdvanced: Boolean read FShowAdvanced write SetShowAdvanced; property Options: Integer read FOptions write SetOptions; end; var WPDFConfig2: TWPDFConfig2; implementation uses DateUtils, UContainer, UUtil1, UStatus,ULicUser, WPPDFR1; const bAutoLaunch = 1; //options for presetting the PDF Dialog {$R *.DFM} { TWPDFProperty } constructor TWPDFConfig2.Create(AOwner: TComponent); var n,f,p: Integer; PDF_DLL: String; begin inherited Create(nil); SettingsName := CFormSettings_WPDFConfig2; PageControl.ActivePage := Security; FOptions := 0; Advanced.TabVisible := False; //this is default try FDoc := AOwner; FPDFExport := TContainer(FDoc).WPPDFPrinter; //reference the PDF printer PDF_DLL := IncludeTrailingPathDelimiter(appPref_DirTools)+'Imaging\IMAGE8.dll'; if FileExists(PDF_DLL) then FPDFExport.DLLName := PDF_DLL else begin ShowNotice('The ClickFORMS PDF Creator was not found. Please ensure it has been installed.'); exit; end; SetConfiguration; //display the defaults FPgSettingChanged := False; //Set the doc page names in grid with PrListGrid do begin if AOwner <> nil then if AOwner is TContainer then with AOwner as TContainer do if docForm.count > 0 then begin FDoc := AOwner; n := 0; Rows := docForm.TotalPages; //set the number of rows SetLength(PgSpec, docForm.TotalPages); //array to store the printer spec for each pg for f := 0 to docForm.count-1 do for p := 0 to docForm[f].frmPage.count-1 do with docForm[f].frmPage[p] do begin Cell[1,n+1] := cbUnchecked; //get set to draw the inital settings if IsBitSet(FPgFlags, bPgInPDFList) then Cell[1,n+1] := cbChecked; Cell[2,n+1] := PgTitleName; inc(n); end; end; end; except ShowNotice('There was a problem using the ClickFORMS PDF Creator. Please ensure it has been installed.'); end; end; destructor TWPDFConfig2.Destroy; begin PgSpec := Nil; Inherited; end; procedure TWPDFConfig2.btnCreatePDFClick(Sender: TObject); var n,f,p: Integer; begin with FDoc as TContainer do begin GetConfiguration; //get all the settings PDFSaveDialog.Title := 'Save PDF File As'; //PDFSaveDialog.FileName := GetNameOnly(docFileName); PDFSaveDialog.FileName := ChangeFileExt(docFileName,'.pdf'); PDFSaveDialog.DefaultExt := 'pdf'; PDFSaveDialog.Filter := 'Adobe PDF (pdf)|*.pdf'; PDFSaveDialog.InitialDir := VerifyInitialDir(appPref_DirPDFs, appPref_DirLastSave); PDFSaveDialog.Options := [ofOverwritePrompt, ofEnableSizing]; if PDFSaveDialog.Execute then begin FPDFExport.Filename := PDFSaveDialog.FileName; n := 0; for f := 0 to docForm.Count-1 do for p := 0 to docForm[f].frmPage.Count-1 do with docForm[f].frmPage[p] do begin //set the doc FPgFlags := SetBit2Flag(FPgFlags, bPgInPDFList, (PrListGrid.Cell[1,n+1] = cbChecked)); //remember //set the printer spec array PgSpec[n].PrIndex := 1; //always use pr #1 (we only have one PDF) PgSpec[n].Copies := 1; //only one copy per page PgSpec[n].Ok2Print := IsBitSet(FPgFlags, bPgInPDFList); //is it checked?? if FPgSettingChanged then TContainer(FDoc).docDataChged := True; inc(n); end; Self.ModalResult := mrOk; end; end; end; procedure TWPDFConfig2.SetOptions(Value: Integer); begin FOptions := Value; cbxLaunchPDF.checked := IsBitSet(FOptions, bAutoLaunch); end; procedure TWPDFConfig2.GetConfiguration; begin if FPDFExport <> nil then begin FPDFExport.AutoLaunch := cbxLaunchPDF.checked; //Get general FPDFExport.CreateThumbnails := cbxThumbnails.Checked; FPDFExport.CreateOutlines := cbxBookmarks.Checked; //Get Author FPDFExport.Info.Producer := 'ClickFORMS'; FPDFExport.Info.Author := edtAuthor.Text; FPDFExport.Info.Subject := edtSubject.Text; FPDFExport.Info.Date := Today; //Get Advanced if ShowAdvanced then begin case CompressionGroup.ItemIndex of 0: FPDFExport.CompressStreamMethod := wpCompressNone; 1: FPDFExport.CompressStreamMethod := wpCompressFlate; end; case FontEmbedGroup.ItemIndex of 0: FPDFExport.FontMode := wpUseTrueTypeFonts; 1: FPDFExport.FontMode := wpEmbedSubsetTrueType_UsedChar; end; end; //Get Security if not cbxEncrypt.Checked then FPDFExport.Encryption := [] else begin FPDFExport.Encryption := [wpEncryptFile]; if cbxAllowPrint.Checked then FPDFExport.Encryption := FPDFExport.Encryption + [wpEnablePrinting]; if cbxAllowCopy.Checked then FPDFExport.Encryption := FPDFExport.Encryption + [wpEnableCopying]; if cbxAllowChange.Checked then FPDFExport.Encryption := FPDFExport.Encryption + [wpEnableChanging]; // if EncryptOpt4.Checked then // FPDFExport.Encryption := FPDFExport.Encryption + [wpEnableForms]; FPDFExport.UserPassword := edtUserPSW.Text; FPDFExport.OwnerPassword := ''; end; // Use PDF Files FPDFExport.InputfileMode := TWPPDFInputfileMode(0); //ignore input file FPDFExport.Inputfile := ''; end; end; procedure TWPDFConfig2.SetConfiguration; begin with FDoc as TContainer do if FPDFExport <> nil then begin cbxLaunchPDF.checked := FPDFExport.AutoLaunch; //Set General cbxThumbnails.Checked := FPDFExport.CreateThumbnails; cbxBookmarks.Checked := FPDFExport.CreateOutlines; //Set Author & Subject edtAuthor.Text := CurrentUser.UserInfo.FName; edtSubject.Text := TContainer(FDoc).GetCellTextByID(46); if ShowAdvanced then begin //Set Advanced - compression case Integer(FPDFExport.CompressStreamMethod) of 0,1 : CompressionGroup.ItemIndex := 1; //set compression 2 : CompressionGroup.ItemIndex := 0; //set none end; //Set Advanced - font enbedding case Integer(FPDFEXport.FontMode) of 0,1,2,3: FontEmbedGroup.ItemIndex := 1; 4,5: FontEmbedGroup.ItemIndex := 0; end; end; //Set Security cbxEncrypt.Checked := wpEncryptFile in FPDFExport.Encryption; cbxViewOnly.checked := False; cbxAllowPrint.Checked := wpEnablePrinting in FPDFExport.Encryption; cbxAllowCopy.Checked := wpEnableCopying in FPDFExport.Encryption; cbxAllowChange.Checked := wpEnableChanging in FPDFExport.Encryption; // EncryptOpt4.Checked := wpEnableForms in FPDFExport.Encryption; edtUserPSW.Text := FPDFExport.UserPassword; // OwnerPW.Text := FPDFExport.OwnerPassword; end; end; procedure TWPDFConfig2.cbxEncryptClick(Sender: TObject); begin if cbxEncrypt.checked then begin cbxViewOnly.enabled := True; cbxAllowPrint.enabled := True; cbxAllowCopy.enabled := True; cbxAllowChange.enabled := True; edtUserPSW.enabled := True; LabelViewPSW.enabled := True; LabelNotReqed.enabled := True; end else begin cbxViewOnly.enabled := False; cbxAllowPrint.enabled := False; cbxAllowCopy.enabled := False; cbxAllowChange.enabled := False; edtUserPSW.enabled := False; LabelViewPSW.enabled := False; LabelNotReqed.enabled := False; end; end; procedure TWPDFConfig2.cbxViewOnlyClick(Sender: TObject); begin if cbxViewOnly.checked then begin cbxAllowPrint.Checked := False; cbxAllowCopy.checked := False; cbxAllowChange.checked := False; cbxAllowPrint.enabled := False; cbxAllowCopy.enabled := False; cbxAllowChange.enabled := False; end else begin cbxAllowPrint.enabled := True; cbxAllowCopy.enabled := True; cbxAllowChange.enabled := True; end; end; procedure TWPDFConfig2.cbxNotViewOnlyClick(Sender: TObject); begin if TCheckBox(Sender).checked then cbxViewOnly.checked := False; end; procedure TWPDFConfig2.PrListGridClickCell(Sender: TObject; DataColDown, DataRowDown, DataColUp, DataRowUp: Integer; DownPos, UpPos: TtsClickPosition); var i: Integer; checked: Boolean; begin //Clicking in column 2 is same as clicking in checkbox FPgSettingChanged := True; with PrListGrid do begin //handle toggle if clicked in col#2, else let chkbox do it if (DataColDown=2) and (DataRowDown > 0) then begin if Cell[1,DataRowDown] = cbChecked then Cell[1,DataRowDown] := cbUnChecked else Cell[1,DataRowDown] := cbChecked; end; //now do the extensions if ((DataColDown = 1) or (DataColDown=2)) and ShiftKeyDown then //clicked in checkbox begin checked := (Cell[1,DataRowDown] = cbChecked); for i := DataRowDown+1 to Rows do begin if ControlKeyDown then //if cntlKeyDown toggle current state begin if Cell[1,i] = cbChecked then Cell[1,i] := cbUnChecked else Cell[1,i] := cbChecked; end else //just run same state down list if checked then Cell[1,i] := cbChecked else Cell[1,i] := cbUnChecked; end; end end; end; Procedure TWPDFConfig2.SetShowAdvanced(value: Boolean); begin FShowAdvanced := Value; Advanced.TabVisible := Value; end; end.
unit Model.Declarations; interface uses Model.ProSu.InterfaceActions, Model.ProSu.Interfaces; type TCustomer = class private fID: Integer; fName: string; fDiscountRate: Double; fBalance: Currency; public property ID: integer read fID write fID; property Name: string read fName write fName; property DiscountRate: double read fDiscountRate write fDiscountRate; property Balance: Currency read fBalance write fBalance; end; TItem = class private fID: Integer; fDescription: string; fPrice: Currency; public property ID: integer read fID write fID; property Description: string read fDescription write fDescription; property Price: Currency read fPrice write fPrice; end; TInvoice = class private fID: integer; fNumber: integer; fCustomerID: Integer; public property ID: Integer read fID write fID; property Number: Integer read fNumber write fNumber; property CustomerID: Integer read fCustomerID write fCustomerID; end; TInvoiceItem = class private fID: integer; fInvoiceID: integer; fItemID: integer; fUnitPrice: Currency; fQuantity: integer; public property ID: integer read fID write fID; property InvoiceID: integer read fInvoiceID write fInvoiceID; property ItemID: integer read fItemID write fItemID; property UnitPrice: Currency read fUnitPrice write fUnitPrice; property Quantity: Integer read fQuantity write fQuantity; end; TMainFormLabelsText = record Title, IssueButtonCaption, TotalSalesText: string; end; TNotificationClass = class (TInterfacedObject, INotificationClass) private fActions: TInterfaceActions; fActionValue: Double; public property Actions: TInterfaceActions read fActions write fActions; property ActionValue: double read fActionValue write fActionValue; end; TInvoiceFormLabelsText = record Title, CustomerDetailsGroupText, CustomerText, CustomerDiscountRateText, CustomerOutstandingBalanceText, InvoiceItemsGroupText, InvoiceItemsText, InvoiceItemsQuantityText, InvoiceItemsAddItemButtonText, InvoiceItemsGridItemText, InvoiceItemsGridQuantityText, InvoiceItemsGridUnitPriceText, InvoiceItemsGridAmountText, BalanceGroupText, BalanceInvoiceBalanceText, BalanceDiscountText, BalanceTotalText, PrintInvoiceButtonText, PrintingText, CancelButtonText: string; end; TCustomerDetailsText = record DiscountRate, OutstandingBalance: string; end; TInvoiceItemsText = record DescriptionText, QuantityText, UnitPriceText, PriceText, IDText: array of string; InvoiceRunningBalance, InvoiceDiscountFigure, InvoiceTotalBalance: string; end; TErrorNotificationClass = class (TInterfacedObject, INotificationClass) private fActions: TInterfaceErrors; fActionMessage: string; public property Actions: TInterfaceErrors read fActions write fActions; property ActionMessage: string read fActionMessage write fActionMessage; end; implementation end.
unit JurosRN; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Mask, RxToolEdit, RxCurrEdit, Vcl.ComCtrls, Vcl.ToolWin, Vcl.ExtCtrls, System.ImageList, Vcl.ImgList, PngImageList, RxLookup, DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, JurosDAO, Juros, TipoJuros; type TJurosRN = class private JurosDAO: TJurosDao; bNovo, bAtualizar, bVisualizar: boolean; public constructor Create; destructor Destroy; override; procedure editarStringGrid(juros: Tjuros); procedure excluir(Juros: TJuros); procedure editar(Juros: TJuros); procedure incluir(Juros: TJuros); procedure abreFormTipoJuros(); procedure Pesquisar(zGet: TZquery; edtDe, edtAte: double; TipoJuros: TTipoJuros); procedure pesquisarStringGrid(zGet: TZQuery); function existeCadastroTipoJuros(TipoJuros: TTipoJuros): boolean; function getTipoJuros(): TDataSource; function getStatusTipoJuros(): TDataSource; function verificaExclusao(Juros: TJuros): boolean; end; implementation uses uCadastroJuros, uPesquisaJuros, uCadastroTipoJuros; constructor TJurosRN.Create; begin JurosDao := TJurosDao.Create; end; destructor TJurosRN.Destroy; begin inherited; end; procedure TJurosRN.editar(Juros: TJuros); begin JurosDao.editar(juros); end; procedure TJurosRN.editarStringGrid(juros: Tjuros); begin JurosDAO.editarStringGrid(juros); end; procedure TJurosRN.excluir(Juros: TJuros); begin JurosDao.excluir(juros); end; function TJurosRN.existeCadastroTipoJuros(TipoJuros: TTipoJuros): boolean; begin result := JurosDAO.existeCadastroTipoJuros(TipoJuros); end; function TJurosRN.getStatusTipoJuros: TDataSource; begin Result := JurosDAO.getStatusTipoJuros; end; function TJurosRN.getTipoJuros: TDataSource; begin result := JurosDAO.getTipoJuros(); end; procedure TJurosRN.incluir(Juros: TJuros); begin JurosDao.incluir(juros); end; function TJurosRN.verificaExclusao(Juros: TJuros): boolean; begin result := JurosDAO.verificaExclusao(Juros); end; procedure TJurosRN.abreFormTipoJuros; begin if frmCadastroTipoJuros = nil then begin frmCadastroTipoJuros := TfrmCadastroTipoJuros.Create(frmCadastroTipoJuros); frmCadastroTipoJuros.ShowModal; end; end; procedure TJurosRN.Pesquisar(zGet: TZquery; edtDe, edtAte: double; TipoJuros: TTipoJuros); begin JurosDAO.pesquisar(zGet, edtde, edtate, tipojuros); end; procedure TJurosRN.pesquisarStringGrid(zGet: TZQuery); begin JurosDAO.pesquisarStringGrid(zGet); end; end.
program StackTestFrame; procedure AnotherProc(aParam: Integer); begin WriteLn('The frame for AnotherProc starts at ', HexStr(get_frame)); WriteLn('-------------------------------'); WriteLn('aParam is at ', HexStr(@aParam)); WriteLn('-------------------------------'); end; procedure Main(aParam: Integer); var myData: Integer; myOtherData: Array [0..1024] of Integer; begin WriteLn('The frame for Main starts at ', HexStr(get_frame)); WriteLn('-------------------------------'); WriteLn('aParam is at ', HexStr(@aParam), ' to ', HexStr(Cardinal(@aParam) + SizeOf(aParam), 8)); WriteLn('myData is at ', HexStr(@myData), ' to ', HexStr(Cardinal(@myData) + SizeOf(myData), 8)); WriteLn('myOtherData goes from ', HexStr(@myOtherData), ' to ', HexStr(Cardinal(@myOtherData) + SizeOf(myOtherData), 8)); //12.3 Stack Frame 111; WriteLn('-------------------------------'); AnotherProc(1); end; begin WriteLn('The frame for the program is at ', HexStr(get_frame)); Main(1); end.
unit Onoff; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TOnOff = class(TGraphicControl) public constructor Create( anOwner : TComponent ); override; destructor Destroy; override; private fState : boolean; fBitmap : TBitmap; fOnChange : TNotifyEvent; fOnTurnOn : TNotifyEvent; fOnTurnOff : TNotifyEvent; protected procedure SetEnabled( aEnabled : boolean ); override; procedure SetState( aState : boolean ); published property State : boolean read fState write SetState default false; property Anchors; property Enabled; published property OnChange : TNotifyEvent read fOnChange write fOnChange; property OnTurnOn : TNotifyEvent read fOnTurnOn write fOnTurnOn; property OnTurnOff : TNotifyEvent read fOnTurnOff write fOnTurnOff; property OnClick; property ShowHint; public property Bitmap : TBitmap read fBitmap; protected procedure Paint; override; private procedure UpdateBitmap; function BitmapName : string; virtual; abstract; end; TBulb = class(TOnOff) private function BitmapName : string; override; end; TLedColor = ( ldRed, ldGreen, ldYellow ); TLed = class(TOnOff) private theColor : TLedColor; procedure SetColor( aColor : TLedColor ); published property Color : TLedColor read theColor write SetColor; private function BitmapName : string; override; end; procedure Register; implementation {$R Onoff.res} { TOnOff methods } constructor TOnOff.Create( anOwner : TComponent ); begin inherited Create( anOwner ); Enabled := true; UpdateBitmap; end; destructor TOnOff.Destroy; begin fBitmap.Free; inherited; end; procedure TOnOff.SetEnabled( aEnabled : boolean ); begin inherited; UpdateBitmap; Repaint; end; procedure TOnOff.SetState( aState : boolean ); begin if Enabled and (fState <> aState) then begin fState := aState; UpdateBitmap; Repaint; if assigned(fOnChange) then fOnChange( Self ); if fState then begin if assigned(fOnTurnOn) then fOnTurnOn( Self ); end else begin if assigned(fOnTurnOff) then fOnTurnOff( Self ); end; end; end; procedure TOnOff.Paint; begin Canvas.Draw( 0, 0, fBitmap ); end; procedure TOnOff.UpdateBitmap; begin if fBitMap = nil then fBitMap := TBitMap.Create; fBitmap.LoadFromResourceName( HInstance, BitmapName ); SetBounds( Left, Top, Bitmap.Width, Bitmap.Height ); end; {TBulb methods} function TBulb.BitmapName : string; begin if Enabled then if State then Result := 'BulbOn' else Result := 'BulbOff' else Result := 'BulbDisabled'; end; {TLed methods} procedure TLed.SetColor( aColor : TLedColor ); begin if theColor <> aColor then begin theColor := aColor; UpdateBitmap; Repaint; end; end; function TLed.BitmapName : string; begin if Enabled then if State then case Color of ldRed : Result := 'RedLedOn'; ldGreen : Result := 'GreenLedOn'; ldYellow : Result := 'YellowLedOn'; else Result := 'LedDisabled'; end else case Color of ldRed : Result := 'RedLedOff'; ldGreen : Result := 'GreenLedOff'; ldYellow : Result := 'YellowLedOff'; else Result := 'LedDisabled'; end else Result := 'LedDisabled'; end; { Public procedures & functions } procedure Register; begin RegisterComponents('Vesta', [TBulb, TLed]); end; end.
unit LoadFarmacyFormTest; interface uses TestFramework, Forms; type TLoadFormTest = class(TTestCase) private function GetForm(FormClass: string): TForm; protected // подготавливаем данные для тестирования procedure SetUp; override; published procedure MainFormTest; // procedure LoadCashFormTest; procedure LoadAccountFormTest; procedure LoadAdditionalGoodsFormTest; procedure LoadAlternativeGroupFormTest; procedure LoadArticleLossEditFormTest; procedure LoadArticleLossFormTest; procedure LoadAreaFormTest; procedure LoadAsinoPharmaSPFormTest; procedure LoadBankFormTest; procedure LoadBankAccountFormTest; procedure LoadBankAccountDocumentFormTest; procedure LoadBankPOSTerminalFormTest; procedure LoadBankStatementFormTest; procedure LoadBuyerFormTest; procedure LoadCalendarFormTest; procedure LoadCancelReasonFormTest; procedure LoadCashRegisterFormTest; procedure LoadChangeIncomePaymentKindFormTest; procedure LoadChangeIncomePaymentFormTest; procedure LoadCheckFormTest; procedure LoadCheckDeferredFormTest; procedure LoadCheckVIPFormTest; procedure LoadCheckLiki24FormTest; procedure LoadCheckSiteFormTest; procedure LoadConditionsKeepFormTest; procedure LoadContactPersonFormTest; procedure LoadClientsByBankFormTest; procedure LoadComputerAccessoriesFormTest; procedure LoadCompetitorMarkupsFormTest; procedure LoadContractFormTest; procedure LoadCreditLimitDistributorFormTest; procedure LoadCurrencyFormTest; procedure LoadCreateOrderFromMCSFormTest; procedure LoadDefaultFormTest; procedure LoadDiscountFormTest; procedure LoadDistributionPromoFormTest; procedure LoadDiffKindFormTest; procedure LoadDivisionPartiesFormTest; procedure LoadDriverTest; procedure LoadDriverSunTest; procedure LoadEnumFormTest; procedure LoadEmailFormTest; procedure LoadEmailSettingsFormTest; procedure LoadEmployeeScheduleFormTest; procedure LoadEmployeeScheduleVIPFormTest; procedure LoadExchangeRatesFormTest; procedure LoadFinalSUAFormTest; procedure LoadFilesToCheckFormTest; procedure LoadFiscalFormTest; procedure LoadGoodsGroupFormTest; procedure LoadGoodsGroupPromoFormTest; procedure LoadGoodsFormTest; procedure LoadGoodsInventoryFormTest; procedure LoadGoodsCategoryFormTest; procedure LoadGoodsSPMovementFormTest; procedure LoadGoodsSP_1303FormTest; procedure LoadGoodsRepriceFormTest; procedure LoadHardwareFormTest; procedure LoadHouseholdInventoryFormTest; procedure LoadInventoryHouseholdInventoryFormTest; procedure LoadInternetRepairFormTest; procedure LoadImportSettingsFormTest; procedure LoadImportTypeFormTest; procedure LoadIncomeFormTest; procedure LoadIncomeHouseholdInventoryFormTest; procedure LoadInfoMoneyGroupFormTest; procedure LoadInfoMoneyDestinationFormTest; procedure LoadInfoMoneyFormTest; procedure LoadInstructionsFormTest; procedure LoadInsuranceCompaniesFormTest; procedure LoadInventoryFormTest; procedure LoadInventoryLocalFormTest; procedure LoadInvoiceFormTest; procedure LoadIlliquidUnitFormTest; procedure LoadJuridicalFormTest; procedure LoadJuridicalAreaFormTest; procedure LoadLayoutFormTest; procedure LoadLayoutFileFormTest; procedure LoadLoadFormTest; procedure LoadLoyaltyFormTest; procedure LoadLoyaltyPresentFormTest; procedure LoadLoyaltySaveMoneyFormTest; procedure LoadLossDebtFormTest; procedure LoadLossFormTest; procedure LoadListDiffFormTest; procedure LoadMakerFormTest; procedure LoadMargineCategory; procedure LoadMarginCategoryMovement; procedure LoadMarginReport; procedure LoadMeasureFormTest; procedure LoadMemberFormTest; procedure LoadMemberICFormTest; procedure LoadMemberIncomeCheckFormTest; procedure LoadMovementReportUnLiquidFormtest; procedure LoadKindFormTest; procedure LoadOrderSheduleFormTest; procedure LoadOrderInternalFormTest; procedure LoadOrderInternalPromoFormTest; procedure LoadOrderExternalFormTest; procedure LoadObjectUnionFormTest; procedure LoadOverFormTest; procedure LoadOverSettingsFormTest; procedure LoadPaidKindFormTest; procedure LoadPaidTypeFormTest; procedure LoadPartnerMedicalFormTest; procedure LoadPartionDateKindFormTest; procedure LoadPaymentFormTest; procedure LoadPermanentDiscountFormTest; procedure LoadPersonalFormTest; procedure LoadPersonalGroupFormTest; procedure LoadPlanIventoryFormTest; procedure LoadPositionEducationFormTest; procedure LoadPriceListFormTest; procedure LoadPretensionFormTest; procedure LoadPriceFormTest; procedure LoadPriceSiteFormTest; procedure LoadPriceChangeFormTest; procedure LoadProjectsImprovementsFormTest; procedure LoadProfitLossFormTest; procedure LoadProfitLossGroupFormTest; procedure LoadProfitLossDirectionFormTest; procedure LoadPromoFormTest; procedure LoadPromoCodeFormTest; procedure LoadPromoBonusFormTest; procedure LoadPromoUnitFormTest; procedure LoadProvinceCityFormTest; procedure LoadReasonDifferencesFormTest; procedure LoadRelatedProductFormTest; procedure LoadReportPromoParamsFormTest; procedure LoadReportSoldParamsFormTest; procedure LoadReportFormTest; procedure LoadRogerseFormTest; procedure LoadReportForSiteTest; procedure LoadReportUploadFormTest; procedure LoadRepriceFormTest; procedure LoadRepriceChangeFormTest; procedure LoadRepriceSiteFormTest; procedure LoadRetailFormTest; procedure LoadRetailCostCreditFormTest; procedure LoadReturnInFormTest; procedure LoadReturnTypeFormTest; procedure LoadReturnOutFormTest; procedure LoadSaleFormTest; procedure LoadSalePromoGoodsFormTest; procedure LoadServiceFormTest; procedure LoadSeasonalityCoefficientFormTest; procedure LoadSendFormTest; procedure LoadSendPartionDateFormTest; procedure LoadSendPartionDateChangeFormTest; procedure LoadSendOnPriceFormTest; procedure LoadSystemFormTest; procedure LoadSPObjectFormTest; procedure LoadSPKindFormTest; procedure LoadSheetWorkTimeFormTest; procedure LoadSunExclusionFormTest; procedure LoadTaxUnitFormTest; procedure LoadTechnicalRediscountFormTest; procedure LoadTestingTuningFormTest; procedure LoadUnitFormTest; procedure LoadUnionFormTest; procedure LoadUnnamedEnterprisesFormTest; procedure LoadWagesFormTest; procedure LoadWagesVIPFormTest; procedure LoadWriteOffHouseholdInventoryFormTest; procedure FormTest; end; implementation uses CommonData, Storage, FormStorage, Classes, Authentication, SysUtils, cxPropertiesStore, cxStorage, DBClient, dsdDB, ActionTest, MainForm, UtilConst; { TLoadFormTest } procedure TLoadFormTest.FormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TTestForm')); TdsdFormStorageFactory.GetStorage.Load('TTestForm'); end; function TLoadFormTest.GetForm(FormClass: string): TForm; begin if GetClass(FormClass) = nil then raise Exception.Create('Не зарегистрирован класс: ' + FormClass); Application.CreateForm(TComponentClass(GetClass(FormClass)), Result); end; procedure TLoadFormTest.LoadDefaultFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TSetUserDefaultsForm')); TdsdFormStorageFactory.GetStorage.Load('TSetUserDefaultsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDefaultsKeyForm')); TdsdFormStorageFactory.GetStorage.Load('TDefaultsKeyForm'); end; procedure TLoadFormTest.LoadDiscountFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TDiscountExternalSupplierEditForm')); TdsdFormStorageFactory.GetStorage.Load('TDiscountExternalSupplierEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDiscountExternalSupplierForm')); TdsdFormStorageFactory.GetStorage.Load('TDiscountExternalSupplierForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDiscountExternalForm')); TdsdFormStorageFactory.GetStorage.Load('TDiscountExternalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDiscountExternalEditForm')); TdsdFormStorageFactory.GetStorage.Load('TDiscountExternalEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDiscountExternal_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TDiscountExternal_ObjectForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TDiscountExternalToolsForm')); TdsdFormStorageFactory.GetStorage.Load('TDiscountExternalToolsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDiscountExternalToolsEditForm')); TdsdFormStorageFactory.GetStorage.Load('TDiscountExternalToolsEditForm'); Exit; TdsdFormStorageFactory.GetStorage.Save (GetForm('TDiscountExternalTools_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TDiscountExternalTools_ObjectForm'); } TdsdFormStorageFactory.GetStorage.Save(GetForm('TDiscountExternalJuridicalForm')); TdsdFormStorageFactory.GetStorage.Load('TDiscountExternalJuridicalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDiscountExternalJuridicalEditForm')); TdsdFormStorageFactory.GetStorage.Load('TDiscountExternalJuridicalEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TBarCodeForm')); TdsdFormStorageFactory.GetStorage.Load('TBarCodeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TBarCodeEditForm')); TdsdFormStorageFactory.GetStorage.Load('TBarCodeEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDiscountCardForm')); TdsdFormStorageFactory.GetStorage.Load('TDiscountCardForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDiscountCardEditForm')); TdsdFormStorageFactory.GetStorage.Load('TDiscountCardEditForm'); end; procedure TLoadFormTest.LoadDistributionPromoFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TDistributionPromoJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TDistributionPromoJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDistributionPromoForm')); TdsdFormStorageFactory.GetStorage.Load('TDistributionPromoForm'); end; procedure TLoadFormTest.LoadAccountFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TAccountGroupForm')); TdsdFormStorageFactory.GetStorage.Load('TAccountGroupForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAccountGroup_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TAccountGroup_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAccountGroupEditForm')); TdsdFormStorageFactory.GetStorage.Load('TAccountGroupEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAccountDirectionForm')); TdsdFormStorageFactory.GetStorage.Load('TAccountDirectionForm'); TdsdFormStorageFactory.GetStorage.Save (GetForm('TAccountDirection_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TAccountDirection_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAccountDirectionEditForm')); TdsdFormStorageFactory.GetStorage.Load('TAccountDirectionEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAccountForm')); TdsdFormStorageFactory.GetStorage.Load('TAccountForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAccount_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TAccount_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAccountEditForm')); TdsdFormStorageFactory.GetStorage.Load('TAccountEditForm'); end; procedure TLoadFormTest.LoadBankFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TBankForm')); TdsdFormStorageFactory.GetStorage.Load('TBankForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TBankEditForm')); TdsdFormStorageFactory.GetStorage.Load('TBankEditForm'); end; procedure TLoadFormTest.LoadAreaFormTest; begin // Регионы TdsdFormStorageFactory.GetStorage.Save(GetForm('TAreaForm')); TdsdFormStorageFactory.GetStorage.Load('TAreaForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAreaEditForm')); TdsdFormStorageFactory.GetStorage.Load('TAreaEditForm'); end; procedure TLoadFormTest.LoadAsinoPharmaSPFormTest; begin // Регионы TdsdFormStorageFactory.GetStorage.Save(GetForm('TAsinoPharmaSPJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TAsinoPharmaSPJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAsinoPharmaSPForm')); TdsdFormStorageFactory.GetStorage.Load('TAsinoPharmaSPForm'); end; procedure TLoadFormTest.LoadDiffKindFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TDiffKindForm')); TdsdFormStorageFactory.GetStorage.Load('TDiffKindForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDiffKindEditForm')); TdsdFormStorageFactory.GetStorage.Load('TDiffKindEditForm'); end; procedure TLoadFormTest.LoadDivisionPartiesFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TDivisionPartiesForm')); TdsdFormStorageFactory.GetStorage.Load('TDivisionPartiesForm'); end; procedure TLoadFormTest.LoadDriverTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TDriverForm')); TdsdFormStorageFactory.GetStorage.Load('TDriverForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDriverEditForm')); TdsdFormStorageFactory.GetStorage.Load('TDriverEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnitLincDriverForm')); TdsdFormStorageFactory.GetStorage.Load('TUnitLincDriverForm'); end; procedure TLoadFormTest.LoadDriverSunTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TDriverSunForm')); TdsdFormStorageFactory.GetStorage.Load('TDriverSunForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDriverSunEditForm')); TdsdFormStorageFactory.GetStorage.Load('TDriverSunEditForm'); end; procedure TLoadFormTest.LoadBankStatementFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TBankStatementJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TBankStatementJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TBankStatementForm')); TdsdFormStorageFactory.GetStorage.Load('TBankStatementForm'); end; procedure TLoadFormTest.LoadBuyerFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TBuyerForm')); TdsdFormStorageFactory.GetStorage.Load('TBuyerForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TBuyerEditForm')); TdsdFormStorageFactory.GetStorage.Load('TBuyerEditForm'); end; procedure TLoadFormTest.LoadBankAccountDocumentFormTest; begin TdsdFormStorageFactory.GetStorage.Save (GetForm('TBankAccountJournalFarmacyForm')); TdsdFormStorageFactory.GetStorage.Load('TBankAccountJournalFarmacyForm'); TdsdFormStorageFactory.GetStorage.Save (GetForm('TBankAccountMovementFarmacyForm')); TdsdFormStorageFactory.GetStorage.Load('TBankAccountMovementFarmacyForm'); TdsdFormStorageFactory.GetStorage.Save (GetForm('TBankAccountJournalFarmacyDialogForm')); TdsdFormStorageFactory.GetStorage.Load ('TBankAccountJournalFarmacyDialogForm'); end; procedure TLoadFormTest.LoadBankPOSTerminalFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TBankPOSTerminalForm')); TdsdFormStorageFactory.GetStorage.Load('TBankPOSTerminalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TBankPOSTerminalEditForm')); TdsdFormStorageFactory.GetStorage.Load('TBankPOSTerminalEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnitBankPOSTerminalForm')); TdsdFormStorageFactory.GetStorage.Load('TUnitBankPOSTerminalForm'); end; procedure TLoadFormTest.LoadBankAccountFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TBankAccountForm')); TdsdFormStorageFactory.GetStorage.Load('TBankAccountForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TBankAccountEditForm')); TdsdFormStorageFactory.GetStorage.Load('TBankAccountEditForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TBankAccount_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TBankAccount_ObjectForm');} end; // procedure TLoadFormTest.LoadCashFormTest; // begin // TdsdFormStorageFactory.GetStorage.Save(GetForm('TMainCashForm')); // TdsdFormStorageFactory.GetStorage.Load('TMainCashForm'); // end; procedure TLoadFormTest.LoadCashRegisterFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TSaleInsuranceCompaniesCashForm')); TdsdFormStorageFactory.GetStorage.Load('TSaleInsuranceCompaniesCashForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TLayoutFileCashForm')); TdsdFormStorageFactory.GetStorage.Load('TLayoutFileCashForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSPReceiptListForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSPReceiptListForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckJackdawsGreenJournalCashForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckJackdawsGreenJournalCashForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCustomerThresho_RemainsGoodsCashForm')); TdsdFormStorageFactory.GetStorage.Load('TCustomerThresho_RemainsGoodsCashForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSP_CashForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSP_CashForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsUnitRetail_CashForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsUnitRetail_CashForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAccommodationLincGoodsForm')); TdsdFormStorageFactory.GetStorage.Load('TAccommodationLincGoodsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAccommodationLincGoodsLogForm')); TdsdFormStorageFactory.GetStorage.Load('TAccommodationLincGoodsLogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsDivisionLockForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsDivisionLockForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOverdueChangeCashPUSHSendForm')); TdsdFormStorageFactory.GetStorage.Load('TOverdueChangeCashPUSHSendForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOverdueChangeCashJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TOverdueChangeCashJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCashRegisterForm')); TdsdFormStorageFactory.GetStorage.Load('TCashRegisterForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCashRegisterEditForm')); TdsdFormStorageFactory.GetStorage.Load('TCashRegisterEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCashRegisterKindForm')); TdsdFormStorageFactory.GetStorage.Load('TCashRegisterKindForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAccommodationForm')); TdsdFormStorageFactory.GetStorage.Load('TAccommodationForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAccommodationEditForm')); TdsdFormStorageFactory.GetStorage.Load('TAccommodationEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCashGoodsOneToExpirationDateForm')); TdsdFormStorageFactory.GetStorage.Load('TCashGoodsOneToExpirationDateForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOverdueDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TOverdueDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOverdueJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TOverdueJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOverdue_UpdateRangeCat5DialogForm')); TdsdFormStorageFactory.GetStorage.Load('TOverdue_UpdateRangeCat5DialogForm'); } end; procedure TLoadFormTest.LoadCalendarFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TCalendarForm')); TdsdFormStorageFactory.GetStorage.Load('TCalendarForm'); end; procedure TLoadFormTest.LoadCancelReasonFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TCancelReasonEditForm')); TdsdFormStorageFactory.GetStorage.Load('TCancelReasonEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCancelReasonForm')); TdsdFormStorageFactory.GetStorage.Load('TCancelReasonForm'); end; procedure TLoadFormTest.LoadCheckFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckSummCardForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckSummCardForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TCommentCheckForm')); TdsdFormStorageFactory.GetStorage.Load('TCommentCheckForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCommentCheckEditForm')); TdsdFormStorageFactory.GetStorage.Load('TCommentCheckEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckErrorInsertDateForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckErrorInsertDateForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckRedForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckRedForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckSiteInsertForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckSiteInsertForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheck_ConfirmedByPhoneCallForm')); TdsdFormStorageFactory.GetStorage.Load('TCheck_ConfirmedByPhoneCallForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheck_RefusalConfirmedForm')); TdsdFormStorageFactory.GetStorage.Load('TCheck_RefusalConfirmedForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMedicForSaleForm')); TdsdFormStorageFactory.GetStorage.Load('TMedicForSaleForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMedicForSaleEditForm')); TdsdFormStorageFactory.GetStorage.Load('TMedicForSaleEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TBuyerForSaleForm')); TdsdFormStorageFactory.GetStorage.Load('TBuyerForSaleForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TBuyerForSaleEditForm')); TdsdFormStorageFactory.GetStorage.Load('TBuyerForSaleEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckJournalDiscountExternalForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckJournalDiscountExternalForm'); Exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TMemberSPChoiceDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TMemberSPChoiceDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckJournalUserForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckJournalUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TChoiceDeferredCheckForm')); TdsdFormStorageFactory.GetStorage.Load('TChoiceDeferredCheckForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TPartionGoodsListForm')); TdsdFormStorageFactory.GetStorage.Load('TPartionGoodsListForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TJackdawsChecksForm')); TdsdFormStorageFactory.GetStorage.Load('TJackdawsChecksForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TJackdawsChecksEditForm')); TdsdFormStorageFactory.GetStorage.Load('TJackdawsChecksEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckNoCashRegisterForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckNoCashRegisterForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckPrintDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckPrintDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDataTimeDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TDataTimeDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheck_SPEditForm')); TdsdFormStorageFactory.GetStorage.Load('TCheck_SPEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckUnCompleteForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckUnCompleteForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCashSummaForDeyForm')); TdsdFormStorageFactory.GetStorage.Load('TCashSummaForDeyForm'); } end; procedure TLoadFormTest.LoadConditionsKeepFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TConditionsKeepForm')); TdsdFormStorageFactory.GetStorage.Load('TConditionsKeepForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TConditionsKeepEditForm')); TdsdFormStorageFactory.GetStorage.Load('TConditionsKeepEditForm'); end; procedure TLoadFormTest.LoadContactPersonFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TContactPersonForm')); TdsdFormStorageFactory.GetStorage.Load('TContactPersonForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TContactPersonEditForm')); TdsdFormStorageFactory.GetStorage.Load('TContactPersonEditForm'); // Вид контакта TdsdFormStorageFactory.GetStorage.Save(GetForm('TContactPersonKindForm')); TdsdFormStorageFactory.GetStorage.Load('TContactPersonKindForm'); // это ж !!!Enum!!! // TdsdFormStorageFactory.GetStorage.Save(GetForm('TContactPersonKindEditForm')); // TdsdFormStorageFactory.GetStorage.Load('TContactPersonKindEditForm'); end; procedure TLoadFormTest.LoadClientsByBankFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TClientsByBankForm')); TdsdFormStorageFactory.GetStorage.Load('TClientsByBankForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TClientsByBankEditForm')); TdsdFormStorageFactory.GetStorage.Load('TClientsByBankEditForm'); end; procedure TLoadFormTest.LoadComputerAccessoriesFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TComputerAccessoriesForm')); TdsdFormStorageFactory.GetStorage.Load('TComputerAccessoriesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TComputerAccessoriesEditForm')); TdsdFormStorageFactory.GetStorage.Load('TComputerAccessoriesEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TComputerAccessoriesRegisterForm')); TdsdFormStorageFactory.GetStorage.Load('TComputerAccessoriesRegisterForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TComputerAccessoriesRegisterJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TComputerAccessoriesRegisterJournalForm'); end; procedure TLoadFormTest.LoadCompetitorMarkupsFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TCompetitorMarkupsForm')); TdsdFormStorageFactory.GetStorage.Load('TCompetitorMarkupsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCompetitorMarkupsJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TCompetitorMarkupsJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCompetitorForm')); TdsdFormStorageFactory.GetStorage.Load('TCompetitorForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCompetitorEditForm')); TdsdFormStorageFactory.GetStorage.Load('TCompetitorEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceSubgroupsEditForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceSubgroupsEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceSubgroupsForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceSubgroupsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMCRequestAllDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TMCRequestAllDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMCRequestShowPUSHForm')); TdsdFormStorageFactory.GetStorage.Load('TMCRequestShowPUSHForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMCRequestInfoPUSHForm')); TdsdFormStorageFactory.GetStorage.Load('TMCRequestInfoPUSHForm'); end; procedure TLoadFormTest.LoadContractFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TContractForm')); TdsdFormStorageFactory.GetStorage.Load('TContractForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TContractEditForm')); TdsdFormStorageFactory.GetStorage.Load('TContractEditForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TContract_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TContract_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TContractChoiceForm')); TdsdFormStorageFactory.GetStorage.Load('TContractChoiceForm'); } end; procedure TLoadFormTest.LoadCreateOrderFromMCSFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TCreateOrderFromMCSLayoutForm')); TdsdFormStorageFactory.GetStorage.Load('TCreateOrderFromMCSLayoutForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRecalcMCSShedulerForm')); TdsdFormStorageFactory.GetStorage.Load('TRecalcMCSShedulerForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TRecalcMCSShedulerEditForm')); TdsdFormStorageFactory.GetStorage.Load('TRecalcMCSShedulerEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRecalcMCSShedulerSunDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TRecalcMCSShedulerSunDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRecalcMCSShedulerMainDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TRecalcMCSShedulerMainDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TWeekForm')); TdsdFormStorageFactory.GetStorage.Load('TWeekForm'); Exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TCreateOrderFromMCSForm')); TdsdFormStorageFactory.GetStorage.Load('TCreateOrderFromMCSForm');} end; procedure TLoadFormTest.LoadCreditLimitDistributorFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TCreditLimitDistributorForm')); TdsdFormStorageFactory.GetStorage.Load('TCreditLimitDistributorForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCreditLimitDistributorEditForm')); TdsdFormStorageFactory.GetStorage.Load('TCreditLimitDistributorEditForm'); end; procedure TLoadFormTest.LoadCurrencyFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TCurrencyForm')); TdsdFormStorageFactory.GetStorage.Load('TCurrencyForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCurrencyEditForm')); TdsdFormStorageFactory.GetStorage.Load('TCurrencyEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCurrency_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TCurrency_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCurrencyValue_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TCurrencyValue_ObjectForm'); end; procedure TLoadFormTest.LoadFinalSUAFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TFinalSUAForm')); TdsdFormStorageFactory.GetStorage.Load('TFinalSUAForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TFinalSUAJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TFinalSUAJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_AutoCalculation_SAUADialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_AutoCalculation_SAUADialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_AutoCalculation_SAUAForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_AutoCalculation_SAUAForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnitAutoSUAForm')); TdsdFormStorageFactory.GetStorage.Load('TUnitAutoSUAForm'); end; procedure TLoadFormTest.LoadFilesToCheckFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TFilesToCheckForm')); TdsdFormStorageFactory.GetStorage.Load('TFilesToCheckForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TFilesToCheckJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TFilesToCheckJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TFilesToCheckCashForm')); TdsdFormStorageFactory.GetStorage.Load('TFilesToCheckCashForm'); end; procedure TLoadFormTest.LoadFiscalFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TFiscalForm')); TdsdFormStorageFactory.GetStorage.Load('TFiscalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TFiscalEditForm')); TdsdFormStorageFactory.GetStorage.Load('TFiscalEditForm'); end; procedure TLoadFormTest.LoadGoodsInventoryFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsInventoryDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsInventoryDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsInventoryForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsInventoryForm'); end; procedure TLoadFormTest.LoadGoodsCategoryFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsCategoryForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsCategoryForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsCategoryEditForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsCategoryEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsCategoryCopyForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsCategoryCopyForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsCategoryAddGoodsForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsCategoryAddGoodsForm'); end; procedure TLoadFormTest.LoadGoodsFormTest; begin { TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsAdditionalEditForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsAdditionalEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsAdditionalEditDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsAdditionalEditDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsMakerNameForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsMakerNameForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TFormDispensingEditForm')); TdsdFormStorageFactory.GetStorage.Load('TFormDispensingEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TFormDispensingForm')); TdsdFormStorageFactory.GetStorage.Load('TFormDispensingForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSUNForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsWagesForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsWagesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSiteForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSiteForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsCashForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsCashForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSiteDiscontDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TSiteDiscontDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsUnitSupplementSUN1Form')); TdsdFormStorageFactory.GetStorage.Load('TGoodsUnitSupplementSUN1Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoods_SiteUpdateForm')); TdsdFormStorageFactory.GetStorage.Load('TGoods_SiteUpdateForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSignOriginForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSignOriginForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSignOriginEditForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSignOriginEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsWhoCanForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsWhoCanForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsWhoCanEditForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsWhoCanEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsMethodApplEditForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsMethodApplEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsMethodApplForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsMethodApplForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsEditForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoods_GoodsPairSun_EditForm')); TdsdFormStorageFactory.GetStorage.Load('TGoods_GoodsPairSun_EditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoods_LimitSUN_T_EditForm')); TdsdFormStorageFactory.GetStorage.Load('TGoods_LimitSUN_T_EditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoods_KoeffSUN_EditForm')); TdsdFormStorageFactory.GetStorage.Load('TGoods_KoeffSUN_EditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsRetailTab_ErrorForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsRetailTab_ErrorForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsMainTab_ErrorForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsMainTab_ErrorForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsAll_TabForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsAll_TabForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsAllRetail_TabForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsAllRetail_TabForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsRetailForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsRetailForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsRetailDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsRetailDialogForm'); exit; } TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoods_BarCodeForm')); TdsdFormStorageFactory.GetStorage.Load('TGoods_BarCodeForm'); exit; { TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsAllForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsAllForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsAllRetailForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsAllRetailForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsAllJuridicalForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsAllJuridicalForm'); //exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsPartnerCodeForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsPartnerCodeForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsPartnerCodeMasterForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsPartnerCodeMasterForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoods_NDS_diffForm')); TdsdFormStorageFactory.GetStorage.Load('TGoods_NDS_diffForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsTopDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsTopDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsAnalogForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsAnalogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsAnalogEditForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsAnalogEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TExchangeForm')); TdsdFormStorageFactory.GetStorage.Load('TExchangeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TExchangeEditForm')); TdsdFormStorageFactory.GetStorage.Load('TExchangeEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsMainForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsMainForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsMainEditForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsMainEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsLiteForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsLiteForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsMainLiteForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsMainLiteForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPartionGoodsChoiceForm')); TdsdFormStorageFactory.GetStorage.Load('TPartionGoodsChoiceForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsAllForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsAllForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsAllRetailForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsAllRetailForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsAllJuridicalForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsAllJuridicalForm'); } end; procedure TLoadFormTest.LoadMemberFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TMemberForm')); TdsdFormStorageFactory.GetStorage.Load('TMemberForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMember_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TMember_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMemberEditForm')); TdsdFormStorageFactory.GetStorage.Load('TMemberEditForm'); end; procedure TLoadFormTest.LoadMemberICFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TMemberICEditForm')); TdsdFormStorageFactory.GetStorage.Load('TMemberICEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMemberICForm')); TdsdFormStorageFactory.GetStorage.Load('TMemberICForm'); end; procedure TLoadFormTest.LoadMemberIncomeCheckFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TMemberIncomeCheckForm')); TdsdFormStorageFactory.GetStorage.Load('TMemberIncomeCheckForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMemberIncomeCheckEditForm')); TdsdFormStorageFactory.GetStorage.Load('TMemberIncomeCheckEditForm'); end; procedure TLoadFormTest.LoadMakerFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TMakerForm')); TdsdFormStorageFactory.GetStorage.Load('TMakerForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMakerEditForm')); TdsdFormStorageFactory.GetStorage.Load('TMakerEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMakerReportForm')); TdsdFormStorageFactory.GetStorage.Load('TMakerReportForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TMakerReportEditForm')); TdsdFormStorageFactory.GetStorage.Load('TMakerReportEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMaker_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TMaker_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCountryForm')); TdsdFormStorageFactory.GetStorage.Load('TCountryForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCountryEditForm')); TdsdFormStorageFactory.GetStorage.Load('TCountryEditForm'); } end; procedure TLoadFormTest.LoadMargineCategory; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategory_AllForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategory_AllForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPersentSalaryDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TPersentSalaryDialogForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategoryAllDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategoryAllDialogForm'); exit; { TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategoryItemHistoryForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategoryItemHistoryForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategoryForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategoryForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategoryEditForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategoryEditForm'); } TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategoryItemEditForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategoryItemEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategoryItemForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategoryItemForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategoryLinkForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategoryLinkForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategory_CrossForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategory_CrossForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategory_CrossDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategory_CrossDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategory_TotalForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategory_TotalForm'); } end; procedure TLoadFormTest.LoadMarginCategoryMovement; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategory_Movement2Form')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategory_Movement2Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategoryJournal2Form')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategoryJournal2Form'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategory_MovementForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategory_MovementForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginCategoryJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginCategoryJournalForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SAMP_AnalysisDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SAMP_AnalysisDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SAMP_AnalysisForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SAMP_AnalysisForm'); end; procedure TLoadFormTest.LoadMarginReport; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginReportForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginReportForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMarginReportItemForm')); TdsdFormStorageFactory.GetStorage.Load('TMarginReportItemForm'); end; procedure TLoadFormTest.LoadMeasureFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TMeasureForm')); TdsdFormStorageFactory.GetStorage.Load('TMeasureForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMeasureEditForm')); TdsdFormStorageFactory.GetStorage.Load('TMeasureEditForm'); end; procedure TLoadFormTest.LoadKindFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TWorkTimeKind_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TWorkTimeKind_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TWorkTimeKindForm')); TdsdFormStorageFactory.GetStorage.Load('TWorkTimeKindForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TConfirmedKindForm')); TdsdFormStorageFactory.GetStorage.Load('TConfirmedKindForm'); end; procedure TLoadFormTest.LoadGoodsGroupFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsGroupForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsGroupForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsGroupEditForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsGroupEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsGroup_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsGroup_ObjectForm'); end; procedure TLoadFormTest.LoadGoodsGroupPromoFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsGroupPromoForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsGroupPromoForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsGroupPromoEditForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsGroupPromoEditForm'); end; procedure TLoadFormTest.LoadLoadFormTest; begin { TdsdFormStorageFactory.GetStorage.Save(GetForm('TChoiceGoodsFromRemains_1303Form')); TdsdFormStorageFactory.GetStorage.Load('TChoiceGoodsFromRemains_1303Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceListLoad_AddForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceListLoad_AddForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceListLoadForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceListLoadForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceListItemsLoadForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceListItemsLoadForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TMovementLoadForm')); TdsdFormStorageFactory.GetStorage.Load('TMovenentLoadForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMovementItemsLoadForm')); TdsdFormStorageFactory.GetStorage.Load('TMovementItemsLoadForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TChoiceGoodsFromPriceListForm')); TdsdFormStorageFactory.GetStorage.Load('TChoiceGoodsFromPriceListForm'); exit; // отчет поиск товара по всей сети TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsFromRemainsSetPriceDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsFromRemainsSetPriceDialogForm'); } TdsdFormStorageFactory.GetStorage.Save(GetForm('TChoiceGoodsFromRemainsForm')); TdsdFormStorageFactory.GetStorage.Load('TChoiceGoodsFromRemainsForm'); { exit; // TdsdFormStorageFactory.GetStorage.Save(GetForm('TColorForm')); TdsdFormStorageFactory.GetStorage.Load('TColorForm'); exit; // TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsBarCodeForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsBarCodeForm'); } end; procedure TLoadFormTest.LoadLoyaltyFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TLoyaltyJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TLoyaltyJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLoyaltyForm')); TdsdFormStorageFactory.GetStorage.Load('TLoyaltyForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TChoiceLoyaltyCheckForm')); TdsdFormStorageFactory.GetStorage.Load('TChoiceLoyaltyCheckForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_LoyaltyDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_LoyaltyDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Loyalty_CreaturesPromocodeForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Loyalty_CreaturesPromocodeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Loyalty_UsedPromocodeForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Loyalty_UsedPromocodeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLoyaltyInsertPromoCodeDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TLoyaltyInsertPromoCodeDialogForm'); end; procedure TLoadFormTest.LoadLoyaltySaveMoneyFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TLoyaltySaveMoneyForm')); TdsdFormStorageFactory.GetStorage.Load('TLoyaltySaveMoneyForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLoyaltySaveMoneyJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TLoyaltySaveMoneyJournalForm'); end; procedure TLoadFormTest.LoadLoyaltyPresentFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TLoyaltyPresentJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TLoyaltyPresentJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLoyaltyPresentForm')); TdsdFormStorageFactory.GetStorage.Load('TLoyaltyPresentForm'); end; procedure TLoadFormTest.LoadLossDebtFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TLossDebtForm')); TdsdFormStorageFactory.GetStorage.Load('TLossDebtForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLossDebtJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TLossDebtJournalForm'); end; procedure TLoadFormTest.LoadReasonDifferencesFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReasonDifferencesForm')); TdsdFormStorageFactory.GetStorage.Load('TReasonDifferencesForm'); end; procedure TLoadFormTest.LoadRelatedProductFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TRelatedProductForm')); TdsdFormStorageFactory.GetStorage.Load('TRelatedProductForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRelatedProductJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TRelatedProductJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TChoiceRelatedProductForm')); TdsdFormStorageFactory.GetStorage.Load('TChoiceRelatedProductForm'); end; procedure TLoadFormTest.LoadReportFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PriceList_BestPriceForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PriceList_BestPriceForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PriceList_BestPriceDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PriceList_BestPriceDialogForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsSaleChechUserForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsSaleChechUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsSaleChechUserDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsSaleChechUserDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_BanToTransferTimeGoodsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_BanToTransferTimeGoodsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PaymentHelsiForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PaymentHelsiForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_FulfillmentPlanMobileAppUserForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_FulfillmentPlanMobileAppUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_FulfillmentPlanMobileAppForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_FulfillmentPlanMobileAppForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_FulfillmentPlanMobileAppDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_FulfillmentPlanMobileAppDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_FulfillmentPlanMobileAppAntiTOPForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_FulfillmentPlanMobileAppAntiTOPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_TabletkiRecreateForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_TabletkiRecreateForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_TabletkiRecreateDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_TabletkiRecreateDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUsersSiteProfileForm')); TdsdFormStorageFactory.GetStorage.Load('TUsersSiteProfileForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Object_Price_MCS_YearForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Object_Price_MCS_YearForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementSiteBonusForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementSiteBonusForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckMobileForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckMobileForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckMobileDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckMobileDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ApplicationAwardForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ApplicationAwardForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_InfoMobileAppChechForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_InfoMobileAppChechForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ConductedSalesMobileForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ConductedSalesMobileForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ApplicationAwardUserForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ApplicationAwardUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_JuridicalRemainsEndDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_JuridicalRemainsEndDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_JuridicalRemainsEndForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_JuridicalRemainsEndForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Goods_LeftTheMarketForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Goods_LeftTheMarketForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_RestTermGoodsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_RestTermGoodsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_AnalysisBonusesIncomeDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_AnalysisBonusesIncomeDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_AnalysisBonusesIncomeForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_AnalysisBonusesIncomeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Inventory_ProficitReturnOutForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Inventory_ProficitReturnOutForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_IncomeDublyDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_IncomeDublyDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_IncomeDublyForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_IncomeDublyForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_OrderFineForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_OrderFineForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_OrderFineDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_OrderFineDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_SiteDelayDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_SiteDelayDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_SiteDelayForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_SiteDelayForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ImplementationPlanEmployeeUserForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ImplementationPlanEmployeeUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CompetitorMarkupsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CompetitorMarkupsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_RecalcMCSDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_RecalcMCSDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_RecalcMCSForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_RecalcMCSForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckUpdateNotMCSForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckUpdateNotMCSForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_NotPaySumIncomeForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_NotPaySumIncomeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_OrderExternal_SupplierFailuresCashForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_OrderExternal_SupplierFailuresCashForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PaymentSumForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PaymentSumForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PaperRecipeSPInsulinForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PaperRecipeSPInsulinForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PaperRecipeSPForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PaperRecipeSPForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_RemainingInsulinsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_RemainingInsulinsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_OrderExternal_JuridicalItogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_OrderExternal_JuridicalItogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_OrderExternal_SupplierFailuresAllForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_OrderExternal_SupplierFailuresAllForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_OrderExternal_SupplierFailuresDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_OrderExternal_SupplierFailuresDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_OrderExternal_SupplierFailuresForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_OrderExternal_SupplierFailuresForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CommodityStockForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CommodityStockForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_Send_RemainsSun_Supplement_v2Form')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_Send_RemainsSun_Supplement_v2Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TContractPriceListDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TContractPriceListDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TContractPriceListForm')); TdsdFormStorageFactory.GetStorage.Load('TContractPriceListForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PriceComparisonBIG3Form')); TdsdFormStorageFactory.GetStorage.Load('TReport_PriceComparisonBIG3Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_WagesVIP_CalcMonthForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_WagesVIP_CalcMonthForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Layout_OutOrderForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Layout_OutOrderForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Layout_NotLinkPriceListForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Layout_NotLinkPriceListForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Sale_PartialReturnInAllForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Sale_PartialReturnInAllForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Sale_PartialReturnInAllDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Sale_PartialReturnInAllDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_FinancialMonitoringForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_FinancialMonitoringForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_TestingAttemptsUserForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_TestingAttemptsUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SummaInsuranceCompaniesForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SummaInsuranceCompaniesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SummaInsuranceCompaniesDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SummaInsuranceCompaniesDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_InsuranceCompaniesDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_InsuranceCompaniesDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_InsuranceCompaniesForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_InsuranceCompaniesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSend_RelatedCodesSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TSend_RelatedCodesSUNForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_RelatedCodesSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_RelatedCodesSUNForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MonitoringCollectionSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MonitoringCollectionSUNForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_TopListDiffGoodsDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_TopListDiffGoodsDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_TopListDiffGoodsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_TopListDiffGoodsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PriceCorrectionSystemForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PriceCorrectionSystemForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckZReportForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckZReportForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckZReportDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckZReportDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_LayoutCheckRemainsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_LayoutCheckRemainsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_LayoutCheckRemainsDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_LayoutCheckRemainsDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ZeroingInOrdersDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ZeroingInOrdersDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ZeroingInOrdersForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ZeroingInOrdersForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Top100GoodsSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Top100GoodsSUNForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ZReportLogDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ZReportLogDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ZReportLogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ZReportLogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PriceCheckForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PriceCheckForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_JackdawsSumDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_JackdawsSumDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_JackdawsSumForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_JackdawsSumForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_CheckDeliverySiteForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_CheckDeliverySiteForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_CheckWithPenniesForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_CheckWithPenniesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_RemainsCovid_19Form')); TdsdFormStorageFactory.GetStorage.Load('TReport_RemainsCovid_19Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_RemainsCovid_19DialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_RemainsCovid_19DialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_SetErasedUserForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_SetErasedUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_DynamicsOrdersEICForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_DynamicsOrdersEICForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SalesGoods_SUADialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SalesGoods_SUADialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SalesGoods_SUAForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SalesGoods_SUAForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheck_UnderreportedDEForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheck_UnderreportedDEForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_KilledCodeRecoveryDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_KilledCodeRecoveryDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_KilledCodeRecoveryForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_KilledCodeRecoveryForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_PromoBonusDiscoDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_PromoBonusDiscoDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_PromoBonusDiscoForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_PromoBonusDiscoForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_CorrectMarketingForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_CorrectMarketingForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_FinalSUAProtocolForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_FinalSUAProtocolForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_PromoBonusEstimateForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_PromoBonusEstimateForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_PromoBonusLossesForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_PromoBonusLossesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_HammerTimeSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_HammerTimeSUNForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsPrice_PromoBonusForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsPrice_PromoBonusForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_UnitDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_UnitDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Reprice_PromoBonusForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Reprice_PromoBonusForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_Send_RemainsSun_SUAForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_Send_RemainsSun_SUAForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SalesOfTermDrugsDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SalesOfTermDrugsDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SalesOfTermDrugsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SalesOfTermDrugsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SalesOfTermDrugsUnitForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SalesOfTermDrugsUnitForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SalesOfTermDrugsUserForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SalesOfTermDrugsUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsRemainsUKTZEDDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsRemainsUKTZEDDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsRemainsUKTZEDForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsRemainsUKTZEDForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_Send_RemainsSun_UKTZEDForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_Send_RemainsSun_UKTZEDForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_QuantityComparisonForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_QuantityComparisonForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_QuantityComparisonDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_QuantityComparisonDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheckSiteDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheckSiteDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheckSiteForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheckSiteForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ClippedReprice_SaleForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ClippedReprice_SaleForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SAUAForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SAUAForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_TwoVendorBindingsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_TwoVendorBindingsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ResortsByLotForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ResortsByLotForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ResortsByLotDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ResortsByLotDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ArrivalWithoutSalesForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ArrivalWithoutSalesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ArrivalWithoutSalesDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ArrivalWithoutSalesDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_FoundPositionsSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_FoundPositionsSUNForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ChangeCommentsSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ChangeCommentsSUNForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CommentSendSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CommentSendSUNForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PositionsUKTVEDonSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PositionsUKTVEDonSUNForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_LeftSendForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_LeftSendForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_CountForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_CountForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_CountDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_CountDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_OrderInternalPromo_DistributionCalculationForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_OrderInternalPromo_DistributionCalculationForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PercentageOccupancySUNForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PercentageOccupancySUNForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_NumberChecksDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_NumberChecksDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_NumberChecksForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_NumberChecksForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_Send_RemainsSun_SupplementForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_Send_RemainsSun_SupplementForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_RemainsOverGoods_NForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_RemainsOverGoods_NForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ImplementationPeriodForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ImplementationPeriodForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_WillNotOrderForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_WillNotOrderForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ImplementationPeriodForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ImplementationPeriodForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_IncomeVATBalanceForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_IncomeVATBalanceForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_IncomeSale_UseNDSKindForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_IncomeSale_UseNDSKindForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_IncomeSale_UseNDSKindDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_IncomeSale_UseNDSKindDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_NomenclaturePeriodForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_NomenclaturePeriodForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_NomenclaturePeriodDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_NomenclaturePeriodDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PharmacyPerformanceForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PharmacyPerformanceForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PharmacyPerformanceDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PharmacyPerformanceDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GeneralMovementGoodsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GeneralMovementGoodsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GeneralMovementGoodsDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GeneralMovementGoodsDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_EntryGoodsMovementDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_EntryGoodsMovementDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_EntryGoodsMovementForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_EntryGoodsMovementForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_JuridicalSalesForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_JuridicalSalesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_JuridicalSalesDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_JuridicalSalesDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_InventoryErrorRemainsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_InventoryErrorRemainsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_InventoryErrorRemainsDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_InventoryErrorRemainsDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_InventoryErrorRemainsDocForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_InventoryErrorRemainsDocForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_JuridicalRemainsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_JuridicalRemainsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_JuridicalRemainsDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_JuridicalRemainsDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SendSUN_SUNv2Form')); TdsdFormStorageFactory.GetStorage.Load('TReport_SendSUN_SUNv2Form'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SUNSaleDatesForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SUNSaleDatesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SUNSaleDatesDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SUNSaleDatesDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MoneyBoxSunForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MoneyBoxSunForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SendSUNLossDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SendSUNLossDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SendSUNLossForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SendSUNLossForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SendSUNDelayForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SendSUNDelayForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SendSUNDelayDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SendSUNDelayDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_InventoryErrorRemainsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_InventoryErrorRemainsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_InventoryErrorRemainsDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_InventoryErrorRemainsDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_StockTiming_RemainderForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_StockTiming_RemainderForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_StockTiming_RemainderDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_StockTiming_RemainderDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheck_PromoDoctorsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheck_PromoDoctorsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheck_PromoEntrancesForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheck_PromoEntrancesForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PercentageOverdueSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PercentageOverdueSUNForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_IlliquidReductionPlanAllForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_IlliquidReductionPlanAllForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_IlliquidReductionPlanListForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_IlliquidReductionPlanListForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_IlliquidReductionPlanAllDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_IlliquidReductionPlanAllDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_IlliquidReductionPlanUserForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_IlliquidReductionPlanUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_ReturnOutForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_ReturnOutForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_ReturnOutDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_ReturnOutDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ProfitabilityForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ProfitabilityForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ProfitabilityDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ProfitabilityDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TActNumberAndAmountDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TActNumberAndAmountDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheck_DiscountExternalForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheck_DiscountExternalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_DiscountExternalDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_DiscountExternalDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckSUNItogDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckSUNItogDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckSUNItogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckSUNItogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckSUNForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckSUNDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckSUNDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckSendSUN_InOutForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckSendSUN_InOutForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckSendSUN_InOutDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckSendSUN_InOutDialogForm'); // exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_BalanceGoodsSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_BalanceGoodsSUNForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_BalanceGoodsSUNDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_BalanceGoodsSUNDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PriceProtocolForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PriceProtocolForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PriceProtocolDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PriceProtocolDialogForm'); //exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_Send_RemainsSun_piForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_Send_RemainsSun_piForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_Send_RemainsSun_expressForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_Send_RemainsSun_expressForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_Send_RemainsSunOut_expressForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_Send_RemainsSunOut_expressForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_Send_RemainsSun_expressDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_Send_RemainsSun_expressDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_Send_RemainsSunOutForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_Send_RemainsSunOutForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_Send_RemainsSunOut_express_v2Form')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_Send_RemainsSunOut_express_v2Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_Send_RemainsSun_expressv2DialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_Send_RemainsSun_expressv2DialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_Send_RemainsSunForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_Send_RemainsSunForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_Send_RemainsSunDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_Send_RemainsSunDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsPartionDate0Form')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsPartionDate0Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsPartionDate5Form')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsPartionDate5Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsPartionDate5DialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsPartionDate5DialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Send_RemainsSun_overForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Send_RemainsSun_overForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsSendSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsSendSUNForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsSendSUNDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsSendSUNDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsRemainsCashForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsRemainsCashForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsRemainsCashDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsRemainsCashDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsPartionMoveCashForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsPartionMoveCashForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsPartionMoveCashDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsPartionMoveCashDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckPartionDateForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckPartionDateForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckPartionDateDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckPartionDateDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsPartionDate_PromoDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsPartionDate_PromoDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsPartionDate_PromoForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsPartionDate_PromoForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsNotSalePastDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsNotSalePastDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsNotSalePastForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsNotSalePastForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsPartionDateForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsPartionDateForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsPartionDateDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsPartionDateDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_ListDiffForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_ListDiffForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_ListDiffDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_ListDiffDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_GoodsPriceChangeForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_GoodsPriceChangeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_GoodsPriceChangeDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_GoodsPriceChangeDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_IncomeSampleForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_IncomeSampleForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_IncomeSampleDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_IncomeSampleDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_PriceChangeForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_PriceChangeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_PriceChangeDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_PriceChangeDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsRemainsCurrentForm')); TdsdFormStorageFactory.GetStorage.Load('TRReport_GoodsRemainsCurrentForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsRemainsCurrentDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TRReport_GoodsRemainsCurrentDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_UKTZEDDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_UKTZEDDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_UKTZEDForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_UKTZEDForm'); //exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MinPrice_byPromoDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MinPrice_byPromoDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MinPrice_byPromoForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MinPrice_byPromoForm'); // exit; // Остатки товара (ID товара другой сети) TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsRemains_AnotherRetailForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsRemains_AnotherRetailForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_AnotherRetailForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_AnotherRetailForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementIncome_byPromoDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementIncome_byPromoDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementIncome_byPromoForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementIncome_byPromoForm'); //exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReportMovementCheckGrowthAndFallingForm')); TdsdFormStorageFactory.GetStorage.Load('TReportMovementCheckGrowthAndFallingForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReportMovementCheckGrowthAndFallingDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReportMovementCheckGrowthAndFallingDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_RatingForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_RatingForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_RatingDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_RatingDialogForm'); //exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_OverOrderForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_OverOrderForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_OverOrderDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_OverOrderDialogForm'); //exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_AssortmentForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_AssortmentdForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_AssortmentDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_AssortmentDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementPriceList_CrossForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementPriceList_CrossForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementPriceListForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementPriceListForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementPriceList_DialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementPriceList_DialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_BadmForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_BadmForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnit_byReportBadmForm')); TdsdFormStorageFactory.GetStorage.Load('TUnit_byReportBadmForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MinPrice_onGoodsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MinPrice_onGoodsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MinPrice_onGoodsDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MinPrice_onGoodsDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckPromoForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckPromoForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PeriodDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PeriodDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PromoDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PromoDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheck_PromoForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheck_PromoForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementIncome_PromoForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementIncome_PromoForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsRemainsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsRemainsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsRemainsDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsRemainsDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOverdueChangeJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TOverdueChangeJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOverdueChangeDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TOverdueChangeDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheckErrorForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheckErrorForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheckErrorDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheckErrorDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Payment_PlanForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Payment_PlanForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Payment_PlanDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Payment_PlanDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheck_UnLiquidForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheck_UnLiquidForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheck_UnLiquidDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheck_UnLiquidDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReportOrderGoodsForm')); TdsdFormStorageFactory.GetStorage.Load('TReportOrderGoodsForm'); // отчет распределение остатков TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_RemainsOverGoodsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_RemainsOverGoodsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_RemainsOverGoodsDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_RemainsOverGoodsDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_RemainsOverGoods_ToForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_RemainsOverGoods_ToForm'); exit; //Отчет Приход на точку TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementIncomeForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementIncomeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementIncomeDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementIncomeDialogForm'); //Отчет Приход на точку для фармацевта TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementIncomeFarmForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementIncomeFarmForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementIncomeFarmDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementIncomeFarmDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_BalanceForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_BalanceForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_JuridicalSoldForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_JuridicalSoldForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_JuridicalCollationForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_JuridicalCollationForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_JuridicalCollationSaldoForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_JuridicalCollationSaldoForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsPartionMoveForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsPartionMoveForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsPartionMoveDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsPartionMoveDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheck_CrossForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheck_CrossForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsRemainsLightForm')); TdsdFormStorageFactory.GetStorage.Load('TRReport_GoodsRemainsLightForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsRemainsLightDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TRReport_GoodsRemainsLightDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReportMovementCheckLightForm')); TdsdFormStorageFactory.GetStorage.Load('TReportMovementCheckLightForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementChecLightDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementChecLightDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReportMovementCheckForm')); TdsdFormStorageFactory.GetStorage.Load('TReportMovementCheckForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheckDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheckDialogForm'); // для фармацевта TdsdFormStorageFactory.GetStorage.Save(GetForm('TReportMovementCheckFarmForm')); TdsdFormStorageFactory.GetStorage.Load('TReportMovementCheckFarmForm'); // Отчет по продажам на кассах физическим лицам TdsdFormStorageFactory.GetStorage.Save(GetForm('TReportMovementCheckFLForm')); TdsdFormStorageFactory.GetStorage.Load('TReportMovementCheckFLForm'); // Отчет по выполнению плана продаж по сотруднику TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ImplementationPlanEmployeeAllForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ImplementationPlanEmployeeAllForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDataDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TDataDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ImplementationPlanEmployeeDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ImplementationPlanEmployeeDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheckFarmDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheckFarmDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsPartionHistoryForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsPartionHistoryForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_GoodsPartionHistoryDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsPartionHistoryDialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SoldForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SoldForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Sold_DayForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Sold_DayForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Sold_DayUserForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Sold_DayUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Movement_ByPartionGoodsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Movement_ByPartionGoodsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_WageForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_WageForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_WageDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_WageDialogForm'); //отчет доходности TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ProfitForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ProfitForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_ProfitDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_ProfitDialogForm'); exit; // средний чек за период TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckMiddle_DetailForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckMiddle_DetailForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckMiddle_DetailDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckMiddle_DetailDialogForm'); // средний чек TdsdFormStorageFactory.GetStorage.Save(GetForm('TReportMovementCheckMiddleForm')); TdsdFormStorageFactory.GetStorage.Load('TReportMovementCheckMiddleForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_MovementCheckMiddleDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_MovementCheckMiddleDialogForm'); //Отчет Ценовая интервенция TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PriceInterventionForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PriceInterventionForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PriceInterventionDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_PriceInterventionDialogForm'); //Отчет Ценовая интервенция2 TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_PriceIntervention2Form')); TdsdFormStorageFactory.GetStorage.Load('TReport_PriceIntervention2Form'); // отчет распределение остатков TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_RemainsOverGoodsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_RemainsOverGoodsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_RemainsOverGoodsDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_RemainsOverGoodsDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_LiquidityForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_LiquidityForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOverdraftForm')); TdsdFormStorageFactory.GetStorage.Load('TOverdraftForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOverdraftEditForm')); TdsdFormStorageFactory.GetStorage.Load('TOverdraftEditForm'); } end; procedure TLoadFormTest.LoadReportForSiteTest; begin TdsdFormStorageFactory.GetStorage.Save (GetForm('TReport_GoodsOnUnit_ForSiteForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_GoodsOnUnit_ForSiteForm'); TdsdFormStorageFactory.GetStorage.Save (GetForm('TReport_GoodsOnUnit_ForSiteDialogForm')); TdsdFormStorageFactory.GetStorage.Load ('TReport_GoodsOnUnit_ForSiteDialogForm'); end; procedure TLoadFormTest.LoadRogerseFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReportRogersMovementCheckForm')); TdsdFormStorageFactory.GetStorage.Load('TReportRogersMovementCheckForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRepriceRogersJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TRepriceRogersJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRepriceRogersForm')); TdsdFormStorageFactory.GetStorage.Load('TRepriceRogersForm'); end; procedure TLoadFormTest.LoadReportSoldParamsFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReportSoldParamsForm')); TdsdFormStorageFactory.GetStorage.Load('TReportSoldParamsForm'); end; procedure TLoadFormTest.LoadReportPromoParamsFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReportPromoParamsForm')); TdsdFormStorageFactory.GetStorage.Load('TReportPromoParamsForm'); end; procedure TLoadFormTest.LoadReportUploadFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_UploadBaDMForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_UploadBaDMForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_UploadOptimaForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_UploadOptimaForm'); end; procedure TLoadFormTest.LoadRepriceFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TRepriceUnitShedulerForm')); TdsdFormStorageFactory.GetStorage.Load('TRepriceUnitShedulerForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRepriceJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TRepriceJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRepriceForm')); TdsdFormStorageFactory.GetStorage.Load('TRepriceForm'); end; procedure TLoadFormTest.LoadMovementReportUnLiquidFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReportUnLiquidJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TReportUnLiquidJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReportUnLiquid_MovementForm')); TdsdFormStorageFactory.GetStorage.Load('TReportUnLiquid_MovementForm'); end; procedure TLoadFormTest.LoadRepriceChangeFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TRepriceChangeJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TRepriceChangeJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRepriceChangeForm')); TdsdFormStorageFactory.GetStorage.Load('TRepriceChangeForm'); end; procedure TLoadFormTest.LoadRepriceSiteFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_RepriceSiteForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_RepriceSiteForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRepriceSiteForm')); TdsdFormStorageFactory.GetStorage.Load('TRepriceSiteForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRepriceSiteJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TRepriceSiteJournalForm'); end; procedure TLoadFormTest.LoadRetailFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TRetailForm')); TdsdFormStorageFactory.GetStorage.Load('TRetailForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRetailEditForm')); TdsdFormStorageFactory.GetStorage.Load('TRetailEditForm'); end; procedure TLoadFormTest.LoadRetailCostCreditFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TRetailCostCreditForm')); TdsdFormStorageFactory.GetStorage.Load('TRetailCostCreditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRetailCostCreditEditForm')); TdsdFormStorageFactory.GetStorage.Load('TRetailCostCreditEditForm'); end; procedure TLoadFormTest.LoadReturnOutFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReturnOutPharmacyForm')); TdsdFormStorageFactory.GetStorage.Load('TReturnOutPharmacyForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReturnOutPharmacyJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TReturnOutPharmacyJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReturnOutForm')); TdsdFormStorageFactory.GetStorage.Load('TReturnOutForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReturnOutJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TReturnOutJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReturnOutPartnerDataDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReturnOutPartnerDataDialogForm'); end; procedure TLoadFormTest.LoadReturnTypeFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReturnTypeForm')); TdsdFormStorageFactory.GetStorage.Load('TReturnTypeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReturnTypeEditForm')); TdsdFormStorageFactory.GetStorage.Load('TReturnTypeEditForm'); end; procedure TLoadFormTest.LoadIlliquidUnitFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TIlliquidUnitForm')); TdsdFormStorageFactory.GetStorage.Load('TIlliquidUnitForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TIlliquidUnitJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TIlliquidUnitJournalForm'); end; procedure TLoadFormTest.LoadLayoutFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TLayoutForm')); TdsdFormStorageFactory.GetStorage.Load('TLayoutForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLayoutEditForm')); TdsdFormStorageFactory.GetStorage.Load('TLayoutEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLayout_MovementForm')); TdsdFormStorageFactory.GetStorage.Load('TLayout_MovementForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLayoutJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TLayoutJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLayoutJournalChoiceForm')); TdsdFormStorageFactory.GetStorage.Load('TLayoutJournalChoiceForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TChoiceLayoutForm')); TdsdFormStorageFactory.GetStorage.Load('TChoiceLayoutForm'); end; procedure TLoadFormTest.LoadLayoutFileFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TLayoutFileForm')); TdsdFormStorageFactory.GetStorage.Load('TLayoutFileForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLayoutFileJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TLayoutFileJournalForm'); end; procedure TLoadFormTest.LoadJuridicalFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TJuridicalForm')); TdsdFormStorageFactory.GetStorage.Load('TJuridicalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TJuridicalEditForm')); TdsdFormStorageFactory.GetStorage.Load('TJuridicalEditForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TJuridicalPriceChoiceForm')); TdsdFormStorageFactory.GetStorage.Load('TJuridicalPriceChoiceForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TJuridicalCorporateForm')); TdsdFormStorageFactory.GetStorage.Load('TJuridicalCorporateForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TJuridical_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TJuridical_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPartnerCodeForm')); TdsdFormStorageFactory.GetStorage.Load('TPartnerCodeForm'); // Адрес TdsdFormStorageFactory.GetStorage.Save(GetForm('TAddressForm')); TdsdFormStorageFactory.GetStorage.Load('TAddressForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAddressEditForm')); TdsdFormStorageFactory.GetStorage.Load('TAddressEditForm'); // Юридический адрес поставщика TdsdFormStorageFactory.GetStorage.Save(GetForm('TJuridicalLegalAddressForm')); TdsdFormStorageFactory.GetStorage.Load('TJuridicalLegalAddressForm'); TdsdFormStorageFactory.GetStorage.Save (GetForm('TJuridicalLegalAddressEditForm')); TdsdFormStorageFactory.GetStorage.Load('TJuridicalLegalAddressEditForm'); // Фактический адрес поставщика TdsdFormStorageFactory.GetStorage.Save (GetForm('TJuridicalActualAddressForm')); TdsdFormStorageFactory.GetStorage.Load('TJuridicalActualAddressForm'); TdsdFormStorageFactory.GetStorage.Save (GetForm('TJuridicalActualAddressEditForm')); TdsdFormStorageFactory.GetStorage.Load('TJuridicalActualAddressEditForm'); } end; procedure TLoadFormTest.LoadJuridicalAreaFormTest; begin // Регионы поставщиков TdsdFormStorageFactory.GetStorage.Save(GetForm('TJuridicalAreaForm')); TdsdFormStorageFactory.GetStorage.Load('TJuridicalAreaForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TJuridicalAreaEditForm')); TdsdFormStorageFactory.GetStorage.Load('TJuridicalAreaEditForm'); end; procedure TLoadFormTest.LoadImportTypeFormTest; begin // Типы импорта TdsdFormStorageFactory.GetStorage.Save(GetForm('TImportTypeForm')); TdsdFormStorageFactory.GetStorage.Load('TImportTypeForm'); end; procedure TLoadFormTest.LoadInternetRepairFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TInternetRepairForm')); TdsdFormStorageFactory.GetStorage.Load('TInternetRepairForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TInternetRepairEditForm')); TdsdFormStorageFactory.GetStorage.Load('TInternetRepairEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TInternetRepairCashEditForm')); TdsdFormStorageFactory.GetStorage.Load('TInternetRepairCashEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TInternetRepairCashForm')); TdsdFormStorageFactory.GetStorage.Load('TInternetRepairCashForm'); end; procedure TLoadFormTest.LoadImportSettingsFormTest; begin { // Настройки импорта TdsdFormStorageFactory.GetStorage.Save(GetForm('TImportSettingsForm')); TdsdFormStorageFactory.GetStorage.Load('TImportSettingsForm'); } TdsdFormStorageFactory.GetStorage.Save(GetForm('TImportGroupForm')); TdsdFormStorageFactory.GetStorage.Load('TImportGroupForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TImportGroupEditForm')); TdsdFormStorageFactory.GetStorage.Load('TImportGroupEditForm'); end; procedure TLoadFormTest.LoadGoodsRepriceFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsRepriceForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsRepriceForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsRepriceEditForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsRepriceEditForm'); end; procedure TLoadFormTest.LoadHardwareFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('THardwareForm')); TdsdFormStorageFactory.GetStorage.Load('THardwareForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('THardwareEditForm')); TdsdFormStorageFactory.GetStorage.Load('THardwareEditForm'); end; procedure TLoadFormTest.LoadHouseholdInventoryFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('THouseholdInventoryForm')); TdsdFormStorageFactory.GetStorage.Load('THouseholdInventoryForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('THouseholdInventoryEditForm')); TdsdFormStorageFactory.GetStorage.Load('THouseholdInventoryEditForm'); end; procedure TLoadFormTest.LoadInventoryHouseholdInventoryFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TInventoryHouseholdInventoryForm')); TdsdFormStorageFactory.GetStorage.Load('TInventoryHouseholdInventoryForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TInventoryHouseholdInventoryJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TInventoryHouseholdInventoryJournalForm'); end; procedure TLoadFormTest.LoadTaxUnitFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TTaxUnitForm')); TdsdFormStorageFactory.GetStorage.Load('TTaxUnitForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TTaxUnitEditForm')); TdsdFormStorageFactory.GetStorage.Load('TTaxUnitEditForm'); end; procedure TLoadFormTest.LoadTechnicalRediscountFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TTechnicalRediscountJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TTechnicalRediscountJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TTechnicalRediscountForm')); TdsdFormStorageFactory.GetStorage.Load('TTechnicalRediscountForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TTechnicalRediscountCashierJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TTechnicalRediscountCashierJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TTechnicalRediscountCashierForm')); TdsdFormStorageFactory.GetStorage.Load('TTechnicalRediscountCashierForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCommentTRForm')); TdsdFormStorageFactory.GetStorage.Load('TCommentTRForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCommentTREditForm')); TdsdFormStorageFactory.GetStorage.Load('TCommentTREditForm'); end; procedure TLoadFormTest.LoadTestingTuningFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TTestingTuningJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TTestingTuningJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TTestingTuningForm')); TdsdFormStorageFactory.GetStorage.Load('TTestingTuningForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TTopicsTestingTuningEditForm')); TdsdFormStorageFactory.GetStorage.Load('TTopicsTestingTuningEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TTopicsTestingTuningForm')); TdsdFormStorageFactory.GetStorage.Load('TTopicsTestingTuningForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_TestingTuning_ManualForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_TestingTuning_ManualForm'); end; procedure TLoadFormTest.LoadUnitFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnitTreeForm')); TdsdFormStorageFactory.GetStorage.Load('TUnitTreeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnitEditForm')); TdsdFormStorageFactory.GetStorage.Load('TUnitEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnit_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TUnit_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnit_PauseDistribListDiffForm')); TdsdFormStorageFactory.GetStorage.Load('TUnit_PauseDistribListDiffForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnit_SUN_LockDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TUnit_SUN_LockDialogForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnit_LimitSUN_EditForm')); TdsdFormStorageFactory.GetStorage.Load('TUnit_LimitSUN_EditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnitForOrderInternalPromoForm')); TdsdFormStorageFactory.GetStorage.Load('TUnitForOrderInternalPromoForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnit_HT_SUN_EditForm')); TdsdFormStorageFactory.GetStorage.Load('TUnit_HT_SUN_EditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnit_SunIncome_EditForm')); TdsdFormStorageFactory.GetStorage.Load('TUnit_SunIncome_EditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnit_T_SUN_EditForm')); TdsdFormStorageFactory.GetStorage.Load('TUnit_T_SUN_EditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnit_KoeffSUN_EditForm')); TdsdFormStorageFactory.GetStorage.Load('TUnit_KoeffSUN_EditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnit_MCSForm')); TdsdFormStorageFactory.GetStorage.Load('TUnit_MCSForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TListDaySUNDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TListDaySUNDialogForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnit_JuridicalAreaForm')); TdsdFormStorageFactory.GetStorage.Load('TUnit_JuridicalAreaForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnitForFarmacyCashForm')); TdsdFormStorageFactory.GetStorage.Load('TUnitForFarmacyCashForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnitCategoryForm')); TdsdFormStorageFactory.GetStorage.Load('TUnitCategoryForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnitCategoryEditForm')); TdsdFormStorageFactory.GetStorage.Load('TUnitCategoryEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TScaleCalcMarketingPlanForm')); TdsdFormStorageFactory.GetStorage.Load('TScaleCalcMarketingPlanForm'); } end; procedure TLoadFormTest.LoadUnionFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnit_Area_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TUnit_Area_ObjectForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TJuridical_Unit_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TJuridical_Unit_ObjectForm'); end; procedure TLoadFormTest.LoadUnnamedEnterprisesFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnnamedEnterprisesForm')); TdsdFormStorageFactory.GetStorage.Load('TUnnamedEnterprisesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnnamedEnterprisesJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TUnnamedEnterprisesJournalForm'); end; procedure TLoadFormTest.LoadWagesFormTest; begin // // TdsdFormStorageFactory.GetStorage.Save(GetForm('TPayrollGroupForm')); // TdsdFormStorageFactory.GetStorage.Load('TPayrollGroupForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TPayrollGroupEditForm')); // TdsdFormStorageFactory.GetStorage.Load('TPayrollGroupEditForm'); // // TdsdFormStorageFactory.GetStorage.Save(GetForm('TPayrollTypeEditForm')); // TdsdFormStorageFactory.GetStorage.Load('TPayrollTypeEditForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TPayrollTypeForm')); // TdsdFormStorageFactory.GetStorage.Load('TPayrollTypeForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TPayrollTypeDialogForm')); // TdsdFormStorageFactory.GetStorage.Load('TPayrollTypeDialogForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TPayrollTypeChoiceForm')); // TdsdFormStorageFactory.GetStorage.Load('TPayrollTypeChoiceForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TWagesJournalForm')); // TdsdFormStorageFactory.GetStorage.Load('TWagesJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TWagesForm')); TdsdFormStorageFactory.GetStorage.Load('TWagesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TWagesAdditionalExpensesForm')); TdsdFormStorageFactory.GetStorage.Load('TWagesAdditionalExpensesForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TWagesSUN1Form')); // TdsdFormStorageFactory.GetStorage.Load('TWagesSUN1Form'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TWagesTechnicalRediscountForm')); // TdsdFormStorageFactory.GetStorage.Load('TWagesTechnicalRediscountForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TWagesTechnicalRediscountUnitForm')); // TdsdFormStorageFactory.GetStorage.Load('TWagesTechnicalRediscountUnitForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TWagesMoneyBoxSunForm')); // TdsdFormStorageFactory.GetStorage.Load('TWagesMoneyBoxSunForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TWagesUserForm')); TdsdFormStorageFactory.GetStorage.Load('TWagesUserForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TCorrectWagesPercentageForm')); // TdsdFormStorageFactory.GetStorage.Load('TCorrectWagesPercentageForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TSurchargeWagesForm')); // TdsdFormStorageFactory.GetStorage.Load('TSurchargeWagesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPartionDateWagesForm')); TdsdFormStorageFactory.GetStorage.Load('TPartionDateWagesForm'); end; procedure TLoadFormTest.LoadWagesVIPFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPayrollTypeVIPEditForm')); TdsdFormStorageFactory.GetStorage.Load('TPayrollTypeVIPEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPayrollTypeVIPForm')); TdsdFormStorageFactory.GetStorage.Load('TPayrollTypeVIPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TWagesVIPJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TWagesVIPJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TWagesVIPForm')); TdsdFormStorageFactory.GetStorage.Load('TWagesVIPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TWagesVIP_UserForm')); TdsdFormStorageFactory.GetStorage.Load('TWagesVIP_UserForm'); end; procedure TLoadFormTest.LoadWriteOffHouseholdInventoryFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TWriteOffHouseholdInventoryForm')); TdsdFormStorageFactory.GetStorage.Load('TWriteOffHouseholdInventoryForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TWriteOffHouseholdInventoryJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TWriteOffHouseholdInventoryJournalForm'); end; procedure TLoadFormTest.LoadEnumFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TNDSKindForm')); TdsdFormStorageFactory.GetStorage.Load('TNDSKindForm'); // Типы файлов TdsdFormStorageFactory.GetStorage.Save(GetForm('TFileTypeKindForm')); TdsdFormStorageFactory.GetStorage.Load('TFileTypeKindForm'); // Типы заказов TdsdFormStorageFactory.GetStorage.Save(GetForm('TOrderKindForm')); TdsdFormStorageFactory.GetStorage.Load('TOrderKindForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOrderKindEditForm')); TdsdFormStorageFactory.GetStorage.Load('TOrderKindEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmailToolsForm')); TdsdFormStorageFactory.GetStorage.Load('TEmailToolsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmailKindForm')); TdsdFormStorageFactory.GetStorage.Load('TEmailKindForm'); end; procedure TLoadFormTest.LoadEmailSettingsFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmailSettingsForm')); TdsdFormStorageFactory.GetStorage.Load('TEmailSettingsForm'); end; procedure TLoadFormTest.LoadEmailFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmailForm')); TdsdFormStorageFactory.GetStorage.Load('TEmailForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmailEditForm')); TdsdFormStorageFactory.GetStorage.Load('TEmailEditForm'); end; procedure TLoadFormTest.LoadProfitLossGroupFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TProfitLossGroupForm')); TdsdFormStorageFactory.GetStorage.Load('TProfitLossGroupForm'); TdsdFormStorageFactory.GetStorage.Save (GetForm('TProfitLossGroup_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TProfitLossGroup_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TProfitLossGroupEditForm')); TdsdFormStorageFactory.GetStorage.Load('TProfitLossGroupEditForm'); end; procedure TLoadFormTest.LoadProfitLossDirectionFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TProfitLossDirectionForm')); TdsdFormStorageFactory.GetStorage.Load('TProfitLossDirectionForm'); TdsdFormStorageFactory.GetStorage.Save (GetForm('TProfitLossDirection_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TProfitLossDirection_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save (GetForm('TProfitLossDirectionEditForm')); TdsdFormStorageFactory.GetStorage.Load('TProfitLossDirectionEditForm'); end; procedure TLoadFormTest.LoadProjectsImprovementsFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TProjectsImprovementsJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TProjectsImprovementsJournalForm'); end; procedure TLoadFormTest.LoadProfitLossFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TProfitLossForm')); TdsdFormStorageFactory.GetStorage.Load('TProfitLossForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TProfitLoss_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TProfitLoss_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TProfitLossEditForm')); TdsdFormStorageFactory.GetStorage.Load('TProfitLossEditForm'); end; procedure TLoadFormTest.LoadPromoFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPromoCodeDoctorForm')); TdsdFormStorageFactory.GetStorage.Load('TPromoCodeDoctorForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPromoJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TPromoJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPromoForm')); TdsdFormStorageFactory.GetStorage.Load('TPromoForm'); end; procedure TLoadFormTest.LoadPromoCodeFormTest; begin // TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_byPromoCodeForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_byPromoCodeForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TPromoCodeForm')); TdsdFormStorageFactory.GetStorage.Load('TPromoCodeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPromoCodeEditForm')); TdsdFormStorageFactory.GetStorage.Load('TPromoCodeEditForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TPromoCodeMovementForm')); TdsdFormStorageFactory.GetStorage.Load('TPromoCodeMovementForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPromoCodeJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TPromoCodeJournalForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TPromoCodeSignDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TPromoCodeSignDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPromoCodeSignPercentDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TPromoCodeSignPercentDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPromoCodeSignUnitNameDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TPromoCodeSignUnitNameDialogForm'); end; procedure TLoadFormTest.LoadPromoBonusFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPromoBonusJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TPromoBonusJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPromoBonusForm')); TdsdFormStorageFactory.GetStorage.Load('TPromoBonusForm'); end; procedure TLoadFormTest.LoadPromoUnitFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPromoUnitJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TPromoUnitJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPromoUnitForm')); TdsdFormStorageFactory.GetStorage.Load('TPromoUnitForm'); end; procedure TLoadFormTest.LoadProvinceCityFormTest; begin // Микрорайон в населенном пункте TdsdFormStorageFactory.GetStorage.Save(GetForm('TProvinceCityForm')); TdsdFormStorageFactory.GetStorage.Load('TProvinceCityForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TProvinceCityEditForm')); TdsdFormStorageFactory.GetStorage.Load('TProvinceCityEditForm'); end; procedure TLoadFormTest.MainFormTest; var ActionDataSet: TClientDataSet; StoredProc: TdsdStoredProc; i: integer; Action: ActionTest.TAction; begin // Здесь мы заполняем справочник Action // Получаем все Action из базы ActionDataSet := TClientDataSet.Create(nil); StoredProc := TdsdStoredProc.Create(nil); MainFormInstance := TMainForm.Create(nil); Action := ActionTest.TAction.Create; try StoredProc.DataSet := ActionDataSet; StoredProc.StoredProcName := 'gpSelect_Object_Action'; StoredProc.Execute; // добавим тех, что нет with MainFormInstance.ActionList do for i := 0 to ActionCount - 1 do if not ActionDataSet.Locate('Name', Actions[i].Name, []) then Action.InsertUpdateAction(0, 0, Actions[i].Name); finally Action.Free; StoredProc.Free; ActionDataSet.Free; MainFormInstance.Free; end; end; procedure TLoadFormTest.SetUp; begin inherited; TAuthentication.CheckLogin(TStorageFactory.GetStorage, 'Админ', gc_AdminPassword, gc_User); end; procedure TLoadFormTest.LoadOrderSheduleFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TOrderSheduleForm')); TdsdFormStorageFactory.GetStorage.Load('TOrderSheduleForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOrderSheduleEditForm')); TdsdFormStorageFactory.GetStorage.Load('TOrderSheduleEditForm'); end; procedure TLoadFormTest.LoadOrderInternalFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TOrderInternalForm')); TdsdFormStorageFactory.GetStorage.Load('TOrderInternalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOrderInternalLiteForm')); TdsdFormStorageFactory.GetStorage.Load('TOrderInternalLiteForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOrderInternalJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TOrderInternalJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOrderInternalZeroingSUAForm')); TdsdFormStorageFactory.GetStorage.Load('TOrderInternalZeroingSUAForm'); end; procedure TLoadFormTest.LoadOrderInternalPromoFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TOrderInternalPromoForm')); TdsdFormStorageFactory.GetStorage.Load('TOrderInternalPromoForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOrderInternalPromoJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TOrderInternalPromoJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_OrderInternalPromoOLAPForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_OrderInternalPromoOLAPForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsPromoChoiceForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsPromoChoiceForm'); } end; procedure TLoadFormTest.LoadObjectUnionFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TMoneyPlace_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TMoneyPlace_ObjectForm'); end; procedure TLoadFormTest.LoadOrderExternalFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TOrderExternalForm')); TdsdFormStorageFactory.GetStorage.Load('TOrderExternalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOrderExternalJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TOrderExternalJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOrderExternalJournalChoiceForm')); TdsdFormStorageFactory.GetStorage.Load('TOrderExternalJournalChoiceForm'); end; procedure TLoadFormTest.LoadInfoMoneyGroupFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TInfoMoneyGroupForm')); TdsdFormStorageFactory.GetStorage.Load('TInfoMoneyGroupForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TInfoMoneyGroup_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TInfoMoneyGroup_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TInfoMoneyGroupEditForm')); TdsdFormStorageFactory.GetStorage.Load('TInfoMoneyGroupEditForm'); end; procedure TLoadFormTest.LoadInstructionsFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TInstructionsKindForm')); TdsdFormStorageFactory.GetStorage.Load('TInstructionsKindForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TInstructionsForm')); TdsdFormStorageFactory.GetStorage.Load('TInstructionsForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TInstructionsEditForm')); TdsdFormStorageFactory.GetStorage.Load('TInstructionsEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TInstructionsCashForm')); TdsdFormStorageFactory.GetStorage.Load('TInstructionsCashForm'); end; procedure TLoadFormTest.LoadInsuranceCompaniesFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TInsuranceCompaniesEditForm')); TdsdFormStorageFactory.GetStorage.Load('TInsuranceCompaniesEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TInsuranceCompaniesForm')); TdsdFormStorageFactory.GetStorage.Load('TInsuranceCompaniesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TInsuranceCompanies_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TInsuranceCompanies_ObjectForm'); end; procedure TLoadFormTest.LoadInventoryFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TInventoryJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TInventoryJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TInventoryForm')); TdsdFormStorageFactory.GetStorage.Load('TInventoryForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TInventoryPartionForm')); TdsdFormStorageFactory.GetStorage.Load('TInventoryPartionForm'); end; procedure TLoadFormTest.LoadInventoryLocalFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnitLocalForm')); TdsdFormStorageFactory.GetStorage.Load('TUnitLocalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsInventoryForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsInventoryForm'); end; procedure TLoadFormTest.LoadInvoiceFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TInvoiceJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TInvoiceJournalForm'); end; procedure TLoadFormTest.LoadGoodsSPMovementFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSPJournalChoiceForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSPJournalChoiceForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSPJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSPJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSP_MovementForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSP_MovementForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSP_Movement_CashForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSP_Movement_CashForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSPJournal_CashForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSPJournal_CashForm'); end; procedure TLoadFormTest.LoadGoodsSP_1303FormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSP408_1303JournalForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSP408_1303JournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSP408_1303Form')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSP408_1303Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSPInform_1303JournalForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSPInform_1303JournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSPInform_1303Form')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSPInform_1303Form'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSPSearch_1303JournalForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSPSearch_1303JournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSPSearch_1303Form')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSPSearch_1303Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TChoiceGoodsSPSearch_1303Form')); TdsdFormStorageFactory.GetStorage.Load('TChoiceGoodsSPSearch_1303Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSPRegistry_1303JournalForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSPRegistry_1303JournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSPRegistry_1303Form')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSPRegistry_1303Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSP_1303Form')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSP_1303Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSP_1303JournalForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSP_1303JournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCountry_1303Form')); TdsdFormStorageFactory.GetStorage.Load('TCountry_1303Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCountry_1303EditForm')); TdsdFormStorageFactory.GetStorage.Load('TCountry_1303EditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMakerSP_1303Form')); TdsdFormStorageFactory.GetStorage.Load('TMakerSP_1303Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMakerSP_1303EditForm')); TdsdFormStorageFactory.GetStorage.Load('TMakerSP_1303EditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCountSP_1303Form')); TdsdFormStorageFactory.GetStorage.Load('TCountSP_1303Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCountSP_1303EditForm')); TdsdFormStorageFactory.GetStorage.Load('TCountSP_1303EditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TKindOutSP_1303Form')); TdsdFormStorageFactory.GetStorage.Load('TKindOutSP_1303Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TKindOutSP_1303EditForm')); TdsdFormStorageFactory.GetStorage.Load('TKindOutSP_1303EditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDosage_1303Form')); TdsdFormStorageFactory.GetStorage.Load('TDosage_1303Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDosage_1303EditForm')); TdsdFormStorageFactory.GetStorage.Load('TDosage_1303EditForm'); } end; procedure TLoadFormTest.LoadLossFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TLossJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TLossJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLossForm')); TdsdFormStorageFactory.GetStorage.Load('TLossForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLossFundJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TLossFundJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLossFundForm')); TdsdFormStorageFactory.GetStorage.Load('TLossFundForm'); end; procedure TLoadFormTest.LoadListDiffFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TListDiffJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TListDiffJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TListDiffForm')); TdsdFormStorageFactory.GetStorage.Load('TListDiffForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TListDiffFormVIPSendForm')); TdsdFormStorageFactory.GetStorage.Load('TListDiffFormVIPSendForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TListDiffFormVIPSendRemainForm')); TdsdFormStorageFactory.GetStorage.Load('TListDiffFormVIPSendRemainForm'); end; procedure TLoadFormTest.LoadArticleLossFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TArticleLossForm')); TdsdFormStorageFactory.GetStorage.Load('TArticleLossForm'); end; procedure TLoadFormTest.LoadArticleLossEditFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TArticleLossEditForm')); TdsdFormStorageFactory.GetStorage.Load('TArticleLossEditForm'); end; procedure TLoadFormTest.LoadInfoMoneyDestinationFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TInfoMoneyDestinationForm')); TdsdFormStorageFactory.GetStorage.Load('TInfoMoneyDestinationForm'); TdsdFormStorageFactory.GetStorage.Save (GetForm('TInfoMoneyDestination_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TInfoMoneyDestination_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save (GetForm('TInfoMoneyDestinationEditForm')); TdsdFormStorageFactory.GetStorage.Load('TInfoMoneyDestinationEditForm'); end; procedure TLoadFormTest.LoadInfoMoneyFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TInfoMoneyForm')); TdsdFormStorageFactory.GetStorage.Load('TInfoMoneyForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TInfoMoney_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TInfoMoney_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TInfoMoneyEditForm')); TdsdFormStorageFactory.GetStorage.Load('TInfoMoneyEditForm'); end; procedure TLoadFormTest.LoadIncomeFormTest; begin { TdsdFormStorageFactory.GetStorage.Save(GetForm('TChoiceIncomeForm')); TdsdFormStorageFactory.GetStorage.Load('TChoiceIncomeForm'); } TdsdFormStorageFactory.GetStorage.Save(GetForm('TIncomeForm')); TdsdFormStorageFactory.GetStorage.Load('TIncomeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TIncomeJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TIncomeJournalForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TIncomeOperDataDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TIncomeOperDataDialogForm'); } TdsdFormStorageFactory.GetStorage.Save(GetForm('TIncomePharmacyForm')); TdsdFormStorageFactory.GetStorage.Load('TIncomePharmacyForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TIncomePharmacyJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TIncomePharmacyJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TIncomeJournalChoiceForm')); TdsdFormStorageFactory.GetStorage.Load('TIncomeJournalChoiceForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TIncome_AmountTroubleForm')); TdsdFormStorageFactory.GetStorage.Load('TIncome_AmountTroubleForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TIncomePartnerDataDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TIncomePartnerDataDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TIncomeCheckDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TIncomeCheckDialogForm'); } TdsdFormStorageFactory.GetStorage.Save(GetForm('TAccommodationUnitEditForm')); TdsdFormStorageFactory.GetStorage.Load('TAccommodationUnitEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAccommodationUnitForm')); TdsdFormStorageFactory.GetStorage.Load('TAccommodationUnitForm'); end; procedure TLoadFormTest.LoadIncomeHouseholdInventoryFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TIncomeHouseholdInventoryForm')); TdsdFormStorageFactory.GetStorage.Load('TIncomeHouseholdInventoryForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TIncomeHouseholdInventoryJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TIncomeHouseholdInventoryJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TIncomeHouseholdInventoryCashJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TIncomeHouseholdInventoryCashJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TIncomeHouseholdInventoryCashForm')); TdsdFormStorageFactory.GetStorage.Load('TIncomeHouseholdInventoryCashForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_HouseholdInventoryRemainsDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_HouseholdInventoryRemainsDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_HouseholdInventoryRemainsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_HouseholdInventoryRemainsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_HouseholdInventoryRemainsCashForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_HouseholdInventoryRemainsCashForm'); end; procedure TLoadFormTest.LoadAdditionalGoodsFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TAdditionalGoodsForm')); TdsdFormStorageFactory.GetStorage.Load('TAdditionalGoodsForm'); end; procedure TLoadFormTest.LoadPriceFormTest; begin { TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceOnDateForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceOnDateForm'); } TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TMCS_LiteForm')); TdsdFormStorageFactory.GetStorage.Load('TMCS_LiteForm'); exit; { TdsdFormStorageFactory.GetStorage.Save(GetForm('TMCSForm')); TdsdFormStorageFactory.GetStorage.Load('TMCSForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRecalcMCS_DialogForm')); TdsdFormStorageFactory.GetStorage.Load('TRecalcMCS_DialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceHistoryForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceHistoryForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceGoodsDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceGoodsDialogForm'); } end; procedure TLoadFormTest.LoadPriceSiteFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceSiteDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceSiteDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceSiteForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceSiteForm'); end; procedure TLoadFormTest.LoadPriceChangeFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceChangeForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceChangeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceChangeHistoryForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceChangeHistoryForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceChangeOnDateForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceChangeOnDateForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceChangeDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceChangeDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceChangeGoodsDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceChangeGoodsDialogForm'); end; procedure TLoadFormTest.LoadAlternativeGroupFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TAlternativeGroupForm')); TdsdFormStorageFactory.GetStorage.Load('TAlternativeGroupForm'); end; procedure TLoadFormTest.LoadCheckDeferredFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckDeferredForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckDeferredForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckDeferred_SearchForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckDeferred_SearchForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckDelayDeferredForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckDelayDeferredForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckCombineForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckCombineForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckSelectionOrderForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckSelectionOrderForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TExpressVIPConfirmForm')); TdsdFormStorageFactory.GetStorage.Load('TExpressVIPConfirmForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckBuyerForSiteForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckBuyerForSiteForm'); end; procedure TLoadFormTest.LoadCheckLiki24FormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckLiki24Form')); TdsdFormStorageFactory.GetStorage.Load('TCheckLiki24Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckLiki24_SearchForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckLiki24_SearchForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckDelayLiki24Form')); TdsdFormStorageFactory.GetStorage.Load('TCheckDelayLiki24Form'); end; procedure TLoadFormTest.LoadCheckVIPFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CashListDiffPeriodForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CashListDiffPeriodForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckVIPForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckVIPForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckDelayVIPForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckDelayVIPForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckVIP_ErrorForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckVIP_ErrorForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckVIP_SearchForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckVIP_SearchForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckCashForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckCashForm'); end; procedure TLoadFormTest.LoadCheckSiteFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckSiteForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckSiteForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckSite_SearchForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckSite_SearchForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckDelaySiteForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckDelaySiteForm'); end; procedure TLoadFormTest.LoadOverFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TOverJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TOverJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOverForm')); TdsdFormStorageFactory.GetStorage.Load('TOverForm'); end; procedure TLoadFormTest.LoadOverSettingsFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TOverSettingsForm')); TdsdFormStorageFactory.GetStorage.Load('TOverSettingsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TOverSettingsEditForm')); TdsdFormStorageFactory.GetStorage.Load('TOverSettingsEditForm'); end; procedure TLoadFormTest.LoadPaidKindFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPaidKindForm')); TdsdFormStorageFactory.GetStorage.Load('TPaidKindForm'); end; procedure TLoadFormTest.LoadPaidTypeFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPaidTypeForm')); TdsdFormStorageFactory.GetStorage.Load('TPaidTypeForm'); end; procedure TLoadFormTest.LoadPartnerMedicalFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPartnerMedical_SPKindForm')); TdsdFormStorageFactory.GetStorage.Load('TPartnerMedical_SPKindForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TPartnerMedical_ObjectForm')); // TdsdFormStorageFactory.GetStorage.Load('TPartnerMedical_ObjectForm'); // // // TdsdFormStorageFactory.GetStorage.Save(GetForm('TPartnerMedicalForm')); // TdsdFormStorageFactory.GetStorage.Load('TPartnerMedicalForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TPartnerMedicalEditForm')); // TdsdFormStorageFactory.GetStorage.Load('TPartnerMedicalEditForm'); end; procedure TLoadFormTest.LoadPaymentFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPaymentJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TPaymentJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPaymentForm')); TdsdFormStorageFactory.GetStorage.Load('TPaymentForm'); end; procedure TLoadFormTest.LoadPermanentDiscountFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPermanentDiscountJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TPermanentDiscountJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPermanentDiscountForm')); TdsdFormStorageFactory.GetStorage.Load('TPermanentDiscountForm'); end; procedure TLoadFormTest.LoadPersonalFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPersonalForm')); TdsdFormStorageFactory.GetStorage.Load('TPersonalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPersonalEditForm')); TdsdFormStorageFactory.GetStorage.Load('TPersonalEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPersonal_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TPersonal_ObjectForm'); end; procedure TLoadFormTest.LoadPersonalGroupFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPersonalGroupForm')); TdsdFormStorageFactory.GetStorage.Load('TPersonalGroupForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPersonalGroupEditForm')); TdsdFormStorageFactory.GetStorage.Load('TPersonalGroupEditForm'); end; procedure TLoadFormTest.LoadPlanIventoryFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPlanIventoryForm')); TdsdFormStorageFactory.GetStorage.Load('TPlanIventoryForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPlanIventoryEditForm')); TdsdFormStorageFactory.GetStorage.Load('TPlanIventoryEditForm'); end; procedure TLoadFormTest.LoadPositionEducationFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPositionForm')); TdsdFormStorageFactory.GetStorage.Load('TPositionForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPositionEditForm')); TdsdFormStorageFactory.GetStorage.Load('TPositionEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TEducationForm')); TdsdFormStorageFactory.GetStorage.Load('TEducationForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TEducationEditForm')); TdsdFormStorageFactory.GetStorage.Load('TEducationEditForm'); end; procedure TLoadFormTest.LoadChangeIncomePaymentFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TChangeIncomePaymentJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TChangeIncomePaymentJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TChangeIncomePaymentForm')); TdsdFormStorageFactory.GetStorage.Load('TChangeIncomePaymentForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCalculationPartialSaleForm')); TdsdFormStorageFactory.GetStorage.Load('TCalculationPartialSaleForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Sale_PartialSaleForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Sale_PartialSaleForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Sale_PartialSaleAllForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Sale_PartialSaleAllForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Sale_PartialSaleAllDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Sale_PartialSaleAllDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Income_PartialSaleDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Income_PartialSaleDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Income_PartialSaleForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Income_PartialSaleForm'); end; procedure TLoadFormTest.LoadChangeIncomePaymentKindFormTest; begin TdsdFormStorageFactory.GetStorage.Save (GetForm('TChangeIncomePaymentKindForm')); TdsdFormStorageFactory.GetStorage.Load('TChangeIncomePaymentKindForm'); end; procedure TLoadFormTest.LoadPretensionFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPretensionForm')); TdsdFormStorageFactory.GetStorage.Load('TPretensionForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPretensionJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TPretensionJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCreatePretensionForm')); TdsdFormStorageFactory.GetStorage.Load('TCreatePretensionForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPretensionJournalIncomeForm')); TdsdFormStorageFactory.GetStorage.Load('TPretensionJournalIncomeForm'); end; procedure TLoadFormTest.LoadPriceListFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceListForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceListForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceListJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceListJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSupplierFailuresForm')); TdsdFormStorageFactory.GetStorage.Load('TSupplierFailuresForm'); end; procedure TLoadFormTest.LoadSaleFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TSaleJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TSaleJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSaleForm')); TdsdFormStorageFactory.GetStorage.Load('TSaleForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMedicSPDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TMedicSPDialogForm'); end; procedure TLoadFormTest.LoadSalePromoGoodsFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TSalePromoGoodsJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TSalePromoGoodsJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSalePromoGoodsForm')); TdsdFormStorageFactory.GetStorage.Load('TSalePromoGoodsForm'); end; procedure TLoadFormTest.LoadReturnInFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReturnInJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TReturnInJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReturnInForm')); TdsdFormStorageFactory.GetStorage.Load('TReturnInForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReturnInCashForm')); TdsdFormStorageFactory.GetStorage.Load('TReturnInCashForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReturnInJournalCashForm')); TdsdFormStorageFactory.GetStorage.Load('TReturnInJournalCashForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckItemJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckItemJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckToReturnForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckToReturnForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckToReturnDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckToReturnDialogForm'); end; procedure TLoadFormTest.LoadSeasonalityCoefficientFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TSeasonalityCoefficientEditForm')); TdsdFormStorageFactory.GetStorage.Load('TSeasonalityCoefficientEditForm'); end; procedure TLoadFormTest.LoadSendFormTest; begin { TdsdFormStorageFactory.GetStorage.Save(GetForm('TChoiceSendForm')); TdsdFormStorageFactory.GetStorage.Load('TChoiceSendForm'); exit; } TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TSendJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendForm')); TdsdFormStorageFactory.GetStorage.Load('TSendForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendMenegerForm')); TdsdFormStorageFactory.GetStorage.Load('TSendMenegerForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendCashSUNForm')); TdsdFormStorageFactory.GetStorage.Load('TSendCashSUNForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TBanCommentSendEditForm')); TdsdFormStorageFactory.GetStorage.Load('TBanCommentSendEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TBanCommentSendForm')); TdsdFormStorageFactory.GetStorage.Load('TBanCommentSendForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendWayNameForm')); TdsdFormStorageFactory.GetStorage.Load('TSendWayNameForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPartionDateGoodsListForm')); TdsdFormStorageFactory.GetStorage.Load('TPartionDateGoodsListForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCommentSendEditForm')); TdsdFormStorageFactory.GetStorage.Load('TCommentSendEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCommentSendForm')); TdsdFormStorageFactory.GetStorage.Load('TCommentSendForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendCashJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TSendCashJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendCashJournalSunForm')); TdsdFormStorageFactory.GetStorage.Load('TSendCashJournalSunForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendCashJournalVIPForm')); TdsdFormStorageFactory.GetStorage.Load('TSendCashJournalVIPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendMenegerJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TSendMenegerJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendMenegerVIPJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TSendMenegerVIPJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TConfirmedDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TConfirmedDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendVIP_ToGenerateCheckForm')); TdsdFormStorageFactory.GetStorage.Load('TSendVIP_ToGenerateCheckForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendVIP_ToGenerateCheckDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TSendVIP_ToGenerateCheckDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendVIP_VIPDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TSendVIP_VIPDialogForm'); // диалог изменения цены получателя TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceBySendDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceBySendDialogForm'); } end; procedure TLoadFormTest.LoadSendPartionDateFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendPartionDateJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TSendPartionDateJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendPartionDateForm')); TdsdFormStorageFactory.GetStorage.Load('TSendPartionDateForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendPartionDate_UpdatePercentDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TSendPartionDate_UpdatePercentDialogForm'); end; procedure TLoadFormTest.LoadSendPartionDateChangeFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendPartionDateChangeForm')); TdsdFormStorageFactory.GetStorage.Load('TSendPartionDateChangeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendPartionDateChangeJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TSendPartionDateChangeJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendPartionDateChangeCashForm')); TdsdFormStorageFactory.GetStorage.Load('TSendPartionDateChangeCashForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendPartionDateChangeCashJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TSendPartionDateChangeCashJournalForm'); end; procedure TLoadFormTest.LoadSendOnPriceFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendOnPriceJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TSendOnPriceJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSendOnPriceForm')); TdsdFormStorageFactory.GetStorage.Load('TSendOnPriceForm'); end; procedure TLoadFormTest.LoadSheetWorkTimeFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_KPUForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_KPUForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_TestingUserForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_TestingUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_TestingUserAttemptsForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_TestingUserAttemptsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPUSHJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TPUSHJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPUSHForm')); TdsdFormStorageFactory.GetStorage.Load('TPUSHForm'); Exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TSheetWorkTimeJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TSheetWorkTimeJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSheetWorkTimeForm')); TdsdFormStorageFactory.GetStorage.Load('TSheetWorkTimeForm'); TdsdFormStorageFactory.GetStorage.Save (GetForm('TSheetWorkTimeAddRecordForm')); TdsdFormStorageFactory.GetStorage.Load('TSheetWorkTimeAddRecordForm'); end; procedure TLoadFormTest.LoadSunExclusionFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TSunExclusionForm')); TdsdFormStorageFactory.GetStorage.Load('TSunExclusionForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TSunExclusionEditForm')); TdsdFormStorageFactory.GetStorage.Load('TSunExclusionEditForm'); end; procedure TLoadFormTest.LoadEmployeeScheduleFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmployeeScheduleJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TEmployeeScheduleJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmployeeScheduleNewForm')); TdsdFormStorageFactory.GetStorage.Load('TEmployeeScheduleNewForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmployeeScheduleEditUserForm')); TdsdFormStorageFactory.GetStorage.Load('TEmployeeScheduleEditUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmployeeScheduleForm')); TdsdFormStorageFactory.GetStorage.Load('TEmployeeScheduleForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmployeeScheduleUserForm')); TdsdFormStorageFactory.GetStorage.Load('TEmployeeScheduleUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmployeeScheduleUnitForm')); TdsdFormStorageFactory.GetStorage.Load('TEmployeeScheduleUnitForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmployeeScheduleFillingForm')); TdsdFormStorageFactory.GetStorage.Load('TEmployeeScheduleFillingForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmployeeScheduleAddUserDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TEmployeeScheduleAddUserDialogForm'); end; procedure TLoadFormTest.LoadEmployeeScheduleVIPFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmployeeScheduleVIPJournalForm')); TdsdFormStorageFactory.GetStorage.Load('TEmployeeScheduleVIPJournalForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmployeeScheduleVIPForm')); TdsdFormStorageFactory.GetStorage.Load('TEmployeeScheduleVIPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TEmployeeScheduleUserVIPForm')); TdsdFormStorageFactory.GetStorage.Load('TEmployeeScheduleUserVIPForm'); end; procedure TLoadFormTest.LoadExchangeRatesFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TExchangeRatesForm')); TdsdFormStorageFactory.GetStorage.Load('TExchangeRatesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TExchangeRatesEditForm')); TdsdFormStorageFactory.GetStorage.Load('TExchangeRatesEditForm'); end; procedure TLoadFormTest.LoadSPKindFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TSPKindForm')); TdsdFormStorageFactory.GetStorage.Load('TSPKindForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMedicalProgramSPEditForm')); TdsdFormStorageFactory.GetStorage.Load('TMedicalProgramSPEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMedicalProgramSPForm')); TdsdFormStorageFactory.GetStorage.Load('TMedicalProgramSPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGroupMedicalProgramSPEditForm')); TdsdFormStorageFactory.GetStorage.Load('TGroupMedicalProgramSPEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGroupMedicalProgramSPForm')); TdsdFormStorageFactory.GetStorage.Load('TGroupMedicalProgramSPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMedicalProgramSPLinkEditForm')); TdsdFormStorageFactory.GetStorage.Load('TMedicalProgramSPLinkEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMedicalProgramSPLinkForm')); TdsdFormStorageFactory.GetStorage.Load('TMedicalProgramSPLinkForm'); end; procedure TLoadFormTest.LoadPartionDateKindFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TPartionDateKindForm')); TdsdFormStorageFactory.GetStorage.Load('TPartionDateKindForm'); end; procedure TLoadFormTest.LoadSystemFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TeSputnikContactsMessagesForm')); TdsdFormStorageFactory.GetStorage.Load('TeSputnikContactsMessagesForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPhoneNoSeparatorDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TPhoneNoSeparatorDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUkraineAlarmForm')); TdsdFormStorageFactory.GetStorage.Load('TUkraineAlarmForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TDataChoiceDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TDataChoiceDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_LoginProtocolForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_LoginProtocolForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TTelegramProtocolForm')); // TdsdFormStorageFactory.GetStorage.Load('TTelegramProtocolForm'); // TdsdFormStorageFactory.GetStorage.Save(GetForm('TStringDialogForm')); // TdsdFormStorageFactory.GetStorage.Load('TStringDialogForm'); // // TdsdFormStorageFactory.GetStorage.Save(GetForm('TTextDialogForm')); // TdsdFormStorageFactory.GetStorage.Load('TTextDialogForm'); // // TdsdFormStorageFactory.GetStorage.Save(GetForm('TAmountDialogForm')); // TdsdFormStorageFactory.GetStorage.Load('TAmountDialogForm'); // // TdsdFormStorageFactory.GetStorage.Save(GetForm('TClearDefaultUnitForm')); // TdsdFormStorageFactory.GetStorage.Load('TClearDefaultUnitForm'); // // TdsdFormStorageFactory.GetStorage.Save(GetForm('TSummaDialogForm')); // TdsdFormStorageFactory.GetStorage.Load('TSummaDialogForm'); // // TdsdFormStorageFactory.GetStorage.Save(GetForm('TIntegerDialogForm')); // TdsdFormStorageFactory.GetStorage.Load('TIntegerDialogForm'); // // TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsDialogForm')); // TdsdFormStorageFactory.GetStorage.Load('TGoodsDialogForm'); // // TdsdFormStorageFactory.GetStorage.Save(GetForm('TGlobalConstForm')); // TdsdFormStorageFactory.GetStorage.Load('TGlobalConstForm'); end; procedure TLoadFormTest.LoadSPObjectFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_SP_ForDPSSDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_SP_ForDPSSDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_SP_ForDPSSForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_SP_ForDPSSForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCategory1303Form')); TdsdFormStorageFactory.GetStorage.Load('TCategory1303Form'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMedicSP_ICForm')); TdsdFormStorageFactory.GetStorage.Load('TMedicSP_ICForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMedicSP_PaperRecipeForm')); TdsdFormStorageFactory.GetStorage.Load('TMedicSP_PaperRecipeForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TMedicKashtanForm')); TdsdFormStorageFactory.GetStorage.Load('TMedicKashtanForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMemberKashtanForm')); TdsdFormStorageFactory.GetStorage.Load('TMemberKashtanForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMemberSP_SPKindForm')); TdsdFormStorageFactory.GetStorage.Load('TMemberSP_SPKindForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SummSPForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SummSPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SummSP_DialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SummSP_DialogForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TMedicSP_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TMedicSP_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMedicSPForm')); TdsdFormStorageFactory.GetStorage.Load('TMedicSPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMedicSPEditForm')); TdsdFormStorageFactory.GetStorage.Load('TMedicSPEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAmbulantClinicSPForm')); TdsdFormStorageFactory.GetStorage.Load('TAmbulantClinicSPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TAmbulantClinicSPEditForm')); TdsdFormStorageFactory.GetStorage.Load('TAmbulantClinicSPEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMemberSPForm')); TdsdFormStorageFactory.GetStorage.Load('TMemberSPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMemberSPEditForm')); TdsdFormStorageFactory.GetStorage.Load('TMemberSPEditForm'); } // отчет реестр по постановлению 1303 TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SaleSPForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SaleSPForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_SaleSPDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_SaleSPDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGroupMemberSPForm')); TdsdFormStorageFactory.GetStorage.Load('TGroupMemberSPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGroupMemberSPEditForm')); TdsdFormStorageFactory.GetStorage.Load('TGroupMemberSPEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TKindOutSPForm')); TdsdFormStorageFactory.GetStorage.Load('TKindOutSPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TKindOutSPEditForm')); TdsdFormStorageFactory.GetStorage.Load('TKindOutSPEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TBrandSPForm')); TdsdFormStorageFactory.GetStorage.Load('TBrandSPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TBrandSPEditForm')); TdsdFormStorageFactory.GetStorage.Load('TBrandSPEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TIntenalSPForm')); TdsdFormStorageFactory.GetStorage.Load('TIntenalSPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TIntenalSPEditForm')); TdsdFormStorageFactory.GetStorage.Load('TIntenalSPEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSP_ObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSP_ObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGoodsSPForm')); TdsdFormStorageFactory.GetStorage.Load('TGoodsSPForm'); exit; } // отчет по продажам товара соц. проекта TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckSPForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckSPForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_CheckSPDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_CheckSPDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TReport_Check_SP_CheckingForm')); TdsdFormStorageFactory.GetStorage.Load('TReport_Check_SP_CheckingForm'); end; procedure TLoadFormTest.LoadServiceFormTest; begin TdsdFormStorageFactory.GetStorage.Save(GetForm('TCashSettingsEditForm')); TdsdFormStorageFactory.GetStorage.Load('TCashSettingsEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCashSettingsHistoryForm')); TdsdFormStorageFactory.GetStorage.Load('TCashSettingsHistoryForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TNewUserForm')); TdsdFormStorageFactory.GetStorage.Load('TNewUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPickUpLogsAndDBFForm')); TdsdFormStorageFactory.GetStorage.Load('TPickUpLogsAndDBFForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TGUIDUnitForm')); TdsdFormStorageFactory.GetStorage.Load('TGUIDUnitForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheckoutTestingForm')); TdsdFormStorageFactory.GetStorage.Load('TCheckoutTestingForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMovementItemContainerCountForm')); TdsdFormStorageFactory.GetStorage.Load('TMovementItemContainerCountForm'); } TdsdFormStorageFactory.GetStorage.Save(GetForm('TJuridicalPrioritiesForm')); TdsdFormStorageFactory.GetStorage.Load('TJuridicalPrioritiesForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TMethodsAssortmentForm')); TdsdFormStorageFactory.GetStorage.Load('TMethodsAssortmentForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('THelsiUserForm')); TdsdFormStorageFactory.GetStorage.Load('THelsiUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLog_CashRemainsForm')); TdsdFormStorageFactory.GetStorage.Load('TLog_CashRemainsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TCheck_CashRegisterForm')); TdsdFormStorageFactory.GetStorage.Load('TCheck_CashRegisterForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TFormsForm')); TdsdFormStorageFactory.GetStorage.Load('TFormsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TObjectDescForm')); TdsdFormStorageFactory.GetStorage.Load('TObjectDescForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRoleForm')); TdsdFormStorageFactory.GetStorage.Load('TRoleForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRoleEditForm')); TdsdFormStorageFactory.GetStorage.Load('TRoleEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TRoleUnionForm')); TdsdFormStorageFactory.GetStorage.Load('TRoleUnionForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUnionDescForm')); TdsdFormStorageFactory.GetStorage.Load('TUnionDescForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUserNickForm')); TdsdFormStorageFactory.GetStorage.Load('TUserNickForm'); } TdsdFormStorageFactory.GetStorage.Save(GetForm('TUserCashForm')); TdsdFormStorageFactory.GetStorage.Load('TUserCashForm'); { TdsdFormStorageFactory.GetStorage.Save(GetForm('TUserEditLanguageForm')); TdsdFormStorageFactory.GetStorage.Load('TUserEditLanguageForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUserForm')); TdsdFormStorageFactory.GetStorage.Load('TUserForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUserHelsiEditForm')); TdsdFormStorageFactory.GetStorage.Load('TUserHelsiEditForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUserEditForm')); TdsdFormStorageFactory.GetStorage.Load('TUserEditForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TUserKeyForm')); TdsdFormStorageFactory.GetStorage.Load('TUserKeyForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TLoadObjectForm')); TdsdFormStorageFactory.GetStorage.Load('TLoadObjectForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceGroupSettingsForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceGroupSettingsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPriceGroupSettingsTopForm')); TdsdFormStorageFactory.GetStorage.Load('TPriceGroupSettingsTopForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TJuridicalSettingsForm')); TdsdFormStorageFactory.GetStorage.Load('TJuridicalSettingsForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TActionForm')); TdsdFormStorageFactory.GetStorage.Load('TActionForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TUserProtocolForm')); TdsdFormStorageFactory.GetStorage.Load('TUserProtocolForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TProcessForm')); TdsdFormStorageFactory.GetStorage.Load('TProcessForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TProtocolForm')); TdsdFormStorageFactory.GetStorage.Load('TProtocolForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMovementProtocolForm')); TdsdFormStorageFactory.GetStorage.Load('TMovementProtocolForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMovementItemProtocolForm')); TdsdFormStorageFactory.GetStorage.Load('TMovementItemProtocolForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TImportExportLinkForm')); TdsdFormStorageFactory.GetStorage.Load('TImportExportLinkForm'); exit; TdsdFormStorageFactory.GetStorage.Save(GetForm('TImportExportLinkTypeForm')); TdsdFormStorageFactory.GetStorage.Load('TImportExportLinkTypeForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMovementItemContainerForm')); TdsdFormStorageFactory.GetStorage.Load('TMovementItemContainerForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMovementDescDataForm')); TdsdFormStorageFactory.GetStorage.Load('TMovementDescDataForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TMovement_PeriodDialogForm')); TdsdFormStorageFactory.GetStorage.Load('TMovement_PeriodDialogForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TStatusForm')); TdsdFormStorageFactory.GetStorage.Load('TStatusForm'); TdsdFormStorageFactory.GetStorage.Save(GetForm('TPeriodCloseForm')); TdsdFormStorageFactory.GetStorage.Load('TPeriodCloseForm'); } end; initialization TestFramework.RegisterTest('Загрузка форм', TLoadFormTest.Suite); end.
{*! * Fano Web Framework (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano * @copyright Copyright (c) 2018 Zamrony P. Juhara * @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT) *} unit JsonFileSessionManagerFactoryImpl; interface {$MODE OBJFPC} uses DependencyIntf, DependencyContainerIntf, FactoryImpl, SessionConsts; type (*!------------------------------------------------ * TJsonFileSessionManager factory class * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *-----------------------------------------------*) TJsonFileSessionManagerFactory = class(TFactory) private fCookieName : string; fBaseDir : string; fPrefix : string; public constructor create( const cookieName : string = FANO_COOKIE_NAME; const baseDir : string = '/tmp'; const prefix : string = '' ); (*!--------------------------------------------------- * build class instance *---------------------------------------------------- * @param container dependency container instance *---------------------------------------------------- * This is implementation of IDependencyFactory *---------------------------------------------------*) function build(const container : IDependencyContainer) : IDependency; override; end; implementation uses StringFileReaderImpl, FileSessionManagerImpl, JsonSessionFactoryImpl, GuidSessionIdGeneratorImpl; constructor TJsonFileSessionManagerFactory.create( const cookieName : string = FANO_COOKIE_NAME; const baseDir : string = '/tmp'; const prefix : string = '' ); begin fCookieName := cookieName; fBaseDir := baseDir; fPrefix := prefix; end; (*!--------------------------------------------------- * build class instance *---------------------------------------------------- * @param container dependency container instance *---------------------------------------------------*) function TJsonFileSessionManagerFactory.build(const container : IDependencyContainer) : IDependency; begin result := TFileSessionManager.create( TGuidSessionIdGenerator.create(), TJsonSessionFactory.create(), fCookieName, TStringFileReader.create(), fBaseDir, fPrefix ); end; end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://localhost:49000/wsdl/ICyclopWS // Version : 1.0 // (4/29/2011 12:18:38 AM - 1.33.2.5) // ************************************************************************ // unit CyclopWS; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns, CommonObjs; type // ************************************************************************ // // Namespace : urn:CyclopWS-ICyclopWS // soapAction: urn:CyclopWS-ICyclopWS#%operationName% // transport : http://schemas.xmlsoap.org/soap/http // style : rpc // binding : ICyclopWSbinding // service : ICyclopWSservice // port : ICyclopWSPort // URL : http://localhost:49000/soap/ICyclopWS // ************************************************************************ // ICyclopWS = interface(IInvokable) ['{178EFFB8-C678-FD45-725D-7119D772FD59}'] function Login(const UserName: WideString; const Password: WideString): Boolean; stdcall; function Logout: Boolean; stdcall; end; function GetICyclopWS(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): ICyclopWS; implementation function GetICyclopWS(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): ICyclopWS; const defWSDL = 'http://localhost:49000/wsdl/ICyclopWS'; defURL = 'http://localhost:49000/soap/ICyclopWS'; defSvc = 'ICyclopWSservice'; defPrt = 'ICyclopWSPort'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as ICyclopWS); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; initialization InvRegistry.RegisterInterface(TypeInfo(ICyclopWS), 'urn:CyclopWS-ICyclopWS', ''); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(ICyclopWS), 'urn:CyclopWS-ICyclopWS#%operationName%'); InvRegistry.RegisterHeaderClass(TypeInfo(ICyclopWS), TCyclopAuthHeader, 'TCyclopAuthHeader', 'urn:CommonObjs'); RemClassRegistry.RegisterXSClass(TCyclopAuthHeader, 'urn:CommonObjs', 'TCyclopAuthHeader'); end.
unit MyPlayground; interface uses GraphABC, MySnake, MyApple, MyQueue; type Playground = class x1: integer; y1: integer; x2: integer; y2: integer; p: Picture; cellSize: integer; field: array [,] of integer; const emptyId: integer = 0; const borderId: integer = 1; const snakeId: integer = 2; const snakeHeadId: integer = 4; const appleId: integer = 3; snake: MySnake.Snake; apple: MyApple.Apple; constructor Create(x1: integer; y1: integer; x2: integer; y2: integer; CellSize: integer); procedure Render(); procedure Update(x1: integer; y1: integer; x2: integer; y2: integer); procedure SetPlaygroundObjects(); function GetArrayOfEmptys(): MyQueue.Queue; function ItShouldBe(x: integer; y: integer): string; function ItShouldBeBorder(x: integer; y: integer): boolean; function ItShouldBeApple(x: integer; y: integer): boolean; function ItShouldBeSnake(x: integer; y: integer): boolean; function ItShouldBeSnakeHead(x: integer; y: integer): boolean; function Width(): integer; function Heigth(): integer; function Columns(): integer; function Rows(): integer; end; implementation constructor Playground.Create(x1: integer; y1: integer; x2: integer; y2: integer; CellSize: integer); begin Self.x1 := x1; Self.y1 := y1; Self.x2 := x2; Self.y2 := y2; Self.cellSize := cellsize; SetLength(field, Columns(), Rows()); snake := MySnake.Snake.Create(Columns() div 2,Rows() div 2); apple := MyApple.Apple.Create(1, 1); SetPlaygroundObjects(); end; // Procedure procedure Playground.SetPlaygroundObjects(); begin for var j := 0 to rows() - 1 do for var i := 0 to columns() - 1 do begin case ItShouldBe(i, j) of 'Border': field[i, j] := borderId; 'Apple': field[i, j] := appleId; 'Snake': field[i, j] := snakeId; 'Snake Head': field[i, j] := snakeHeadId; 'Empty': field[i, j] := emptyId; end; end; end; procedure Playground.Render(); var currentColor: GraphABC.Color; begin GraphABC.SetPenColor(clDarkBlue); GraphABC.DrawRectangle(x1, y1, x1 + cellsize * Columns() + 1, y1 + cellsize * Rows() + 1); for var i := 1 to Columns() - 1 do begin GraphABC.SetPenColor(rgb(211, 211, 211)); GraphABC.Line(x1 + i * cellSize, y1, x1 + i * cellSize, y1 + cellsize * Rows()); end; for var i := 1 to Rows() - 1 do begin GraphABC.SetPenColor(rgb(211, 211, 211)); GraphABC.Line(x1, y1 + i * cellSize, x1 + cellsize * Columns(), y1 + i * cellSize); end; for var j := 0 to rows() - 1 do for var i := 0 to columns() - 1 do begin case field[i, j] of borderId: currentColor := rgb(32, 178, 170); snakeId: currentColor := rgb(70, 130, 180); snakeHeadId: currentColor := rgb(238, 130, 238); appleId: currentColor := rgb(144, 238, 144); emptyId: currentColor := rgb(240, 248, 255); end; GraphABC.SetBrushColor(currentColor); GraphABC.FillRect(x1 + i * cellsize + 1, y1 + j * cellsize + 1, x1 + i * cellsize + cellsize, y1 + j * cellsize + cellsize); end; end; procedure Playground.Update(x1: integer; y1: integer; x2: integer; y2: integer); begin Self.x1 := x1; Self.y1 := y1; Self.x2 := x2; Self.y2 := y2; SetLength(field, Columns(), Rows()); SetPlaygroundObjects(); end; // Function function Playground.GetArrayOfEmptys(): MyQueue.Queue; begin Result := MyQueue.Queue.Create(); for var j := 0 to Rows() - 1 do begin for var i := 0 to Columns() - 1 do begin if (field[i, j] = emptyId) then begin Result.Push(i, j); end; end; end; end; function Playground.ItShouldBeBorder(x: integer; y: integer): boolean; begin if (y = 0) or (y = (rows() - 1)) or (x = 0) or (x = columns() - 1) then begin Result := true; end; end; function Playground.ItShouldBeApple(x: integer; y: integer): boolean; begin if (apple.x = x) and (apple.y = y) then begin Result := True; end; end; function Playground.ItShouldBeSnake(x: integer; y: integer): boolean; begin for var i := 1 to snake.queue.length - 1 do begin if (snake.queue.queue[i, 0] = x) and (snake.queue.queue[i, 1] = y) then begin Result := True; exit; end; end; end; function Playground.ItShouldBeSnakeHead(x: integer; y: integer): boolean; begin if (snake.GetHead()[0] = x) and (snake.GetHead()[1] = y) then begin Result := True; end; end; function Playground.ItShouldBe(x: integer; y: integer): string; begin Result := 'Empty'; if ItShouldBeSnakeHead(x, y) then begin Result := 'Snake Head'; exit; end; if ItShouldBeSnake(x, y) then begin Result := 'Snake'; exit; end; if ItShouldBeBorder(x, y) then begin Result := 'Border'; exit; end; if ItShouldBeApple(x, y) then begin Result := 'Apple'; exit; end; end; function Playground.Width(): integer; begin Result := x2 - x1; end; function Playground.Heigth(): integer; begin Result := y2 - y1; end; function Playground.Columns(): integer; begin Result := Width() div cellSize; end; function Playground.Rows(): integer; begin Result := Heigth() div cellSize; end; initialization finalization end.
unit UPref; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } { This unit controls all of the user preferences} { There are individual Frames(TFrame) that contain the code for loading and saving the prefs} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, RzTreeVw, StdCtrls, ExtCtrls, RzLstBox, RzGroupBar, UContainer, UPrefFAppStartUp, UPrefFAppFolders, UPrefFAppDatabases, UPrefFAppSaving, UPrefFAppPDF, UPrefFAppPhotoInbox, UPrefFDocOperation, UPrefFDocDisplay, UPrefFDocPrinting, UPrefFDocColor, UPrefFDocFont, UPrefFDocFormatting, UPrefFUsers, UPrefFUserLicenseInfo, UPrefFToolBuiltIn, UPrefFToolPlugIn, UPrefFToolUserSpecified, UPrefFToolSketcher,// UPrefFToolMapping, UPrefFAppraiserXFer, UPrefFAppraiserCalcs, UPrefAppAutoUpdate, UPrefAppFiletypes, UPrefFUserFHADigSignatures, RzBorder, UForms; type TPrefs = class(TAdvancedForm) Panel1: TPanel; btnCancel: TButton; btnOK: TButton; PgCntl: TPageControl; AppStartup: TTabSheet; AppFolders: TTabSheet; AppDatabases: TTabSheet; AppSaving: TTabSheet; RzGroupBar: TRzGroupBar; AppPrefs: TRzGroup; Document: TRzGroup; Users: TRzGroup; Tools: TRzGroup; Appraisal: TRzGroup; AppUpdate: TTabSheet; AppPDF: TTabSheet; AppPhotoInBox: TTabSheet; docOperation: TTabSheet; docDisplay: TTabSheet; docPrinting: TTabSheet; docColor: TTabSheet; docFonts: TTabSheet; docFormatting: TTabSheet; appUsers: TTabSheet; toolPlugIn: TTabSheet; toolUserDefined: TTabSheet; toolSketcher: TTabSheet; apprsalXFers: TTabSheet; apprsalCalcs: TTabSheet; toolBuiltIn: TTabSheet; btnApply: TButton; appUserLicInfo: TTabSheet; AppFiletypes: TTabSheet; appUserFHACertificates: TTabSheet; procedure AppPrefsClose(Sender: TObject); //For the Photo Watch Pref procedure PreferenceClick(Sender: TObject); procedure PrefCategoryShow(Sender: TObject); procedure btnApplyClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private FDoc: TContainer; FCurPref: TFrame; FPrefAppStartUp: TPrefAppStartUp; FPrefAppFolders: TPrefAppFolders; FPrefAppDatabases: TPrefAppDatabases; FPrefAppSaving: TPrefAppSaving; FPrefAppUpdate: TPrefAutoUpdateFrame; FPrefAppPDF: TPrefAppPDF; FPrefAppPhotoInbox: TPrefAppPhotoInbox; FPrefAppFileTypes: TPrefAppFiletypes; FPrefDocOperation: TPrefDocOperation; FPrefDocDisplay: TPrefDocDisplay; FPrefDocPrinting: TPrefDocPrinting; FPrefDocColor: TPrefDocColor; FPrefDocFonts: TPrefDocFonts; FPrefDocFormatting: TPrefDocFormatting; FPrefUsers: TPrefUsers; FPrefUserLicenseInfo: TPrefUserLicenseInfo; // FPrefUserSecCertificates: TPrefUserSecCertificates; FPrefUserFHADigSignatures: TFHADigitalSignatures; FPrefToolBuiltIn: TPrefToolBuiltIn; FPrefToolPlugIn: TPrefToolPlugIn; FPrefToolUserSpecified: TPrefToolUserSpecified; FPrefToolSketcher: TPrefToolSketcher; //FPrefToolMapping: TPrefToolMapping; FPrefAppraiserXFer: TPrefAppraiserXFer; FPrefAppraiserCalcs: TPrefAppraiserCalcs; procedure SaveChanges; procedure LoadPrefFrames; procedure AppHighlight; procedure DocHighlight; procedure UserHighlight; procedure ToolHighlight; procedure AppraiserHighlight; public constructor Create(AOwner: TComponent); override; end; function ClickFormsPreferences(AOwner: TComponent): Boolean; //Main function for setting preferences implementation {$R *.dfm} Uses UGlobals, UInit, UStatus, ULicUser, UUtil1; const iAppStartup = 1; iAppFolder = 2; iAppDbases = 3; iAppSaving = 4; iAppPDF = 5; iAppUpdates = 6; iAppPhotoInbox = 7; iDocOperations = 21; iDocDisplay = 22; iDocPrinting = 23; iDocColor = 24; iDocFonts = 25; iDocFormatting = 26; iUsers = 41; iUsersLicInfo = 42; iUserFHADigSign = 43; //FHA Digal Signature/Cert iToolBuiltIn = 51; iToolPlugIn = 52; iToolUsers = 53; iToolSketchers = 54; //iToolMappers = 55; iAppraisalXFers = 71; iAppraisalCalcs = 72; Unused73 = 73; iAppFileTypes = 74; function ClickFormsPreferences(AOwner: TComponent): Boolean; var Pref: TPrefs; begin Pref := TPrefs.Create(AOwner); try Pref.Users.Visible := True; //###Remove: not IsStudentVersion; //hide users - student version Pref.Appraisal.Visible := True; Pref.AppPrefs.Items[2].Visible := True; //###Remove: not IsStudentVersion; //hide databases - student version Pref.AppPrefs.Items[7].Visible := True; //Pref.AppPrefs.Items[7].Enabled := Pref.FPrefAppFileTypes.isAssocBroken; Pref.Tools.Items[1].Visible := True; //###Remove: not IsStudentVersion; //hide plug in tools for Student Version Pref.Tools.Items[3].Visible := True; //###Remove: not IsStudentVersion; //hide sketching for Student Version Pref.AppPrefs.Items[4].Visible := Pref.AppPrefs.Items[4].Visible; //###Remove: and not IsStudentVersion; //hide updates - student version If (Pref.FDoc <> nil) then Pref.Document.Visible := not Pref.Fdoc.Locked; //hide doc prefs when report is locked result := Pref.ShowModal = mrOk; if result then try begin Pref.SaveChanges; WriteAppPrefs; end except ShowNotice('There was a problem saving preferences.'); end finally Pref.Free; //free the form end; end; { TPrefs} constructor TPrefs.Create(AOwner: TComponent); begin inherited Create(nil); SettingsName := CFormSettings_Prefs; FDoc := TContainer(AOwner); LoadPrefFrames; // 061711 JWyatt Override any automatic settings to ensure that these buttons // appear and move properly at 120DPI. btnApply.Left := Panel1.Left + 499; btnApply.Width := 75; btnOK.Left := Panel1.Left + 587; btnOK.Width := 75; btnCancel.Left := Panel1.Left + 675; btnCancel.Width := 75; //Display the Application Startup Prefs first AppPrefs.Items[0].Selected := True; AppPrefs.ShowItemSelection := True; AppPrefs.Special := True; end; procedure TPrefs.LoadPrefFrames; begin //create the frames and owner and parent association FPrefAppStartUp := TPrefAppStartUp.CreateFrame(AppStartup, FDoc); FPrefAppStartUp.Parent := AppStartup; FPrefAppStartUp.Align := AlClient; FPrefAppFolders := TPrefAppFolders.CreateFrame(AppFolders, FDoc); FPrefAppFolders.Parent := AppFolders; FPrefAppFolders.Align := AlClient; FPrefAppDatabases := TPrefAppDatabases.CreateFrame(AppDatabases, FDoc); FPrefAppDatabases.Parent := AppDatabases; FPrefAppDatabases.Align := AlClient; FPrefAppSaving := TPrefAppSaving.CreateFrame(AppSaving, FDoc); FPrefAppSaving.Parent := AppSaving; FPrefAppSaving.Align := AlClient; FPrefAppUpdate := TPrefAutoUpdateFrame.CreateFrame(AppUpdate, FDoc); FPrefAppUpdate.Parent := AppUpdate; FPrefAppUpdate.Align := AlClient; FPrefAppPDF := TPrefAppPDF.CreateFrame(AppPDF, FDoc); FPrefAppPDF.Parent := AppPDF; FPrefAppPDF.Align := AlClient; FPrefAppPhotoInbox := TPrefAppPhotoInbox.CreateFrame(AppPhotoInBox, FDoc); FPrefAppPhotoInbox.Parent := AppPhotoInBox; FPrefAppPhotoInbox.Align := AlClient; FPrefAppFiletypes := TPrefAppFiletypes.CreateFrame(AppFiletypes); FPrefAppFiletypes.Parent := AppFiletypes; FPrefAppFiletypes.Align := AlClient; FPrefDocOperation := TPrefDocOperation.CreateFrame(docOperation, FDoc); FPrefDocOperation.Parent := docOperation; FPrefDocOperation.Align := AlClient; FPrefDocDisplay := TPrefDocDisplay.CreateFrame(docDisplay, FDoc); FPrefDocDisplay.Parent := docDisplay; FPrefDocDisplay.Align := AlClient; FPrefDocPrinting := TPrefDocPrinting.CreateFrame(docPrinting, FDoc); FPrefDocPrinting.Parent := docPrinting; FPrefDocPrinting.Align := AlClient; FPrefDocColor := TPrefDocColor.CreateFrame(docColor, FDoc); FPrefDocColor.Parent := docColor; FPrefDocColor.Align := AlClient; FPrefDocFonts := TPrefDocFonts.CreateFrame(docFonts, FDoc); FPrefDocFonts.Parent := docFonts; FPrefDocFonts.Align := AlClient; FPrefDocFormatting := TPrefDocFormatting.CreateFrame(docFormatting, FDoc); FPrefDocFormatting.Parent := docFormatting; FPrefDocFormatting.Align := AlClient; FPrefUsers := TPrefUsers.CreateFrame(appUsers, FDoc); FPrefUsers.Parent := appUsers; FPrefUsers.Align := AlClient; FPrefUserLicenseInfo := TPrefUserLicenseInfo.CreateFrame(appUserLicInfo, FDoc); FPrefUserLicenseInfo.Parent := appUserLicInfo; FPrefUserLicenseInfo.Align := AlClient; FPrefUserFHADigSignatures := TFHADigitalSignatures.CreateFrame(appUserFHACertificates, FDoc); FPrefUserFHADigSignatures.Parent := appUserFHACertificates; FPrefUserFHADigSignatures.Align := AlClient; FPrefToolBuiltIn := TPrefToolBuiltIn.CreateFrame(toolBuiltIn, FDoc); FPrefToolBuiltIn.Parent := toolBuiltIn; FPrefToolBuiltIn.Align := AlClient; FPrefToolPlugIn := TPrefToolPlugIn.CreateFrame(toolPlugIn, FDoc); FPrefToolPlugIn.Parent := toolPlugIn; FPrefToolPlugIn.Align := AlClient; FPrefToolUserSpecified := TPrefToolUserSpecified.CreateFrame(toolUserDefined, FDoc); FPrefToolUserSpecified.Parent := toolUserDefined; FPrefToolUserSpecified.Align := AlClient; FPrefToolSketcher := TPrefToolSketcher.CreateFrame(toolSketcher, FDoc); FPrefToolSketcher.Parent := toolSketcher; FPrefToolSketcher.Align := AlClient; {FPrefToolMapping := TPrefToolMapping.CreateFrame(toolMapper, FDoc); FPrefToolMapping.Parent := toolMapper; FPrefToolMapping.Align := AlClient; } FPrefAppraiserXFer := TPrefAppraiserXFer.CreateFrame(apprsalXFers, FDoc); FPrefAppraiserXFer.Parent := apprsalXFers; FPrefAppraiserXFer.Align := AlClient; FPrefAppraiserCalcs := TPrefAppraiserCalcs.CreateFrame(apprsalCalcs, FDoc); FPrefAppraiserCalcs.Parent := apprsalCalcs; FPrefAppraiserCalcs.Align := AlClient; end; procedure TPrefs.SaveChanges; begin FPrefAppStartUp.SavePrefs; FPrefAppFolders.SavePrefs; FPrefAppDatabases.SavePrefs; FPrefAppSaving.SavePrefs; FPrefAppUpdate.SavePrefs; FPrefAppPDF.SavePrefs; FPrefAppPhotoInbox.SavePrefs; FPrefDocOperation.SavePrefs; FPrefDocDisplay.ApplyPreferences; FPrefDocDisplay.SavePrefs; FPrefDocPrinting.SavePrefs; FPrefDocColor.SavePrefs; FPrefDocColor.ApplyPreferences; FPrefDocFonts.SavePrefs; FPrefDocFormatting.SavePrefs; FPrefUsers.SavePrefs; FPrefUserLicenseInfo.SavePrefs; FPrefToolBuiltIn.SavePrefs; FPrefToolPlugIn.SavePrefs; FPrefToolUserSpecified.SavePrefs; FPrefToolSketcher.SavePrefs; //FPrefToolMapping.SavePrefs; FPrefAppraiserXFer.SavePrefs; FPrefAppraiserCalcs.SavePrefs; end; procedure TPrefs.FormCloseQuery(Sender: TObject; var CanClose: Boolean); //this came from the photo inbox code begin CanClose := (ModalResult = mrCancel) or ((ModalResult = mrOK) and FPrefAppPhotoInbox.FolderWatcherSetupOK); end; //procedures for setting the correct highlighting on the sidebar procedure TPrefs.AppHighlight; begin AppPrefs.ShowItemSelection := True; AppPrefs.Special := True; Document.ShowItemSelection := False; Document.Special := False; Users.ShowItemSelection := False; Users.Special := False; Tools.ShowItemSelection := False; Tools.Special := False; Appraisal.ShowItemSelection := False; Appraisal.Special := False; end; procedure TPrefs.DocHighlight; begin AppPrefs.ShowItemSelection := False; AppPrefs.Special := False; Document.ShowItemSelection := True; Document.Special := True; Users.ShowItemSelection := False; Users.Special := False; Tools.ShowItemSelection := False; Tools.Special := False; Appraisal.ShowItemSelection := False; Appraisal.Special := False; end; procedure TPrefs.UserHighlight; begin AppPrefs.ShowItemSelection := False; AppPrefs.Special := False; Document.ShowItemSelection := False; Document.Special := False; Users.ShowItemSelection := True; Users.Special := True; Tools.ShowItemSelection := False; Tools.Special := False; Appraisal.ShowItemSelection := False; Appraisal.Special := False; end; procedure TPrefs.ToolHighlight; begin AppPrefs.ShowItemSelection := False; AppPrefs.Special := False; Document.ShowItemSelection := False; Document.Special := False; Users.ShowItemSelection := False; Users.Special := False; Tools.ShowItemSelection := True; Tools.Special := True; Appraisal.ShowItemSelection := False; Appraisal.Special := False; end; procedure TPrefs.AppraiserHighlight; begin AppPrefs.ShowItemSelection := False; AppPrefs.Special := False; Document.ShowItemSelection := False; Document.Special := False; Users.ShowItemSelection := False; Users.Special := False; Tools.ShowItemSelection := False; Tools.Special := False; Appraisal.ShowItemSelection := True; Appraisal.Special := True; end; procedure TPrefs.AppPrefsClose(Sender: TObject); const CAutoUpdatingIndex = 4; begin // this is a secret to show the auto updating preferences AppPrefs.Items[CAutoUpdatingIndex].Visible := True; end; procedure TPrefs.PreferenceClick(Sender: TObject); begin case TRzGroupItem(Sender).tag of iAppStartup: begin PgCntl.ActivePage := AppStartup; FCurPref := FPrefAppStartUp; AppHighlight; end; iAppFolder: begin PgCntl.ActivePage := AppFolders; AppHighlight; end; iAppDbases: begin PgCntl.ActivePage := AppDatabases; AppHighlight; end; iAppSaving: begin PgCntl.ActivePage := AppSaving; AppHighlight; end; iAppPDF: begin PgCntl.ActivePage := AppUpdate; AppHighlight; end; iAppUpdates: begin PgCntl.ActivePage := AppPDF; AppHighlight; end; iAppPhotoInbox: begin PgCntl.ActivePage := AppPhotoInBox; AppHighlight; end; iAppFiletypes: begin PgCntl.ActivePage := AppFileTypes; AppHighlight; end; iDocOperations: begin PgCntl.ActivePage := docOperation; DocHighlight; end; iDocDisplay: begin PgCntl.ActivePage := docDisplay; DocHighlight; end; iDocPrinting: begin PgCntl.ActivePage := docPrinting; DocHighlight; end; iDocColor: begin PgCntl.ActivePage := docColor; DocHighlight; end; iDocFonts: begin PgCntl.ActivePage := docFonts; DocHighlight; end; iDocFormatting: begin PgCntl.ActivePage := docFormatting; DocHighlight; end; iUsers: begin PgCntl.ActivePage := appUsers; UserHighlight; end; iUsersLicInfo: begin PgCntl.ActivePage := appUserLicInfo; UserHighlight; end; iUserFHADigSign: begin PgCntl.ActivePage := appUserFHACertificates; UserHighlight; FPrefUserFHADigSignatures.ShowCertWindow; end; iToolBuiltIn: begin PgCntl.ActivePage := toolBuiltIn; ToolHighlight; end; iToolPlugIn: begin PgCntl.ActivePage := toolPlugIn; ToolHighlight; end; iToolUsers: begin PgCntl.ActivePage := toolUserDefined; ToolHighlight; end; iToolSketchers: begin PgCntl.ActivePage := toolSketcher; ToolHighlight; end; {iToolMappers: begin PgCntl.ActivePage := toolMapper; ToolHighlight; end; } iAppraisalXFers: begin PgCntl.ActivePage := apprsalXFers; AppraiserHighlight; end; iAppraisalCalcs: begin PgCntl.ActivePage := apprsalCalcs; AppraiserHighlight; end; end; end; procedure TPrefs.PrefCategoryShow(Sender: TObject); var Sheet: TTabSheet; begin Sheet := Sender as TTabSheet; case Sheet.Tag of iAppStartup: begin FCurPref := FPrefAppStartUp; end; iAppFolder: begin FCurPref := FPrefAppFolders; end; iAppDbases: begin FCurPref := FPrefAppDatabases; end; iAppSaving: begin FCurPref := FPrefAppSaving; end; iAppPhotoInbox: begin FCurPref := FPrefAppPhotoInbox; end; iAppPDF: begin FCurPref := FPrefAppPDF; end; iAppFileTypes: begin FCurPref := FPrefAppFileTypes; //FPrefAppFileTypes.GetSettings; end; iDocOperations: begin FCurPref := FPrefDocOperation; end; iDocDisplay: begin FCurPref := FPrefDocDisplay; end; iDocPrinting: begin FCurPref := FPrefDocPrinting; end; iDocColor: begin FCurPref := FPrefDocColor; end; iDocFonts: begin FCurPref := FPrefDocFonts; end; iDocFormatting: begin FCurPref := FPrefDocFormatting; end; iUsers: begin FCurPref := FPrefUsers; LicensedUsers.GatherUserLicFiles; //get the latest -- in case there is a preference change FPrefUsers.LoadUserList; // load the users end; iUsersLicInfo: begin FCurPref := FPrefUserLicenseInfo; LicensedUsers.GatherUserLicFiles; //get the latest -- in case there is a preference change FPrefUserLicenseInfo.LoadUserList; // load the users end; iUserFHADigSign: begin FCurPref := FPrefUserFHADigSignatures; end; iToolBuiltIn: begin FCurPref := FPrefToolBuiltIn; end; iToolPlugIn: begin FCurPref := FPrefToolPlugIn; end; iToolUsers: begin FCurPref := FPrefToolUserSpecified; end; iToolSketchers: begin FCurPref := FPrefToolSketcher; end; {iToolMappers: begin FCurPref := FPrefToolMapping; end; } iAppraisalXFers: begin FCurPref := FPrefAppraiserXFer; end; iAppraisalCalcs: begin FCurPref := FPrefAppraiserCalcs; end; end; end; procedure TPrefs.btnApplyClick(Sender: TObject); //apply changes to active tabsheet begin If PgCntl.ActivePage <> nil then try case PgCntl.ActivePage.Tag of iAppStartup: begin FPrefAppStartUp.SavePrefs; end; iAppFolder: begin FPrefAppFolders.SavePrefs; end; iAppDbases: begin FPrefAppDatabases.SavePrefs; end; iAppSaving: begin FPrefAppSaving.SavePrefs; end; iAppPDF: begin FPrefAppPDF.SavePrefs; end; iAppUpdates: begin FPrefAppUpdate.ApplyPreferences; end; iAppPhotoInbox: begin FPrefAppPhotoInbox.SavePrefs; FPrefAppPhotoInbox.FolderWatcherSetupOK; //apply button needs to check for valid folder end; iAppfiletypes: begin FPrefAppFiletypes.SetFileAssociations; end; iDocOperations: begin FPrefDocOperation.SavePrefs; end; iDocDisplay: begin FPrefDocDisplay.ApplyPreferences; //same as preview FPrefDocDisplay.SavePrefs; //in case they hit cancel end; iDocPrinting: begin FPrefDocPrinting.SavePrefs; end; iDocColor: begin FPrefDocColor.ApplyPreferences; //same as preview FPrefDocColor.SavePrefs; //in case they hit cancel end; iDocFonts: begin FPrefDocFonts.ApplyPreferences; //same as preview FPrefDocFonts.SavePrefs; //in case they hit cancel end; iDocFormatting: begin FPrefDocFormatting.ApplyPrefClick; //does the same thing as the old Apply button end; iUsers: begin FPrefUsers.SavePrefs; end; iUsersLicInfo: begin FPrefUserLicenseInfo.SavePrefs; end; iToolBuiltIn: begin FPrefToolBuiltIn.SavePrefs; end; iToolPlugIn: begin FPrefToolPlugIn.SavePrefs; end; iToolUsers: begin FPrefToolUserSpecified.SavePrefs; end; iToolSketchers: begin FPrefToolSketcher.SavePrefs; end; {iToolMappers: begin FPrefToolMapping.SavePrefs; end; } iAppraisalXFers: begin FPrefAppraiserXFer.SavePrefs; end; iAppraisalCalcs: begin FPrefAppraiserCalcs.SavePrefs; end; end; except ShowNotice('There was a problem applying preferences.'); end; end; end.
unit IdTestCmdTCPServer; interface uses IdTest, IdGlobal, IdTCPClient, IdCmdTCPServer, IdIOHandlerStack, IdLogDebug, IdSys; type TIdTestCmdTCPServer = class(TIdTest) published procedure TestServer; end; implementation procedure TIdTestCmdTCPServer.TestServer; var aClient: TIdTCPClient; aServer: TIdCmdTCPServer; o: &Object; const cTestPort=20202; cGreetingText = 'Hello There'; begin aClient:= TIdTCPClient.Create(nil); aServer:= TIdCmdTCPServer.Create(nil); try aClient.IOHandler := TIdIOHandlerStack.Create; aClient.IOHandler.Intercept := TIdLogDebug.Create; TIdLogDebug(AClient.IOHandler.Intercept).Active := true; try aServer.DefaultPort:=cTestPort; aServer.Greeting.Text.Text := cGreetingText; aServer.Greeting.Code := '200'; aServer.Active:=True; aClient.Port:=cTestPort; aClient.Host:='127.0.0.1'; aClient.Connect; Assert(aClient.GetResponse(200) = 200); Console.WriteLine('LastCmdResult.Text = "{0}"', AClient.LastCmdResult.Text.Text); Assert(aClient.LastCmdResult.Text.Text = cGreetingText); aClient.Disconnect; finally o := AClient.IOHandler.Intercept; Sys.FreeAndNil(o); o := AClient.IOHandler; Sys.FreeAndNil(o); end; finally Sys.FreeAndNil(aClient); Sys.FreeAndNil(aServer); end; end; initialization TIdTest.RegisterTest(TIdTestCmdTCPServer); end.
unit UUADSaleFinConcession; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, Dialogs, UCell, UContainer, UEditor, UUADUtils, UGlobals, UStatus, UForms; type TdlgUADSaleFinConcession = class(TAdvancedForm) bbtnCancel: TBitBtn; bbtnOK: TBitBtn; cbSaleType: TComboBox; lblSaleType: TLabel; bbtnHelp: TBitBtn; gbGSEFinConcession: TGroupBox; lblFinType: TLabel; lblTotalConcessAmt: TLabel; lblFinOtherDesc: TLabel; cbFinType: TComboBox; edtTotalConcessAmt: TEdit; edtFinOtherDesc: TEdit; bbtnClear: TBitBtn; procedure FormShow(Sender: TObject); procedure bbtnHelpClick(Sender: TObject); procedure bbtnOKClick(Sender: TObject); procedure EnDisOtherDesc(IsEnabled: Boolean); procedure cbFinTypeChange(Sender: TObject); procedure edtTotalConcessAmtKeyPress(Sender: TObject; var Key: Char); procedure bbtnClearClick(Sender: TObject); procedure edtTotalConcessAmtExit(Sender: TObject); private { Private declarations } FClearData: Boolean; FFinCell: TBaseCell; FConCell: TBaseCell; FDocument: TContainer; function GetDisplayText: String; public { Public declarations } FCell: TBaseCell; procedure LoadForm; procedure SaveToCell; procedure Clear; end; var dlgUADSaleFinConcession: TdlgUADSaleFinConcession; implementation {$R *.dfm} uses UStrings; procedure TdlgUADSaleFinConcession.FormShow(Sender: TObject); begin LoadForm; cbSaleType.SetFocus; end; procedure TdlgUADSaleFinConcession.bbtnHelpClick(Sender: TObject); begin ShowUADHelp('FILE_HELP_UAD_SALE_FIN_CONCESSION', Caption); end; procedure TdlgUADSaleFinConcession.bbtnOKClick(Sender: TObject); begin if cbSaleType.ItemIndex < 0 then begin ShowAlert(atWarnAlert, 'A sale concession type must be selected.'); cbSaleType.SetFocus; Exit; end; // 041211 JWyatt Add check to make sure a description is entered when 'Other' is selected if (cbFinType.ItemIndex = MaxFinTypes) and ((Trim(edtFinOtherDesc.Text) = '') or (Uppercase(Trim(edtFinOtherDesc.Text)) = 'OTHER')) then begin ShowAlert(atWarnAlert, 'A valid type description such as "Pending" or "Unknown" must be entered when ''Other'' is selected.'); edtFinOtherDesc.SetFocus; Exit; end; SaveToCell; ModalResult := mrOK; end; procedure TdlgUADSaleFinConcession.EnDisOtherDesc(IsEnabled: Boolean); begin lblFinOtherDesc.Enabled := IsEnabled; edtFinOtherDesc.Enabled := IsEnabled; end; procedure TdlgUADSaleFinConcession.cbFinTypeChange(Sender: TObject); begin EnDisOtherDesc((cbFinType.ItemIndex = MaxFinTypes)); end; procedure TdlgUADSaleFinConcession.edtTotalConcessAmtKeyPress( Sender: TObject; var Key: Char); begin Key := PositiveNumKey(Key); //allow comma, but no negative numbers end; function TdlgUADSaleFinConcession.GetDisplayText: String; var SelOther, Text: String; begin // 040611 JWyatt Add check so text is not saved unless 'Other' is selected if cbFinType.ItemIndex = MaxFinTypes then SelOther := Trim(edtFinOtherDesc.Text) else SelOther := ''; if SelOther = '' then Text := FinDesc[cbFinType.ItemIndex] + ';' else Text := SelOther + ';'; Text := Text + Trim(edtTotalConcessAmt.Text); FConCell.Text := Text; FConCell.Display; if cbSaleType.ItemIndex = -1 then Result := '' else Result := SalesTypesDisplay[cbSaleType.ItemIndex]; end; procedure TdlgUADSaleFinConcession.LoadForm; const GridFinXID = 956; GridConXID = 958; var Cntr, PosItem: Integer; UID: CellUID; ConType, ConAmt: String; begin Clear; FClearData := False; FDocument := FCell.ParentPage.ParentForm.ParentDocument as TContainer; if FCell.FCellXID = GridFinXID then begin FFinCell := FCell; UID := FCell.UID; UID.Num := UID.Num + 2; // use fixed increment - subject is not enabled FConCell := FDocument.GetCell(UID); end else begin FConCell := FCell; UID := FCell.UID; UID.Num := UID.Num - 2; // use fixed increment - subject is not enabled FFinCell := FDocument.GetCell(UID); end; PosItem := Pos(';', FConCell.Text); if PosItem > 1 then begin ConType := Copy(FConCell.Text, 1, Pred(PosItem)); ConAmt := Copy(FConCell.Text, Succ(PosItem), Length(FConCell.Text)); end else begin ConType := Trim(FConCell.Text); ConAmt := '0'; end; for Cntr := 0 to MaxSalesTypes do if FFinCell.Text = SalesTypesDisplay[Cntr] then cbSaleType.ItemIndex := Cntr; if Uppercase(ConType) = 'NONE' then begin cbFinType.ItemIndex := MaxFinTypes; edtFinOtherDesc.Text := 'None'; end else begin for Cntr := 0 to MaxFinTypes do if ConType = FinDesc[Cntr] then cbFinType.ItemIndex := Cntr; if (cbFinType.ItemIndex = -1) and (ConType <> '') then begin edtFinOtherDesc.Text := ConType; cbFinType.ItemIndex := MaxFinTypes; end; end; edtTotalConcessAmt.Text := ConAmt; if edtTotalConcessAmt.Text = '' then edtTotalConcessAmt.Text := '0'; EnDisOtherDesc((cbFinType.ItemIndex = MaxFinTypes)); end; procedure TdlgUADSaleFinConcession.SaveToCell; begin // Remove any legacy data - no longer used FFinCell.GSEData := ''; // Save the cleared or formatted text if FClearData then // clear ALL GSE data and blank the cell begin FFinCell.Text := ''; FConCell.Text := ''; end else begin if cbFinType.ItemIndex < 0 then begin cbFinType.ItemIndex := MaxFinTypes; edtFinOtherDesc.Text := 'None'; end; FFinCell.Text := GetDisplayText; end; FFinCell.Display; FConCell.Display; end; procedure TdlgUADSaleFinConcession.Clear; begin cbSaleType.ItemIndex := -1; cbFinType.ItemIndex := -1; edtFinOtherDesc.Text := ''; edtTotalConcessAmt.Text := ''; end; procedure TdlgUADSaleFinConcession.bbtnClearClick(Sender: TObject); begin if WarnOK2Continue(msgUAGClearDialog) then begin Clear; FClearData := True; SaveToCell; ModalResult := mrOK; end; end; procedure TdlgUADSaleFinConcession.edtTotalConcessAmtExit(Sender: TObject); begin if edtTotalConcessAmt.Text = '' then edtTotalConcessAmt.Text := '0'; end; end.
program S17_Seril5; const baa = 100; bc = 50; var ac: array[-5..-2] of integer; var a: integer; var f: string; var dd: integer; function cmp_lala(B: integer): Boolean; const baa = 10; var de: array[1..3] of integer; begin; WriteLn('Entering function cmp_lala'); WriteLn('B: ', B); WriteLn('F: ', F); WriteLn('baa: ', baa); for a := 1 to 3 do begin; WriteLn('de[a] + a + baa: ', de[a] + a + baa); end; cmp_lala := B >= 5; end; procedure HH(A: integer); var b: integer; var cdd, dd: string; begin; WriteLn('Entering function HH'); cmp_lala(A); for b:=-5 to -2 do begin; WriteLn('ac[', b, ']=', ac[b]); end; WriteLn('ac[3]: ', ac[3]); WriteLn('Enter integer for a: '); read(a); WriteLn('a (local)=', a); WriteLn('Enter string for cdd: '); Read(cdd); WriteLn('cdd: ', cdd); WriteLn('Enter string for dd: '); Read(dd); WriteLn('dd: ', dd); for a := 2 to baa do begin; WriteLn('a + baa=', a + baa); WriteLn('abc=', a * bc); end end; (** comments please! **) begin writeln ('Hello World'); Writeln('1' + 'H'); HH(4); Writeln(cmp_lala(5)); if not (-1 > 5) and (a and 5 > 2) then begin; WriteLn('Not -1 > 5', nOt -1 > 5); WriteLn(); end; WriteLn('Is this on?: ', 1 + 2 + 3 > -1 - -2 - -3); WriteLn('a (global) =', a); Write('Enter string for f: '); Read(f); f := '5'; Writeln('f: ', f); WriteLn('dd (global)', dd); (* baa := 250 mod 4; *) F := 'a';;;;;;;;;;; for a := baa downto dd do begin; WriteLn('Hello'); end; WriteLn(a);;;;;;;;;;;;;;;;;; end.
unit IBAN.Types; interface uses System.Classes, System.SysUtils, System.Character, System.Generics.Defaults, System.Generics.Collections; type /// <summary>Типове невалидни IBAN проверки /// <para><see cref="IBAN.Types|ecIvalidBBANFormat"/> - невалиден BBAN формат</para> /// <para><see cref="IBAN.Types|ecInvalidCheckSum"/> - невалидна Check сума на IBAN</para> /// <para><see cref="IBAN.Types|ecIncorectLength"/> - невалидна дължина на IBAN</para> /// </summary> TIBANErrorCode = (ecIvalidBBANFormat, ecInvalidCheckSum, ecIncorectLength); /// <summary> /// Структура представляваща единен IBAN /// </summary> TIBANFormat = packed record strict private function GetIBANPattern(): string; function GetPatternByDenote(const ADenote: string): string; public Country: string; IBANLength: System.Byte; BBANFormat: string; IBANFields: string; property IBANPattern: string read GetIBANPattern; /// <summary>Статитен метод за дефиниране на запис тип <see cref="TIBANFormat"/> на съответната държава</summary> /// <param name="ACountry">Двубуквено дефиниране на държавата спрямо ISO 3166-1 alpha-2</param> /// <param name="AIBANLength">Брой символи за IBAN-а в съответната държава</param> /// <param name="ABBANFormat">BBAN формата на IBAN-а спрямо спецификацията.</param> /// <returns>Запис от тип <see cref="TIBANFormat"/></returns> /// <remarks>Към ABBANFormat винаги в началото се добавят <c>2a - Country code; 2n - Check sum</c> за валиден IBAN</remarks> class function Define(const ACountry: string; const AIBANLength: System.Byte; const ABBANFormat: string; const AIBANFields: string = string.Empty): TIBANFormat; static; end; TIBANManager = class strict private class var FIBANComparer: IComparer<TIBANFormat>; class var FIBANCountries: TArray<TIBANFormat>; class constructor Create(); class destructor Destroy(); class procedure InitIBANComparer(); class procedure InitIBANCountries(); public /// <summary>Статитен метод за намиране на запис по зададен параметър <c>CountryCode</c></summary> /// <param name="CountryCode">Код на държавата спрямо ISO 3166-1 alpha-2</param> /// <param name="IBANRec">Връща намерения запис</param> /// <returns>True, ако намери съвпадение</returns> class function FindIBANCountryFormat(const CountryCode: string; var IBANRec: TIBANFormat): Boolean; end; const MAX_COUNTRY = 1; SUB_IBAN_LEN = 9; IBAN_SWAP_POS = 4; CHAR_OFFSET = 55; MOD_97 = 97; arrLastErrorMsg: array [TIBANErrorCode] of string = ( // 'Невалиден формат на IBAN-а', // 'Невалиден IBAN', // 'Невалидна дължина на IBAN-a'); implementation {$REGION 'TIBANContryFormat methods implementation'} class function TIBANFormat.Define(const ACountry: string; const AIBANLength: System.Byte; const ABBANFormat: string; const AIBANFields: string): TIBANFormat; begin Result.Country := ACountry.ToUpper(); Result.IBANLength := AIBANLength; Result.BBANFormat := string.Format('2a,2n,%s', [ABBANFormat]); Result.IBANFields := AIBANFields; end; function TIBANFormat.GetIBANPattern(): string; var sDenote: string; arrDenote: TArray<string>; begin arrDenote := Self.BBANFormat.Split([',']); for sDenote in arrDenote do begin Result := string.Format('%s%s', [Result, Self.GetPatternByDenote(sDenote.Trim())]); end; end; function TIBANFormat.GetPatternByDenote(const ADenote: string): string; var iLen: System.Integer; sPattern: string; begin try iLen := ADenote.Substring(0, ADenote.Length - 1).ToInteger(); except on ex: Exception do begin raise Exception.CreateFmt('Invalid number %s', [ADenote.Substring(0, ADenote.Length - 1)]); end; end; case ADenote.Chars[ADenote.Length - 1].ToLower() of 'a': begin sPattern := '[A-Z]'; end; 'n': begin sPattern := '\d'; end; 'c': begin sPattern := '[A-Za-z0-9]'; end; else raise Exception.CreateFmt('Invalid denote char "%s"', [ADenote.Chars[1]]); end; Result := string.Format('(%s{%d})', [sPattern, iLen]); end; {$ENDREGION} {$REGION 'TIBANManager methods implementation'} class constructor TIBANManager.Create(); begin TIBANManager.FIBANComparer := nil; SetLength(TIBANManager.FIBANCountries, 0); TIBANManager.InitIBANComparer(); TIBANManager.INitIBANCountries(); end; class destructor TIBANManager.Destroy(); begin TIBANManager.FIBANComparer := nil; SetLength(TIBANManager.FIBANCountries, 0); end; class function TIBANManager.FindIBANCountryFormat(const CountryCode: string; var IBANRec: TIBANFormat): Boolean; var recSearch: TIBANFormat; iFound: System.Integer; begin recSearch.Country := CountryCode.Substring(0, 2).ToUpper(); Result := TArray.BinarySearch<TIBANFormat>(TIBANManager.FIBANCountries, recSearch, iFound, TIBANManager.FIBANComparer); if Result then begin IBANRec := TIBANManager.FIBANCountries[iFound]; end; end; class procedure TIBANManager.InitIBANComparer(); begin TIBANManager.FIBANComparer := TDelegatedComparer<TIBANFormat>.Construct( function(const Left, Right: TIBANFormat): System.Integer begin Result := string.Compare(Left.Country, Right.Country); end); end; class procedure TIBANManager.InitIBANCountries(); begin TIBANManager.FIBANCountries := [//списъка с всички държави използващи IBAN TIBANFormat.Define('AL', 28, '8n,16c'), //Albania), TIBANFormat.Define('AD', 24, '8n,12c'), //Andorra), TIBANFormat.Define('AT', 20, '5n,11n', 'b,c'), //Austria), TIBANFormat.Define('AZ', 28, '4c,20n'), //Azerbaijan), TIBANFormat.Define('BH', 22, '4a,14c'), //Bahrain), TIBANFormat.Define('BE', 16, '12n'), //Belgium), TIBANFormat.Define('BA', 20, '16n'), //Bosnia and Herzegovina), TIBANFormat.Define('BR', 29, '23n, 1a, 1c'), //Brazil), TIBANFormat.Define('BG', 22, '4a,4n,2n,8c', 'b,s,t,c'), //Bulgaria), TIBANFormat.Define('CR', 21, '17n'), //Costa Rica), TIBANFormat.Define('HR', 21, '17n'), //Croatia), TIBANFormat.Define('CY', 28, '8n,16c'), //Cyprus), TIBANFormat.Define('CZ', 24, '20n'), //Czech Republic), TIBANFormat.Define('DK', 18, '14n'), //Denmark), TIBANFormat.Define('DO', 28, '4a,20n'), //Dominican Republic), TIBANFormat.Define('TL', 23, '19n'), //East Timor), TIBANFormat.Define('EE', 20, '16n'), //Estonia), TIBANFormat.Define('FO', 18, '14n'), //Faroe Islands[Note 4]), TIBANFormat.Define('FI', 18, '14n'), //Finland), TIBANFormat.Define('FR', 27, '5n,5n,11c,2n', 'b,s,c,x'), //France[Note 5]), TIBANFormat.Define('GE', 22, '2c,16n'), //Georgia), TIBANFormat.Define('DE', 22, '8n,10n', 'b,c'), //Germany), TIBANFormat.Define('GI', 23, '4a,15c'), //Gibraltar), TIBANFormat.Define('GR', 27, '3n,4n,16c', 'b,s,c'), //Greece), TIBANFormat.Define('GL', 18, '14n'), //Greenland[Note 4]), TIBANFormat.Define('GT', 28, '4c,20c'), //Guatemala [32]), TIBANFormat.Define('HU', 28, '24n'), //Hungary), TIBANFormat.Define('IS', 26, '22n'), //Iceland), TIBANFormat.Define('IE', 22, '4c,14n'), //Ireland), TIBANFormat.Define('IL', 23, '19n'), //Israel), TIBANFormat.Define('IT', 27, '1a,5n,5n,12c', 'x,b,s,c'), //Italy), TIBANFormat.Define('JO', 30, '4a, 22n'), //Jordan[33]), TIBANFormat.Define('KZ', 20, '3n,13c'), //Kazakhstan), TIBANFormat.Define('XK', 20, '4n,10n,2n'), //Kosovo), TIBANFormat.Define('KW', 30, '4a, 22c'), //Kuwait), TIBANFormat.Define('LV', 21, '4a,13c'), //Latvia), TIBANFormat.Define('LB', 28, '4n,20c'), //Lebanon), TIBANFormat.Define('LI', 21, '5n,12c'), //Liechtenstein), TIBANFormat.Define('LT', 20, '16n'), //Lithuania), TIBANFormat.Define('LU', 20, '3n,13c'), //Luxembourg), TIBANFormat.Define('MK', 19, '3n,10c,2n'), //Macedonia), TIBANFormat.Define('MT', 31, '4a,5n,18c'), //Malta), TIBANFormat.Define('MR', 27, '23n'), //Mauritania), TIBANFormat.Define('MU', 30, '4a,19n,3a'), //Mauritius), TIBANFormat.Define('MC', 27, '10n,11c,2n'), //Monaco), TIBANFormat.Define('MD', 24, '2c,18c'), //Moldova), TIBANFormat.Define('ME', 22, '18n'), //Montenegro), TIBANFormat.Define('NL', 18, '4a,10n', 'b,c'), //Netherlands[Note 6]), TIBANFormat.Define('NO', 15, '11n'), //Norway), TIBANFormat.Define('PK', 24, '4c,16n'), //Pakistan), TIBANFormat.Define('PS', 29, '4c,21n'), //Palestinian territories), TIBANFormat.Define('PL', 28, '24n'), //Poland), TIBANFormat.Define('PT', 25, '21n'), //Portugal), TIBANFormat.Define('QA', 29, '4a, 21c'), //Qatar), TIBANFormat.Define('RO', 24, '4a,16c', 'b,c'), //Romania), TIBANFormat.Define('SM', 27, '1a,10n,12c'), //San Marino), TIBANFormat.Define('SA', 24, '2n,18c'), //Saudi Arabia), TIBANFormat.Define('RS', 22, '3n,13n,2n', 'b,c,x'), //Serbia), TIBANFormat.Define('SK', 24, '20n'), //Slovakia), TIBANFormat.Define('SI', 19, '15n'), //Slovenia), TIBANFormat.Define('ES', 24, '4n,4n,2n,10n', 'b,s,x,c'), //Spain), TIBANFormat.Define('SE', 24, '3n,17n', 'b,c'), //Sweden), TIBANFormat.Define('CH', 21, '5n,12c', 'b,c'), //Switzerland), TIBANFormat.Define('TN', 24, '20n'), //Tunisia), TIBANFormat.Define('TR', 26, '5n,17c'), //Turkey), TIBANFormat.Define('AE', 23, '3n,16n'), //United Arab Emirates), TIBANFormat.Define('GB', 22, '4a,6n,8n', 'b,s,c'), //United Kingdom[Note 7]), TIBANFormat.Define('VG', 24, '4c,16n'), //Virgin Islands, British), TIBANFormat.Define('DZ', 24, '20n'), //Algeria), TIBANFormat.Define('AO', 25, '21n'), //Angola), TIBANFormat.Define('BJ', 28, '1a,23n'), //Benin), TIBANFormat.Define('BF', 27, '23n'), //Burkina Faso), TIBANFormat.Define('BI', 16, '12n'), //Burundi), TIBANFormat.Define('CM', 27, '23n'), //Cameroon), TIBANFormat.Define('CV', 25, '21n'), //Cape Verde), TIBANFormat.Define('IR', 26, '22n'), //Iran), TIBANFormat.Define('CI', 28, '1a,23n'), //Ivory Coast), TIBANFormat.Define('MG', 27, '23n'), //Madagascar), TIBANFormat.Define('ML', 28, '1a,23n'), //Mali), TIBANFormat.Define('MZ', 25, '21n'), //Mozambique), TIBANFormat.Define('SN', 28, '1a,23n'), //Senegal), TIBANFormat.Define('UA', 29, '6n,19c', 'b,c')//Ukraine ]; TArray.Sort<TIBANFormat>(TIBANManager.FIBANCountries, TIBANManager.FIBANComparer); end; {$ENDREGION} end.
unit StreamUnit; interface uses Classes; const SpaceChars: set of char= [' ']; type { TMyTextStream } TMyTextStream= class (TObject) private FTargerStream: TStream; function GetPosition: Integer; function GetSize: Integer; procedure SetPosition (Pos: Integer); public property Size: Integer read GetSize; property Position: Integer read GetPosition; function ReadCh: Char; function ReadLine: AnsiString; function ReadInteger: Integer; procedure WriteLine (const S: String); procedure WriteChar (Ch: Char); procedure WriteStr (S: String); constructor Create (AnStream: TStream); end; { TMyBinStream } TMyBinStream= class (TObject) private FTargerStream: TStream; public function ReadCh: Char; function ReadInt: Integer; function ReadStr: AnsiString; procedure WriteChar (const Ch: Char); procedure WriteInt (const n: Integer); procedure WriteStr (const S: AnsiString); constructor Create (AnStream: TStream); end; { function ReadCharFromStream (AnStream: TStream): Char; function ReadLineFromStream (AnStream: TStream): String; procedure WriteLineToStream (AnStream: TStream; S: String); procedure WriteCharToStream (AnStream: TStream; Ch: Char); procedure WriteCharToStream (AnStream: TStream; Ch: Char); procedure WriteStrToStream (AnStream: TStream; S: String); } implementation uses SysUtils; { function ReadCharFromStream (AnStream: TStream): Char; begin AnStream.Read (Result, 1); end; function ReadLineFromStream (AnStream: TStream): String; var Ch: Char; begin Result:= ''; while AnStream.Position< AnStream.Size do begin Ch:= ReadCharFromStream (AnStream); if (Ch= #10) then Break; Result:= Result+ Ch; end; if Result= '' then Exit; if Result [Length (Result)]= #13 then Delete (Result, Length (Result), 1); end; procedure WriteLineToStream (AnStream: TStream; S: String); begin AnStream.Write (Pointer (@S[1])^, Length (S)); (*$ifdef LINUX*) WriteCharToStream (AnStream, #10); (*$else*) WriteCharToStream (AnStream, #13); WriteCharToStream (AnStream, #10); (*$endif*) end; procedure WriteCharToStream (AnStream: TStream; Ch: Char); begin AnStream.Write (Ch, 1); end; procedure WriteStrToStream (AnStream: TStream; S: String); begin AnStream.Write (Pointer (@S[1])^, Length (S)); end; } { TMyStream } function TMyTextStream.GetPosition: Integer; begin Result:= FTargerStream.Position; end; function TMyTextStream.GetSize: Integer; begin Result:= FTargerStream.Size; end; procedure TMyTextStream.SetPosition (Pos: Integer); begin FTargerStream.Position:= Pos; end; function TMyTextStream.ReadCh: Char; begin FTargerStream.Read (Result, 1); end; function TMyTextStream.ReadLine: AnsiString; var Ch: Char; begin Result:= ''; while Position< Size do begin Ch:= ReadCh; if (Ch= #10) then Break; Result:= Result+ Ch; end; if Result= '' then Exit; if Result [Length (Result)]= #13 then Delete (Result, Length (Result), 1); end; function TMyTextStream.ReadInteger: Integer; const IntDigitChar: set of Char= ['0'..'9']; var Ch: Char; begin Result:= 0; Ch:= ReadCh; while (Ch in SpaceChars) and (Position< Size) do Ch:= ReadCh; if Ch in SpaceChars then Exit; while (Ch in IntDigitChar) and (Position< Size) do begin Result:= 10* Result+ Ord (Ch)- 48; Ch:= ReadCh; end; if not (Ch in IntDigitChar) then SetPosition (Position- 1); end; procedure TMyTextStream.WriteStr (S: String); begin FTargerStream.Write (Pointer (@S[1])^, Length (S)); end; constructor TMyTextStream.Create (AnStream: TStream); begin inherited Create; FTargerStream:= AnStream; end; procedure TMyTextStream.WriteChar (Ch: Char); begin FTargerStream.Write (Ch, 1); end; procedure TMyTextStream.WriteLine (const S: String); begin FTargerStream.Write (Pointer (@S[1])^, Length (S)); (*$ifdef LINUX*) WriteChar (#10); (*$else*) WriteChar (#13); WriteChar (#10); (*$endif*) end; { TMyBinStream } function TMyBinStream.ReadCh: Char; begin FTargerStream.Read (Result, 1); end; function TMyBinStream.ReadInt: Integer; begin FTargerStream.Read (Result, 4); end; function TMyBinStream.ReadStr: AnsiString; begin raise Exception.Create ('Not Implemented Yet!'); end; procedure TMyBinStream.WriteChar (const Ch: Char); begin FTargerStream.Write (Ch, 1); end; procedure TMyBinStream.WriteInt (const n: Integer); begin FTargerStream.Write (n, 4); end; procedure TMyBinStream.WriteStr (const S: AnsiString); begin raise Exception.Create ('Not Implemented Yet!'); end; constructor TMyBinStream.Create (AnStream: TStream); begin inherited Create; FTargerStream:= AnStream; end; end.
unit dmPanelMensaje; interface uses SysUtils, Classes, DB, IBCustomDataSet, IBQuery, Tipos, mensajesPanel, flags, dmThreadDataModule, dmDataModuleBase; type TMensajeField = record iFieldOR: integer; iFieldParams: integer; FieldOR: TIntegerField; // FieldParams: TMemoField; FieldParams: TStringField; end; TMensajeFields = array of TMensajeField; TPanelMensaje = class(TThreadDataModule) CotizacionMensajes: TIBQuery; TipoMensajes: TIBQuery; TipoMensajesOID_TIPO_MENSAJE: TSmallintField; TipoMensajesDESCRIPCION: TIBStringField; TipoMensajesPOSICION: TSmallintField; TipoMensajesCAMPO: TIBStringField; qMensaje: TIBQuery; qMensajeES: TMemoField; procedure CotizacionMensajesBeforeOpen(DataSet: TDataSet); private FOnMensajeCambiado: TNotificacion; FMensajes: TMensajes; FMensajeFields: TMensajeFields; FOIDBetas: integer; FOIDPrincipal: integer; procedure MapFields; procedure InicializarCotizacionMensajes; function GetMensajes: TMensajes; procedure SetOnMensajeCambiado(const Value: TNotificacion); function GetFlagsMensajes: TFlags; procedure OnStructureMessageChanged; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure OnCotizacionCambiada; property FlagsMensajes: TFlags read GetFlagsMensajes; property Mensajes: TMensajes read GetMensajes; property OnMensajeCambiado: TNotificacion read FOnMensajeCambiado write SetOnMensajeCambiado; property OIDBetas: integer read FOIDBetas; property OIDPrincipal: integer read FOIDPrincipal; end; implementation uses dmData, UtilDB, dmConfiguracion, dmBD, dmConfigMensajes, BusCommunication, dmActualizarDatos, IBDatabase; {$R *.dfm} procedure TPanelMensaje.CotizacionMensajesBeforeOpen(DataSet: TDataSet); begin CotizacionMensajes.Params[0].AsInteger := Data.CotizacionOID_COTIZACION.Value; end; constructor TPanelMensaje.Create(AOwner: TComponent); begin inherited; InicializarCotizacionMensajes; MapFields; Bus.RegisterEvent(MessageStructureMessageChanged, OnStructureMessageChanged); Bus.RegisterEvent(MessageTipoCotizacionCambiada, OnStructureMessageChanged); end; destructor TPanelMensaje.Destroy; begin Bus.UnregisterEvent(MessageStructureMessageChanged, OnStructureMessageChanged); Bus.UnregisterEvent(MessageTipoCotizacionCambiada, OnStructureMessageChanged); inherited; end; function TPanelMensaje.GetFlagsMensajes: TFlags; begin result := TFlags.Create; result.Flags := CotizacionMensajes.FieldByName('FLAGS').AsInteger; end; function TPanelMensaje.GetMensajes: TMensajes; var i: integer; cad: string; field: TField; begin // // if Data.TipoCotizacion = tcDiaria then begin // for i := Low(FMensajes) to High(FMensajes) do begin // FMensajes[i].IsNull := true; // FMensajes[i].Mensaje := ''; // end; // FMensajes[Low(FMensajes)].IsNull := false; // FMensajes[Low(FMensajes)].Mensaje := '<b>MENSAJES E INDICADORES NO DISPONIBLES EN DATOS DIARIOS.</b>'; // end // else begin // for i := Low(FMensajes) to High(FMensajes) do begin field := FMensajeFields[i].FieldOR; FMensajes[i].IsNull := field.IsNull; if FMensajes[i].IsNull then begin FMensajes[i].mensaje := ''; end else begin qMensaje.Close; qMensaje.Params[0].AsInteger := field.Value; OpenDataSet(qMensaje); cad := ''; while not qMensaje.Eof do begin cad := cad + qMensajeES.Value + '. '; qMensaje.Next; end; FMensajes[i].mensaje := cad; FMensajes[i].Params := FMensajeFields[i].FieldParams.Value; end; end; // end; result := FMensajes; end; procedure TPanelMensaje.InicializarCotizacionMensajes; var nombre, titulo: string; num, i: integer; database: TIBDatabase; transaction: TIBTransaction; begin //La longitud de las columnas de la tabla cotizacion_mensaje pueden variar. //Cuando se actualizan los datos puede que haya uno que su longitud //sea mayor que la longitud de la columna, por lo que la actualización varía //la longitud de la bd y vuelve a importar. Cuando varía la longitud, tira el //evento MessageStructureMessageChanged. Como la estructura ha variado, se debe //reabrir la base de datos para que CotizacionMensajes reciba las longitudes //correctas de las columnas. Por esto CotizacionMensajes tiene su propia conexión //a la base de datos, para poder reabrirla en caso necesario. Por otra parte //cuando se actualizan los datos, CotizacionMensajes no los ve, ya que tiene //otra conexión con otra transacción abierta, por lo que no ve los cambios de //la base de datos. Para que vea los cambios, debe hacer un Commit de su transacción. database := BD.GetNewDatabase(Self, scdDatos, Data.BDDatos); transaction := TIBTransaction.Create(Self); database.DefaultTransaction := transaction; CotizacionMensajes.Database := database; OpenDataSet(CotizacionMensajes); OpenDataSet(TipoMensajes); TipoMensajes.Last; num := TipoMensajes.RecordCount; SetLength(FMensajes, num); SetLength(FMensajeFields, num); //El primer mensaje es el principal FMensajes[0].Titulo := ''; FMensajes[0].visible := true; FMensajes[0].TipoOID := TipoMensajesOID_TIPO_MENSAJE.Value; FMensajeFields[0].iFieldOR := CotizacionMensajes.FieldByName('OR_PRINCIPAL').FieldNo - 1; FMensajeFields[0].iFieldParams := CotizacionMensajes.FieldByName('PARAMS_PRINCIPAL').FieldNo - 1; i := 1; TipoMensajes.Prior; while not TipoMensajes.Bof do begin nombre := TipoMensajesCAMPO.Value; FMensajeFields[i].iFieldOR := CotizacionMensajes.FieldByName('OR_' + nombre).FieldNo - 1; FMensajeFields[i].iFieldParams := CotizacionMensajes.FieldByName('PARAMS_' + nombre).FieldNo - 1; titulo := TipoMensajesDESCRIPCION.Value; FMensajes[i].Titulo := titulo; //En Configuracion.Mensajes se crean los mensajes igual que en TipoMensajes //pero sin el principal, por lo que será i - 1 FMensajes[i].visible := Configuracion.Mensajes.Visible[i - 1]; FMensajes[i].TipoOID := TipoMensajesOID_TIPO_MENSAJE.Value; TipoMensajes.Prior; inc(i); end; if TipoMensajes.Locate('CAMPO', 'BETAS', []) then FOIDBetas := TipoMensajesOID_TIPO_MENSAJE.Value else raise Exception.Create('No se ha encontrado el campo de las Betas'); if TipoMensajes.Locate('CAMPO', 'PRINCIPAL', []) then FOIDPrincipal := TipoMensajesOID_TIPO_MENSAJE.Value else raise Exception.Create('No se ha encontrado el campo principal'); end; procedure TPanelMensaje.MapFields; var i: integer; begin for i := Low(FMensajeFields) to High(FMensajeFields) do begin FMensajeFields[i].FieldOR := CotizacionMensajes.Fields[FMensajeFields[i].iFieldOR] as TIntegerField; FMensajeFields[i].FieldParams := CotizacionMensajes.Fields[FMensajeFields[i].iFieldParams] as TStringField; end; end; procedure TPanelMensaje.OnCotizacionCambiada; begin //La longitud de las columnas de la tabla cotizacion_mensaje pueden variar. //Cuando se actualizan los datos puede que haya uno que su longitud //sea mayor que la longitud de la columna, por lo que la actualización varía //la longitud de la bd y vuelve a importar. Cuando varía la longitud, tira el //evento MessageStructureMessageChanged. Como la estructura ha variado, se debe //reabrir la base de datos para que CotizacionMensajes reciba las longitudes //correctas de las columnas. Por esto CotizacionMensajes tiene su propia conexión //a la base de datos, para poder reabrirla en caso necesario. Por otra parte //cuando se actualizan los datos, CotizacionMensajes no los ve, ya que tiene //otra conexión con otra transacción abierta, por lo que no ve los cambios de //la base de datos. Para que vea los cambios, debe hacer un Commit de su transacción. CotizacionMensajes.Transaction.Commit; OpenDataSet(CotizacionMensajes); MapFields; if Assigned(FOnMensajeCambiado) then FOnMensajeCambiado; end; procedure TPanelMensaje.OnStructureMessageChanged; begin //La longitud de las columnas de la tabla cotizacion_mensaje pueden variar. //Cuando se actualizan los datos puede que haya uno que su longitud //sea mayor que la longitud de la columna, por lo que la actualización varía //la longitud de la bd y vuelve a importar. Cuando varía la longitud, tira el //evento MessageStructureMessageChanged. Como la estructura ha variado, se debe //reabrir la base de datos para que CotizacionMensajes reciba las longitudes //correctas de las columnas. Por esto CotizacionMensajes tiene su propia conexión //a la base de datos, para poder reabrirla en caso necesario. Por otra parte //cuando se actualizan los datos, CotizacionMensajes no los ve, ya que tiene //otra conexión con otra transacción abierta, por lo que no ve las actualizaciones de //la base de datos. Para que vea los cambios, debe hacer un Commit de su transacción. CotizacionMensajes.Close; CotizacionMensajes.UnPrepare; CotizacionMensajes.Database.DefaultTransaction.Free; CotizacionMensajes.Database.Free; InicializarCotizacionMensajes; end; procedure TPanelMensaje.SetOnMensajeCambiado(const Value: TNotificacion); begin FOnMensajeCambiado := Value; end; end.
unit CheckError; interface var ErrorFlag : boolean; // тру, если ошибка есть, фолс, если нет ErrorStr : string; procedure InitCheckError; procedure WriteErrorPolynoms(NameError : string); procedure WriteErrorRationals(NameError : string); procedure WriteErrorNaturals(NameError : string); (* В переменную Error надо писать название процедуры, в котором произошла ошибка. *) implementation procedure InitCheckError; begin ErrorFlag := false; end; procedure MakeFlag; begin ErrorFlag := true; end; procedure AddtoErrorStr(s, error : string); begin MakeFlag; ErrorStr := ErrorStr + 'Error in ' + s + Error {+ #13#10}; end; procedure WriteErrorPolynoms(NameError : string); begin AddtoErrorStr('Polynoms.', NameError); end; procedure WriteErrorRationals(NameError : string); begin AddtoErrorStr('Rationals.', NameError); end; procedure WriteErrorNaturals(NameError : string); begin AddtoErrorStr('Naturals.', NameError); end; begin ErrorStr := ''; end.
unit u_EnumDoublePointFilterEqual; interface uses t_GeoTypes, i_DoublePointFilter, i_EnumDoublePoint; type TEnumDoublePointFilterEqual = class(TInterfacedObject, IEnumDoublePoint) private FSourceEnum: IEnumDoublePoint; FPrevEmpty: Boolean; FPrevPoint: TDoublePoint; FFinished: Boolean; private function Next(out APoint: TDoublePoint): Boolean; public constructor Create( const ASourceEnum: IEnumDoublePoint ); end; TEnumProjectedPointFilterEqual = class(TEnumDoublePointFilterEqual, IEnumProjectedPoint) public constructor Create( const ASourceEnum: IEnumProjectedPoint ); end; TEnumLocalPointFilterEqual = class(TEnumDoublePointFilterEqual, IEnumLocalPoint) public constructor Create( const ASourceEnum: IEnumLocalPoint ); end; TDoublePointFilterRemoveEqual = class(TInterfacedObject, IDoublePointFilter) private function CreateFilteredEnum(const ASource: IEnumDoublePoint): IEnumDoublePoint; end; TProjectedPointFilterRemoveEqual = class(TInterfacedObject, IProjectedPointFilter) private function CreateFilteredEnum(const ASource: IEnumProjectedPoint): IEnumProjectedPoint; end; TLocalPointFilterRemoveEqual = class(TInterfacedObject, ILocalPointFilter) private function CreateFilteredEnum(const ASource: IEnumLocalPoint): IEnumLocalPoint; end; implementation uses u_GeoFun; { TEnumDoublePointFilterEqual } constructor TEnumDoublePointFilterEqual.Create(const ASourceEnum: IEnumDoublePoint); begin inherited Create; FSourceEnum := ASourceEnum; FPrevEmpty := True; FFinished := False; end; function TEnumDoublePointFilterEqual.Next(out APoint: TDoublePoint): Boolean; var VPoint: TDoublePoint; VPointIsEmpty: Boolean; begin while not FFinished do begin if FSourceEnum.Next(VPoint) then begin VPointIsEmpty := PointIsEmpty(VPoint); if VPointIsEmpty then begin if not FPrevEmpty then begin FPrevEmpty := True; FPrevPoint := VPoint; APoint := VPoint; Break; end; end else begin if FPrevEmpty then begin FPrevEmpty := False; FPrevPoint := VPoint; APoint := VPoint; Break; end else begin if (abs(VPoint.X - FPrevPoint.X) > 1) or (abs(VPoint.Y - FPrevPoint.Y) > 1) then begin FPrevEmpty := False; FPrevPoint := VPoint; APoint := VPoint; Break; end; end; end; end else begin FFinished := True; end; end; Result := not FFinished; end; { TEnumProjectedPointFilterEqual } constructor TEnumProjectedPointFilterEqual.Create( const ASourceEnum: IEnumProjectedPoint ); begin inherited Create(ASourceEnum); end; { TEnumLocalPointFilterEqual } constructor TEnumLocalPointFilterEqual.Create( const ASourceEnum: IEnumLocalPoint ); begin inherited Create(ASourceEnum); end; { TDoublePointFilterRemoveEqual } function TDoublePointFilterRemoveEqual.CreateFilteredEnum( const ASource: IEnumDoublePoint ): IEnumDoublePoint; begin Result := TEnumDoublePointFilterEqual.Create(ASource); end; { TProjectedPointFilterRemoveEqual } function TProjectedPointFilterRemoveEqual.CreateFilteredEnum( const ASource: IEnumProjectedPoint ): IEnumProjectedPoint; begin Result := TEnumProjectedPointFilterEqual.Create(ASource); end; { TLocalPointFilterRemoveEqual } function TLocalPointFilterRemoveEqual.CreateFilteredEnum( const ASource: IEnumLocalPoint ): IEnumLocalPoint; begin Result := TEnumLocalPointFilterEqual.Create(ASource); end; end.
Unit U2chCatList; (* 2ちゃんねる カテゴリ一覧 *) (* Copyright (c) 2001,2002 Twiddle <hetareprog@hotmail.com> *) interface uses Classes, StrUtils, SysUtils, U2chCat, U2chBoard, U2chThread, StrSub, FileSub, UDat2HTML; type (*-------------------------------------------------------*) (* BBS MENU *) TCategoryList = class(TList) private bbsMenu: string; function GetItems(index: integer): TCategory; procedure Setitems(index: integer; value: TCategory); public RootDir: string; (* 作業ルートディレクトリ: \附き *) lastModified: string; (* 最終更新日時 *) topIndex: integer; (* *) selIndex: integer; constructor Create(root: string); destructor Destroy; override; procedure Clear; override; function Load: boolean; function Save: boolean; function Analyze(const contents: string; const lastModified: string): boolean; property Items[index: integer]: TCategory read GetItems write SetItems; function GetLogDir: string; procedure SafeClear; function FindBoard(const HOST, BBS: string; strict: Boolean = False): TBoard; function FindBoardByName(const catName, boardName: string): TBoard; function FindThread(const catName, boardName, datName: string): TThreadItem; procedure SearchLogDir(List: TStrings); end; (*=======================================================*) implementation (*=======================================================*) {$B-} uses Main; const LOG2CH = 'Logs\2ch'; BOARDFILE = 'jane2ch.brd'; LOGBBSMENU = '\bbsmenu.dat'; IDXBBSMENU = '\bbsmenu.idx'; IDX_BOARD_NAME = 0; IDX_LAST_MODIFIED = 1; IDX_TOP_INDEX = 2; IDX_EXPANDED = 3; (* ボード一覧系の生成とか *) constructor TCategoryList.Create(root: string); begin inherited Create; RootDir := root; topIndex := 0; selIndex := 0; end; (* ボード一覧系の廃棄とか *) destructor TCategoryList.Destroy; begin Clear; inherited Destroy; end; (* 内部のボード一覧の廃棄とか *) procedure TCategoryList.Clear; var i: integer; node: TCategory; begin for i := 0 to Count -1 do begin node := Items[i]; if node <> nil then node.Free; end; inherited; end; (* アイテムオーバーライド *) function TCategoryList.GetItems(index: integer): TCategory; begin result := TCategory(inherited Items[index]); end; (* アイテムオーバーライド *) procedure TCategoryList.SetItems(index: integer; value: TCategory); begin inherited Items[index] := value; end; (* ボード一覧情報をファイルから読込み *) function TCategoryList.Load: boolean; procedure LoadBBSMenuInfo; var strList: TStringList; begin strList := TStringList.Create; lastModified := ''; try strList.LoadFromFile(GetLogDir + IDXBBSMENU); if 2 <= strList.Count then lastModified := strList.Strings[1]; except end; strList.Free; end; var strList, tmpList: TStringList; i: integer; category: TCategory; board: TBoard; startPos, endPos: integer; begin category := nil; strList := TStringList.Create; try strList.LoadFromFile(RootDir + BOARDFILE); tmpList := TStringList.Create; tmpList.CommaText := strList.Strings[0]; try topIndex := StrToInt(tmpList.Strings[0]); selIndex := StrToInt(tmpList.Strings[1]); except end; tmpList.Free; for i := 1 to StrList.Count -1 do begin if StrList[i][1] = #9 then begin (* タブで始るのは板 *) board := TBoard.Create(category); startPos := 2; endPos := FindPos(#9, StrList[i], 2); board.host := Copy(StrList[i], startPos, endPos - startPos); startPos := endPos + 1; endPos := FindPos(#9, StrList[i], startPos); board.bbs := Copy(StrList[i], startPos, endPos - startPos); startPos := endPos + 1; endPos := FindPos(#9, StrList[i], startPos); if endPos <= 0 then begin board.Name := Copy(StrList[i], startPos, Length(StrList[i]) - startPos + 1); board.past := False; end else begin board.name := Copy(StrList[i], startPos, endPos - startPos); board.past := True; end; if category <> nil then category.Add(board) else board.Free; end else begin category := TCategory.Create(self); startPos := 1; endPos := FindPos(#9, StrList[i], startPos); category.Name := Copy(StrList[i], startPos, endPos - startPos); if StrList[i][endPos+1] = '1' then category.expanded := true; if (endPos + 2 <= length(StrList[i])) and (StrList[i][endPos + 2] = 'C') then category.custom := true; Add(category); end; end; Load := True; except Load := False; end; if (strList.Count > 1) and AnsiStartsStr('【機能】', strList[1]) then Delete(0); strList.Free; //▼機能カテゴリを追加 category := TCategory.Create(self); category.Name := '【機能】'; category.expanded := false; category.custom := true; Insert(0, category); board := TLogListBoard.Create(category); category.Add(board); board := TFavoriteListBoard.Create(category); category.Add(board); board := TOpenThreadsBoard.Create(category); category.Add(board); LoadBBSMenuInfo; end; (* ボード一覧情報を保存:何かの時に安心な かちゅ〜しゃもどき *) function TCategoryList.Save: boolean; procedure SaveBBSMenuInfo; var stream: TPSStream; strList: TStringList; begin if 0 < length(bbsMenu) then begin stream := TPSStream.Create(bbsMenu); RecursiveCreateDir(GetLogDir); try stream.SaveToFile(GetLogDir + LOGBBSMENU); except end; stream.Free; end; strList := TStringList.Create; strList.Add('2ch'); strList.Add(lastModified); try strList.SaveToFile(GetLogDir + IDXBBSMENU); except end; strList.Free; end; var strList: TStringList; i, j: integer; category: TCategory; board: TBoard; str: string; begin strList := TStringList.Create; strList.Add(IntToStr(topIndex) + ',' + IntToStr(selIndex)); for i := 1 to Count -1 do begin //【機能】を除外 category := Items[i]; str := category.name + #9; if category.expanded then str := str + '1' else str := str + '0'; if category.custom then str := str + 'C'; strList.Add(str); for j := 0 to category.Count -1 do begin board := category.Items[j]; if board.past then str := #9'past' else str := ''; strList.Add(#9 + board.host + #9 + board.bbs + #9 + board.Name + str); end; end; try strList.SaveToFile(rootDir + BOARDFILE); result := True; except result := False; end; strList.Free; SaveBBSMenuInfo; end; (* 'BBSMENU'のHTMLをカッコわるく解析する *) function TCategoryList.analyze(const contents: string; const lastModified: string): boolean; function GetToken(const str: string; index, endPos: integer): string; begin while index <= endPos do begin case str[index] of #$21, #$23..#$3B, #$3D, #$3F..#$7E: result := result + str[index]; else break; end; Inc(index); end; end; procedure extractParts(const uri: string; var hostPart: string; var bbsPart: string); var strList: TStringList; i, len: integer; begin (* http://hogehoge/bbs1/index.html が普通の2ch *) (* http://hogehoge/bbs1/bbs2/ は まちBBS *) hostPart := ''; bbsPart := ''; len := length(uri); i := FindPosIC('href', uri, 1, len); if i <= 0 then exit; i := FindPosIC('http://', uri, i, len); if i <= 0 then exit; strList := TStringList.Create; strList.Delimiter := '/'; strList.DelimitedText := GetToken(uri, i + 7, length(uri)); if strList.Count < 3 then begin strList.Free; exit; end; bbsPart := strList.Strings[strList.Count -2]; for i := 0 to strList.Count -3 do begin if 0 < length(hostPart) then hostPart := hostPart + '/'; hostPart := hostPart + strList.Strings[i]; end; strList.Free; end; var refered: TList; refBoards: TList; target: string; (* ターゲットURI *) boardName: string; (* 板名 *) hostPart: string; bbsPart: string; category: TCategory; board: TBoard; i: integer; parser: TPoorHTMLParser; typeCode: TPoorHTMLObjCode; tmp: string; procedure ReserveRefered; var i: integer; begin if 0 < Count then begin for i := 0 to Count -1 do begin if not Items[i].custom then begin refered.Add(Items[i]); Items[i] := nil; end; end; Pack; //inherited Clear; end; end; procedure AddRefBoard; var i: integer; begin for i := 0 to refBoards.Count -1 do category.Add(refBoards.Items[i]); refBoards.Clear; end; function FindFromRefered: TCategory; var i: integer; begin result := nil; for i := 0 to refered.Count -1 do begin if AnsiCompareStr(TCategory(refered.Items[i]).name, target) = 0 then begin result := TCategory(refered.Items[i]); refered.Delete(i); break; end; end; end; begin (* *) SafeClear; refered := TList.Create; refBoards := TList.Create; (* 参照中のカテゴリをreferedに退避する *) ReserveRefered; category := nil; parser := TPoorHTMLParser.Create(contents); while parser.GetBlock(typeCode, tmp) do begin if typeCode = hocTAG then begin target := GetTagName(tmp); if (target = 'B') then begin if parser.GetBlock(typeCode, target) then begin if typeCode = hocTEXT then begin //if (target = 'チャット') then // break; (* 直前のカテゴリの後始末 *) if category <> nil then AddRefBoard; category := nil; if (target = 'おすすめ') or (target = '特別企画') or (target = 'チャット') or (target = '運営案内') or (target = 'ツール類') or (target = '他のサイト') then continue; category := FindFromRefered; if category <> nil then begin for i := 0 to category.Count -1 do begin refBoards.Add(category.Items[i]); category.Items[i] := nil; end; category.Clear; end else begin category := TCategory.Create(self); category.Name := target; end; Add(category); end; end; end else if (category <> nil) and (target = 'A') then begin (* *) extractParts(tmp, hostPart, bbsPart); if (0 < length(bbsPart)) and parser.GetBlock(typeCode, boardName) then begin if (typeCode = hocTEXT) then begin board := nil; for i := 0 to refBoards.Count -1 do begin if AnsiCompareStr(TBoard(refBoards.Items[i]).name, boardName) = 0 then begin board := TBoard(refBoards.Items[i]); refBoards.Delete(i); break; end; end; if ((board <> nil) or (FindBoard(hostPart, bbsPart, True) = nil)) and (hostPart <> 'info.2ch.net') then begin if board = nil then board := TBoard.Create(category); board.Name := boardName; board.host := hostPart; board.bbs := bbsPart; category.Add(board); end; end; end; end; end; end; if category <> nil then begin for i := 0 to refBoards.Count -1 do category.Add(refBoards.Items[i]); refBoards.Clear; end; (* 残ったカテゴリを追加 *) for i := 0 to refered.Count -1 do Add(refered.Items[i]); for i := Count -1 downto 0 do begin if Items[i].Count <= 0 then begin Items[i].Free; Delete(i); end; end; refered.Free; refBoards.Free; parser.Free; self.bbsMenu := contents; self.lastModified := lastModified; result := true; end; (* ログディレクトリを返す *) function TCategoryList.GetLogDir: string; begin result := RootDir + LOG2CH; end; (* 参照ブツを残してクリアする *) procedure TCategoryList.SafeClear; var i: integer; begin for i := 0 to Count -1 do begin Items[i].SafeClear; if Items[i].Count <= 0 then begin Items[i].Free; Items[i] := nil; end; end; Pack; end; function TCategoryList.FindBoard(const HOST, BBS: string; strict: Boolean): TBoard; var category: TCategory; board, substitute: TBoard; i, j, k: integer; begin result := nil; substitute := nil; if (BBS = '') or (Pos('?', HOST) > 0) then exit; for i := 0 to Count -1 do begin category := Items[i]; for j := 0 to category.Count -1 do begin board := category.Items[j]; if (AnsiCompareStr(board.bbs, BBS) = 0) then begin if AnsiCompareText(board.host, HOST) = 0 then begin result := board; exit; end; case board.BBSType of bbs2ch: for k := 0 to Config.bbs2chServers.Count -1 do begin if (0 < Pos(Config.bbs2chServers[k], HOST)) then begin substitute := board; break; end; end; bbsMachi: for k := 0 to Config.bbsMachiServers.Count -1 do begin if (0 < Pos(Config.bbsMachiServers[k], HOST)) then begin substitute := board; break; end; end; bbsJBBSShitaraba: for k := 0 to Config.bbsJBBSServers.Count -1 do begin if (0 < Pos(Config.bbsJBBSServers[k], HOST)) then begin substitute := board; break; end; end; end; end; end; end; if not strict then result := substitute; end; function TCategoryList.FindBoardByName(const catName, boardName: string): TBoard; var cat: TCategory; i, j: integer; begin result := nil; for i := 0 to Count -1 do begin if Items[i].name = catName then begin cat := Items[i]; for j := 0 to cat.Count -1 do begin if cat.Items[j].name = boardName then begin result := cat.Items[j]; exit; end; end; exit; end; end; end; function TCategoryList.FindThread(const catName, boardName, datName: string): TThreadItem; var board: TBoard; begin result := nil; board := FindBoardByName(catName, boardName); if board <> nil then begin board.Activate; result := board.Find(datName); end; end; procedure TCategoryList.SearchLogDir(List: TStrings); function FindCategory(catName: String): TCategory; var i: Integer; begin Result := nil; for i := 0 to Count - 1 do begin if Items[i].name = catName then begin Result := Items[i]; Break; end; end; end; function FindBrd(cat: TCategory; boardName: String): TBoard; var i: Integer; begin Result := nil; for i := 0 to cat.Count - 1 do begin if cat.Items[i].name = boardName then begin Result := cat.Items[i]; Break; end; end; end; const faForDirSearch = faAnyFile - faSysFile - faVolumeID; var FindPath: String; DirRec1, DirRec2: TSearchRec; FindResult1, FindResult2: Integer; cat: TCategory; LogDir: String; begin LogDir := GetLogDir + '\'; FindPath := LogDir + '*.*'; FindResult1 := FindFirst(FindPath, faForDirSearch, DirRec1); while FindResult1 = 0 do begin if ((DirRec1.Attr and faDirectory) <> 0) and (DirRec1.Name <> '.') and (DirRec1.Name <> '..') then begin cat := FindCategory(DirRec1.Name); if cat = nil then List.Add(DirRec1.Name); FindResult2 := FindFirst(LogDir + DirRec1.Name + '\*.*', faForDirSearch, DirRec2); while FindResult2 = 0 do begin if ((DirRec2.Attr and faDirectory) <> 0) and (DirRec2.Name <> '.') and (DirRec2.Name <> '..') then if (cat = nil) or (FindBrd(cat, DirRec2.Name) = nil) then List.Add(DirRec1.Name + '\' + DirRec2.Name); FindResult2 := FindNext(DirRec2); end; end; FindResult1 := FindNext(DirRec1); end; end; end.
unit UPediScore; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, UBasicScore, Grids, StdCtrls, ExtCtrls, Buttons, UzLogCOnst, UzLogGlobal, UzLogQSO, Vcl.Menus; type TPediScore = class(TBasicScore) Grid: TStringGrid; procedure FormShow(Sender: TObject); procedure GridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); protected function GetFontSize(): Integer; override; procedure SetFontSize(v: Integer); override; private { Private declarations } Stats: array[b19..HiBand, mCW..mOther] of integer; public { Public declarations } procedure UpdateData; override; procedure AddNoUpdate(var aQSO : TQSO); override; procedure Reset; override; procedure SummaryWriteScore(FileName : string); override; property FontSize: Integer read GetFontSize write SetFontSize; end; implementation {$R *.DFM} procedure TPediScore.FormShow(Sender: TObject); begin inherited; Button1.SetFocus; Grid.Col := 1; Grid.Row := 1; CWButton.Visible := False; end; procedure TPediScore.GridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin inherited; Draw_GridCell(TStringGrid(Sender), ACol, ARow, Rect); end; procedure TPediScore.SummaryWriteScore(FileName: string); var f: textfile; b: TBand; M: TMode; TotQSO, TotBandQSO: LongInt; ModeQSO: array [mCW .. mOther] of Integer; begin AssignFile(f, FileName); Append(f); write(f, 'MHz '); for M := mCW to mOther do begin write(f, FillLeft(ModeString[M], 6)); end; write(f, ' QSO'); writeln(f); TotQSO := 0; for M := mCW to mOther do begin ModeQSO[M] := 0; end; for b := b19 to HiBand do begin TotBandQSO := 0; write(f, FillRight(MHzString[b], 8)); for M := mCW to mOther do begin write(f, FillLeft(IntToStr(Stats[b, M]), 6)); Inc(TotBandQSO, Stats[b, M]); Inc(ModeQSO[M], Stats[b, M]); end; Inc(TotQSO, TotBandQSO); write(f, FillLeft(IntToStr(TotBandQSO), 6)); writeln(f); end; write(f, FillRight('Total', 8)); for M := mCW to mOther do begin write(f, FillLeft(IntToStr(ModeQSO[M]), 6)); end; writeln(f, FillLeft(IntToStr(TotQSO), 6)); CloseFile(f); end; procedure TPediScore.UpdateData; var b: TBand; M: TMode; TotQSO, TotBandQSO: LongInt; ModeQSO: array [mCW .. mOther] of Integer; w: Integer; begin TotQSO := 0; Grid.Cells[0, 0] := 'MHz'; Grid.Cells[1, 0] := 'Total'; Grid.Cells[2, 0] := 'CW'; Grid.Cells[3, 0] := 'SSB'; Grid.Cells[4, 0] := 'FM'; Grid.Cells[5, 0] := 'AM'; Grid.Cells[6, 0] := 'RTTY'; Grid.Cells[7, 0] := 'FT4'; Grid.Cells[8, 0] := 'FT8'; Grid.Cells[9, 0] := 'Other'; for M := mCW to mOther do begin ModeQSO[M] := 0; end; for b := b19 to HiBand do begin TotBandQSO := 0; Grid.Cells[0, ord(b) + 1] := '*' + MHzString[b]; for M := mCW to mOther do begin Grid.Cells[ord(M) + 2, ord(b) + 1] := IntToStr3(Stats[b, M]); Inc(TotBandQSO, Stats[b, M]); Inc(ModeQSO[M], Stats[b, M]); end; Inc(TotQSO, TotBandQSO); Grid.Cells[1, ord(b) + 1] := IntToStr3(TotBandQSO); end; Grid.Cells[0, ord(HiBand) + 2] := 'Total'; Grid.Cells[1, ord(HiBand) + 2] := IntToStr3(TotQSO); for M := mCW to mOther do begin Grid.Cells[ord(M) + 2, ord(HiBand) + 2] := IntToStr3(ModeQSO[M]); end; Grid.ColCount := 10; Grid.RowCount := 18; // カラム幅をセット w := Grid.Canvas.TextWidth('9'); Grid.ColWidths[0] := w * 6; Grid.ColWidths[1] := w * 7; Grid.ColWidths[2] := w * 7; Grid.ColWidths[3] := w * 7; Grid.ColWidths[4] := w * 7; Grid.ColWidths[5] := w * 7; Grid.ColWidths[6] := w * 7; Grid.ColWidths[7] := w * 7; Grid.ColWidths[8] := w * 7; Grid.ColWidths[9] := w * 7; // グリッドサイズ調整 AdjustGridSize(Grid, Grid.ColCount, Grid.RowCount); end; procedure TPediScore.AddNoUpdate(var aQSO: TQSO); begin aQSO.points := 1; Inc(Stats[aQSO.band, aQSO.Mode]); end; procedure TPediScore.Reset; var b: TBand; M: TMode; begin for b := b19 to HiBand do begin for M := mCW to mOther do begin Stats[b, M] := 0; end; end; end; function TPediScore.GetFontSize(): Integer; begin Result := Grid.Font.Size; end; procedure TPediScore.SetFontSize(v: Integer); begin Inherited; SetGridFontSize(Grid, v); UpdateData(); end; end.
unit ChangeVideoMatrixForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.OleCtrls, TrueConf_CallXLib_TLB, Vcl.ComCtrls, System.Actions, Vcl.ActnList, Vcl.Menus, ConfigForm, UserCacheUnit, CallX_Common, HardwareForm, Vcl.StdCtrls, Vcl.ExtCtrls, System.ImageList, Vcl.ImgList; const TITLE = 'ChangeVideoMatrix Demo'; type TfrmChangeVideoMatrix = class(TForm) PageControl: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; CallX: TTrueConfCallX; MainMenu: TMainMenu; File1: TMenuItem; miExit: TMenuItem; miTools: TMenuItem; miConnectionSetting: TMenuItem; miHardwareSetting: TMenuItem; ActionList: TActionList; actCall: TAction; actHangUp: TAction; memoLog: TMemo; Splitter1: TSplitter; Panel1: TPanel; lbParticipants: TListBox; Panel2: TPanel; Button1: TButton; actShakeUp: TAction; rgMatrixType: TRadioGroup; procedure FormCreate(Sender: TObject); procedure CallXInviteReceived(ASender: TObject; const eventDetails: WideString); procedure miExitClick(Sender: TObject); procedure CallXXAfterStart(Sender: TObject); procedure miConnectionSettingClick(Sender: TObject); procedure miHardwareSettingClick(Sender: TObject); procedure CallXChangeVideoMatrixReport(ASender: TObject; const eventDetails: WideString); procedure CallXXChangeState(ASender: TObject; prevState, newState: Integer); procedure CallXServerConnected(ASender: TObject; const eventDetails: WideString); procedure FormDestroy(Sender: TObject); procedure CallXUpdateParticipantList(ASender: TObject; const eventDetails: WideString); procedure actShakeUpUpdate(Sender: TObject); procedure actShakeUpExecute(Sender: TObject); procedure CallXXError(ASender: TObject; errorCode: Integer; const errorMsg: WideString); private { Private declarations } // server, call_id, password and others... FCallXSettings: TCallXSettings; // TrueConf CallX has already started working FStarted: boolean; // current authorized user status FStatus: TMyStatus; protected procedure WriteLog(ALine: string); public { Public declarations } end; var frmChangeVideoMatrix: TfrmChangeVideoMatrix; implementation {$R *.dfm} uses LogUnit; { OnXAfterStart event handler } { When CallX component is succesfully started } { I recommend set the hardware ((camera, microphone, speakers)) in this event handler } procedure TfrmChangeVideoMatrix.CallXXAfterStart(Sender: TObject); begin WriteLog('OnXAfterStart: =============================================='); if (FCallXSettings.sServer <> '') or ((FCallXSettings.sUser <> '') and (FCallXSettings.sPassword <> '')) then CallX.connectToServer(FCallXSettings.sServer) else WriteLog('Empty connect & login info'); if TfrmHardware.ApplySettings(self, TfrmConfigurator.GetRegKey, CallX) then begin end; FStarted := True; miConnectionSetting.Enabled := True; miHardwareSetting.Enabled := True; end; procedure TfrmChangeVideoMatrix.CallXXChangeState(ASender: TObject; prevState, newState: Integer); begin FStatus := IntToMyStatus(newState); Caption := Format('%s. Authorized user: %s [%s]', [TITLE, FCallXSettings.sUser, IntToMyStringState(newState)]); end; procedure TfrmChangeVideoMatrix.CallXXError(ASender: TObject; errorCode: Integer; const errorMsg: WideString); begin WriteLog('OnXError: ' + errorMsg); end; procedure TfrmChangeVideoMatrix.FormCreate(Sender: TObject); begin PageControl.ActivePageIndex := 0; FStatus := csBeforeInit; Caption := TITLE + ' [connecting...]'; { Get settings: server, call_id, password } TfrmConfigurator.LoadSettings(FCallXSettings); end; procedure TfrmChangeVideoMatrix.FormDestroy(Sender: TObject); begin CallX.shutdown; // have to do it! or shutdown2() end; procedure TfrmChangeVideoMatrix.miConnectionSettingClick(Sender: TObject); begin if FStarted then ShowConfigurator(CallX); end; procedure TfrmChangeVideoMatrix.miExitClick(Sender: TObject); begin Close; end; procedure TfrmChangeVideoMatrix.miHardwareSettingClick(Sender: TObject); begin if TfrmHardware.ShowDialog(self, TfrmConfigurator.GetRegKey, CallX) then begin end; end; procedure TfrmChangeVideoMatrix.WriteLog(ALine: string); begin if not FCallXSettings.bWriteLog then Exit; { write to log file } Log(NowToString + ' ' + ALine); end; // { "matrixType": 1, // "participants": [ "brasilia@conference.oversee.com.br", "amynthas@conference.oversee.com.br" ] } procedure TfrmChangeVideoMatrix.actShakeUpExecute(Sender: TObject); procedure _ShakeUpStrings(AStrings: TStrings); var ii, iRandomIdx: integer; s: string; begin Randomize; if lbParticipants.Items.Count < 2 then begin end else if lbParticipants.Items.Count < 4 then begin s := lbParticipants.Items[0]; lbParticipants.Items.Delete(0); lbParticipants.Items.Add(s) end else for ii := 0 to AStrings.Count - 1 do begin iRandomIdx := Random(AStrings.Count - 1); if iRandomIdx <> ii then begin s := lbParticipants.Items[0]; lbParticipants.Items.Delete(0); lbParticipants.Items.Insert(iRandomIdx, s); end; end; end; var sParticipants, sJSONResult, sUser: string; i: integer; begin sParticipants := ''; { Shake up } _ShakeUpStrings(lbParticipants.Items); for i := 0 to lbParticipants.Items.Count - 1 do begin if i <> 0 then sParticipants := sParticipants + ', '; sParticipants := sParticipants + '"' + lbParticipants.Items[i] + '"'; end; // Prepare a JSON string sJSONResult := Format('{"matrixType": %d, "participants": [%s]}', [rgMatrixType.ItemIndex, sParticipants]); // —hange video layout CallX.changeVideoMatrix(sJSONResult); end; procedure TfrmChangeVideoMatrix.actShakeUpUpdate(Sender: TObject); begin actShakeUp.Enabled := (FStatus in [csInConference]) and (lbParticipants.Items.Count > 0); end; procedure TfrmChangeVideoMatrix.CallXChangeVideoMatrixReport(ASender: TObject; const eventDetails: WideString); begin memoLog.Lines.Insert(0, '=== OnChangeVideoMatrixReport ====================='); memoLog.Lines.Insert(0, eventDetails); end; procedure TfrmChangeVideoMatrix.CallXInviteReceived(ASender: TObject; const eventDetails: WideString); begin CallX.accept; end; procedure TfrmChangeVideoMatrix.CallXServerConnected(ASender: TObject; const eventDetails: WideString); begin WriteLog('OnServerConnected: ' + eventDetails); if (FCallXSettings.sUser <> '') and (FCallXSettings.sPassword <> '') then begin WriteLog('Try to login: ' + FCallXSettings.sUser); CallX.login(FCallXSettings.sUser, FCallXSettings.sPassword) end else WriteLog('Empty login info'); end; procedure TfrmChangeVideoMatrix.CallXUpdateParticipantList(ASender: TObject; const eventDetails: WideString); begin memoLog.Lines.Insert(0, '=== OnUpdateParticipantList ======================='); memoLog.Lines.Insert(0, eventDetails); memoLog.Lines.Insert(0, '=== getParticipantsList() ======================='); memoLog.Lines.Insert(0, CallX.getParticipantsList()); lbParticipants.Items.Text := JSON_ParticipantsListToText(CallX.getParticipantsList()); end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { Copyright(c) 2013 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX.VirtualKeyboard.iOS; interface procedure RegisterVirtualKeyboardServices; procedure UnregisterVirtualKeyboardServices; implementation uses System.Classes, System.SysUtils, System.TypInfo, System.Generics.Collections, System.UITypes, System.Types, Macapi.ObjectiveC, Macapi.ObjCRuntime, iOSapi.CocoaTypes, iOSapi.Foundation, iOSapi.UIKit, FMX.Types, FMX.VirtualKeyboard, FMX.Platform, FMX.Forms, FMX.Platform.iOS, FMX.Messages, FMX.Consts; const TOOLBAR_HEIGHT = 44; type IKeyboardEvents = interface(NSObject) ['{72D3A7FD-DDE3-473D-9750-46C072E7B3B7}'] { Keyboard notifications } procedure KeyboardWillShow(notification: Pointer); cdecl; procedure KeyboardWillHide(notification: Pointer); cdecl; procedure KeyboardWillChangeFrame(notification: Pointer); cdecl; { Actions } procedure HideVirtualKeyboard; cdecl; procedure CustomButtonAction(sender: Pointer); cdecl; { Orientation notification } procedure DeviceOrientationChangeNotification(notification: Pointer); cdecl; end; TKeyboardEventHandler = class(TOCLocal) strict private type TKeyboardState = (ksShowed, ksHidden); private FKeepFocus: Boolean; { Keyborad Notifications } procedure SendNotificationAboutKeyboardEvent(const AVKRect: TRect; AKeyboardState :TKeyboardState); function GetKeyboardRect(Notification: Pointer): TRect; protected { TOCLocal } function GetObjectiveCClass: PTypeInfo; override; public { IKeyboardEvents } procedure KeyboardWillShow(notification: Pointer); cdecl; procedure KeyboardWillHide(notification: Pointer); cdecl; procedure KeyboardWillChangeFrame(notification: Pointer); cdecl; procedure HideVirtualKeyboard; cdecl; procedure CustomButtonAction(sender: Pointer); cdecl; procedure DeviceOrientationChangeNotification(notification: Pointer); cdecl; end; TCocoaVirtualKeyboardService = class(TInterfacedObject, IFMXVirtualKeyboardService, IFMXVirtualKeyboardToolbarService) private FKeyboardHandler: TKeyboardEventHandler; { IFMXVirtualKeyboardToolbarService } FToolbarVisible: Boolean; FToolBar: UIToolBar; FFlexibleSepararator: UIBarButtonItem; FHideButton: UIBarButtonItem; FButtons: TList<TVirtualKeyboardToolButton>; FUpdatingButtons: Boolean; FToolbarEnabled: Boolean; FHideButtonVisible: Boolean; FStoredActiveForm: TComponent; procedure SetToolbarVisible(const Value: Boolean); procedure SetToolbarFrame(const Frame: NSRect; const UseAnimation: Boolean); function GetToolbarFrame: NSRect; procedure RefreshToolbarButtons; procedure CreateToolbar; procedure ChangeToolbarOrientation; // property ToolbarVisible: Boolean read FToolbarVisible write SetToolbarVisible; public constructor Create; destructor Destroy; override; { IFMXVirtualKeyboardService } function ShowVirtualKeyboard(const AControl: TFmxObject): Boolean; function HideVirtualKeyboard: Boolean; procedure SetTransientState(Value: Boolean); function GetVirtualKeyBoardState: TVirtualKeyBoardState; property VirtualKeyBoardState: TVirtualKeyBoardState read GetVirtualKeyBoardState; { IFMXVirtualKeyboardToolbarService } procedure SetToolbarEnabled(const Value: Boolean); function IsToolbarEnabled: Boolean; procedure SetHideKeyboardButtonVisibility(const Value: Boolean); function IsHideKeyboardButtonVisible: Boolean; function AddButton(const Title: string; ExecuteEvent: TNotifyEvent): TVirtualKeyboardToolButton; procedure DeleteButton(const Index: Integer); function ButtonsCount: Integer; function GetButtonByIndex(const Index: Integer): TVirtualKeyboardToolButton; procedure ClearButtons; end; TVKToolbarButton_iOS = class(TVirtualKeyboardToolButton) protected procedure DoChanged; override; end; var CocoaKeyboardService: TCocoaVirtualKeyboardService; procedure RegisterVirtualKeyboardServices; begin CocoaKeyboardService := TCocoaVirtualKeyboardService.Create; TPlatformServices.Current.AddPlatformService(IFMXVirtualKeyboardService, CocoaKeyboardService); TPlatformServices.Current.AddPlatformService(IFMXVirtualKeyboardToolbarService, CocoaKeyboardService); end; procedure UnregisterVirtualKeyboardServices; begin TPlatformServices.Current.RemovePlatformService(IFMXVirtualKeyboardService); TPlatformServices.Current.RemovePlatformService(IFMXVirtualKeyboardToolbarService); FreeAndNil(CocoaKeyboardService); end; { TVirtualKeyboardEventHandler } procedure TKeyboardEventHandler.CustomButtonAction(sender: Pointer); var Index: Integer; begin Index := TUIBarButtonItem.Wrap(sender).tag - 1; if Index >= 0 then TVKToolbarButton_iOS(CocoaKeyboardService.FButtons[Index]).DoExecute; end; procedure TKeyboardEventHandler.DeviceOrientationChangeNotification(notification: Pointer); begin CocoaKeyboardService.ChangeToolbarOrientation; end; function TKeyboardEventHandler.GetKeyboardRect(Notification: Pointer): TRect; var OCRect: NSRect; ScreenService: IFMXScreenService; Orientation: TScreenOrientation; begin OCRect := iOSapi.UIKit.TNSValue.Wrap(TNSNotification.Wrap(Notification).userInfo.valueForKey(NSSTR('UIKeyboardFrameEndUserInfoKey'))).CGRectValue; Orientation := TScreenOrientation.soPortrait; if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, IInterface(ScreenService)) then Orientation := ScreenService.GetScreenOrientation; case Orientation of TScreenOrientation.soPortrait, TScreenOrientation.soInvertedPortrait: Result := TRect.Create(Point(Round(OCRect.origin.x), Round(OCRect.origin.y)), Round(OCRect.size.width), Round(OCRect.size.height)); TScreenOrientation.soLandscape, TScreenOrientation.soInvertedLandscape: Result := TRect.Create(Point(Round(OCRect.origin.y), Round(OCRect.origin.x)), Round(OCRect.size.height), Round(OCRect.size.width)); end; end; function TKeyboardEventHandler.GetObjectiveCClass: PTypeInfo; begin Result := TypeInfo(IKeyboardEvents); end; procedure TKeyboardEventHandler.HideVirtualKeyboard; begin try Screen.ActiveForm.Focused := nil; except Application.HandleException(Screen.ActiveForm); end; end; procedure TKeyboardEventHandler.KeyboardWillChangeFrame( notification: Pointer); begin end; procedure TKeyboardEventHandler.KeyboardWillHide(notification: Pointer); var VKRect: TRect; begin CocoaKeyboardService.ToolbarVisible := False; VKRect := GetKeyboardRect(notification); SendNotificationAboutKeyboardEvent(VKRect, TKeyboardState.ksHidden); if not FKeepFocus then HideVirtualKeyboard; end; procedure TKeyboardEventHandler.KeyboardWillShow(notification: Pointer); var VKRect: TRect; begin VKRect := GetKeyboardRect(notification); CocoaKeyboardService.CreateToolbar; CocoaKeyboardService.ToolbarVisible := True; if CocoaKeyboardService.IsToolbarEnabled then VKRect.Top := VKRect.Top - TOOLBAR_HEIGHT; SendNotificationAboutKeyboardEvent(VKRect, TKeyboardState.ksShowed); end; procedure TKeyboardEventHandler.SendNotificationAboutKeyboardEvent(const AVKRect: TRect; AKeyboardState: TKeyboardState); var Message: TVKStateChangeMessage; begin Message := TVKStateChangeMessage.Create(AKeyboardState = TKeyboardState.ksShowed, AVKRect); TMessageManager.DefaultManager.SendMessage(Self, Message, True); end; type TStoredActiveForm = class (TComponent) private [weak]FForm: TCommonCustomForm; procedure SetForm(const Value: TCommonCustomForm); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public property Form: TCommonCustomForm read FForm write SetForm; end; { TStoredActiveForm } procedure TStoredActiveForm.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = opRemove then begin if AComponent = FForm then FForm := nil; end; end; procedure TStoredActiveForm.SetForm(const Value: TCommonCustomForm); begin if FForm <> Value then begin if Assigned(FForm) then begin //if Assigned(FForm.Handle) then // WindowHandleToPlatform(FForm.Handle).View.resignFirstResponder; TComponent(FForm).RemoveFreeNotification(self); FForm := nil; end; FForm := Value; if Assigned(FForm) then begin TComponent(FForm).FreeNotification(self); end; end; end; { TCocoaVirtualKeyboardToolbarService } function TCocoaVirtualKeyboardService.AddButton(const Title: string; ExecuteEvent: TNotifyEvent): TVirtualKeyboardToolButton; begin FUpdatingButtons := True; Result := TVKToolbarButton_iOS.Create; Result.Title := Title; Result.OnExecute := ExecuteEvent; FUpdatingButtons := False; FButtons.Add(Result); RefreshToolbarButtons; end; function TCocoaVirtualKeyboardService.ButtonsCount: Integer; begin Result := FButtons.Count; end; procedure TCocoaVirtualKeyboardService.ChangeToolbarOrientation; begin //Need to change orientation without animation if Assigned(FToolBar) then SetToolbarFrame(GetToolbarFrame, False); end; procedure TCocoaVirtualKeyboardService.ClearButtons; begin if FButtons.Count > 0 then begin FUpdatingButtons := True; FButtons.Clear; FUpdatingButtons := False; RefreshToolbarButtons; end; end; constructor TCocoaVirtualKeyboardService.Create; begin inherited Create; FStoredActiveForm := TStoredActiveForm.Create(nil); FKeyboardHandler := TKeyboardEventHandler.Create; //Subscribing to events TNSNotificationCenter.Wrap(TNSNotificationCenter.OCClass.defaultCenter).addObserver( FKeyboardHandler.GetObjectID, sel_getUid('KeyboardWillShow:'), (NSSTR('UIKeyboardWillShowNotification') as ILocalObject).GetObjectID, nil); TNSNotificationCenter.Wrap(TNSNotificationCenter.OCClass.defaultCenter).addObserver( FKeyboardHandler.GetObjectID, sel_getUid('KeyboardWillHide:'), (NSSTR('UIKeyboardWillHideNotification') as ILocalObject).GetObjectID, nil); TNSNotificationCenter.Wrap(TNSNotificationCenter.OCClass.defaultCenter).addObserver( FKeyboardHandler.GetObjectID, sel_getUid('KeyboardWillChangeFrame:'), (NSSTR('UIKeyboardWillChangeFrameNotification') as ILocalObject).GetObjectID, nil); TNSNotificationCenter.Wrap(TNSNotificationCenter.OCClass.defaultCenter).addObserver( FKeyboardHandler.GetObjectID, sel_getUid('DeviceOrientationChangeNotification:'), (NSSTR(FMXStartChangeDeviceOrientation) as ILocalObject).GetObjectID, nil); //IFMXVirtualKeyboardToolbarService FUpdatingButtons := False; FToolbarVisible := False; FButtons := TList<TVirtualKeyboardToolButton>.Create; // FToolbarEnabled := (TUIDevice.Wrap(TUIDevice.OCClass.currentDevice).userInterfaceIdiom = UIUserInterfaceIdiomPhone); FHideButtonVisible := (TUIDevice.Wrap(TUIDevice.OCClass.currentDevice).userInterfaceIdiom = UIUserInterfaceIdiomPhone); end; procedure TCocoaVirtualKeyboardService.CreateToolbar; var SharedApplication: UIApplication; KeyWindow: UIWindow; begin SharedApplication := TUIApplication.Wrap(TUIApplication.OCClass.sharedApplication); KeyWindow := SharedApplication.keyWindow; if Assigned(KeyWindow) and Assigned(KeyWindow.rootViewController) then begin if not Assigned(FToolBar) and FToolbarEnabled then begin FToolBar := TUIToolbar.Create; FToolBar.setBarStyle(UIBarStyleBlackOpaque); FToolBar.setAlpha(0.8); SetToolbarFrame(GetToolbarFrame, False); RefreshToolbarButtons; KeyWindow.rootViewController.view.addSubview(FToolbar); end else KeyWindow.rootViewController.view.bringSubviewToFront(FToolbar); end; end; procedure TCocoaVirtualKeyboardService.DeleteButton( const Index: Integer); begin if (Index >= 0) and (Index < FButtons.Count) then begin FButtons.Delete(Index); RefreshToolbarButtons; end; end; destructor TCocoaVirtualKeyboardService.Destroy; begin TNSNotificationCenter.Wrap(TNSNotificationCenter.OCClass.defaultCenter).removeObserver(FKeyboardHandler.GetObjectID); FreeAndNil(FKeyboardHandler); //IFMXVirtualKeyboardToolbarService FUpdatingButtons := True; FreeAndNil(FButtons); if Assigned(FToolBar) then begin if Assigned(FToolBar.items) then FToolBar.items.release; FToolBar.release; FToolBar := nil; end; if Assigned(FFlexibleSepararator) then begin FFlexibleSepararator.release; FFlexibleSepararator := nil; end; if Assigned(FHideButton) then begin FHideButton.release; FHideButton := nil; end; FreeAndNil(FStoredActiveForm); inherited; end; function TCocoaVirtualKeyboardService.GetButtonByIndex( const Index: Integer): TVirtualKeyboardToolButton; begin if (Index >= 0) and (Index < FButtons.Count) then Result := FButtons[Index] else Result := nil; end; function TCocoaVirtualKeyboardService.GetToolbarFrame: NSRect; var ScreenRect: NSRect; begin ScreenRect := TUIScreen.Wrap(TUIScreen.OCClass.mainScreen).applicationFrame; Result.origin.x := 0; Result.size.height := TOOLBAR_HEIGHT; case TUIDevice.Wrap(TUIDevice.OCClass.currentDevice).orientation of UIDeviceOrientationUnknown, UIDeviceOrientationFaceDown, UIDeviceOrientationFaceUp, UIDeviceOrientationPortrait, UIDeviceOrientationPortraitUpsideDown: begin if ToolbarVisible then if TUIDevice.Wrap(TUIDevice.OCClass.currentDevice).userInterfaceIdiom = UIUserInterfaceIdiomPhone then Result.origin.y := ScreenRect.size.height - 260 else Result.origin.y := ScreenRect.size.height - 308 else Result.origin.y := ScreenRect.size.height; Result.size.width := ScreenRect.size.width; end; UIDeviceOrientationLandscapeLeft, UIDeviceOrientationLandscapeRight: begin if ToolbarVisible then if TUIDevice.Wrap(TUIDevice.OCClass.currentDevice).userInterfaceIdiom = UIUserInterfaceIdiomPhone then Result.origin.y := ScreenRect.size.width - 206 else Result.origin.y := ScreenRect.size.width - 396 else Result.origin.y := ScreenRect.size.width; Result.size.width := ScreenRect.size.height; end; end; end; function TCocoaVirtualKeyboardService.GetVirtualKeyBoardState: TVirtualKeyBoardState; begin Result := [vksAutoShow]; end; procedure TCocoaVirtualKeyboardService.SetTransientState(Value: Boolean); begin end; function TCocoaVirtualKeyboardService.IsHideKeyboardButtonVisible: Boolean; begin Result := FHideButtonVisible; end; function TCocoaVirtualKeyboardService.IsToolbarEnabled: Boolean; begin Result := FToolbarEnabled; end; procedure TCocoaVirtualKeyboardService.RefreshToolbarButtons; var Buttons: NSMutableArray; I: Integer; B: UIBarButtonItem; begin if not FUpdatingButtons and Assigned(FToolBar) then begin if Assigned(FToolBar.items) then begin FToolBar.items.release; FFlexibleSepararator := nil; FHideButton := nil; end; Buttons := TNSMutableArray.Create; //Custom buttons for I := 0 to FButtons.Count - 1 do begin B := TUIBarButtonItem.Create; B.setTitle(NSSTR(FButtons[I].Title)); B.setStyle(UIBarButtonItemStyleBordered); B.setTag(I + 1); B.setTarget(FKeyboardHandler.GetObjectID); B.setAction(sel_getUid('CustomButtonAction:')); B.setEnabled(False); Buttons.addObject(ILocalObject(B).GetObjectID); end; if FHideButtonVisible then begin //Separator if not Assigned(FFlexibleSepararator) then begin FFlexibleSepararator := TUIBarButtonItem.Create; FFlexibleSepararator.initWithBarButtonSystemItem(UIBarButtonSystemItemFlexibleSpace, nil, nil); end; Buttons.addObject(ILocalObject(FFlexibleSepararator).GetObjectID); //Hide button if not Assigned(FHideButton) then begin FHideButton := TUIBarButtonItem.Create; FHideButton.setTitle(NSSTR(SEditorDone)); FHideButton.setStyle(UIBarButtonItemStyleDone); FHideButton.setTarget(FKeyboardHandler.GetObjectID); FHideButton.setAction(sel_getUid('HideVirtualKeyboard')); end; Buttons.addObject(ILocalObject(FHideButton).GetObjectID); end; FToolBar.setItems(Buttons); end; end; procedure TCocoaVirtualKeyboardService.SetHideKeyboardButtonVisibility( const Value: Boolean); begin if FHideButtonVisible <> Value then begin FHideButtonVisible := Value; RefreshToolbarButtons; end; end; procedure TCocoaVirtualKeyboardService.SetToolbarEnabled( const Value: Boolean); begin if FToolbarEnabled <> Value then begin if not Value then ToolbarVisible := False; FToolbarEnabled := Value; end; end; procedure TCocoaVirtualKeyboardService.SetToolbarFrame( const Frame: NSRect; const UseAnimation: Boolean); begin if Assigned(FToolBar) then if UseAnimation then begin TUIView.OCClass.beginAnimations(nil, nil); try TUIView.OCClass.setAnimationDuration(0.25); TUIView.OCClass.setAnimationBeginsFromCurrentState(True); FToolBar.setFrame(Frame); finally TUIView.OCClass.commitAnimations; end; end else FToolBar.setFrame(Frame); end; procedure TCocoaVirtualKeyboardService.SetToolbarVisible(const Value: Boolean); begin if FToolbarVisible <> Value then begin FToolbarVisible := Value; if Assigned(FToolBar) and FToolbarEnabled then SetToolbarFrame(GetToolbarFrame, True); end; end; function TCocoaVirtualKeyboardService.ShowVirtualKeyboard( const AControl: TFmxObject): Boolean; var RootObj: TFmxObject; RootView: UIView; begin RootObj := AControl.Root.GetObject; if RootObj is TCommonCustomForm then begin if Assigned(FStoredActiveForm) then TStoredActiveForm(FStoredActiveForm).Form := TCommonCustomForm(RootObj); RootView := WindowHandleToPlatform(TCommonCustomForm(RootObj).Handle).View; Result := RootView.becomeFirstResponder; end else Result := False; end; function TCocoaVirtualKeyboardService.HideVirtualKeyboard: Boolean; var RootObj: TCommonCustomForm; begin RootObj := nil; if Assigned(FStoredActiveForm) then RootObj := TStoredActiveForm(FStoredActiveForm).Form; if Assigned(RootObj) then begin FKeyboardHandler.FKeepFocus := True; Result := WindowHandleToPlatform(RootObj.Handle).View.resignFirstResponder; FKeyboardHandler.FKeepFocus := False; end else Result := False; end; { TVKToolbarButton } procedure TVKToolbarButton_iOS.DoChanged; begin inherited; CocoaKeyboardService.RefreshToolbarButtons; end; initialization RegisterVirtualKeyboardServices; finalization UnregisterVirtualKeyboardServices; end.
unit Calculadora; interface uses Winapi.Windows, Winapi.Messages, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.Grids, Data.DB, Vcl.DBGrids, Datasnap.DBClient; type TForm1 = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; edtCampo1: TEdit; edtCampo2: TEdit; btnSomar: TButton; btnSubtrair: TButton; btnMultiplicar: TButton; btnDividir: TButton; Label4: TLabel; edtResultado: TEdit; dbGridResultados: TDBGrid; cdsValores: TClientDataSet; cdsValoresValor1: TFloatField; cdsValoresValor2: TFloatField; dsValores: TDataSource; cdsValoresResultado: TFloatField; procedure btnSomarClick(Sender: TObject); procedure btnSubtrairClick(Sender: TObject); procedure btnMultiplicarClick(Sender: TObject); procedure btnDividirClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } Function Somar(pValor1, pValor2 : Double): Double; Function Subtrair(pValor1, pValor2 : Double): Double; Function Multiplicar(pValor1, pValor2 : Double): Double; Function Dividir(pValor1, pValor2 : Double): Double; Function VerificaCampos(pValor1, pValor2 : Double): Boolean; procedure AtribuiValoresAoGrid(pValor1, pValor2, pResultado: Double); end; var Form1: TForm1; implementation uses System.SysUtils, Dialogs; {$R *.dfm} procedure TForm1.AtribuiValoresAoGrid(pValor1, pValor2, pResultado: Double); begin cdsValores.Insert; cdsValores.FieldByName('Valor1').AsFloat := pValor1; cdsValores.FieldByName('Valor2').AsFloat := pValor2; cdsValores.FieldByName('Resultado').AsFloat := pResultado; cdsValores.Post; end; procedure TForm1.btnDividirClick(Sender: TObject); begin edtResultado.Text := floatToStr(Dividir(StrToFloat(edtCampo1.Text), StrToFloat(edtCampo2.Text))); AtribuiValoresAoGrid(StrToFloat(edtCampo1.Text), StrToFloat(edtCampo2.Text), StrToFloat(edtResultado.Text)); end; procedure TForm1.btnMultiplicarClick(Sender: TObject); begin edtResultado.Text := floatToStr(Multiplicar(StrToFloat(edtCampo1.Text), StrToFloat(edtCampo2.Text))); AtribuiValoresAoGrid(StrToFloat(edtCampo1.Text), StrToFloat(edtCampo2.Text), StrToFloat(edtResultado.Text)); end; procedure TForm1.btnSomarClick(Sender: TObject); begin edtResultado.Text := floatToStr(Somar(StrToFloat(edtCampo1.Text), StrToFloat(edtCampo2.Text))); AtribuiValoresAoGrid(StrToFloat(edtCampo1.Text), StrToFloat(edtCampo2.Text), StrToFloat(edtResultado.Text)); end; procedure TForm1.btnSubtrairClick(Sender: TObject); begin edtResultado.Text := floatToStr(Subtrair(StrToFloat(edtCampo1.Text), StrToFloat(edtCampo2.Text))); AtribuiValoresAoGrid(StrToFloat(edtCampo1.Text), StrToFloat(edtCampo2.Text), StrToFloat(edtResultado.Text)); end; function TForm1.Dividir(pValor1, pValor2: Double): Double; begin if VerificaCampos(pValor1, pValor2) then begin ShowMessage('Não poderá calcular com valores iguais a zero'); Exit; end; Result := pValor1/pValor2; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin cdsValores.Close; end; procedure TForm1.FormCreate(Sender: TObject); begin cdsValores.CreateDataSet; cdsValores.Open; end; function TForm1.Multiplicar(pValor1, pValor2: Double): Double; begin if VerificaCampos(pValor1, pValor2) then begin ShowMessage('Não poderá calcular com valores iguais a zero'); Exit; end; Result := pValor1*pValor2; end; function TForm1.Somar(pValor1, pValor2: Double): Double; begin if VerificaCampos(pValor1, pValor2) then begin ShowMessage('Não poderá calcular com valores iguais a zero'); Exit; end; Result := pValor1+pValor2; end; function TForm1.Subtrair(pValor1, pValor2: Double): Double; begin if VerificaCampos(pValor1, pValor2) then begin ShowMessage('Não poderá calcular com valores iguais a zero'); Exit; end; Result := pValor1-pValor2; end; function TForm1.VerificaCampos(pValor1, pValor2: Double): Boolean; begin Result := (pValor1 = 0) and (pValor2 = 0); end; end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit Server.Claims; interface uses System.Classes, WiRL.Core.JSON, WiRL.Core.Auth.Context; type // Custom Claims Class TServerClaims = class(TWiRLSubject) private const CLAIM_GROUP = 'group'; const CLAIM_LANGUAGE = 'language'; private function GetGroup: string; function GetLanguage: string; procedure SetLanguage(const Value: string); procedure SetGroup(const Value: string); public property Group: string read GetGroup write SetGroup; property Language: string read GetLanguage write SetLanguage; end; implementation uses JOSE.Types.JSON, JOSE.Core.Base; { TServerClaims } function TServerClaims.GetGroup: string; begin Result := TJSONUtils.GetJSONValue(CLAIM_GROUP, FJSON).AsString; end; function TServerClaims.GetLanguage: string; begin Result := TJSONUtils.GetJSONValue(CLAIM_LANGUAGE, FJSON).AsString; end; procedure TServerClaims.SetGroup(const Value: string); begin if Value = '' then TJSONUtils.RemoveJSONNode(CLAIM_GROUP, FJSON) else TJSONUtils.SetJSONValueFrom<string>(CLAIM_GROUP, Value, FJSON); end; procedure TServerClaims.SetLanguage(const Value: string); begin if Value = '' then TJSONUtils.RemoveJSONNode(CLAIM_LANGUAGE, FJSON) else TJSONUtils.SetJSONValueFrom<string>(CLAIM_LANGUAGE, Value, FJSON); end; end.
(* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * 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 TurboPower Abbrevia * * The Initial Developer of the Original Code is * Robert Love * * Portions created by the Initial Developer are Copyright (C) 1997-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) unit AbZipperTests; {$I AbDefine.inc} interface uses AbTestFrameWork, AbZipper; type TAbZipperTests = class(TAbCompTestCase) private Component : TAbZipper; protected procedure SetUp; override; procedure TearDown; override; published procedure TestDefaultStreaming; procedure TestComponentLinks; procedure BasicZipFile; procedure CreateAndTestBasicZipFile; procedure CreateAndTestBasicZipFile2; procedure CreateAndTestBasicZipFile3; procedure CreateAndTestBasicZipFile4; procedure BasicGZipTarFile; procedure BasicGZipTarFile2; procedure TestBasicForceTypeZip; procedure TestBasicForceTypeGZipTar; procedure CreatePasswordProtectedAddedByStream; procedure GZipInputStreamClearTest; procedure CreateSimplePWZip; procedure CreateMultiple; procedure TestLocale1; procedure TestLocale2; procedure TestLocale3; procedure TestLocale4; end; implementation uses {$IFDEF MSWINDOWS} Windows, {$ENDIF} Classes, SysUtils, TestFrameWork, AbArcTyp, AbUtils, AbUnZper, AbZipTyp; { TAbZipperTests } procedure TAbZipperTests.BasicGZipTarFile; var TestFileName : string; begin // This test only insure that the Gzip Tar file is created without raising errors // it is not designed to test the data in the resulting zip file. TestFileName := TestTempDir + 'basic.tgz'; Component.FileName := TestFileName; Component.BaseDirectory := TestFileDir; Component.AddFiles('*.*',faAnyFile); Component.Save; CheckFileExists(TestFileName); end; procedure TAbZipperTests.BasicGZipTarFile2; var TestFileName : string; begin TestFileName := TestTempDir + 'basic.tar.gz'; Component.FileName := TestFileName; Component.BaseDirectory := TestFileDir; Component.AddFiles('*.*',faAnyFile); Component.Save; CheckFileExists(TestFileName); end; procedure TAbZipperTests.BasicZipFile; var TestFileName : string; begin // This test only insure that the zip file is created without raising errors // it is not designed to test the data in the resulting zip file. TestFileName := TestTempDir + 'basic.zip'; Component.FileName := TestFileName; Component.BaseDirectory := TestFileDir; Component.AddFiles('*.*',faAnyFile); Component.Save; CheckFileExists(TestFileName); end; procedure TAbZipperTests.CreateAndTestBasicZipFile; var ExtractDir, TestFileName : string; AbUnZip : TAbUnZipper; begin // Test with Setting BaseDirectory and not specifying AutoSave TestFileName := TestTempDir + 'basic.zip'; if FileExists(TestFileName) then DeleteFile(TestFileName); Component.FileName := TestFileName; Component.BaseDirectory := TestFileDir; Component.AddFiles('*.*',faAnyFile); Component.Save; Component.FileName := ''; CheckFileExists(TestFileName); AbUnZip := TAbUnZipper.Create(nil); try AbUnZip.FileName := TestFileName; // Clean out old Directory and create a new one. Extractdir := TestTempDir + 'extracttest'; if DirectoryExists(ExtractDir) then DelTree(ExtractDir); CreateDir(ExtractDir); // Extract Files. AbUnZip.BaseDirectory := ExtractDir; AbUnZip.ExtractFiles('*.*'); // Compare Extracted Files CheckDirMatch(TestFileDir,ExtractDir); finally AbUnZip.Free; end; DeleteFile(TestFileName); end; procedure TAbZipperTests.CreateAndTestBasicZipFile2; var TestFileName : String; ExtractDir : String; AbUnZip : TAbUnZipper; begin // Test AutoSave and not setting BaseDirectory specify full path AddFiles TestFileName := TestTempDir + 'basic.zip'; if FileExists(TestFileName) then DeleteFile(TestFileName); Component.AutoSave := True; Component.FileName := TestFileName; Component.AddFiles(TestFileDir + '*.*',faAnyFile); Component.FileName := ''; CheckFileExists(TestFileName); AbUnZip := TAbUnZipper.Create(nil); try AbUnZip.FileName := TestFileName; // Clean out old Directory and create a new one. Extractdir := TestTempDir + 'extracttest'; if DirectoryExists(ExtractDir) then DelTree(ExtractDir); CreateDir(ExtractDir); // Extract Files. AbUnZip.BaseDirectory := ExtractDir; AbUnZip.ExtractFiles('*.*'); // Compare Extracted Files CheckDirMatch(TestFileDir,ExtractDir); finally AbUnZip.Free; end; DeleteFile(TestFileName); end; procedure TAbZipperTests.CreateAndTestBasicZipFile3; var ExtractDir, TestFileName : string; AbUnZip : TAbUnZipper; begin // Test AutoSave setting Base Directory. TestFileName := TestTempDir + 'basic.zip'; Component.AutoSave := True; Component.BaseDirectory := TestFileDir; Component.FileName := TestFileName; Component.AddFiles('*.*',faAnyFile); Component.FileName := ''; CheckFileExists(TestFileName); AbUnZip := TAbUnZipper.Create(nil); try AbUnZip.FileName := TestFileName; // Clean out old Directory and create a new one. Extractdir := TestTempDir + 'extracttest'; if DirectoryExists(ExtractDir) then DelTree(ExtractDir); CreateDir(ExtractDir); // Extract Files. AbUnZip.BaseDirectory := ExtractDir; AbUnZip.ExtractFiles('*.*'); // Compare Extracted Files CheckDirMatch(TestFileDir,ExtractDir); finally AbUnZip.Free; end; end; procedure TAbZipperTests.CreateAndTestBasicZipFile4; var ExtractDir, TestFileName : String; AbUnZip : TAbUnZipper; begin // Test AutoSave setting BaseDirectory and specifing full path to AddFiles TestFileName := TestTempDir + 'basic.zip'; Component.AutoSave := True; Component.BaseDirectory := TestTempDir; Component.FileName := TestFileName; Component.AddFiles(TestFileDir + '*.*',faAnyFile); Component.FileName := ''; CheckFileExists(TestFileName); AbUnZip := TAbUnZipper.Create(nil); try AbUnZip.FileName := TestFileName; // Clean out old Directory and create a new one. Extractdir := TestTempDir + 'extracttest'; if DirectoryExists(ExtractDir) then DelTree(ExtractDir); CreateDir(ExtractDir); // Extract Files. AbUnZip.BaseDirectory := ExtractDir; AbUnZip.ExtractFiles('*.*'); // Compare Extracted Files CheckDirMatch(TestFileDir,ExtractDir); finally AbUnZip.Free; end; end; procedure TAbZipperTests.SetUp; begin inherited; Component := TAbZipper.Create(nil); end; procedure TAbZipperTests.TearDown; begin Component.Free; inherited; end; procedure TAbZipperTests.TestBasicForceTypeGZipTar; var TestFileName : string; begin TestFileName := TestTempDir + 'basicGzipTar'; Component.ArchiveType := atGzippedTar; Component.ForceType := True; Component.FileName := TestFileName; Component.BaseDirectory := TestFileDir; Component.AddFiles('*.*',faAnyFile); Component.Save; CheckFileExists(TestFileName); end; procedure TAbZipperTests.TestBasicForceTypeZip; var TestFileName : string; begin TestFileName := TestTempDir + 'basic'; Component.ArchiveType := atZip; Component.ForceType := True; Component.FileName := TestFileName; Component.BaseDirectory := TestFileDir; Component.AddFiles('*.*',faAnyFile); Component.Save; CheckFileExists(TestFileName); end; procedure TAbZipperTests.TestComponentLinks; begin TestComponentLink(Component, 'ArchiveProgressMeter', TAbTestMeter); TestComponentLink(Component, 'ArchiveSaveProgressMeter', TAbTestMeter); TestComponentLink(Component, 'ItemProgressMeter', TAbTestMeter); end; procedure TAbZipperTests.TestDefaultStreaming; begin inherited TestDefaultStreaming(Component); end; procedure TAbZipperTests.CreatePasswordProtectedAddedByStream; var oFileStream : TFileStream; sZipFile : string; begin // Remove the path from the zip Component.StoreOptions := [soStripPath]; sZipFile := TestTempDir + 'PWStream.zip'; // Create the directory if it doesn't exist {$IFDEF DELPHI5} // ForceDirectories not part of Delphi 4 so assume created by hand Check(ForceDirectories(TestTempDir),'Unable to create Test Temp directory.'); {$ELSE} Check(DirectoryExists(TestTempDir),'Test Temp Directory needs to be created.'); {$ENDIF} // File we need to zip Component.FileName := sZipFile; // Password protect the source file // Component.Password := 'password'; oFileStream := TFileStream.Create(MPLDir + 'MPL-1_1.txt', fmOpenRead or fmShareDenyNone); try // Add file to the zip file Component.AddFromStream('file.ext', oFileStream); Component.Save; finally oFileStream.Free; end; CheckFileExists(sZipFile); end; procedure TAbZipperTests.GZipInputStreamClearTest; // [ 820489 ] CloseArchive does not close input stream var fs,fs2 : TFileStream; extractFilename, filename : string; unzip : TAbUnZipper; begin fs := TFileStream.Create(MPLDir + 'MPL-1_1.txt',fmOpenRead); try filename := TestTempDir + 'clearinputstr.gz'; if FileExists(filename) then DeleteFile(fileName); Component.ForceType := true; Component.ArchiveType := atGzip; Component.FileName := FileName; Fs.Position := 0; Component.AddFromStream('', fs); Component.Save; Component.CloseArchive; if FileExists(filename) then DeleteFile(fileName); Component.ForceType := true; Component.ArchiveType := atGzip; Component.FileName := FileName; Fs.Position := 0; Component.AddFromStream('', fs); Component.Save; Component.CloseArchive; //Check Archive for match unzip := TAbUnZipper.Create(nil); try extractFilename := TestTempDir + 'extractmpl.txt'; unzip.FileName := filename; unzip.ExtractAt(0,extractFileName); finally unzip.free; end; fs2 := TFileStream.Create(extractFilename, fmOpenRead); try CheckStreamMatch(fs, fs2, 'Extracted file does not match original'); finally fs2.free; end; finally fs.free; end; end; procedure TAbZipperTests.CreateSimplePWZip; var TestFile : string; begin // This is to address a problem where archives where not created at all // when a password is used. It is not designed to test if the archive // is extractable. Another test should be written for that. TestFile := TestTempDir + 'simplepw.zip'; if FileExists(TestFile) then DeleteFile(TestFile); Component.Password := 'simple'; Component.StoreOptions := []; Component.BaseDirectory := MPLDir; Component.FileName := TestFile; Component.AddFiles('MPL-1_1.txt',0); Component.Save; Component.CloseArchive; //Current Actual Size 9151 (Could change if we change default compresion so not testing for it) Check(AbFileGetSize(TestFile) > 8000, TestFile + ' too small check if created correctly'); end; procedure TAbZipperTests.CreateMultiple; var I : Integer; SL : TStringList; begin SL := TStringList.Create; SL.Add('Test File Test File Test File Test File'); SL.Add('Test File Test File Test File Test File'); SL.Add('Test File Test File Test File Test File'); SL.Add('Test File Test File Test File Test File'); SL.Add('Test File Test File Test File Test File'); SL.Add('Test File Test File Test File Test File'); SL.Add('Test File Test File Test File Test File'); for I := 0 to 30 do begin SL.SaveToFile(TestTempDir + 'multi' + IntToStr(I) + '.txt'); Component.DeflationOption := doMaximum; Component.BaseDirectory := TestTempDir; Component.FileName := TestTempDir + 'multi' + IntToStr(I) + '.zip'; Component.AddFiles(TestTempDir + 'multi' + IntToStr(I) + '.txt',0); Component.Save; Component.CloseArchive; end; Check(True); //TODO: Replace this with a proper test end; procedure TAbZipperTests.TestLocale1; var ltestdir, ltestfile : string; begin // This test verifies use Ability to use Charactes such as ãëíõú // In the Archive Directory Name // 236 changes into a ? on my machine in the delphi editor // so I thought it would be a good character to test with ltestdir := TestTempDir + chr(236) + 'ãëíõú'; ForceDirectories(ltestDir); ltestFile := lTestdir + PathDelim + 'locale1.zip'; if FileExists(lTestFile) then DeleteFile(lTestFile); Component.FileName := lTestFile; Component.BaseDirectory := MPLDir; Component.AddFiles('MPL-1_1.txt',0); Component.Save; CheckFileExists(lTestFile); end; procedure TAbZipperTests.TestLocale2; var ltestdir, ltestfile : string; begin // This test verifies use Ability to use Charactes such as ãëíõú // In the Archive File Name ltestdir := TestTempDir; ForceDirectories(ltestDir); // 236 changes into a ? on my machine in the delphi editor // so I thought it would be a good character to test with ltestFile := lTestdir + chr(236)+ 'ãëíõú.zip'; if FileExists(lTestFile) then DeleteFile(lTestFile); Component.FileName := lTestFile; Component.BaseDirectory := MPLDir; Component.AddFiles('MPL-1_1.txt',0); Component.Save; CheckFileExists(lTestFile); end; procedure TAbZipperTests.TestLocale3; var lBaseDir, ltestdir, ltestfile : string; begin // This test verifies use Ability to use Charactes such as ãëíõú // In the BaseDirectory ltestdir := TestTempDir; ForceDirectories(ltestDir); ltestFile := lTestdir + 'locale3.zip'; if FileExists(lTestFile) then DeleteFile(lTestFile); // 236 changes into a ? on my machine in the delphi editor // so I thought it would be a good character to test with lBaseDir := TestTempDir + chr(236) + 'ãëíõú' + PathDelim; ForceDirectories(lBaseDir); CreateDummyFile(lBaseDir + 'test1.lc3', 4000); CreateDummyFile(lBaseDir + 'test2.lc3', 6000); CreateDummyFile(lBaseDir + 'test3.lc3', 1000); Component.FileName := lTestFile; Component.BaseDirectory := lBaseDir; Component.AddFiles('*.lc3',0); Component.Save; CheckFileExists(lTestFile); end; procedure TAbZipperTests.TestLocale4; var ltestdir : string; ltestfile : string; lBaseDir : string; begin // This test verifies use Ability to use Charactes such as ãëíõú // In the Zip Archive Files (Base directory also has character in it) ltestdir := TestTempDir; ForceDirectories(ltestDir); ltestFile := lTestdir + 'locale4.zip'; if FileExists(lTestFile) then DeleteFile(lTestFile); //236 changes into a ? on my machine in the delphi editor // so I thought it would be a good character to test with lBaseDir := TestTempDir + chr(236) + 'ãëíõú' + PathDelim; ForceDirectories(lBaseDir); CreateDummyFile(lBaseDir + 'testãëíõú1.lc4',4000); CreateDummyFile(lBaseDir + 'testãëíõú2.lc4',6000); CreateDummyFile(lBaseDir + 'testãëíõú3.lc4',1000); Component.FileName := lTestFile; Component.BaseDirectory := lBaseDir; Component.AddFiles('*.lc4',0); Component.Save; CheckFileExists(lTestFile); end; initialization TestFramework.RegisterTest('Abbrevia.Component Level Test Suite', TAbZipperTests.Suite); end.
(* Name: UfrmBitmapEditorText Copyright: Copyright (C) SIL International. Documentation: Description: Create Date: 14 Sep 2006 Modified Date: 24 Jul 2015 Authors: mcdurdin Related Files: Dependencies: Bugs: Todo: Notes: History: 14 Sep 2006 - mcdurdin - Initial version 19 Nov 2007 - mcdurdin - I1157 - const string parameters 18 May 2012 - mcdurdin - I3306 - V9.0 - Remove TntControls + Win9x support 24 Jul 2015 - mcdurdin - I4796 - Refresh Keyman Developer look and feel for release *) unit UfrmBitmapEditorText; // I3306 // I4796 interface uses System.UITypes, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ClearTypeDrawCharacter, UfrmTike; type TBitmapEditorTextDrawPreviewEvent = procedure(ADisplayQuality: TClearTypeDisplayQuality; AInsertFont: TFont; AInsertText: WideString) of object; TfrmBitmapEditorText = class(TTIKEForm) editText: TEdit; lblText: TLabel; cmdOK: TButton; cmdCancel: TButton; dlgFont: TFontDialog; cbDisplayQuality: TComboBox; lblFont: TLabel; editFont: TEdit; lblQuality: TLabel; cmdFont: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure cbDisplayQualityClick(Sender: TObject); procedure editTextChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure cmdFontClick(Sender: TObject); procedure dlgFontApply(Sender: TObject; Wnd: HWND); private FInsertFont: TFont; FOnDrawPreview: TBitmapEditorTextDrawPreviewEvent; FDisplayQuality: TClearTypeDisplayQuality; FExcludeDisplayRect: TRect; procedure EnableControls; function GetInsertText: WideString; procedure SetInsertText(Value: WideString); procedure SetInsertFont(const Value: TFont); procedure DrawPreview; procedure SetDisplayQuality(const Value: TClearTypeDisplayQuality); { Private declarations } public { Public declarations } property DisplayQuality: TClearTypeDisplayQuality read FDisplayQuality write SetDisplayQuality; property InsertText: WideString read GetInsertText write SetInsertText; property InsertFont: TFont read FInsertFont write SetInsertFont; property ExcludeDisplayRect: TRect read FExcludeDisplayRect write FExcludeDisplayRect; property OnDrawPreview: TBitmapEditorTextDrawPreviewEvent read FOnDrawPreview write FOnDrawPreview; end; implementation uses UFixFontDialogBold, UframeBitmapEditor; {$R *.dfm} { TfrmBitmapEditorText } procedure TfrmBitmapEditorText.FormCreate(Sender: TObject); begin inherited; FInsertFont := TFont.Create; end; procedure TfrmBitmapEditorText.FormDestroy(Sender: TObject); begin FInsertFont.Free; end; procedure TfrmBitmapEditorText.FormShow(Sender: TObject); var X, Y: Integer; r: TRect; begin X := (Screen.Width - Width) div 2; Y := (Screen.Height - Height) div 2; r := Rect(X, Y, X+Width, Y+Height); if IntersectRect(r, FExcludeDisplayRect, r) then begin r := FExcludeDisplayRect; OffsetRect(r, -4, -4); Inc(r.Right, 8); Inc(r.Bottom, 8); if r.Bottom + Height > Screen.Height then if r.Top - Height < 0 then if r.Right + Width > Screen.Width then if r.Left - Width < 0 then // Don't move the dialog from center, because it will always overlap the editor else X := r.Left - Width else X := r.Right else Y := r.Top - Height else Y := r.Bottom; end; SetBounds(X, Y, Width, Height); DrawPreview; end; function TfrmBitmapEditorText.GetInsertText: WideString; begin Result := editText.Text; end; procedure TfrmBitmapEditorText.cbDisplayQualityClick(Sender: TObject); begin FDisplayQuality := TClearTypeDisplayQuality(cbDisplayQuality.ItemIndex); DrawPreview; end; procedure TfrmBitmapEditorText.DrawPreview; begin if Assigned(FOnDrawPreview) then FOnDrawPreview(DisplayQuality, InsertFont, InsertText); end; procedure TfrmBitmapEditorText.editTextChange(Sender: TObject); begin DrawPreview; EnableControls; end; procedure TfrmBitmapEditorText.EnableControls; begin cmdOK.Enabled := InsertText <> ''; end; procedure TfrmBitmapEditorText.SetDisplayQuality(const Value: TClearTypeDisplayQuality); begin FDisplayQuality := Value; cbDisplayQuality.ItemIndex := Ord(FDisplayQuality); DrawPreview; end; procedure TfrmBitmapEditorText.SetInsertFont(const Value: TFont); function FontDetailsToString(Font: TFont): WideString; begin Result := Font.Name + ', ' + IntToStr(Abs(Font.Size)) + 'pt'; if fsBold in Font.Style then Result := 'Bold '+Result; if fsItalic in Font.Style then Result := 'Italic '+Result; if fsUnderline in Font.Style then Result := 'Underline '+Result; if fsStrikeOut in Font.Style then Result := 'Strikethrough '+Result; end; begin FInsertFont.Assign(Value); editText.Font := FInsertFont; editFont.Text := FontDetailsToString(Value); DrawPreview; end; procedure TfrmBitmapEditorText.SetInsertText(Value: WideString); begin editText.Text := Value; DrawPreview; end; procedure TfrmBitmapEditorText.cmdFontClick(Sender: TObject); begin dlgFont.Font := FInsertFont; if dlgFont.Execute then InsertFont := FixFontDialogBold(dlgFont.Font); end; procedure TfrmBitmapEditorText.dlgFontApply(Sender: TObject; Wnd: HWND); begin InsertFont := FixFontDialogBold(dlgFont.Font); end; end.
unit MD_CSV_ABTRAAntaq; interface uses MD_CET_TRP_ABTRAAntaq, XMLDoc, XMLIntf, ActiveX, SysUtils, Contnrs, Classes, HTTPApp; type CSV_ABTRAAntaq = class(TObject) private AIM_CET_TRP_ContainerCargaPerigosa : CET_TRP_ContainerCargaPerigosa; AIM_CodigoRetorno: string; AIM_MensagemRetorno: string; function MIM_XMLToSOAPEnv(prstXML: string): string; public procedure MSV_AddContainerCargaPerigosa(prstAltura: string; prstBloco: string; prstConteiner: string; prstISOCode: string; prstLastro: string; prstPeso: string; prstPilha: string; prstQuadra: string; prinSituacao: Integer; prstTerminal: string); function MSV_AddNCM(prstCodigo: string; prstDescricao: string): Integer; function MSV_AddCargaPerigosa(prstClassificacao: string; prstDescricao: string; prstEspecificacao: string; prstONU: string): Integer; procedure MSV_Limpar(); function MAC_SetXMLRetorno(prstXML: string): string; function MAC_GetXMLEnvio(): string; function MAC_GetCodigoRetorno():string; function MAC_GetMensagemRetorno():string; constructor create; destructor destroy; override; end; implementation { CSV_ABTRAAntaq } constructor CSV_ABTRAAntaq.create; begin AIM_CET_TRP_ContainerCargaPerigosa := nil; AIM_CodigoRetorno := ''; AIM_MensagemRetorno := ''; end; destructor CSV_ABTRAAntaq.destroy; begin AIM_CET_TRP_ContainerCargaPerigosa.Free; inherited; end; procedure CSV_ABTRAAntaq.MSV_AddContainerCargaPerigosa(prstAltura: string; prstBloco: string; prstConteiner: string; prstISOCode: string; prstLastro: string; prstPeso: string; prstPilha: string; prstQuadra: string; prinSituacao: Integer; prstTerminal: string); begin AIM_CET_TRP_ContainerCargaPerigosa := CET_TRP_ContainerCargaPerigosa.Create(prstAltura, prstBloco, prstConteiner, prstISOCode, prstLastro, prstPeso, prstPilha, prstQuadra, prinSituacao, prstTerminal); end; function CSV_ABTRAAntaq.MSV_AddNCM(prstCodigo, prstDescricao: string): Integer; begin Result := -1; //TO DO cNULL_INTEGER if Assigned(AIM_CET_TRP_ContainerCargaPerigosa) then Result := AIM_CET_TRP_ContainerCargaPerigosa.MSV_AddNCM(CET_TRP_NCM.Create(prstCodigo, prstDescricao)); end; function CSV_ABTRAAntaq.MSV_AddCargaPerigosa(prstClassificacao: string; prstDescricao: string; prstEspecificacao: string; prstONU: string): Integer; begin Result := -1; //TO DO cNULL_INTEGER if Assigned(AIM_CET_TRP_ContainerCargaPerigosa) then Result := AIM_CET_TRP_ContainerCargaPerigosa.MSV_AddCargaPerigosa(CET_TRP_CargaPerigosa.Create(prstClassificacao, prstDescricao, prstEspecificacao, prstONU)); end; procedure CSV_ABTRAAntaq.MSV_Limpar; begin if Assigned(AIM_CET_TRP_ContainerCargaPerigosa) then AIM_CET_TRP_ContainerCargaPerigosa.Free; AIM_CET_TRP_ContainerCargaPerigosa := nil; AIM_CodigoRetorno := ''; AIM_MensagemRetorno := ''; end; function CSV_ABTRAAntaq.MAC_GetXMLEnvio: string; var lXMLDoc : IXMLDocument; lNodeCadastrar: IXMLNode; lNodeConteinerCargaPerigosa: IXMLNode; lNodeCargas: IXMLNode; lNodeCargaPerigosa: IXMLNode; lNodeListaNCM: IXMLNode; lNodeNCM: IXMLNode; lNodeAux: IXMLNode; linContador : Integer; begin Result := ''; if Assigned(AIM_CET_TRP_ContainerCargaPerigosa) then begin lXMLDoc := NewXMLDocument(''); lXMLDoc.Active := True; lXMLDoc.Encoding := 'UTF-8'; lNodeCadastrar := lXMLDoc.CreateElement('Cadastrar', ''); lXMLDoc.DocumentElement := lNodeCadastrar; lNodeConteinerCargaPerigosa := lNodeCadastrar.AddChild('conteinercargaperigosa'); lNodeAux := lNodeConteinerCargaPerigosa.AddChild('Altura'); lNodeAux.Text:= AIM_CET_TRP_ContainerCargaPerigosa.Altura; lNodeAux := lNodeConteinerCargaPerigosa.AddChild('Bloco'); lNodeAux.Text:= AIM_CET_TRP_ContainerCargaPerigosa.Bloco; lNodeCargas := lNodeConteinerCargaPerigosa.AddChild('Cargas'); for linContador := 0 to Length(AIM_CET_TRP_ContainerCargaPerigosa.Cargas)-1 do begin lNodeCargaPerigosa := lNodeCargas.AddChild('cargaperigosa'); lNodeAux := lNodeCargaPerigosa.AddChild('Classificacao'); lNodeAux.Text := (AIM_CET_TRP_ContainerCargaPerigosa.Cargas[linContador] as CET_TRP_CargaPerigosa).Classificacao; lNodeAux := lNodeCargaPerigosa.AddChild('Descricao'); lNodeAux.Text := (AIM_CET_TRP_ContainerCargaPerigosa.Cargas[linContador] as CET_TRP_CargaPerigosa).Descricao; lNodeAux := lNodeCargaPerigosa.AddChild('Especificacao'); lNodeAux.Text := (AIM_CET_TRP_ContainerCargaPerigosa.Cargas[linContador] as CET_TRP_CargaPerigosa).Especificacao; lNodeAux := lNodeCargaPerigosa.AddChild('Onu'); lNodeAux.Text := (AIM_CET_TRP_ContainerCargaPerigosa.Cargas[linContador] as CET_TRP_CargaPerigosa).Onu; end; lNodeAux := lNodeConteinerCargaPerigosa.AddChild('Conteiner'); lNodeAux.Text:= AIM_CET_TRP_ContainerCargaPerigosa.Conteiner; ; lNodeAux := lNodeConteinerCargaPerigosa.AddChild('IsoCode'); lNodeAux.Text:= AIM_CET_TRP_ContainerCargaPerigosa.ISOCode; lNodeAux := lNodeConteinerCargaPerigosa.AddChild('Lastro'); lNodeAux.Text:= AIM_CET_TRP_ContainerCargaPerigosa.Lastro; lNodeListaNCM := lNodeConteinerCargaPerigosa.AddChild('ListaNCM'); for linContador := 0 to Length(AIM_CET_TRP_ContainerCargaPerigosa.ListaNCM)-1 do begin lNodeNCM := lNodeListaNCM.AddChild('ncm'); lNodeAux := lNodeNCM.AddChild('Codigo'); lNodeAux.Text := (AIM_CET_TRP_ContainerCargaPerigosa.ListaNCM[linContador] as CET_TRP_NCM).Codigo; lNodeAux := lNodeNCM.AddChild('Descricao'); lNodeAux.Text := (AIM_CET_TRP_ContainerCargaPerigosa.ListaNCM[linContador] as CET_TRP_NCM).Descricao; end; lNodeAux := lNodeConteinerCargaPerigosa.AddChild('Peso'); lNodeAux.Text:= AIM_CET_TRP_ContainerCargaPerigosa.Peso; lNodeAux := lNodeConteinerCargaPerigosa.AddChild('Pilha'); lNodeAux.Text:= AIM_CET_TRP_ContainerCargaPerigosa.Pilha; lNodeAux := lNodeConteinerCargaPerigosa.AddChild('Quadra'); lNodeAux.Text:= AIM_CET_TRP_ContainerCargaPerigosa.Quadra; lNodeAux := lNodeConteinerCargaPerigosa.AddChild('Situacao'); // lNodeAux.Text:= '0';//TO DO AIM_CET_TRP_ContainerCargaPerigosa.inSituacao; lNodeAux := lNodeConteinerCargaPerigosa.AddChild('Terminal'); lNodeAux.Text:= AIM_CET_TRP_ContainerCargaPerigosa.Terminal; Result :=lXMLDoc.XML.Text; Result := MIM_XMLToSOAPEnv(Result); end; end; function CSV_ABTRAAntaq.MAC_SetXMLRetorno(prstXML: string): string; var lXMLDoc : IXMLDocument; lXMLNodeEnvelope : IXMLNode; lXMLNodeBody : IXMLNode; lXMLNodeResponse : IXMLNode; lXMLNodeCadastrarResult : IXMLNode; lXMLNodeAux: IXMLNode; lXMLNodeFault: IXMLNode; lstCodigo: string; lstMensagem: string; lstErro: string; begin lstErro := ''; lstCodigo := ''; lstMensagem := ''; if prstXML <> '' then begin try lXMLDoc := LoadXMLData(prstXML); except on E: Exception do lstErro := E.Message; end; end; if lstErro = '' then begin lXMLNodeEnvelope := lXMLDoc.DocumentElement; lXMLNodeBody := lXMLNodeEnvelope.ChildNodes.Get(0); lXMLNodeResponse := lXMLNodeBody.ChildNodes.Get(0); lXMLNodeAux := lXMLNodeResponse.ChildNodes.Get(0); if lXMLNodeAux.NodeName = 'CadastrarResult' then begin lXMLNodeCadastrarResult := lXMLNodeAux.ChildNodes.Get(0); lstCodigo := lXMLNodeCadastrarResult.Text; lXMLNodeCadastrarResult := lXMLNodeAux.ChildNodes.Get(1); lstMensagem := lXMLNodeCadastrarResult.Text; end else begin lXMLNodeFault := lXMLNodeResponse.ChildNodes.Get(0);; lstCodigo := lXMLNodeFault.Text; lXMLNodeFault := lXMLNodeResponse.ChildNodes.Get(1); lstMensagem := lXMLNodeFault.Text; end; end; AIM_CodigoRetorno := lstCodigo; AIM_MensagemRetorno := lstMensagem; Result := lstErro; end; function CSV_ABTRAAntaq.MIM_XMLToSOAPEnv(prstXML: string): string; var ltsAux: TStringList; begin ltsAux := TStringList.Create(); ltsAux.Text := prstXML; ltsAux.Delete(0); prstXML := ltsAux.Text; ltsAux.Free; Result := '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">'; Result := Result + '<soapenv:Header/>'; Result := Result + '<soapenv:Body>'; Result := Result + prstXML; Result := Result + '</soapenv:Body>'; Result := Result + '</soapenv:Envelope>'; end; function CSV_ABTRAAntaq.MAC_GetCodigoRetorno: string; begin Result := AIM_CodigoRetorno; end; function CSV_ABTRAAntaq.MAC_GetMensagemRetorno: string; begin Result := AIM_MensagemRetorno; end; end.
unit rfNoCashGroupForm_Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Front_DataBase_Unit, FrontData_Unit, BaseFrontForm_Unit, ExtCtrls, AdvPanel, AdvSmoothButton, ActnList, kbmMemTable, DB, Contnrs, AdvSmoothToggleButton, AdvStyleIF; type TrfNoCashGroup = class(TBaseFrontForm) pnlBottom: TAdvPanel; pnlRight: TAdvPanel; pnlMain: TAdvPanel; btnExit: TAdvSmoothButton; aclPayGroup: TActionList; actGroupUp: TAction; actGroupDown: TAction; btnScrollDown: TAdvSmoothButton; btnScrollUp: TAdvSmoothButton; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure actGroupUpExecute(Sender: TObject); procedure actGroupUpUpdate(Sender: TObject); procedure actGroupDownExecute(Sender: TObject); procedure actGroupDownUpdate(Sender: TObject); private FMemTable: TkbmMemTable; // FFirstTopButton : Integer; FLastLeftButton : Integer; FLastTopButton : Integer; FGroupButtonNumber: Integer; // FButtonList : TObjectList; FNoFiscal: Integer; FPayTypeKey: Integer; FCurrentPayName: String; FExternalPay: Boolean; procedure AddButton; procedure ScrollControl(const FControl: TWinControl; const Down: Boolean; var Top: Integer; var Bottom: Integer); procedure PayFormButtonOnClick(Sender: TObject); public property PayTypeKey: Integer read FPayTypeKey write FPayTypeKey; property CurrentPayName: String read FCurrentPayName write FCurrentPayName; property NoFiscal: Integer read FNoFiscal write FNoFiscal; property ExternalPay: Boolean read FExternalPay write FExternalPay; end; const btnHeight = 51; btnWidth = 145; var rfNoCashGroup: TrfNoCashGroup; implementation uses PayForm_Unit; {$R *.dfm} procedure TrfNoCashGroup.actGroupDownExecute(Sender: TObject); begin LockWindowUpdate(Self.Handle); try ScrollControl(pnlMain, True, FFirstTopButton, FLastTopButton); finally LockWindowUpdate(0); end; end; procedure TrfNoCashGroup.actGroupDownUpdate(Sender: TObject); begin actGroupDown.Enabled := (FLastTopButton + btnHeight > pnlMain.Height); end; procedure TrfNoCashGroup.actGroupUpExecute(Sender: TObject); begin LockWindowUpdate(Self.Handle); try ScrollControl(pnlMain, False, FFirstTopButton, FLastTopButton); finally LockWindowUpdate(0); end; end; procedure TrfNoCashGroup.actGroupUpUpdate(Sender: TObject); begin actGroupUp.Enabled := (FFirstTopButton > 8); end; procedure TrfNoCashGroup.AddButton; var FButton: TAdvSmoothToggleButton; begin //Создание кнопки FButton := TAdvSmoothToggleButton.Create(nil); // FButton.AllowAllUp := True; FButton.Parent := pnlMain; FButton.OnClick := PayFormButtonOnClick; FButton.Name := Format('btnPayForm%d', [FGroupButtonNumber]); FButton.GroupIndex := 1; FButton.Height := 51; FButton.Width := 145; FButton.Appearance.Font.Name := cn_FontType; FButton.Appearance.Font.Size := cn_ButtonFontSize; FButton.SetComponentStyle(tsOffice2007Silver); //проверяем, есть ли ещё место в ряду if (FLastLeftButton + btnWidth) > pnlMain.Width then begin FLastTopButton := FLastTopButton + btnHeight + 8; FLastLeftButton := 8; FButton.Left := FLastLeftButton; FButton.Top := FLastTopButton; end else begin FButton.Left := FLastLeftButton; FButton.Top := FLastTopButton; end; FButton.Tag := FMemTable.FieldByName('ID').AsInteger; FButton.Caption := FMemTable.FieldByName('NAME').AsString; FLastLeftButton := FLastLeftButton + btnWidth + 10; FButtonList.Add(FButton); Inc(FGroupButtonNumber); end; procedure TrfNoCashGroup.FormClose(Sender: TObject; var Action: TCloseAction); begin FMemTable.Free; FButtonList.Free; end; procedure TrfNoCashGroup.FormCreate(Sender: TObject); begin FFirstTopButton := 8; FLastLeftButton := 8; FLastTopButton := 8; FButtonList := TObjectList.Create; FMemTable := TkbmMemTable.Create(nil); FMemTable.FieldDefs.Add('ID', ftInteger, 0); FMemTable.FieldDefs.Add('NAME', ftString, 60); FMemTable.CreateTable; FMemTable.Open; btnScrollUp.Picture := FrontData.RestPictureContainer.FindPicture('Up'); btnScrollDown.Picture := FrontData.RestPictureContainer.FindPicture('Down'); end; procedure TrfNoCashGroup.FormShow(Sender: TObject); begin // должны отобразить виды безнальной оплаты // исходя из групп FExternalPay := False; FFrontBase.GetNoCashGroupList(FMemTable); FMemTable.First; while not FMemTable.Eof do begin AddButton; FMemTable.Next; end; end; procedure TrfNoCashGroup.PayFormButtonOnClick(Sender: TObject); var FForm: TPayForm; begin FForm := TPayForm.CreateWithFrontBase(nil, FFrontBase); FForm.PayType := TAdvSmoothToggleButton(Sender).Tag; FForm.IsPlCard := 0; ExternalPay := FFrontBase.CheckExternalPay(TAdvSmoothToggleButton(Sender).Tag); try if FFrontBase.GetPayKindType(FForm.PayFormDataSet, FForm.PayType, FForm.IsPlCard, ExternalPay) then begin if FForm.PayFormDataSet.RecordCount > 0 then begin if (FForm.PayFormDataSet.RecordCount = 1) and (not ExternalPay) then begin FPayTypeKey := FForm.PayFormDataSet.FieldByName('USR$PAYTYPEKEY').AsInteger; FCurrentPayName := FForm.PayFormDataSet.FieldByName('USR$NAME').AsString; FNoFiscal := FForm.PayFormDataSet.FieldByName('USR$NOFISCAL').AsInteger; ModalResult := mrOK; end else begin FForm.ShowModal; if FForm.ModalResult = mrOK then begin FPayTypeKey := FForm.PayFormDataSet.FieldByName('USR$PAYTYPEKEY').AsInteger; FCurrentPayName := FForm.PayFormDataSet.FieldByName('USR$NAME').AsString; FNoFiscal := FForm.PayFormDataSet.FieldByName('USR$NOFISCAL').AsInteger; ModalResult := mrOK; end; end; end; end; finally FForm.Free; end; end; procedure TrfNoCashGroup.ScrollControl(const FControl: TWinControl; const Down: Boolean; var Top, Bottom: Integer); var Step: Integer; begin Step := 0; if Down then begin while (Step < btnHeight + 8) and (Bottom + btnHeight > FControl.Height) do begin FControl.ScrollBy(0, -1); Dec(Bottom); Inc(Top); Inc(Step); end; end else begin while (Step < btnHeight + 8) and (Top > 8) do begin FControl.ScrollBy(0, 1); Inc(Bottom); Dec(Top); Inc(Step); end; end; end; end.
unit Project87.ScannerWave; interface uses Strope.Math, Project87.Types.GameObject; type TScannerWave = class (TGameObject) private FLife: Single; FMaxLife: Single; public constructor CreateWave(const APosition, AVelocity: TVector2F; AAngle, ALife: Single); procedure OnDraw; override; procedure OnUpdate(const ADelta: Double); override; procedure OnCollide(OtherObject: TPhysicalObject); override; end; implementation uses QEngine.Texture, Project87.Hero, Project87.BaseEnemy, Project87.Asteroid, Project87.Resources; {$REGION ' TScannerWave '} constructor TScannerWave.CreateWave(const APosition, AVelocity: TVector2F; AAngle, ALife: Single); begin inherited Create; FPreviosPosition := APosition; FPosition := APosition; FVelocity := AVelocity; FAngle := AAngle; FLife := ALife; FMaxLife := ALife; end; procedure TScannerWave.OnDraw; var Size: Single; begin Size := 2.2 - FLife / FMaxLife * 2; TheResources.WaveTexture.Draw(FPosition, TVector2F.Create(40 * Size, 10 * Size), FAngle, $FFFFFFFF); end; procedure TScannerWave.OnUpdate(const ADelta: Double); begin FLife := FLife - ADelta; if FLife < 0 then FIsDead := True; end; procedure TScannerWave.OnCollide(OtherObject: TPhysicalObject); begin if (OtherObject is TAsteroid) then begin FIsDead := True; TAsteroid(OtherObject).Scan; end; end; {$ENDREGION} end.
unit LS.AndroidTimer; interface uses System.Classes, Androidapi.JNI.Os, Androidapi.JNI.JavaTypes, Androidapi.JNIBridge; type TAndroidTimer = class; TTimerRunnable = class(TJavaLocal, JRunnable) private FTimer: TAndroidTimer; public { JRunnable } procedure run; cdecl; public constructor Create(ATimer: TAndroidTimer); end; TAndroidTimer = class(TObject) private FEnabled: Boolean; FHandler: JHandler; FInterval: Integer; FRunnable: JRunnable; FOnTimer: TNotifyEvent; procedure DoTimer; procedure SetEnabled(const Value: Boolean); procedure SetInterval(const Value: Integer); procedure StartTimer; procedure StopTimer; procedure TimerEvent; public constructor Create; destructor Destroy; override; property Enabled: Boolean read FEnabled write SetEnabled; property Interval: Integer read FInterval write SetInterval; property OnTimer: TNotifyEvent read FOnTimer write FOnTimer; end; implementation // Note: // As per the documentation for postDelayed: // // https://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long) // // The runnable's run method is called in the same thread as where postDelayed was called from, so there should be no // need to synchronize { TTimerRunnable } constructor TTimerRunnable.Create(ATimer: TAndroidTimer); begin inherited Create; FTimer := ATimer; end; procedure TTimerRunnable.run; begin FTimer.TimerEvent; end; { TAndroidTimer } constructor TAndroidTimer.Create; begin inherited; FInterval := 1000; FHandler := TJHandler.JavaClass.init; FRunnable := TTimerRunnable.Create(Self); end; destructor TAndroidTimer.Destroy; begin FHandler := nil; FRunnable := nil; inherited; end; procedure TAndroidTimer.DoTimer; begin if Assigned(FOnTimer) then FOnTimer(Self); end; procedure TAndroidTimer.SetEnabled(const Value: Boolean); begin if Value <> FEnabled then begin FEnabled := Value; if FEnabled then StartTimer else StopTimer; end; end; procedure TAndroidTimer.SetInterval(const Value: Integer); begin if Value <> Interval then begin if FEnabled then StopTimer; FInterval := Value; if FEnabled then StartTimer; end; end; procedure TAndroidTimer.StartTimer; begin FHandler.postDelayed(FRunnable, Interval); end; procedure TAndroidTimer.StopTimer; begin FHandler.removeCallbacks(FRunnable); end; procedure TAndroidTimer.TimerEvent; begin DoTimer; StartTimer; end; end.
program ejercicio_8; //Testeado pero por si acaso vuelvan a revisarlo ya que en algunas partes seguro puede mejorar :) type cadena=string[50]; docente=record DNI:integer; nombreCompleto:cadena; email:cadena; end; proyecto=record codigo:integer; titulo:cadena; docente:docente; cant_alumnos:integer; escuela:cadena; localidad:cadena; end; function cumple_C(cod:integer):boolean; var cant_pares,cant_impares:integer; aux:integer; begin cant_pares:=0; cant_impares:=0; while(cod<>0)do begin aux:=cod MOD 10; if((aux MOD 2)= 0) then cant_pares:=cant_pares+1 else cant_impares:=cant_impares+1; cod:=cod DIV 10; end; if(cant_pares = cant_impares)then cumple_C:=true else cumple_C:=false; end; procedure Punto_C(codigo:integer;actualLocalidad,nombre:cadena); begin if(actualLocalidad = 'Daireaux') and (cumple_C(codigo))then //Punto C writeln('Proyecto: ',nombre, ' (Cumplen la condicion del punto C)'); end; procedure Leer(var reg:proyecto); begin writeln('======================================'); writeln(' PROYECTO '); writeln('======================================'); write('Ingrese el codigo del proyecto: '); readln(reg.codigo); if(reg.codigo<>-1)then begin write('Ingrese el titulo: '); readln(reg.titulo); writeln; writeln('Datos del docente a cargo'); write('DNI: '); readln(reg.docente.DNI); write('Nombre Completo: '); readln(reg.docente.nombreCompleto); write('Email: '); readln(reg.docente.email); writeln; write('Ingrese la cantidad de alumnos: '); readln(reg.cant_alumnos); write('Ingrese el nombre de la escuela: '); readln(reg.escuela); write('Ingrese la localidad: '); readln(reg.localidad); writeln('------------------------------------'); writeln; end; end; procedure calcular_maxAlumnos(reg:proyecto;cant_alumnos:integer;var max1,max2:integer;var nombre1,nombre2:cadena;var DNI_1,DNI_2:integer); begin if(cant_alumnos>max1)then begin max2:=max1; nombre2:=nombre1; DNI_2:=DNI_1; max1:=cant_alumnos; nombre1:=reg.escuela; DNI_1:=reg.docente.DNI; end else if(cant_alumnos>max2) then begin max2:=cant_alumnos; nombre2:=reg.escuela; DNI_2:=reg.docente.DNI; end; end; var totalEscuelas:integer; reg:proyecto; actualLocalidad:cadena; totalEscuelasLocalidad:integer; actualEscuela:cadena; cantidad_alumnos:integer; max1:integer; max2:integer; nombre1:cadena; nombre2:cadena; DNI_1:integer; DNI_2:integer; reg2:proyecto; begin totalEscuelas:=0; max1:=-999; max2:=-999; nombre1:=' '; nombre2:=' '; DNI_1:= -999; // Placeholder DNI_2:=-999; // Placeholder Leer(reg); while(reg.codigo<>-1)do begin actualLocalidad:=reg.localidad; totalEscuelasLocalidad:=0; while(actualLocalidad=reg.localidad) and (reg.codigo <>-1) do begin actualEscuela:=reg.escuela; totalEscuelasLocalidad:=totalEscuelasLocalidad+1; while(actualEscuela=reg.escuela) and (actualLocalidad = reg.localidad) and (reg.codigo<>-1) do begin cantidad_alumnos:=cantidad_alumnos+reg.cant_alumnos; // Punto B Punto_C(reg.codigo,actualLocalidad,reg.titulo); //Punto C duh reg2:=reg; //Atado con alambre, en calcular_maxAlumnos si paso 'reg' estoy trabajando con datos nuevos. ERROR! Leer(reg); end; calcular_maxAlumnos(reg2,cantidad_alumnos,max1,max2,nombre1,nombre2,DNI_1,DNI_2); //Punto B cantidad_alumnos:=0; //Ya no es la misma escuela end; //Cambie de localidad totalEscuelas:=totalEscuelas+totalEscuelasLocalidad; writeln; writeln('La cantidad de escuelas en la localidad ',actualLocalidad,' es: ',totalEscuelasLocalidad); //Informo A end; writeln; writeln('La cantidad de escuelas que participaron en total de la convocatoria es: ',totalEscuelas); //Informo A parte 2 //Ahora informo B writeln('La escuela con mayor cantidad de alumnos es: ',nombre1,' (DNI de Coordinador -> ',DNI_1,')'); writeln('La segunda escuela con mayor cantidad de alumnos es: ',nombre2,' (DNI de Coordinador -> ',DNI_2,')'); readln; end.
unit shape; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FGL, props, propman; type TShapeType = (stCamera, stPointLight, stPlane, stCube, stCylinder, stSphere, stDoughnut, stLathe, stSOR, stCSG); TShape = class private _propertyManager: TPropertyManager; function GetDirty: boolean; function GetPropertyCount: integer; public constructor Create(stShape: TShapeType); destructor Destroy; override; function GetProperty(const name: string): TProperty; function GetProperty(index: integer): TProperty; class function GetShapeTypeDescription(shapeType: TShapeType): string; class function MakeCamera(const name: string): TShape; static; class function MakePointLight(const name: string): TShape; static; class function MakeGeneralShape(const name: string; shapeType: TShapeType): TShape; static; property IsDirty: boolean read GetDirty; property PropertyCount: integer read GetPropertyCount; end; TShapeTypeProperty = specialize TReadOnlyProperty<TShapeType>; TShapeList = specialize TFPGObjectList<TShape>; implementation uses vector, colour; constructor TShape.Create(stShape: TShapeType); begin _propertyManager := TPropertyManager.Create; _propertyManager.AddProperty('Type', TShapeTypeProperty.Create('Type', stShape)); _propertyManager.AddProperty('Name', TStringProperty.Create('Name')); end; destructor TShape.Destroy; begin inherited; _propertyManager.Free; end; function TShape.GetDirty: boolean; begin result := _propertyManager.IsDirty; end; function TShape.GetPropertyCount: integer; begin result := _propertyManager.Count; end; function TShape.GetProperty(const name: string): TProperty; begin result := _propertyManager.FindProperty(name); end; function TShape.GetProperty(index: integer): TProperty; begin result := _propertyManager.GetProperty(index); end; class function TShape.GetShapeTypeDescription(shapeType: TShapeType): string; begin case shapeType of stCamera: result := 'Camera'; stPointLight: result := 'Point Light'; stPlane: result := 'Plane'; stCube: result := 'Cube'; stCylinder: result := 'Cylinder'; stSphere: result := 'Sphere'; stDoughnut: result := 'Doughnut'; stLathe: result := 'Lathe'; stSOR: result := 'Solid of Revolution'; stCSG: result := 'CSG'; else result := 'Generic'; end; end; class function TShape.MakeCamera(const name: string): TShape; var shape: TShape; nameProp: TStringProperty; vectorProp: TVectorProperty; begin shape := TShape.Create(stCamera); nameProp := shape.GetProperty('Name') as TStringProperty; nameProp.Value := name; vectorProp := TVectorProperty.Create('Translation'); vectorProp.Value := TVector.Create(0.0, 0.0, 0.0); shape._propertyManager.AddProperty('Translation', vectorProp); vectorProp := TVectorProperty.Create('LookAt'); vectorProp.Value := TVector.Create(0.0, 0.0, -5.0); shape._propertyManager.AddProperty('LookAt', vectorProp); result := shape; end; class function TShape.MakePointLight(const name: string): TShape; var shape: TShape; nameProp: TStringProperty; vectorProp: TVectorProperty; colourProp: TColourProperty; begin shape := TShape.Create(stPointLight); nameProp := shape.GetProperty('Name') as TStringProperty; nameProp.Value := name; vectorProp := TVectorProperty.Create('Translation'); vectorProp.Value := TVector.Create(0.0, 0.0, 0.0); shape._propertyManager.AddProperty('Translation', vectorProp); colourProp := TColourProperty.Create('Colour'); colourProp.Value := TColour.Create(1.0, 1.0, 1.0); shape._propertyManager.AddProperty('Colour', colourProp); result := shape; end; class function TShape.MakeGeneralShape(const name: string; shapeType: TShapeType): TShape; var shape: TShape; nameProp: TStringProperty; vectorProp: TVectorProperty; colourProp: TColourProperty; begin shape := TShape.Create(shapeType); nameProp := shape.GetProperty('Name') as TStringProperty; nameProp.Value := name; vectorProp := TVectorProperty.Create('Translation'); vectorProp.Value := TVector.Create(0.0, 0.0, 0.0); shape._propertyManager.AddProperty('Translation', vectorProp); vectorProp := TVectorProperty.Create('Scale'); vectorProp.Value := TVector.Create(1.0, 1.0, 1.0); shape._propertyManager.AddProperty('Scale', vectorProp); vectorProp := TVectorProperty.Create('Rotation'); vectorProp.Value := TVector.Create(0.0, 0.0, 0.0); shape._propertyManager.AddProperty('Rotation', vectorProp); colourProp := TColourProperty.Create('Colour'); colourProp.Value := TColour.Create(1.0, 1.0, 1.0); shape._propertyManager.AddProperty('Colour', colourProp); result := shape; end; end.
unit View.MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.PlatformDefaultStyleActnCtrls, System.Actions, Vcl.ActnList, Vcl.ActnMan, Vcl.ToolWin, Vcl.ActnCtrls, Vcl.ActnMenus, Vcl.StdCtrls, Vcl.ExtCtrls, System.ImageList, Vcl.ImgList, Vcl.Buttons, JvExComCtrls, JvComCtrls, Vcl.CategoryButtons, JvExControls, JvEmbeddedForms, JvExExtCtrls, JvExtComponent, JvPanel, JvComponentBase, JvExStdCtrls, JvEdit, JvCheckBox, JvListBox, JvLabel, JvXPBar, JvXPCore, JvXPContainer, JvSplitter, Model.Interfaces, Model.ProSu.Interfaces, Model.Main, ViewModel.Main, Model.ProSu.Subscriber, Model.ProSu.InterfaceActions, JvSpeedButton, JvMenus, Vcl.Menus, JvActionsEngine, JvControlActions, Model.FormDeclarations, Model.Fabrication, JvFormPlacement, JvXPButtons, TB2Item, TB2Dock, TB2Toolbar, JvCombobox, JvImageList, Vcl.DBActns, Vcl.Mask, JvExMask, JvToolEdit; type TMainForm = class(TForm) ImageList16: TImageList; ImageList32: TImageList; ImageList64: TImageList; ImageList24: TImageList; ActionList1: TActionList; actViewPersonelGridForm: TAction; actStartEmployeeRecruitment: TAction; actStartEmployeeJobTermination: TAction; actPayrollScoringEntryForm: TAction; actPayrollOtherIncomesCutsEntryForm: TAction; actPayrollChangeYearPeriod: TAction; actPayrollExamine: TAction; actPayrollClosePeriod: TAction; actCurrencyDaily: TAction; actCurrency: TAction; actParamsGeneralParameters: TAction; actParamsCompanyParameters: TAction; actRepPayrollReportWideDlg: TAction; actRepPayrollReportLaserDlg: TAction; actRepEnvelopeDumpDlg: TAction; actRepPayrollCompendiumDlg: TAction; actRepPersonelWageListDlg: TAction; actRepPersonnelTimekeepingListDlg: TAction; actRepSocialPaymentsListDlg: TAction; actRepOtherPaymentsListDlg: TAction; actRepOtherCutsListDlg: TAction; actRepMonthlySGKPremiumsDeclarationReportDlg: TAction; actRepDeclarationReportOfSocialSecurityPremiumSupportDlg: TAction; actRepAFour_monthInsurancePremiumsPayrollReportDlg: TAction; actRepSGKPremiumsReportDlg: TAction; actRepUserDefinedReportsDlg: TAction; actPayrollCalculation: TAction; actPayrollTransferToGeneralLedger: TAction; actPayrollTotalIncomeTaxBaseEntry: TAction; actParamsBankEntry: TAction; actParamsCityEntry: TAction; actParamsCountryEntry: TAction; actParamsDepartmentEntry: TAction; actParamsLanguageEntry: TAction; actParamsLocationEntry: TAction; actParamsOthIncomeCutsEntry: TAction; actParamsRelationshipTypeEntry: TAction; actParamsTitleEntry: TAction; actParamsTownEntry: TAction; actOpsDatabaseConnectionOptions: TAction; actOpsProgramOptions: TAction; actCompanyList: TAction; actSecUser: TAction; actSecPermission: TAction; actSecGroup: TAction; actSecRole: TAction; ActionManager1: TActionManager; JvFormStorage1: TJvFormStorage; ActionMainMenuBar1: TActionMainMenuBar; JvPanel1: TJvPanel; Panel2: TPanel; Splitter1: TSplitter; Panel1: TPanel; catbtnLeftMenu: TCategoryButtons; TBDock1: TTBDock; tbtTableActions: TTBToolbar; tbiDelete: TTBItem; tbiEdit: TTBItem; tbiAdd: TTBItem; ActImageList16: TImageList; tbiFind: TTBItem; tbiView: TTBItem; tbiPrint: TTBItem; tbtEditActions: TTBToolbar; tbiSaveAsTemplate: TTBItem; tbiCancel: TTBItem; tbiSave: TTBItem; TBSubmenuItem1: TTBSubmenuItem; btiDeactivateFilter: TTBItem; btiActivateFilter: TTBItem; tbiDefineFilter: TTBItem; tbiRefresh: TTBItem; actFirst: TAction; actPrior: TAction; actNext: TAction; actLast: TAction; actInsert: TAction; actDelete: TAction; actEdit: TAction; actPost: TAction; actCancel: TAction; actRefresh: TAction; actShowDetail: TAction; actFind: TAction; actPrint: TAction; actSaveAsTemplate: TAction; actActivateFilter: TAction; actBuildFilter: TAction; actDeactivateFilter: TAction; TBItem2: TTBItem; actFormClose: TAction; actUndelete: TAction; tbiUndelete: TTBItem; actCreateDatabase: TAction; tbtCompany: TTBToolbar; TBControlItem2: TTBControlItem; TBControlItem1: TTBControlItem; TBItem1: TTBItem; cbxCurrentPeriod: TJvComboBox; cbxCurrentYear: TJvComboBox; edSelectCompany: TJvComboEdit; TBControlItem3: TTBControlItem; actSecLogin: TAction; actSecAuthorize: TAction; tbtLogin: TTBToolbar; TBItem3: TTBItem; TBItem4: TTBItem; actSecLogout: TAction; JvEmbeddedFormPanel1: TJvEmbeddedFormPanel; procedure actTahakkuklarExecute(Sender: TObject); procedure actCreateDatabaseExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure actParamsCountryEntryExecute(Sender: TObject); procedure actViewPersonelGridFormExecute(Sender: TObject); procedure actFirstExecute(Sender: TObject); procedure actPriorExecute(Sender: TObject); procedure actNextExecute(Sender: TObject); procedure actLastExecute(Sender: TObject); procedure actInsertExecute(Sender: TObject); procedure actDeleteExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure actPostExecute(Sender: TObject); procedure actCancelExecute(Sender: TObject); procedure actRefreshExecute(Sender: TObject); procedure actShowDetailExecute(Sender: TObject); procedure actFindExecute(Sender: TObject); procedure actPrintExecute(Sender: TObject); procedure actSaveAsTemplateExecute(Sender: TObject); procedure actActivateFilterExecute(Sender: TObject); procedure actBuildFilterExecute(Sender: TObject); procedure actDeactivateFilterExecute(Sender: TObject); procedure actPayrollScoringEntryFormExecute(Sender: TObject); procedure actCompanyListExecute(Sender: TObject); procedure actUndeleteExecute(Sender: TObject); procedure edSelectCompanyButtonClick(Sender: TObject); procedure JvFormStorage1BeforeSavePlacement(Sender: TObject); procedure JvFormStorage1RestorePlacement(Sender: TObject); procedure cbxCurrentYearChange(Sender: TObject); procedure actParamsCityEntryExecute(Sender: TObject); procedure actParamsTownEntryExecute(Sender: TObject); procedure actParamsLocationEntryExecute(Sender: TObject); procedure actParamsLanguageEntryExecute(Sender: TObject); procedure actParamsDepartmentEntryExecute(Sender: TObject); procedure actParamsTitleEntryExecute(Sender: TObject); procedure actParamsBankEntryExecute(Sender: TObject); procedure actCurrencyExecute(Sender: TObject); procedure actSecLoginExecute(Sender: TObject); procedure actSecLogoutExecute(Sender: TObject); procedure actSecPermissionExecute(Sender: TObject); procedure actSecUserExecute(Sender: TObject); procedure actParamsRelationshipTypeEntryExecute(Sender: TObject); procedure actParamsOthIncomeCutsEntryExecute(Sender: TObject); procedure actSecGroupExecute(Sender: TObject); procedure actSecRoleExecute(Sender: TObject); private fSubscriber: ISubscriberInterface; fMainModel : IMainModelInterface; //TMainModel; fViewModel : IMainViewModelInterface; // TMainViewModel; procedure SetViewModel(const newViewModel: IMainViewModelInterface); procedure UpdateLabels; procedure NotificationFromProvider(const notifyClass : INotificationClass); procedure ActivateNewForm(const name : string); procedure SendActionMessageToActiveForm(aMsg : TBrowseFormCommand); public property ViewModel: IMainViewModelInterface read fViewModel write SetViewModel; end; var MainForm: TMainForm; implementation uses View.TemplateForm, Model.Declarations, Model.LanguageDictionary, View.CompanySelectForm, Sec.Declarations, MainDM; {$R *.dfm} procedure TMainForm.actCreateDatabaseExecute(Sender: TObject); begin if Assigned(DMMain) then DMMain.BuildDatabase; end; procedure TMainForm.actCurrencyExecute(Sender: TObject); begin ActivateNewForm('TCurrencyListForm'); end; procedure TMainForm.actActivateFilterExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdActivateFilter); end; procedure TMainForm.actBuildFilterExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdBuildFilter); end; procedure TMainForm.actCancelExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdClose); end; procedure TMainForm.actCompanyListExecute(Sender: TObject); begin ActivateNewForm('TCompanyListForm'); end; procedure TMainForm.actDeactivateFilterExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdDeactivateFilter); end; procedure TMainForm.actDeleteExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdDelete); end; procedure TMainForm.actEditExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdEdit); end; procedure TMainForm.actFindExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdFind); end; procedure TMainForm.actFirstExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdFirst); end; procedure TMainForm.actInsertExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdAdd); end; procedure TMainForm.actLastExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdLast); end; procedure TMainForm.actNextExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdNext); end; procedure TMainForm.actPrintExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdPrint); end; procedure TMainForm.actPriorExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdPrev); end; procedure TMainForm.actRefreshExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdRefresh); end; procedure TMainForm.actShowDetailExecute(Sender: TObject); begin SendActionMessageToActiveForm(efcmdViewDetail); end; procedure TMainForm.actPostExecute(Sender: TObject); begin SendActionMessageToActiveForm(TBrowseFormCommand.efcmdPost); end; procedure TMainForm.actSaveAsTemplateExecute(Sender: TObject); begin SendActionMessageToActiveForm(TBrowseFormCommand.efcmdSaveAsTemplate); end; procedure TMainForm.actSecGroupExecute(Sender: TObject); begin ActivateNewForm('TGroupListForm'); end; procedure TMainForm.actSecLoginExecute(Sender: TObject); begin DMMain.LoggedIn := ExecLoginForm; if DMMain.LoggedIn then begin tbtTableActions.Enabled := True; tbtEditActions.Enabled := True; tbtCompany.Enabled := True; ActionMainMenuBar1.Enabled := True; catbtnLeftMenu.Enabled := True; end else actSecLogoutExecute(Sender); end; procedure TMainForm.actSecLogoutExecute(Sender: TObject); begin DMMain.LoggedIn := False; tbtTableActions.Enabled := False; tbtEditActions.Enabled := False; tbtCompany.Enabled := False; ActionMainMenuBar1.Enabled := False; catbtnLeftMenu.Enabled := False; end; procedure TMainForm.actSecPermissionExecute(Sender: TObject); begin ActivateNewForm('TPermissionListForm'); end; procedure TMainForm.actSecRoleExecute(Sender: TObject); begin ActivateNewForm('TRoleListForm') end; procedure TMainForm.actSecUserExecute(Sender: TObject); begin ActivateNewForm('TUserListForm'); end; procedure TMainForm.actParamsBankEntryExecute(Sender: TObject); begin ActivateNewForm('TBankListForm'); end; procedure TMainForm.actParamsCityEntryExecute(Sender: TObject); begin ActivateNewForm('TCityListForm'); end; procedure TMainForm.actParamsCountryEntryExecute(Sender: TObject); begin ActivateNewForm('TCountryListForm'); end; procedure TMainForm.actParamsDepartmentEntryExecute(Sender: TObject); begin ActivateNewForm('TDepartmentListForm'); end; procedure TMainForm.actParamsLanguageEntryExecute(Sender: TObject); begin ActivateNewForm('TLanguageListForm'); end; procedure TMainForm.actParamsLocationEntryExecute(Sender: TObject); begin ActivateNewForm('TLocationListForm'); end; procedure TMainForm.actParamsOthIncomeCutsEntryExecute(Sender: TObject); begin ActivateNewForm('TOthIncomeOutcomeDefListForm'); end; procedure TMainForm.actParamsRelationshipTypeEntryExecute(Sender: TObject); begin ActivateNewForm('TRelationshipTypeListForm'); end; procedure TMainForm.actParamsTitleEntryExecute(Sender: TObject); begin ActivateNewForm('TTitleListForm'); end; procedure TMainForm.actParamsTownEntryExecute(Sender: TObject); begin ActivateNewForm('TTownListForm'); end; procedure TMainForm.actPayrollScoringEntryFormExecute(Sender: TObject); begin ActivateNewForm('TTahakkukForm'); end; procedure TMainForm.ActivateNewForm(const name: string); var f : TTemplateForm; begin if Assigned(JvEmbeddedFormPanel1.LinkedForm) then begin if (JvEmbeddedFormPanel1.LinkedForm.ClassName=name) then Exit; JvEmbeddedFormPanel1.LinkedForm.Close; end; f := MyFactory.GetForm(name); JvEmbeddedFormPanel1.FormLink := f.FormLink; f.Provider.Subscribe(fSubscriber); f.Show; end; procedure TMainForm.actTahakkuklarExecute(Sender: TObject); var f : TTemplateForm; begin //ActivateNewForm(''); end; procedure TMainForm.actUndeleteExecute(Sender: TObject); begin SendActionMessageToActiveForm(TBrowseFormCommand.efcmdUndelete); end; procedure TMainForm.actViewPersonelGridFormExecute(Sender: TObject); var f : TTemplateForm; begin ActivateNewForm('TEmployeeListForm'); end; procedure TMainForm.cbxCurrentYearChange(Sender: TObject); begin StrToInt(cbxCurrentYear.Text); end; procedure TMainForm.edSelectCompanyButtonClick(Sender: TObject); var sel : string; begin sel := edSelectCompany.Text; if TCompanySelectForm.ExecuteSelect('CompanyCode', sel) and (sel<>edSelectCompany.Text) then begin DMMain.SetCurrentCompanyCode(sel); if Assigned(JvEmbeddedFormPanel1.LinkedForm) then (JvEmbeddedFormPanel1.LinkedForm as TTemplateForm).Refresh; //JvEmbeddedFormPanel1.LinkedForm.Close; edSelectCompany.Text := sel; JvFormStorage1.StoredValue['CurrentCompany'] := edSelectCompany.Text; end; end; procedure TMainForm.FormCreate(Sender: TObject); var s: string; item : TJvStoredValue; begin DMMain := TDMMain.Create(Application); fMainModel := CreateMainModelClass; fViewModel := CreateMainViewModelClass; fViewModel.Model := fMainModel; fSubscriber := CreateProSuSubscriberClass; fSubscriber.SetUpdateSubscriberMethod(NotificationFromProvider); UpdateLabels; actSecLogoutExecute(Sender); actSecLoginExecute(Sender); end; procedure TMainForm.JvFormStorage1BeforeSavePlacement(Sender: TObject); begin if DMMain.Company=nil then Exit; JvFormStorage1.StoredValue['CurrentCompany'] := DMMain.Company.CompanyCode; if cbxCurrentYear.Text<>'' then JvFormStorage1.StoredValue['CurrentYear'] := StrToInt(cbxCurrentYear.Text); JvFormStorage1.StoredValue['CurrentPeriod'] := cbxCurrentPeriod.ItemIndex; end; procedure TMainForm.JvFormStorage1RestorePlacement(Sender: TObject); var item : TJvStoredValue; itemP : TJvStoredValue; itemY : TJvStoredValue; code : string; D, P, Y : Word; begin code := ''; DecodeDate(Date, Y, P, D); DMMain.FileUploadFolder := JvFormStorage1.StoredValue['FileUploadFolder']; item := JvFormStorage1.StoredValues.Values['CurrentCompany']; //.StoredValue['CurrentCompany'].ToString; if item<>nil then code := item.Value; DMMain.SetCurrentCompanyCode(code); edSelectCompany.Text := code; itemY := JvFormStorage1.StoredValues.Values['CurrentYear']; itemP := JvFormStorage1.StoredValues.Values['CurrentPeriod']; if itemP<>nil then P := itemP.Value; if not(P in [0..11]) then P := 0; if itemY<>nil then Y := itemY.Value; cbxCurrentYear.Text := IntToStr(Y); cbxCurrentPeriod.ItemIndex := P; end; procedure TMainForm.NotificationFromProvider( const notifyClass: INotificationClass); var tmpNotifClass : TNotificationClass; begin if notifyClass is TNotificationClass then begin tmpNotifClass := notifyClass as TNotificationClass; { Add here the codes to notify main form... } end; end; procedure TMainForm.SendActionMessageToActiveForm(aMsg: TBrowseFormCommand); begin if Assigned(JvEmbeddedFormPanel1.LinkedForm) then begin TTemplateForm(JvEmbeddedFormPanel1.LinkedForm).OrderCommand(aMsg); end; end; procedure TMainForm.SetViewModel(const newViewModel: IMainViewModelInterface); begin fViewModel := newViewModel; UpdateLabels; end; procedure TMainForm.UpdateLabels; begin ActionMainMenuBar1.ActionClient.Items[0].Caption := ComponentDictionary.GetText(ClassName, 'ActionMainMenuBar1.ActionClient.Items[0].Caption'); catbtnLeftMenu.Categories[0].Caption := ActionMainMenuBar1.ActionClient.Items[0].Caption; ActionMainMenuBar1.ActionClient.Items[1].Caption := ComponentDictionary.GetText(ClassName, 'ActionMainMenuBar1.ActionClient.Items[1].Caption'); catbtnLeftMenu.Categories[1].Caption := ActionMainMenuBar1.ActionClient.Items[1].Caption; ActionMainMenuBar1.ActionClient.Items[2].Caption := ComponentDictionary.GetText(ClassName, 'ActionMainMenuBar1.ActionClient.Items[2].Caption'); catbtnLeftMenu.Categories[2].Caption := ActionMainMenuBar1.ActionClient.Items[2].Caption; ActionMainMenuBar1.ActionClient.Items[3].Caption := ComponentDictionary.GetText(ClassName, 'ActionMainMenuBar1.ActionClient.Items[3].Caption'); catbtnLeftMenu.Categories[3].Caption := ActionMainMenuBar1.ActionClient.Items[3].Caption; ActionMainMenuBar1.ActionClient.Items[4].Caption := ComponentDictionary.GetText(ClassName, 'ActionMainMenuBar1.ActionClient.Items[4].Caption'); catbtnLeftMenu.Categories[4].Caption := ActionMainMenuBar1.ActionClient.Items[4].Caption; ActionMainMenuBar1.ActionClient.Items[5].Caption := ComponentDictionary.GetText(ClassName, 'ActionMainMenuBar1.ActionClient.Items[5].Caption'); catbtnLeftMenu.Categories[5].Caption := ActionMainMenuBar1.ActionClient.Items[5].Caption; ActionMainMenuBar1.ActionClient.Items[6].Caption := ComponentDictionary.GetText(ClassName, 'ActionMainMenuBar1.ActionClient.Items[6].Caption'); catbtnLeftMenu.Categories[6].Caption := ActionMainMenuBar1.ActionClient.Items[6].Caption; ActionMainMenuBar1.ActionClient.Items[7].Caption := ComponentDictionary.GetText(ClassName, 'ActionMainMenuBar1.ActionClient.Items[7].Caption'); catbtnLeftMenu.Categories[7].Caption := ActionMainMenuBar1.ActionClient.Items[7].Caption; { actViewPersonelGridForm.ImageIndex := 0; actStartEmployeeRecruitment.ImageIndex := 1; actStartEmployeeJobTermination.ImageIndex := 2; actPayrollCalculation.ImageIndex := 3; actPayrollExamine.ImageIndex := 4; actPayrollClosePeriod.ImageIndex := 5; actPayrollChangeYearPeriod.ImageIndex := 6; actPayrollTransferToGeneralLedger.ImageIndex := 7; actPayrollTotalIncomeTaxBaseEntry.ImageIndex := 8; actPayrollScoringEntryForm.ImageIndex := 9; actCurrencyDaily.ImageIndex := 12; actCurrency.ImageIndex := 13; actRepPayrollReportWideDlg.ImageIndex := 14; actRepPayrollReportLaserDlg.ImageIndex := 15; actRepEnvelopeDumpDlg.ImageIndex := 16; actRepPayrollCompendiumDlg.ImageIndex := 17; actRepPersonelWageListDlg.ImageIndex := 18; actRepPersonnelTimekeepingListDlg.ImageIndex := 19; actRepSocialPaymentsListDlg.ImageIndex := 20; actRepOtherPaymentsListDlg.ImageIndex := 21; actRepOtherCutsListDlg.ImageIndex := 22; actRepMonthlySGKPremiumsDeclarationReportDlg.ImageIndex := 23; actRepDeclarationReportOfSocialSecurityPremiumSupportDlg.ImageIndex := 24; actRepAFour_monthInsurancePremiumsPayrollReportDlg.ImageIndex := 25; actRepSGKPremiumsReportDlg.ImageIndex := 26; actRepUserDefinedReportsDlg.ImageIndex := 27; actParamsCountryEntry.ImageIndex := 28; actParamsCityEntry.ImageIndex := 29; actParamsTownEntry.ImageIndex := 30; actParamsLocationEntry.ImageIndex := 31; actParamsLanguageEntry.ImageIndex := 32; actParamsDepartmentEntry.ImageIndex := 33; actParamsTitleEntry.ImageIndex := 34; actParamsBankEntry.ImageIndex := 35; actParamsOthIncomeCutsEntry.ImageIndex := 36; actParamsRelationshipTypeEntry.ImageIndex := 37; actParamsGeneralParameters.ImageIndex := 38; actParamsCompanyParameters.ImageIndex := 39; actOpsDatabaseConnectionOptions.ImageIndex := 40; actOpsProgramOptions.ImageIndex := 41; actCompanyList.ImageIndex := 42; actSecUser.ImageIndex := 45; actSecPermission.ImageIndex := 46; actSecGroup.ImageIndex := 47; actSecRole.ImageIndex := 48; } actViewPersonelGridForm.Caption := ComponentDictionary.GetText(ClassName, 'actViewPersonelGridForm.Caption'); actStartEmployeeRecruitment.Caption := ComponentDictionary.GetText(ClassName, 'actStartEmployeeRecruitment.Caption'); //lbltexts.RecruitmentCaption; actStartEmployeeJobTermination.Caption := ComponentDictionary.GetText(ClassName, 'actStartEmployeeJobTermination.Caption');//lbltexts.JobTerminationCaption; actPayrollCalculation.Caption := ComponentDictionary.GetText(ClassName, 'actPayrollCalculation.Caption');//lbltexts.CalculationCaption; actPayrollExamine.Caption := ComponentDictionary.GetText(ClassName, 'actPayrollExamine.Caption');//lbltexts.PayrollExamineCaption; actPayrollClosePeriod.Caption := ComponentDictionary.GetText(ClassName, 'actPayrollClosePeriod.Caption');//lbltexts.ClosePeriodCaption; actPayrollChangeYearPeriod.Caption := ComponentDictionary.GetText(ClassName, 'actPayrollChangeYearPeriod.Caption');//lbltexts.ChangeYearAndPeriodCaption; actPayrollTransferToGeneralLedger.Caption := ComponentDictionary.GetText(ClassName, 'actPayrollTransferToGeneralLedger.Caption');//lbltexts.TransferToGeneralLedgerCaption; actPayrollTotalIncomeTaxBaseEntry.Caption := ComponentDictionary.GetText(ClassName, 'actPayrollTotalIncomeTaxBaseEntry.Caption');//lbltexts.TotalIncomeTaxBaseEntryCaption; actPayrollScoringEntryForm.Caption := ComponentDictionary.GetText(ClassName, 'actPayrollScoringEntryForm.Caption');//lbltexts.ScoringEntryCaption; { actPayrollOtherIncomesEntryForm.Caption := ComponentDictionary.GetText(ClassName, 'actPayrollOtherIncomesEntryForm.Caption');//lbltexts.OtherIncomeEntryCaption; actPayrollOtherIncomesEntryForm.ImageIndex := 10; actPayrollOtherCutsEntryForm.Caption := ComponentDictionary.GetText(ClassName, 'actPayrollOtherCutsEntryForm.Caption');//lbltexts.OtherCutsEntryCaption; actPayrollOtherCutsEntryForm.ImageIndex := 11; } actCurrencyDaily.Caption := ComponentDictionary.GetText(ClassName, 'actCurrencyDaily.Caption');//lbltexts.CurrencyDaily; actCurrency.Caption := ComponentDictionary.GetText(ClassName, 'actCurrency.Caption');//lbltexts.Currency; actRepPayrollReportWideDlg.Caption := ComponentDictionary.GetText(ClassName, 'actRepPayrollReportWideDlg.Caption');//lbltexts.PayrollReportWideCaption; actRepPayrollReportLaserDlg.Caption := ComponentDictionary.GetText(ClassName, 'actRepPayrollReportLaserDlg.Caption');//lbltexts.PayrollReportLaserCaption; actRepEnvelopeDumpDlg.Caption := ComponentDictionary.GetText(ClassName, 'actRepEnvelopeDumpDlg.Caption');//lbltexts.EnvelopeDumpCaption; actRepPayrollCompendiumDlg.Caption := ComponentDictionary.GetText(ClassName, 'actRepPayrollCompendiumDlg.Caption');//lbltexts.PayrollCompendiumCaption; actRepPersonelWageListDlg.Caption := ComponentDictionary.GetText(ClassName, 'actRepPersonelWageListDlg.Caption');//lbltexts.PersonelWageListCaption; actRepPersonnelTimekeepingListDlg.Caption := ComponentDictionary.GetText(ClassName, 'actRepPersonnelTimekeepingListDlg.Caption');//lbltexts.PersonnelTimekeepingListCaption; actRepSocialPaymentsListDlg.Caption := ComponentDictionary.GetText(ClassName, 'actRepSocialPaymentsListDlg.Caption');//lbltexts.SocialPaymentsListCaption; actRepOtherPaymentsListDlg.Caption := ComponentDictionary.GetText(ClassName, 'actRepOtherPaymentsListDlg.Caption');//lbltexts.OtherPaymentsListCaption; actRepOtherCutsListDlg.Caption := ComponentDictionary.GetText(ClassName, 'actRepOtherCutsListDlg.Caption');//lbltexts.OtherCutsEntryCaption; actRepMonthlySGKPremiumsDeclarationReportDlg.Caption := ComponentDictionary.GetText(ClassName, 'actRepMonthlySGKPremiumsDeclarationReportDlg.Caption');//lbltexts.MonthlySGKPremiumsDeclarationReportCaption; actRepDeclarationReportOfSocialSecurityPremiumSupportDlg.Caption := ComponentDictionary.GetText(ClassName, 'actRepDeclarationReportOfSocialSecurityPremiumSupportDlg.Caption');//lbltexts.DeclarationReportOfSocialSecurityPremiumSupportCaption; actRepAFour_monthInsurancePremiumsPayrollReportDlg.Caption := ComponentDictionary.GetText(ClassName, 'actRepAFour_monthInsurancePremiumsPayrollReportDlg.Caption');//lbltexts.AFour_monthInsurancePremiumsPayrollReportCaption; actRepSGKPremiumsReportDlg.Caption := ComponentDictionary.GetText(ClassName, 'actRepSGKPremiumsReportDlg.Caption');//lbltexts.SGKPremiumsReportCaption; actRepUserDefinedReportsDlg.Caption := ComponentDictionary.GetText(ClassName, 'actRepUserDefinedReportsDlg.Caption');//lbltexts.UserDefinedReportsCaption; actParamsCountryEntry.Caption := ComponentDictionary.GetText(ClassName, 'actParamsCountryEntry.Caption');//lbltexts.CountryEntryCaption; actParamsCityEntry.Caption := ComponentDictionary.GetText(ClassName, 'actParamsCityEntry.Caption');//lbltexts.CityEntryCaption; actParamsTownEntry.Caption := ComponentDictionary.GetText(ClassName, 'actParamsTownEntry.Caption');//lbltexts.TownEntryCaption; actParamsLocationEntry.Caption := ComponentDictionary.GetText(ClassName, 'actParamsLocationEntry.Caption');//lbltexts.LocationEntryCaption; actParamsLanguageEntry.Caption := ComponentDictionary.GetText(ClassName, 'actParamsLanguageEntry.Caption');//lbltexts.LanguageEntryCaption; actParamsDepartmentEntry.Caption := ComponentDictionary.GetText(ClassName, 'actParamsDepartmentEntry.Caption');//lbltexts.DepartmentEntryCaption; actParamsTitleEntry.Caption := ComponentDictionary.GetText(ClassName, 'actParamsTitleEntry.Caption');//lbltexts.TitleEntryCaption; actParamsBankEntry.Caption := ComponentDictionary.GetText(ClassName, 'actParamsBankEntry.Caption');//lbltexts.BankEntryCaption; actParamsOthIncomeCutsEntry.Caption := ComponentDictionary.GetText(ClassName, 'actParamsOthIncomeCutsEntry.Caption');//lbltexts.OthIncomeCutsEntryCaption; actParamsRelationshipTypeEntry.Caption := ComponentDictionary.GetText(ClassName, 'actParamsRelationshipTypeEntry.Caption');//lbltexts.RelationshipTypeEntryCaption; actParamsGeneralParameters.Caption := ComponentDictionary.GetText(ClassName, 'actParamsGeneralParameters.Caption');//lbltexts.GeneralParametersCaption; actParamsCompanyParameters.Caption := ComponentDictionary.GetText(ClassName, 'actParamsCompanyParameters.Caption');//lbltexts.CompanyParametersCaption; actOpsDatabaseConnectionOptions.Caption := ComponentDictionary.GetText(ClassName, 'actOpsDatabaseConnectionOptions.Caption');//lbltexts.DatabaseConnectionOptionsCaption; actOpsProgramOptions.Caption := ComponentDictionary.GetText(ClassName, 'actOpsProgramOptions.Caption');//lbltexts.ProgramOptionsCaption; actCompanyList.Caption := ComponentDictionary.GetText(ClassName, 'actCompanyList.Caption');//lbltexts.CompanyListCaption; actSecUser.Caption := ComponentDictionary.GetText(ClassName, 'actSecUser.Caption');//lbltexts.UserEntryCaption; actSecPermission.Caption := ComponentDictionary.GetText(ClassName, 'actSecPermission.Caption');//lbltexts.PermissionEntryCaption; actSecGroup.Caption := ComponentDictionary.GetText(ClassName, 'actSecGroup.Caption');//lbltexts.GroupEntryCaption; actSecRole.Caption := ComponentDictionary.GetText(ClassName, 'actSecRole.Caption');//lbltexts.RoleEntryCaption; catbtnLeftMenu.Categories[0].Items[0].Action := actViewPersonelGridForm; catbtnLeftMenu.Categories[0].Items[1].Action := actStartEmployeeRecruitment; catbtnLeftMenu.Categories[0].Items[2].Action := actStartEmployeeJobTermination; catbtnLeftMenu.Categories[1].Items[0].Action := actPayrollCalculation; catbtnLeftMenu.Categories[1].Items[1].Action := actPayrollExamine; catbtnLeftMenu.Categories[1].Items[2].Action := actPayrollClosePeriod; catbtnLeftMenu.Categories[1].Items[3].Action := actPayrollChangeYearPeriod; catbtnLeftMenu.Categories[1].Items[4].Action := actPayrollTransferToGeneralLedger; catbtnLeftMenu.Categories[1].Items[5].Action := actPayrollTotalIncomeTaxBaseEntry; catbtnLeftMenu.Categories[1].Items[6].Action := actPayrollScoringEntryForm; catbtnLeftMenu.Categories[1].Items[7].Action := actPayrollOtherIncomesCutsEntryForm; catbtnLeftMenu.Categories[2].Items[0].Action := actCurrencyDaily; catbtnLeftMenu.Categories[2].Items[1].Action := actCurrency; catbtnLeftMenu.Categories[3].Items[0].Action := actRepPayrollReportWideDlg; catbtnLeftMenu.Categories[3].Items[1].Action := actRepPayrollReportLaserDlg; catbtnLeftMenu.Categories[3].Items[2].Action := actRepEnvelopeDumpDlg; catbtnLeftMenu.Categories[3].Items[3].Action := actRepPayrollCompendiumDlg; catbtnLeftMenu.Categories[3].Items[4].Action := actRepPersonelWageListDlg; catbtnLeftMenu.Categories[3].Items[5].Action := actRepPersonnelTimekeepingListDlg; catbtnLeftMenu.Categories[3].Items[6].Action := actRepSocialPaymentsListDlg; catbtnLeftMenu.Categories[3].Items[7].Action := actRepOtherPaymentsListDlg; catbtnLeftMenu.Categories[3].Items[8].Action := actRepOtherCutsListDlg; catbtnLeftMenu.Categories[3].Items[9].Action := actRepMonthlySGKPremiumsDeclarationReportDlg; catbtnLeftMenu.Categories[3].Items[10].Action := actRepDeclarationReportOfSocialSecurityPremiumSupportDlg; catbtnLeftMenu.Categories[3].Items[11].Action := actRepAFour_monthInsurancePremiumsPayrollReportDlg; catbtnLeftMenu.Categories[3].Items[12].Action := actRepSGKPremiumsReportDlg; catbtnLeftMenu.Categories[3].Items[13].Action := actRepUserDefinedReportsDlg; catbtnLeftMenu.Categories[4].Items[0].Action := actParamsCountryEntry; catbtnLeftMenu.Categories[4].Items[1].Action := actParamsCityEntry; catbtnLeftMenu.Categories[4].Items[2].Action := actParamsTownEntry; catbtnLeftMenu.Categories[4].Items[3].Action := actParamsLocationEntry; catbtnLeftMenu.Categories[4].Items[4].Action := actParamsLanguageEntry; catbtnLeftMenu.Categories[4].Items[5].Action := actParamsDepartmentEntry; catbtnLeftMenu.Categories[4].Items[6].Action := actParamsTitleEntry; catbtnLeftMenu.Categories[4].Items[7].Action := actParamsBankEntry; catbtnLeftMenu.Categories[4].Items[8].Action := actParamsOthIncomeCutsEntry; catbtnLeftMenu.Categories[4].Items[9].Action := actParamsRelationshipTypeEntry; catbtnLeftMenu.Categories[4].Items[10].Action := actParamsGeneralParameters; catbtnLeftMenu.Categories[4].Items[11].Action := actParamsCompanyParameters; catbtnLeftMenu.Categories[5].Items[0].Action := actOpsDatabaseConnectionOptions; catbtnLeftMenu.Categories[5].Items[1].Action := actOpsProgramOptions; catbtnLeftMenu.Categories[6].Items[0].Action := actCompanyList; catbtnLeftMenu.Categories[7].Items[0].Action := actSecUser; catbtnLeftMenu.Categories[7].Items[0].ImageIndex := actSecUser.ImageIndex; catbtnLeftMenu.Categories[7].Items[1].Action := actSecPermission; catbtnLeftMenu.Categories[7].Items[1].ImageIndex := actSecPermission.ImageIndex; catbtnLeftMenu.Categories[7].Items[2].Action := actSecGroup; catbtnLeftMenu.Categories[7].Items[2].ImageIndex := actSecGroup.ImageIndex; catbtnLeftMenu.Categories[7].Items[3].Action := actSecRole; catbtnLeftMenu.Categories[7].Items[3].ImageIndex := actSecRole.ImageIndex; catbtnLeftMenu.Categories[0].Items[0].ImageIndex := actViewPersonelGridForm.ImageIndex; catbtnLeftMenu.Categories[0].Items[1].ImageIndex := actStartEmployeeRecruitment.ImageIndex; catbtnLeftMenu.Categories[0].Items[2].ImageIndex := actStartEmployeeJobTermination.ImageIndex; catbtnLeftMenu.Categories[1].Items[0].ImageIndex := actPayrollCalculation.ImageIndex; catbtnLeftMenu.Categories[1].Items[1].ImageIndex := actPayrollExamine.ImageIndex; catbtnLeftMenu.Categories[1].Items[2].ImageIndex := actPayrollClosePeriod.ImageIndex; catbtnLeftMenu.Categories[1].Items[3].ImageIndex := actPayrollChangeYearPeriod.ImageIndex; catbtnLeftMenu.Categories[1].Items[4].ImageIndex := actPayrollTransferToGeneralLedger.ImageIndex; catbtnLeftMenu.Categories[1].Items[5].ImageIndex := actPayrollTotalIncomeTaxBaseEntry.ImageIndex; catbtnLeftMenu.Categories[1].Items[6].ImageIndex := actPayrollScoringEntryForm.ImageIndex; catbtnLeftMenu.Categories[1].Items[7].ImageIndex := actPayrollOtherIncomesCutsEntryForm.ImageIndex; catbtnLeftMenu.Categories[2].Items[0].ImageIndex := actCurrencyDaily.ImageIndex; catbtnLeftMenu.Categories[2].Items[1].ImageIndex := actCurrency.ImageIndex; catbtnLeftMenu.Categories[3].Items[0].ImageIndex := actRepPayrollReportWideDlg.ImageIndex; catbtnLeftMenu.Categories[3].Items[1].ImageIndex := actRepPayrollReportLaserDlg.ImageIndex; catbtnLeftMenu.Categories[3].Items[2].ImageIndex := actRepEnvelopeDumpDlg.ImageIndex; catbtnLeftMenu.Categories[3].Items[3].ImageIndex := actRepPayrollCompendiumDlg.ImageIndex; catbtnLeftMenu.Categories[3].Items[4].ImageIndex := actRepPersonelWageListDlg.ImageIndex; catbtnLeftMenu.Categories[3].Items[5].ImageIndex := actRepPersonnelTimekeepingListDlg.ImageIndex; catbtnLeftMenu.Categories[3].Items[6].ImageIndex := actRepSocialPaymentsListDlg.ImageIndex; catbtnLeftMenu.Categories[3].Items[7].ImageIndex := actRepOtherPaymentsListDlg.ImageIndex; catbtnLeftMenu.Categories[3].Items[8].ImageIndex := actRepOtherCutsListDlg.ImageIndex; catbtnLeftMenu.Categories[3].Items[9].ImageIndex := actRepMonthlySGKPremiumsDeclarationReportDlg.ImageIndex; catbtnLeftMenu.Categories[3].Items[10].ImageIndex := actRepDeclarationReportOfSocialSecurityPremiumSupportDlg.ImageIndex; catbtnLeftMenu.Categories[3].Items[11].ImageIndex := actRepAFour_monthInsurancePremiumsPayrollReportDlg.ImageIndex; catbtnLeftMenu.Categories[3].Items[12].ImageIndex := actRepSGKPremiumsReportDlg.ImageIndex; catbtnLeftMenu.Categories[3].Items[13].ImageIndex := actRepUserDefinedReportsDlg.ImageIndex; catbtnLeftMenu.Categories[4].Items[0].ImageIndex := actParamsCountryEntry.ImageIndex; catbtnLeftMenu.Categories[4].Items[1].ImageIndex := actParamsCityEntry.ImageIndex; catbtnLeftMenu.Categories[4].Items[2].ImageIndex := actParamsTownEntry.ImageIndex; catbtnLeftMenu.Categories[4].Items[3].ImageIndex := actParamsLocationEntry.ImageIndex; catbtnLeftMenu.Categories[4].Items[4].ImageIndex := actParamsLanguageEntry.ImageIndex; catbtnLeftMenu.Categories[4].Items[5].ImageIndex := actParamsDepartmentEntry.ImageIndex; catbtnLeftMenu.Categories[4].Items[6].ImageIndex := actParamsTitleEntry.ImageIndex; catbtnLeftMenu.Categories[4].Items[7].ImageIndex := actParamsBankEntry.ImageIndex; catbtnLeftMenu.Categories[4].Items[8].ImageIndex := actParamsOthIncomeCutsEntry.ImageIndex; catbtnLeftMenu.Categories[4].Items[9].ImageIndex := actParamsRelationshipTypeEntry.ImageIndex; catbtnLeftMenu.Categories[4].Items[10].ImageIndex := actParamsGeneralParameters.ImageIndex; catbtnLeftMenu.Categories[4].Items[11].ImageIndex := actParamsCompanyParameters.ImageIndex; catbtnLeftMenu.Categories[5].Items[0].ImageIndex := actOpsDatabaseConnectionOptions.ImageIndex; catbtnLeftMenu.Categories[5].Items[1].ImageIndex := actOpsProgramOptions.ImageIndex; catbtnLeftMenu.Categories[6].Items[0].ImageIndex := actCompanyList.ImageIndex; end; end.
unit StatisticsWSIntf; interface uses InvokeRegistry, Types, XSBuiltIns; type IStatisticsWS = interface(IInvokable) ['{CAA9269D-4FC3-448A-AB10-DC01A27741FE}'] //IStatistics function Get_SwitchedOnRDA: Integer; safecall; function Get_SwitchedOnRadar: Integer; safecall; function Get_SwitchedOnAcc: Integer; safecall; function Get_SwitchedOnMotorAz: Integer; safecall; function Get_SwitchedOnMotorEl: Integer; safecall; function Get_SwitchedOnTxCaldeo: Integer; safecall; function Get_SwitchedOnTxAnodo: Integer; safecall; function Get_SwitchedOnRx: Integer; safecall; function Get_MagnetronCaldeo: Integer; safecall; function Get_MagnetronAnodo: Integer; safecall; function Get_TiratronPrincipal: Integer; safecall; function Get_TiratronAuxiliar: Integer; safecall; function Get_SwitchedOnTxCaldeo2: Integer; safecall; function Get_SwitchedOnTxAnodo2: Integer; safecall; function Get_SwitchedOnRx2: Integer; safecall; function Get_MagnetronCaldeo2: Integer; safecall; function Get_MagnetronAnodo2: Integer; safecall; function Get_TiratronPrincipal2: Integer; safecall; function Get_TiratronAuxiliar2: Integer; safecall; function Get_TiratronPrincipalAnodo2: Integer; safecall; function Get_TiratronPrincipalAnodo1: Integer; safecall; //IStatisticsControl procedure Set_SwitchedOnRDA(value: Integer); safecall; procedure Set_SwitchedOnRadar(value: Integer); safecall; procedure Set_SwitchedOnAcc(value: Integer); safecall; procedure Set_SwitchedOnMotorAz(value: Integer); safecall; procedure Set_SwitchedOnMotorEl(value: Integer); safecall; procedure Set_SwitchedOnTxCaldeo(value: Integer); safecall; procedure Set_SwitchedOnTxAnodo(value: Integer); safecall; procedure Set_SwitchedOnRx(value: Integer); safecall; procedure Set_MagnetronCaldeo(value: Integer); safecall; procedure Set_MagnetronAnodo(value: Integer); safecall; procedure Set_TiratronPrincipal(value: Integer); safecall; procedure Set_TiratronAuxiliar(value: Integer); safecall; procedure Set_SwitchedOnTxCaldeo2(value: Integer); safecall; procedure Set_SwitchedOnTxAnodo2(value: Integer); safecall; procedure Set_SwitchedOnRx2(value: Integer); safecall; procedure Set_MagnetronCaldeo2(value: Integer); safecall; procedure Set_MagnetronAnodo2(value: Integer); safecall; procedure Set_TiratronAuxiliar2(value: Integer); safecall; procedure Set_TiratronPrincipal2(value: Integer); safecall; procedure Set_TiratronPrincipalAnodo1(value: Integer); safecall; procedure Set_TiratronPrincipalAnodo2(value: Integer); safecall; property SwitchedOnRDA: Integer read Get_SwitchedOnRDA write Set_SwitchedOnRDA; property SwitchedOnRadar: Integer read Get_SwitchedOnRadar write Set_SwitchedOnRadar; property SwitchedOnAcc: Integer read Get_SwitchedOnAcc write Set_SwitchedOnAcc; property SwitchedOnMotorAz: Integer read Get_SwitchedOnMotorAz write Set_SwitchedOnMotorAz; property SwitchedOnMotorEl: Integer read Get_SwitchedOnMotorEl write Set_SwitchedOnMotorEl; property SwitchedOnTxCaldeo: Integer read Get_SwitchedOnTxCaldeo write Set_SwitchedOnTxCaldeo; property SwitchedOnTxAnodo: Integer read Get_SwitchedOnTxAnodo write Set_SwitchedOnTxAnodo; property SwitchedOnRx: Integer read Get_SwitchedOnRx write Set_SwitchedOnRx; property MagnetronCaldeo: Integer read Get_MagnetronCaldeo write Set_MagnetronCaldeo; property MagnetronAnodo: Integer read Get_MagnetronAnodo write Set_MagnetronAnodo; property TiratronPrincipal: Integer read Get_TiratronPrincipal write Set_TiratronPrincipal; property TiratronAuxiliar: Integer read Get_TiratronAuxiliar write Set_TiratronAuxiliar; property SwitchedOnTxCaldeo2: Integer read Get_SwitchedOnTxCaldeo2 write Set_SwitchedOnTxCaldeo2; property SwitchedOnTxAnodo2: Integer read Get_SwitchedOnTxAnodo2 write Set_SwitchedOnTxAnodo2; property SwitchedOnRx2: Integer read Get_SwitchedOnRx2 write Set_SwitchedOnRx2; property MagnetronCaldeo2: Integer read Get_MagnetronCaldeo2 write Set_MagnetronCaldeo2; property MagnetronAnodo2: Integer read Get_MagnetronAnodo2 write Set_MagnetronAnodo2; property TiratronPrincipal2: Integer read Get_TiratronPrincipal2 write Set_TiratronAuxiliar2; property TiratronAuxiliar2: Integer read Get_TiratronAuxiliar2 write Set_TiratronPrincipal2; property TiratronPrincipalAnodo2: Integer read Get_TiratronPrincipalAnodo2 write Set_TiratronPrincipalAnodo2; property TiratronPrincipalAnodo1: Integer read Get_TiratronPrincipalAnodo1 write Set_TiratronPrincipalAnodo1; end; implementation initialization InvRegistry.RegisterInterface(TypeInfo(IStatisticsWS)); end.
(* Copyright (c) 2011-2012, Stefan Glienke 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 this library 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 HOLDER 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 DSharp.PresentationModel.ConventionManager; interface uses Classes, DSharp.Bindings, DSharp.PresentationModel.ElementConvention, Generics.Collections, Rtti; type ConventionManager = record private class var FConventions: TDictionary<TClass, TElementConvention>; public class constructor Create; class destructor Destroy; class function AddElementConvention<T: class>(APropertyName: string; AEventName: string): TElementConvention; static; class procedure ApplyValidation(ABinding: TBinding; AViewModel: TObject; APropertyName: string); static; class procedure ConfigureSelectedItem(AViewModel: TObject; APropertyName: string; AViewElement: TComponent; ASelectedItemPropertyName: string); static; class function GetElementConvention( AElementType: TClass): TElementConvention; static; class procedure SetBinding(AViewModel: TObject; APropertyName: string; AViewElement: TComponent; ABindingType: TBindingType; AConvention: TElementConvention); overload; static; class procedure SetBinding(AViewModel: TObject; APropertyName: string; AViewElement: TComponent; ATargetPropertyName: string); overload; static; end; implementation uses DSharp.Core.Reflection, DSharp.PresentationModel.Validations, StrUtils; function Singularize(const AName: string): string; begin if EndsText('ies', AName) then Result := LeftStr(AName, Length(AName) - 3) + 'y' else if EndsText('s', AName) then Result := LeftStr(AName, Length(AName) - 1) else Result := AName; end; function DerivePotentialSelectionNames(const AName: string): TArray<string>; var LSingular: string; begin LSingular := Singularize(AName); Result := TArray<string>.Create( 'Active' + LSingular, 'Selected' + LSingular, 'Current' + LSingular); end; { ConventionManager } class function ConventionManager.AddElementConvention<T>(APropertyName, AEventName: string): TElementConvention; begin Result := TElementConvention.Create(APropertyName, AEventName); FConventions.AddOrSetValue(T, Result); end; class procedure ConventionManager.ApplyValidation(ABinding: TBinding; AViewModel: TObject; APropertyName: string); var LProperty: TRttiProperty; LAttribute: ValidationAttribute; begin LProperty := AViewModel.GetProperty(APropertyName); if Assigned(LProperty) then begin for LAttribute in LProperty.GetCustomAttributes<ValidationAttribute> do begin ABinding.ValidationRules.Add(LAttribute.ValidationRuleClass.Create); end; end; end; class procedure ConventionManager.ConfigureSelectedItem(AViewModel: TObject; APropertyName: string; AViewElement: TComponent; ASelectedItemPropertyName: string); var LBindingGroup: TBindingGroup; LProperty: TRttiProperty; LPotentialName: string; begin LBindingGroup := FindBindingGroup(AViewElement); for LPotentialName in DerivePotentialSelectionNames(AViewElement.Name) do begin LProperty := AViewModel.GetProperty(LPotentialName); if Assigned(LProperty) then begin LBindingGroup.AddBinding( AViewModel, LPotentialName, AViewElement, ASelectedItemPropertyName); end; end; end; class constructor ConventionManager.Create; begin FConventions := TObjectDictionary<TClass, TElementConvention>.Create([doOwnsValues]); end; class destructor ConventionManager.Destroy; begin FConventions.Free(); end; class function ConventionManager.GetElementConvention( AElementType: TClass): TElementConvention; begin if not FConventions.TryGetValue(AElementType, Result) and (AElementType.ClassParent <> nil) then begin Result := GetElementConvention(AElementType.ClassParent); end; end; class procedure ConventionManager.SetBinding(AViewModel: TObject; APropertyName: string; AViewElement: TComponent; ABindingType: TBindingType; AConvention: TElementConvention); var LTargetPropertyName: string; begin case ABindingType of btProperty: LTargetPropertyName := AConvention.PropertyName; btEvent: LTargetPropertyName := AConvention.EventName; end; SetBinding(AViewModel, APropertyName, AViewElement, LTargetPropertyName); end; class procedure ConventionManager.SetBinding(AViewModel: TObject; APropertyName: string; AViewElement: TComponent; ATargetPropertyName: string); var LBindingGroup: TBindingGroup; LBinding: TBinding; begin LBindingGroup := FindBindingGroup(AViewElement); if not Assigned(LBindingGroup) then begin LBindingGroup := TBindingGroup.Create(AViewElement.Owner); end; LBinding := LBindingGroup.AddBinding(); ApplyValidation(LBinding, AViewModel, APropertyName); LBinding.Source := AViewModel; LBinding.SourcePropertyName := APropertyName; LBinding.Target := AViewElement; LBinding.TargetPropertyName := ATargetPropertyName; end; end.
{$MODESWITCH RESULT+} {$GOTO ON} (************************************************************************* Cephes Math Library Release 2.8: June, 2000 Copyright 1984, 1987, 1995, 2000 by Stephen L. Moshier Contributors: * Sergey Bochkanov (ALGLIB project). Translation from C to pseudocode. See subroutines comments for additional copyrights. >>> SOURCE LICENSE >>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (www.fsf.org); either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************) unit fdistr; interface uses Math, Sysutils, Ap, gammafunc, normaldistr, ibetaf; function FDistribution(a : AlglibInteger; b : AlglibInteger; x : Double):Double; function FCDistribution(a : AlglibInteger; b : AlglibInteger; x : Double):Double; function InvFDistribution(a : AlglibInteger; b : AlglibInteger; y : Double):Double; implementation (************************************************************************* F distribution Returns the area from zero to x under the F density function (also known as Snedcor's density or the variance ratio density). This is the density of x = (u1/df1)/(u2/df2), where u1 and u2 are random variables having Chi square distributions with df1 and df2 degrees of freedom, respectively. The incomplete beta integral is used, according to the formula P(x) = incbet( df1/2, df2/2, (df1*x/(df2 + df1*x) ). The arguments a and b are greater than zero, and x is nonnegative. ACCURACY: Tested at random points (a,b,x). x a,b Relative error: arithmetic domain domain # trials peak rms IEEE 0,1 0,100 100000 9.8e-15 1.7e-15 IEEE 1,5 0,100 100000 6.5e-15 3.5e-16 IEEE 0,1 1,10000 100000 2.2e-11 3.3e-12 IEEE 1,5 1,10000 100000 1.1e-11 1.7e-13 Cephes Math Library Release 2.8: June, 2000 Copyright 1984, 1987, 1995, 2000 by Stephen L. Moshier *************************************************************************) function FDistribution(a : AlglibInteger; b : AlglibInteger; x : Double):Double; var w : Double; begin Assert((a>=1) and (b>=1) and AP_FP_Greater_Eq(x,0), 'Domain error in FDistribution'); w := a*x; w := w/(b+w); Result := IncompleteBeta(Double(0.5)*a, Double(0.5)*b, w); end; (************************************************************************* Complemented F distribution Returns the area from x to infinity under the F density function (also known as Snedcor's density or the variance ratio density). inf. - 1 | | a-1 b-1 1-P(x) = ------ | t (1-t) dt B(a,b) | | - x The incomplete beta integral is used, according to the formula P(x) = incbet( df2/2, df1/2, (df2/(df2 + df1*x) ). ACCURACY: Tested at random points (a,b,x) in the indicated intervals. x a,b Relative error: arithmetic domain domain # trials peak rms IEEE 0,1 1,100 100000 3.7e-14 5.9e-16 IEEE 1,5 1,100 100000 8.0e-15 1.6e-15 IEEE 0,1 1,10000 100000 1.8e-11 3.5e-13 IEEE 1,5 1,10000 100000 2.0e-11 3.0e-12 Cephes Math Library Release 2.8: June, 2000 Copyright 1984, 1987, 1995, 2000 by Stephen L. Moshier *************************************************************************) function FCDistribution(a : AlglibInteger; b : AlglibInteger; x : Double):Double; var w : Double; begin Assert((a>=1) and (b>=1) and AP_FP_Greater_Eq(x,0), 'Domain error in FCDistribution'); w := b/(b+a*x); Result := IncompleteBeta(Double(0.5)*b, Double(0.5)*a, w); end; (************************************************************************* Inverse of complemented F distribution Finds the F density argument x such that the integral from x to infinity of the F density is equal to the given probability p. This is accomplished using the inverse beta integral function and the relations z = incbi( df2/2, df1/2, p ) x = df2 (1-z) / (df1 z). Note: the following relations hold for the inverse of the uncomplemented F distribution: z = incbi( df1/2, df2/2, p ) x = df2 z / (df1 (1-z)). ACCURACY: Tested at random points (a,b,p). a,b Relative error: arithmetic domain # trials peak rms For p between .001 and 1: IEEE 1,100 100000 8.3e-15 4.7e-16 IEEE 1,10000 100000 2.1e-11 1.4e-13 For p between 10^-6 and 10^-3: IEEE 1,100 50000 1.3e-12 8.4e-15 IEEE 1,10000 50000 3.0e-12 4.8e-14 Cephes Math Library Release 2.8: June, 2000 Copyright 1984, 1987, 1995, 2000 by Stephen L. Moshier *************************************************************************) function InvFDistribution(a : AlglibInteger; b : AlglibInteger; y : Double):Double; var w : Double; begin Assert((a>=1) and (b>=1) and AP_FP_Greater(y,0) and AP_FP_Less_Eq(y,1), 'Domain error in InvFDistribution'); // // Compute probability for x = 0.5 // w := IncompleteBeta(Double(0.5)*b, Double(0.5)*a, Double(0.5)); // // If that is greater than y, then the solution w < .5 // Otherwise, solve at 1-y to remove cancellation in (b - b*w) // if AP_FP_Greater(w,y) or AP_FP_Less(y,Double(0.001)) then begin w := InvIncompleteBeta(Double(0.5)*b, Double(0.5)*a, y); Result := (b-b*w)/(a*w); end else begin w := InvIncompleteBeta(Double(0.5)*a, Double(0.5)*b, Double(1.0)-y); Result := b*w/(a*(Double(1.0)-w)); end; end; end.
program DoubleVarPart; var a: char; var b: boolean; begin a := 'a'; write('a', '=', a, eol) end.
unit main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, wclBluetooth, wclWeDoWatcher, wclWeDoHub, Vcl.StdCtrls; type TfmMain = class(TForm) btConnect: TButton; btDisconnect: TButton; laStatus: TLabel; laIoState: TLabel; laColorMode: TLabel; cbColorMode: TComboBox; laR: TLabel; edR: TEdit; laG: TLabel; edG: TEdit; laB: TLabel; edB: TEdit; btSetRgb: TButton; laColorIndex: TLabel; cbColorIndex: TComboBox; btSetIndex: TButton; btSetDefault: TButton; btTurnOff: TButton; btSetMode: TButton; procedure FormCreate(Sender: TObject); procedure btDisconnectClick(Sender: TObject); procedure btConnectClick(Sender: TObject); procedure btSetRgbClick(Sender: TObject); procedure btSetDefaultClick(Sender: TObject); procedure btTurnOffClick(Sender: TObject); procedure btSetIndexClick(Sender: TObject); procedure btSetModeClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private FManager: TwclBluetoothManager; FWatcher: TwclWeDoWatcher; FHub: TwclWeDoHub; FRgb: TwclWeDoRgbLight; procedure UpdateMode; procedure UpdateRgb; procedure UpdateIndex; procedure UpdateValues; procedure EnableSetColors(Attached: Boolean); procedure EnableConnect(Connected: Boolean); procedure EnableColorControls; procedure FHub_OnDeviceDetached(Sender: TObject; Device: TwclWeDoIo); procedure FHub_OnDeviceAttached(Sender: TObject; Device: TwclWeDoIo); procedure FHub_OnDisconnected(Sender: TObject; Reason: Integer); procedure FHub_OnConnected(Sender: TObject; Error: Integer); procedure FRgb_OnColorChanged(Sender: TObject); procedure FRgb_OnModeChanged(Sender: TObject); procedure FWatcher_OnHubFound(Sender: TObject; Address: Int64; Name: string); procedure Disconnect; end; var fmMain: TfmMain; implementation uses wclErrors; {$R *.dfm} procedure TfmMain.btConnectClick(Sender: TObject); var Res: Integer; Radio: TwclBluetoothRadio; begin // The very first thing we have to do is to open Bluetooth Manager. // That initializes the underlying drivers and allows us to work with // Bluetooth. // Always check result! Res := FManager.Open; if Res <> WCL_E_SUCCESS then // It should never happen but if it does notify user. ShowMessage('Unable to open Bluetooth Manager: 0x' + IntToHex(Res, 8)) else begin // Assume that no one Bluetooth Radio available. Radio := nil; Res := FManager.GetLeRadio(Radio); if Res <> WCL_E_SUCCESS then // If not, let user know that he has no Bluetooth. ShowMessage('No available Bluetooth Radio found') else begin // If found, try to start discovering. Res := FWatcher.Start(Radio); if Res <> WCL_E_SUCCESS then // It is something wrong with discovering starting. Notify user about // the error. ShowMessage('Unable to start discovering: 0x' + IntToHex(Res, 8)) else begin btConnect.Enabled := False; btDisconnect.Enabled := True; laStatus.Caption := 'Searching...'; end; end; // Again, check the found Radio. if Res <> WCL_E_SUCCESS then begin // And if it is null (not found or discovering was not started // close the Bluetooth Manager to release all the allocated resources. FManager.Close; // Also clean up found Radio variable so we can check it later. Radio := nil; end; end; end; procedure TfmMain.btDisconnectClick(Sender: TObject); begin Disconnect; end; procedure TfmMain.btSetDefaultClick(Sender: TObject); var Res: Integer; begin if FRgb = nil then ShowMessage('Device is not attached') else begin Res := FRgb.SwitchToDefaultColor; if Res <> WCL_E_SUCCESS then ShowMessage('Unable to set default color: 0x' + IntToHex(Res, 8)); end; end; procedure TfmMain.btSetIndexClick(Sender: TObject); var Res: Integer; begin if FRgb = nil then ShowMessage('Device is not attached') else begin Res := FRgb.SetColorIndex(TwclWeDoColor(cbColorIndex.ItemIndex)); if Res <> WCL_E_SUCCESS then ShowMessage('Unable to set default color: 0x' + IntToHex(Res, 8)); end; end; procedure TfmMain.btSetModeClick(Sender: TObject); var Res: Integer; RgbEnabled: Boolean; IndexEnabled: Boolean; begin if FRgb = nil then ShowMessage('Device is not attached') else begin RgbEnabled := cbColorMode.ItemIndex = 1; IndexEnabled := cbColorMode.ItemIndex = 0; Res := WCL_E_SUCCESS; if RgbEnabled then Res := FRgb.SetMode(lmAbsolute) else begin if IndexEnabled then Res := FRgb.SetMode(lmDiscrete); end; if Res <> WCL_E_SUCCESS then ShowMessage('Unable to change color mode: 0x' + IntToHex(Res, 8)) else begin EnableColorControls; if RgbEnabled then UpdateRgb else begin if IndexEnabled then UpdateIndex; end; end; end; end; procedure TfmMain.btSetRgbClick(Sender: TObject); var c: TColor; Res: Integer; begin if FRgb = nil then ShowMessage('Device is not attached') else begin c := Rgb(StrToInt(edR.Text), StrToInt(edG.Text), StrToInt(edB.Text)); Res := FRgb.SetColor(c); if Res <> WCL_E_SUCCESS then ShowMessage('Unable to set color: 0x' + IntToHex(Res, 8)); end; end; procedure TfmMain.btTurnOffClick(Sender: TObject); var Res: Integer; begin if FRgb = nil then ShowMessage('Device is not attached') else begin Res := FRgb.SwitchOff; if Res <> WCL_E_SUCCESS then ShowMessage('Unable to set color: 0x' + IntToHex(Res, 8)); end; end; procedure TfmMain.Disconnect; begin FWatcher.Stop; FHub.Disconnect; FManager.Close; btConnect.Enabled := True; btDisconnect.Enabled := False; end; procedure TfmMain.EnableColorControls; var RgbEnabled: Boolean; IndexEnabled: Boolean; begin RgbEnabled := cbColorMode.ItemIndex = 1; IndexEnabled := cbColorMode.ItemIndex = 0; laR.Enabled := RgbEnabled; laG.Enabled := RgbEnabled; laB.Enabled := RgbEnabled; edR.Enabled := RgbEnabled; edG.Enabled := RgbEnabled; edB.Enabled := RgbEnabled; btSetRgb.Enabled := RgbEnabled; laColorIndex.Enabled := IndexEnabled; cbColorIndex.Enabled := IndexEnabled; btSetIndex.Enabled := IndexEnabled; end; procedure TfmMain.EnableConnect(Connected: Boolean); begin if Connected then begin btConnect.Enabled := False; btDisconnect.Enabled := True; laStatus.Caption := 'Connected'; end else begin btConnect.Enabled := True; btDisconnect.Enabled := False; laStatus.Caption := 'Disconnected'; end; end; procedure TfmMain.EnableSetColors(Attached: Boolean); begin if Attached then laIoState.Caption := 'Attached' else begin laIoState.Caption := 'Dectahed'; edR.Text := ''; edG.Text := ''; edB.Text := ''; cbColorIndex.ItemIndex := -1; cbColorMode.ItemIndex := -1; end; cbColorMode.Enabled := Attached; laColorMode.Enabled := Attached; laR.Enabled := Attached; laG.Enabled := Attached; laB.Enabled := Attached; edR.Enabled := Attached; edG.Enabled := Attached; edB.Enabled := Attached; btSetRgb.Enabled := Attached; laColorIndex.Enabled := Attached; cbColorIndex.Enabled := Attached; btSetIndex.Enabled := Attached; btSetDefault.Enabled := Attached; btTurnOff.Enabled := Attached; btSetMode.Enabled := Attached; if Attached then UpdateValues; end; procedure TfmMain.FHub_OnConnected(Sender: TObject; Error: Integer); begin if Error <> WCL_E_SUCCESS then begin ShowMessage('Connect failed: 0x' + IntToHex(Error, 8)); EnableConnect(False); FManager.Close; end else EnableConnect(True); end; procedure TfmMain.FHub_OnDeviceAttached(Sender: TObject; Device: TwclWeDoIo); begin if Device.DeviceType = iodRgb then begin FRgb := TwclWeDoRgbLight(Device); FRgb.OnColorChanged := FRgb_OnColorChanged; FRgb.OnModeChanged := FRgb_OnModeChanged; EnableSetColors(True); EnableColorControls; end; end; procedure TfmMain.FHub_OnDeviceDetached(Sender: TObject; Device: TwclWeDoIo); begin if Device.DeviceType = iodRgb then begin FRgb := nil; EnableSetColors(False); end; end; procedure TfmMain.FHub_OnDisconnected(Sender: TObject; Reason: Integer); begin EnableConnect(False); FManager.Close; end; procedure TfmMain.FormCreate(Sender: TObject); begin cbColorMode.ItemIndex := -1; FManager := TwclBluetoothManager.Create(nil); FWatcher := TwclWeDoWatcher.Create(nil); FWatcher.OnHubFound := FWatcher_OnHubFound; FHub := TwclWeDoHub.Create(nil); FHub.OnConnected := FHub_OnConnected; FHub.OnDisconnected := FHub_OnDisconnected; FHub.OnDeviceAttached := FHub_OnDeviceAttached; FHub.OnDeviceDetached := FHub_OnDeviceDetached; FRgb := nil; end; procedure TfmMain.FormDestroy(Sender: TObject); begin Disconnect; FManager.Free; FWatcher.Free; FHub.Free; end; procedure TfmMain.FRgb_OnColorChanged(Sender: TObject); begin UpdateRgb; UpdateIndex; end; procedure TfmMain.FRgb_OnModeChanged(Sender: TObject); begin UpdateMode; end; procedure TfmMain.FWatcher_OnHubFound(Sender: TObject; Address: Int64; Name: string); var Radio: TwclBluetoothRadio; Res: Integer; begin Radio := FWatcher.Radio; FWatcher.Stop; Res := FHub.Connect(Radio, Address); if Res <> WCL_E_SUCCESS then begin ShowMessage('Connect failed: 0x' + IntToHex(Res, 8)); EnableConnect(False); end else laStatus.Caption := 'Connecting'; end; procedure TfmMain.UpdateIndex; begin cbColorIndex.ItemIndex := Integer(FRgb.ColorIndex); end; procedure TfmMain.UpdateMode; begin if FRgb <> nil then begin case FRgb.Mode of lmDiscrete: cbColorMode.ItemIndex := 0; lmAbsolute: cbColorMode.ItemIndex := 1; else cbColorMode.ItemIndex := -1; end; end; end; procedure TfmMain.UpdateRgb; var c: TColor; begin c := FRgb.Color; edR.Text := IntToStr(c and $000000FF); edG.Text := IntToStr((c shr 8) and $000000FF); edB.Text := IntToStr((c shr 16) and $000000FF); end; procedure TfmMain.UpdateValues; begin UpdateRgb; UpdateIndex; UpdateMode; end; end.
unit Splash; { SimThyr Project } { A numerical simulator of thyrotropic feedback control } { Version 4.0.0 (Merlion) } { (c) J. W. Dietrich, 1994 - 2017 } { (c) Ludwig Maximilian University of Munich 1995 - 2002 } { (c) Ruhr University of Bochum 2005 - 2017 } { This unit implements a splash screen, while other windows are loaded } { Source code released under the BSD License } { See http://simthyr.sourceforge.net for details } {$mode objfpc} interface uses Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, LaunchDialog, VersionSupport; type { TSplashScreen } TSplashScreen = class(TForm) CopyrightLabel1: TLabel; CopyrightLabel2: TLabel; CopyrightLabel3: TLabel; CopyrightLabel4: TLabel; CopyrightLabel5: TLabel; CopyrightLabel6: TLabel; CopyrightLabel7: TLabel; Image1: TImage; Timer1: TTimer; VersionLabel: TLabel; procedure FormCreate(Sender: TObject); procedure Image1Click(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { private declarations } public { public declarations } end; var SplashScreen: TSplashScreen; implementation { TSplashScreen } procedure TSplashScreen.Timer1Timer(Sender: TObject); begin Timer1.Free; Close; Free; end; procedure TSplashScreen.Image1Click(Sender: TObject); begin end; procedure TSplashScreen.FormCreate(Sender: TObject); begin VersionLabel.Caption := 'Version ' + GetFileVersion; end; initialization {$I splash.lrs} end.
unit MainForm1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.StdCtrls, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.Buttons, FileDrop, MyHash5; const // buf size to compare at once (Test : speed improved until 512KB, little improved more than 512KB) maxRecord = 1024 * 512; maxRecord32 = maxRecord div 4; type // To use Int64 with Max & Position (up to 2TB) TProgressBar = class(Vcl.ComCtrls.TProgressBar) private FInt32: Boolean; FMax64: Int64; FPosition64: Int64; procedure SetMax64(const Value: Int64); procedure SetPosition64(const Value: Int64); public procedure StepBy64(Delta: Int64); published property Max64: Int64 read FMax64 write SetMax64; property Position64: Int64 read FPosition64 write SetPosition64; end; TMainForm = class(TForm) Memo1: TMemo; Label1: TLabel; Label2: TLabel; curFile: TLabel; fileRate: TLabel; totalRate: TLabel; ProgressBar1: TProgressBar; ProgressBar2: TProgressBar; btRun: TBitBtn; btPause: TBitBtn; btStop: TBitBtn; btCopyText: TButton; btClear: TButton; btExit: TButton; btTemp: TBitBtn; FileDrop1: TFileDrop; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FileDrop1Drop(Sender: TObject); procedure Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btRunClick(Sender: TObject); procedure btPauseClick(Sender: TObject); procedure btStopClick(Sender: TObject); procedure btCopyTextClick(Sender: TObject); procedure btClearClick(Sender: TObject); procedure btExitClick(Sender: TObject); procedure btTempClick(Sender: TObject); private { Private declarations } FFileList: TStringList; pauseCompare: boolean; stopCompare: boolean; FTime: TDateTime; FBuf: array[1..maxRecord] of byte; procedure CheckPause; function GetTotalSize: Int64; function Int64ToKiloMegaGiga(ASize: Int64): string; function GetMyMd5Sum(const FileName: string): string; procedure BeforeRun; procedure AfterRun; public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} uses IdHashMessageDigest, IdHash, ClipBrd, Math, BlankUtils; { TProgressBar } // ----------------------------------------------------------------------------- // Implement to show Int64 (2GB ~ 2TB) as (Value div 1024) KB procedure TProgressBar.SetMax64(const Value: Int64); begin FMax64:= Value; // if bigger than 2GB save as KB (Value div 1024) if Value <= $7FFFFFFF then FInt32:= True else FInt32:= False; if FInt32 then Max:= Value else Max:= Value shr 10; end; procedure TProgressBar.SetPosition64(const Value: Int64); begin FPosition64:= Value; if FInt32 then Position:= Value else Position:= Value shr 10; end; procedure TProgressBar.StepBy64(Delta: Int64); begin SetPosition64(FPosition64+Delta); end; { MainForm } // ----------------------------------------------------------------------------- // Create and Destroy procedure TMainForm.FormCreate(Sender: TObject); begin // Manage dropped files with FFileList FFileList:= TStringList.Create; // Initialize members stopCompare:= False; pauseCompare:= false; curFile.Caption:= ''; {$IFOPT D+} btTemp.Show; {$ENDIF} end; procedure TMainForm.FormDestroy(Sender: TObject); begin FFileList.Free; end; // ----------------------------------------------------------------------------- // Private functions procedure TMainForm.BeforeRun; var s: string; begin // Initialize before run btRun.Enabled:= False; btStop.Enabled:= True; btPause.Enabled:= True; btExit.Enabled:= False; stopCompare := False; pauseCompare:= False; ProgressBar2.Max64:= GetTotalSize; ProgressBar1.Position64:= 0; ProgressBar2.Position64:= 0; fileRate.Caption:= '0%'; totalRate.Caption:= '0%'; FTime:= Now; DatetimeToString(s, 'hh:nn:ss', FTime); Memo1.Lines.Add(''); Memo1.Lines.Add('[' + s + '] start md5sum calculation...'); end; procedure TMainForm.AfterRun; var s, t: string; begin // Finish after run btRun.Enabled:= True; btStop.Enabled:= False; if pauseCompare then btPauseClick(Self); btPause.Enabled:= False; btExit.Enabled:= True; DatetimeToString(s, 'hh:nn:ss', Now); DatetimeToString(t, 'hh:nn:ss', Now-FTime); Memo1.Lines.Add('[' + s + '] finish (' + t + ' elapsed)'); end; procedure TMainForm.CheckPause; begin // Check if the Pause button is pressed if pauseCompare then repeat // Wait while processing other events Application.ProcessMessages; // exit loop if Stop button is pressed if stopCompare then break; // exit loop if Restart button is pressed until not pauseCompare; end; function TMainForm.GetTotalSize: Int64; var i: integer; begin // get sum of all file size Result:= 0; for i:= 1 to FFileList.Count do Inc(Result, File_Size(FFileList[i-1], 0)); end; function TMainForm.Int64ToKiloMegaGiga(ASize: Int64): string; const KILO = Int64(1024); MEGA = Int64(KILO * 1024); GIGA = Int64(MEGA * 1024); begin // Bytes를 용량에 따라 적당한 단위로 보기좋게 출력한다 if ASize < 1000 * 1 then Result:= inttostr(ASize) + ' Bytes' else if ASize < 10 * KILO then Result:= Format('%3.2f KB', [ASize / KILO]) else if ASize < 100 * KILO then Result:= Format('%3.1f KB', [ASize / KILO]) else if ASize < 1000 * KILO then Result:= Format('%3.0f KB', [ASize / KILO]) else if ASize < 10 * MEGA then Result:= Format('%3.2f MB', [ASize / MEGA]) else if ASize < 100 * MEGA then Result:= Format('%3.1f MB', [ASize / MEGA]) else if ASize < 1000 * MEGA then Result:= Format('%3.0f MB', [ASize / MEGA]) else if ASize < 10 * GIGA then Result:= Format('%3.2f GB', [ASize / GIGA]) else if ASize < 100 * GIGA then Result:= Format('%3.1f GB', [ASize / GIGA]) else {if ASize < 100 * GIGA then} Result:= Format('%3.0f GB', [ASize / GIGA]); end; procedure TMainForm.btTempClick(Sender: TObject); begin {$IFOPT D+} // Only for Test.. Memo1.Lines.Add(''); Memo1.Lines.Add('Int64ToKiloMegaGiga Test'); Memo1.Lines.Add(Int64ToKiloMegaGiga(1011)); Memo1.Lines.Add(Int64ToKiloMegaGiga(12345)); Memo1.Lines.Add(Int64ToKiloMegaGiga(101*1024)); Memo1.Lines.Add(Int64ToKiloMegaGiga(999*1024)); Memo1.Lines.Add(Int64ToKiloMegaGiga(1000*1024)); Memo1.Lines.Add(Int64ToKiloMegaGiga(1024*1024)); Memo1.Lines.Add(Int64ToKiloMegaGiga(123456)); Memo1.Lines.Add(Int64ToKiloMegaGiga(1234567)); Memo1.Lines.Add(Int64ToKiloMegaGiga(12345678)); Memo1.Lines.Add(Int64ToKiloMegaGiga(123456789)); Memo1.Lines.Add(Int64ToKiloMegaGiga(1234567890)); Memo1.Lines.Add(Int64ToKiloMegaGiga(12345678901)); Memo1.Lines.Add(Int64ToKiloMegaGiga(123456789012)); Memo1.Lines.Add(Int64ToKiloMegaGiga(1234567890123)); {$ENDIF} end; function TMainForm.GetMyMd5Sum(const FileName: string): string; var srcFile: TFileStream; memStream: TMemoryStream; numRead: integer; idmd5: TMyIdHashMessageDigest5; begin //returns MD5 hash for a file if not FileExists(FileName) then exit; idmd5:= TMyIdHashMessageDigest5.Create; idmd5.InitializeState; srcFile:= TFileStream.Create(fileName, fmOpenRead OR fmShareDenyWrite); srcFile.Seek(0, soBeginning); memStream:= TMemoryStream.Create; memStream.Seek(0, soBeginning); curFile.Caption:= FileName; ProgressBar1.Max64:= srcFile.Size; ProgressBar1.Position64:= 0; fileRate.Caption:= '0%'; try // until v1.3 : only 1 line, very slow, no response // Result:= idmd5.HashStreamAsHex(srcFile); // from v1.4 : New Improved method repeat Application.ProcessMessages; CheckPause; if stopCompare then break; // read maxRecord bytes. numRead is bytes actually read numRead:= srcFile.Read(FBuf, maxRecord); if numRead = 0 then break; // show progress bytes read ProgressBar1.StepBy64(numRead); fileRate.Caption:= inttostr(Floor(ProgressBar1.Position64/ProgressBar1.Max64*100)) + '%'; ProgressBar2.StepBy64(numRead); totalRate.Caption:= inttostr(Floor(ProgressBar2.Position64/ProgressBar2.Max64*100)) + '%'; // prepare data into memStream as bytes read memStream.Seek(0, soBeginning); memStream.Write(FBuf, numRead); memStream.Seek(0, soBeginning); // Depends on whether it is the body or the tail if srcFile.Position < srcFile.Size then idmd5.HashBody(memStream, numRead) else begin Result:= idmd5.HashTail(memStream, numRead, srcFile.Size); break; end; until false; finally idmd5.Free; memStream.Free; srcFile.Free; end; end; // ----------------------------------------------------------------------------- // Published event functions procedure TMainForm.FileDrop1Drop(Sender: TObject); var i: integer; s: string; begin // if several dropped FileDrop1 only keeps the last drop // so we must save it into FFileList accumulatively for i:= 1 to FileDrop1.FileCount do FFileList.Add(FileDrop1.Files[i-1]); // Show message on the screen (count & size) s:= Int64ToKiloMegaGiga(GetTotalSize); Memo1.Lines.Add(inttostr(FileDrop1.FileCount) + ' Files Added (Total ' + FFileList.Count.ToString + ' files, ' + s + ')'); end; procedure TMainForm.btRunClick(Sender: TObject); var i: integer; fn, s: string; begin // Initialize before run if FFileList.Count = 0 then exit; BeforeRun; // Calculate MD5SUM for i:= 1 to FFileList.Count do begin // Check if Stop button is pressed if stopCompare then break; // Feetch 1 file fn:= FFileList[i-1]; // calculate md5sum by v1.4 method (NEW) s:= LowerCase(GetMyMd5Sum(fn)); Memo1.Lines.Add(s + ': ' + ExtractFileName(fn)); end; // Finish after run AfterRun; end; procedure TMainForm.btPauseClick(Sender: TObject); begin // Pause pauseCompare:= not pauseCompare; if pauseCompare then begin btPause.Caption:= 'Start'; btPause.Glyph:= btRun.Glyph; end else begin btPause.Caption:= 'Pause'; btPause.Glyph:= btTemp.Glyph; end; end; procedure TMainForm.btStopClick(Sender: TObject); begin // Stop stopCompare:= true; // if paused than go to continue state if pauseCompare then btPauseClick(Sender); end; procedure TMainForm.btCopyTextClick(Sender: TObject); begin // Copy all Text of Memo1 to ClipBoard ClipBrd.Clipboard.AsText:= Memo1.Text; end; procedure TMainForm.btClearClick(Sender: TObject); begin // Clear all, go to initial state FileDrop1.Files.Clear; FFileList.Clear; Memo1.Lines.Clear; Memo1.Lines.Add('Please Drag & Drop Files and click RUN! button.'); curFile.Caption:= ''; ProgressBar1.Max64:= 100; ProgressBar2.Max64:= 100; ProgressBar1.Position64:= 0; ProgressBar2.Position64:= 0; fileRate.Caption:= '0%'; totalRate.Caption:= '0%'; end; procedure TMainForm.btExitClick(Sender: TObject); begin Close; end; procedure TMainForm.Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // Ctrl-A (Select All) / Ctrl-C (Copy) if ssCtrl in Shift then begin if (Key = Ord('A')) or (Key = Ord('a')) then Memo1.SelectAll; if (Key = Ord('C')) or (Key = Ord('c')) then ClipBrd.Clipboard.AsText:= Memo1.SelText; end; end; end.
unit ui_main_menu; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, ui_menu_template, BitmapLabel, core_game, core_types, core_ui, core_input, core_network, core_player, DCPsha256, lNetComponents, fgl, core_logic, core_tcp, core_orders_manager, core_orders, VectorGeometry, core_actor_definitions, lNet, math; type { TmenuForm } TmenuForm = class(TmenuTemplate) BitmapLabel1: TBitmapLabel; addressE: TComboBox; sha: TDCP_sha256; loginBtn: TBitmapLabel; loginE: TEdit; tcp: TLTCPComponent; passE: TEdit; singleBtn: TBitmapLabel; joinBtn: TBitmapLabel; hostBtn: TBitmapLabel; topBar1: TBitmapLabel; procedure FormDestroy(Sender: TObject); procedure hostBtnClick(Sender: TObject); procedure loginBtnClick(Sender: TObject); procedure singleBtnClick(Sender: TObject); procedure joinBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure tcpConnect(aSocket: TLSocket); procedure tcpDisconnect(aSocket: TLSocket); procedure tcpError(const msg: string; aSocket: TLSocket); procedure tcpReceive(aSocket: TLSocket); private { private declarations } buf:array [0..255] of byte; function playerExists(const l:tlogin):integer; public { public declarations } me:TPlayerInfo; mapInfo:rMapInfo; //MapInfo:rMapInfo; seats:TPlayerInfoArray; procedure startHostGame; procedure joinGame; end; var menuForm: TmenuForm; implementation {$R *.lfm} { TmenuForm } procedure TmenuForm.FormCreate(Sender: TObject); begin inherited; lockWidth:=true; lockHeight:=true; logine.Text:=format('demo%d',[random(99999)]); end; procedure TmenuForm.tcpConnect(aSocket: TLSocket); var i,count:cardinal; s:string; begin log('connected to planet'); fillchar(buf,length(Buf),0); //set own ip, wtf? convertIp(asocket.LocalAddress,me.ip); //encode which command this is Buf[0]:=byte(mmLogin); //length of login count := min(length(logine.text),16); Buf[1]:=count; //copy login s:=lowercase(logine.Text); move(s[1],Buf[2],count); inc(count,2); //len of pass sha.Init; s:=passe.text; sha.Update(s[1],length(s)); sha.Final(Buf[count]); //move(s[1],Buf[count],length(s)); i:=sha.HashSize div 8; //i:=length(s); inc(count,i); tcp.Send(Buf,count); end; procedure TmenuForm.tcpDisconnect(aSocket: TLSocket); begin log('disconnected from planet'); end; procedure TmenuForm.tcpError(const msg: string; aSocket: TLSocket); begin log('achtung! tcp:' + msg); end; procedure TmenuForm.tcpReceive(aSocket: TLSocket); var s:string; got,i:integer; c:cardinal; begin got:=aSocket.Get(Buf[0],length(Buf)); if got>0 then begin //log(format('%s> %s',[asocket.PeerAddress,s])); case eTcpMessages(Buf[0]) of mmStartGameHost:startHostGame; mmJoinGame:joinGame; mmRoomState:begin move(buf[1],MapInfo,sizeof(rMapInfo)); c:=sizeof(rMapInfo)+1; //port assigned to this client move(buf[c],me.qport,2); inc(c,2); //loadout move(buf[c],me.info,sizeof(rPlayerInfo)); inc(c,sizeof(rPlayerInfo)); //how many players? +1 for self at end of table SetLength(seats,min(buf[c],maxPlayers-1)+1); inc(c); //info about other players in a room for i:=0 to length(seats)-2 do with seats[i] do begin setString(login,@buf[c+1],buf[c]); c+=length(login)+1; move(buf[c],ip,sizeof(ip)); inc(c,sizeof(ip)); move(buf[c],info,sizeof(rPlayerInfo)); inc(c,sizeof(rPlayerInfo)); end; //copy 'own' data to last seat for iterating convenievne move(me,seats[length(seats)-1],sizeof(TPlayerInfo)); //state of the game. player will start the game immiedietly if rsInGame if eRoomStates(buf[c])=rsInGame then joinGame; end; mmPlayerInfo:begin //if player already exists on the list then update, oterhwise add SetString(s,@buf[2],buf[1]); // move(buf[2],s[1],length(s)); i:=playerExists(s); if i=-1 then begin i:=length(seats); setlength(seats,length(seats)+1); end; with seats[i] do begin //buf[1]:=length(login); login:=s; c:=2+length(login)+1; move(buf[c],ip,sizeof(ip)); inc(c,sizeof(ip)); move(buf[c],info,sizeof(rPlayerInfo)); inc(c,sizeof(rPlayerInfo)); move(buf[c],qport,2); end; end; end; end; end; function TmenuForm.playerExists(const l: tlogin): integer; var i:integer; begin result:=-1; for i:=0 to length(seats)-1 do if seats[i].login=l then begin result:=i; break; end; end; procedure TmenuForm.startHostGame; var i:integer; begin player1.login:=me.login; network.initializeGame(mapInfo,seats); //multi mode, hosting a game game.loadGame(format('%s%s%s%dx%d%s',[appPath,'world',DirectorySeparator,mapInfo.mapX,mapInfo.mapY,'.terrain']),true); //lock mouse inputManager.mouseLocked:=true; //show crosshairs uiManager.toggleCrosshair(true); //tell network that we are hosting network.setMode(true); //spawn host's actor. probably should be done elswhere.. i:=logic.getNextFreeId; network.clients[0].actorId:=i; network.clients[0].port:=10; player1.actorID:=i; om.addOrder(orCreateActor, i, integer(network.clients[0].characterType), vector3fmake(0,32,0), getActorCommonProperties(network.clients[0].characterType).size ); oM.addOrder(orToggleBrain,player1.actorID,0); oM.addCameraMode(player1.actorID,cm3rdPerson); close; end; procedure TmenuForm.joinGame; begin player1.login:=me.login; network.initializeGame(mapInfo,seats); //first set player name to player2 cause server is already player1 game.loadGame(format('%s%s%s%dx%d%s',[appPath,'world',DirectorySeparator,mapInfo.mapX,mapInfo.mapY,'.terrain']),true); //lock mouse inputManager.mouseLocked:=true; //show crosshairs uiManager.toggleCrosshair(true); //tell network that we are joining network.setMode(false); close; end; procedure TmenuForm.singleBtnClick(Sender: TObject); begin //single player mode game.loadGame(format('%s%s%s%s',[appPath,'saves',DirectorySeparator,'map.terrain']),false); //lock mouse inputManager.mouseLocked:=true; //show crosshairs uiManager.toggleCrosshair(true); close; end; procedure TmenuForm.hostBtnClick(Sender: TObject); var i:integer; begin //create game room and put self in the first slot setlength(seats,1); move(me,seats[0],sizeof(me)); Buf[0]:=byte(mmHost); tcp.Send(Buf,1); end; procedure TmenuForm.FormDestroy(Sender: TObject); var i:integer; begin // for i:=0 to length(seats)-1 do seats[i].free; //seats.free; end; procedure TmenuForm.loginBtnClick(Sender: TObject); begin me.login:=lowercase(logine.Text); // moje ip? //me.ip; //me.info; tcp.Connect(addresse.Text,440); log('connecting..'); end; procedure TmenuForm.joinBtnClick(Sender: TObject); begin //send find match request Buf[0]:=byte(mmFind); tcp.Send(Buf,1); end; end.
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Ported to Delphi by Michal Wojcik. // // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved. // Released under the terms of the GNU General Public License version 2 or later. {$H+} unit CachingResultFormatter; interface uses ContentBuffer, ResultFormatter, classes, InputStream, PageResult, Counts, ResultHandler; type TCachingResultFormatter = class(TInterfacedObject, TResultFormatter) private buffer : TContentBuffer; subHandlers : TList; public constructor Create; destructor Destroy; override; function getByteCount() : Integer; function getResultStream() : TInputStream; procedure acceptResult(result : TPageResult); procedure acceptFinalCount(count : TCounts); procedure addHandler(handler : TResultHandler); procedure cleanUp; end; implementation uses ByteArrayOutputStream, FitProtocol; constructor TCachingResultFormatter.Create; begin subHandlers := TList.Create; buffer := TContentBuffer.Create('.results'); end; destructor TCachingResultFormatter.Destroy; begin buffer.Free; subHandlers.Free; end; procedure TCachingResultFormatter.acceptResult(result : TPageResult); var output : TByteArrayOutputStream; i : Integer; begin output := TByteArrayOutputStream.Create(); TFitProtocol.writeData(result.toString() + #13#10, output); buffer.append(output.toByteArray()); for i := 0 to subHandlers.Count - 1 do TResultHandler(subHandlers[i]).acceptResult(result); end; procedure TCachingResultFormatter.acceptFinalCount(count : TCounts); var output : TByteArrayOutputStream; i : Integer; begin output := TByteArrayOutputStream.Create(); TFitProtocol.writeCounts(count, output); buffer.append(output.toByteArray()); for i := 0 to subHandlers.Count - 1 do TResultHandler(subHandlers[i]).acceptFinalCount(count); end; function TCachingResultFormatter.getByteCount() : Integer; begin Result := buffer.getSize(); end; function TCachingResultFormatter.getResultStream() : TInputStream; begin Result := buffer.getNonDeleteingInputStream(); end; procedure TCachingResultFormatter.cleanUp(); begin buffer.delete(); end; procedure TCachingResultFormatter.addHandler(handler : TResultHandler); begin subHandlers.add(Pointer(handler)); end; end.
unit Model.Title; interface uses Model.Interfaces, Model.IMyConnection, System.Generics.Collections, Spring.Collections, MainDM; function CreateTitleModelClass: ITitleModelInterface; implementation uses System.SysUtils, Spring.Data.ObjectDataset, Spring.Persistence.Criteria.Interfaces, Spring.Persistence.Criteria.Restrictions, Spring.Persistence.Criteria.OrderBy, Model.Declarations, Model.FormDeclarations, Forms; type TTitleModel = class (TInterfacedObject, ITitleModelInterface) private fTitle: TTitle; public function GetAllTitles(const acompanyId : Integer; const filter : string) : IObjectList; function GetAllTitlesDS(const acompanyId : Integer; const filter : string) : TObjectDataset; procedure AddTitle(const newTitle: TTitle); function GetTitle(const TitleId : Integer) : TTitle; procedure UpdateTitle(const Title: TTitle); procedure DeleteTitle(const Title: TTitle); end; function CreateTitleModelClass: ITitleModelInterface; begin result:=TTitleModel.Create; end; { TTitleModel } procedure TTitleModel.AddTitle(const newTitle: TTitle); begin DMMain.Session.Insert(newTitle); end; procedure TTitleModel.DeleteTitle(const Title: TTitle); begin DMMain.Session.Delete(Title); end; function TTitleModel.GetAllTitles(const acompanyId : Integer; const filter: string): IObjectList; var FCriteria : ICriteria<TTitle>; begin FCriteria := DMMain.Session.CreateCriteria<TTitle>; Result := FCriteria .Add(Restrictions.Eq('CompanyId', acompanyId)) .Add(Restrictions.Eq('IsDeleted', 0)) .OrderBy(TOrderBy.Asc('TitleId')).ToList as IObjectList; end; function TTitleModel.GetAllTitlesDS(const acompanyId : Integer; const filter: string): TObjectDataset; begin Result := TObjectDataSet.Create(Application); Result.DataList := GetAllTitles(acompanyId, ''); end; function TTitleModel.GetTitle(const TitleId : Integer) : TTitle; begin Result := DMMain.Session.FindOne<TTitle>(TitleId); end; procedure TTitleModel.UpdateTitle(const Title: TTitle); begin DMMain.Session.Update(Title); end; end.
unit TarFTP.MocksAndStubs; interface uses SysUtils, Classes, TarFTP.Interfaces, TarFTP.MVC, TarFTP.Factory; type TArchiverStub = class(TInterfacedObject, IArchiver) public { IArchiver } function GetOnProgress : TProgressEvent; procedure SetOnProgress(Value : TProgressEvent); property OnProgress : TProgressEvent read GetOnProgress write SetOnProgress; procedure AddFile(const FileName : String); procedure CompressToFile(const OutputFile : String); end; TFtpSenderStub = class(TInterfacedObject, IFtpSender) public { IFtpSender } function GetOnProgress : TProgressEvent; procedure SetOnProgress(Value : TProgressEvent); property OnProgress : TProgressEvent read GetOnProgress write SetOnProgress; procedure EstablishConnection(const Url : String); procedure LogIn(const Url, Login, Password: string); procedure UploadFile(const FileName : String); procedure Abort; procedure Disconnect; end; TModelStub = class(TInterfacedObject, IModel) public { IModel } function GetOnFileCompress : TWorkProgressEvent; procedure SetOnFileCompress(Value : TWorkProgressEvent); property OnFileCompress : TWorkProgressEvent read GetOnFileCompress write SetOnFileCompress; function GetOnFileUpload : TWorkProgressEvent; procedure SetOnFileUpload(Value : TWorkProgressEvent); property OnFileUpload : TWorkProgressEvent read GetOnFileUpload write SetOnFileUpload; function GetOnTaskEvent : TModelNotifyEvent; procedure SetOnTaskEvent(Value : TModelNotifyEvent); property OnTaskEvent : TModelNotifyEvent read GetOnTaskEvent write SetOnTaskEvent; function GetTerminated : Boolean; property Terminated : Boolean read GetTerminated; function GetError : Boolean; property Error: Boolean read GetError; procedure Reset; procedure AddFile(const FileName : String); procedure SetOutputFile(const OutputFile : String); procedure SetFtpCredentials(const Host, Login, Password: string); procedure NeedError; procedure Compress; procedure Upload; procedure TerminateTask; procedure ForcedTerminateTask; end; TArchiverMock = class(TInterfacedObject, IArchiver) private FAddFile_FileName: String; FArchiver: IArchiver; FCompressToFile_OutputFile: String; public { IArchiver } function GetOnProgress : TProgressEvent; procedure SetOnProgress(Value : TProgressEvent); property OnProgress : TProgressEvent read GetOnProgress write SetOnProgress; procedure AddFile(const FileName : String); procedure CompressToFile(const OutputFile : String); { Common } property AddFile_FileName: String read FAddFile_FileName write FAddFile_FileName; property CompressToFile_OutputFile: String read FCompressToFile_OutputFile write FCompressToFile_OutputFile; constructor Create; destructor Destroy; override; end; TFtpSenderMock = class(TInterfacedObject, IFtpSender) private FLogIn_Url: String; FLogIn_Login: String; FLogIn_Password: String; FUploadFile_FileName: String; FDisconnectCalled: Boolean; FFtpSender: IFtpSender; public { IFtpSender } function GetOnProgress : TProgressEvent; procedure SetOnProgress(Value : TProgressEvent); property OnProgress : TProgressEvent read GetOnProgress write SetOnProgress; procedure LogIn(const Url, Login, Password : String); procedure UploadFile(const FileName : String); procedure Abort; procedure Disconnect; { Common } property LogIn_Url: String read FLogIn_Url write FLogIn_Url; property LogIn_Login: String read FLogIn_Login write FLogIn_Login; property LogIn_Password: String read FLogIn_Password write FLogIn_Password; property UploadFile_FileName: String read FUploadFile_FileName write FUploadFile_FileName; property DisconnectCalled: Boolean read FDisconnectCalled write FDisconnectCalled; constructor Create; destructor Destroy; override; end; TFactoryMock = class(TInterfacedObject, IFactory) private FArchiver : IArchiver; FFtpSender : IFtpSender; public { IFactory } function CreateArchiver : IArchiver; function CreateFtpSender : IFtpSender; function CreateTask : ITask; { Common } property Archiver: IArchiver read FArchiver write FArchiver; property FtpSender: IFtpSender read FFtpSender write FFtpSender; destructor Destroy; override; end; implementation uses TarFTP.Tasks; { TArchiverStub } procedure TArchiverStub.AddFile(const FileName: String); begin end; procedure TArchiverStub.CompressToFile(const OutputFile: String); begin with TStringList.Create do try SaveToFile( OutputFile ); finally Free; end; end; function TArchiverStub.GetOnProgress: TProgressEvent; begin Result := nil; end; procedure TArchiverStub.SetOnProgress(Value: TProgressEvent); begin end; { TFtpSenderStub } procedure TFtpSenderStub.Abort; begin end; procedure TFtpSenderStub.Disconnect; begin end; procedure TFtpSenderStub.EstablishConnection(const Url: String); begin end; function TFtpSenderStub.GetOnProgress: TProgressEvent; begin Result := nil; end; procedure TFtpSenderStub.LogIn(const Url, Login, Password: string); begin end; procedure TFtpSenderStub.SetOnProgress(Value: TProgressEvent); begin end; procedure TFtpSenderStub.UploadFile(const FileName: String); begin end; { TModelStub } procedure TModelStub.AddFile(const FileName: String); begin end; procedure TModelStub.Compress; begin end; procedure TModelStub.ForcedTerminateTask; begin end; function TModelStub.GetError: Boolean; begin Result := False; end; function TModelStub.GetOnFileCompress: TWorkProgressEvent; begin Result := nil; end; function TModelStub.GetOnFileUpload: TWorkProgressEvent; begin Result := nil; end; function TModelStub.GetOnTaskEvent: TModelNotifyEvent; begin Result := nil; end; function TModelStub.GetTerminated: Boolean; begin Result := False; end; procedure TModelStub.NeedError; begin end; procedure TModelStub.Reset; begin end; procedure TModelStub.SetFtpCredentials(const Host, Login, Password: string); begin end; procedure TModelStub.SetOnFileCompress(Value: TWorkProgressEvent); begin end; procedure TModelStub.SetOnFileUpload(Value: TWorkProgressEvent); begin end; procedure TModelStub.SetOnTaskEvent(Value: TModelNotifyEvent); begin end; procedure TModelStub.SetOutputFile(const OutputFile: String); begin end; procedure TModelStub.TerminateTask; begin end; procedure TModelStub.Upload; begin end; { TFactoryMock } function TFactoryMock.CreateArchiver: IArchiver; begin Result := FArchiver; end; function TFactoryMock.CreateFtpSender: IFtpSender; begin Result := FFtpSender; end; function TFactoryMock.CreateTask: ITask; begin Result := TSimpleTask.Create; end; destructor TFactoryMock.Destroy; begin FArchiver := nil; FFtpSender := nil; inherited; end; { TArchiverMock } procedure TArchiverMock.AddFile(const FileName: String); begin FAddFile_FileName := FileName; FArchiver.AddFile( FileName ); end; procedure TArchiverMock.CompressToFile(const OutputFile: String); begin FCompressToFile_OutputFile := OutputFile; FArchiver.CompressToFile( OutputFile ); end; constructor TArchiverMock.Create; begin with TFactory.Create do try FArchiver := CreateArchiver; finally Free; end; end; destructor TArchiverMock.Destroy; begin FArchiver := nil; inherited; end; function TArchiverMock.GetOnProgress: TProgressEvent; begin Result := FArchiver.OnProgress; end; procedure TArchiverMock.SetOnProgress(Value: TProgressEvent); begin FArchiver.OnProgress := Value; end; { TFtpSenderMock } procedure TFtpSenderMock.Abort; begin FFtpSender.Abort; end; constructor TFtpSenderMock.Create; begin with TFactory.Create do try FFtpSender := CreateFtpSender; finally Free; end; end; destructor TFtpSenderMock.Destroy; begin FFtpSender := nil; inherited; end; procedure TFtpSenderMock.Disconnect; begin FDisconnectCalled := True; FFtpSender.Disconnect; end; function TFtpSenderMock.GetOnProgress: TProgressEvent; begin Result := FFtpSender.OnProgress; end; procedure TFtpSenderMock.LogIn(const Url, Login, Password: String); begin FLogIn_Url := Url; FLogIn_Login := Login; FLogIn_Password := Password; FFtpSender.LogIn( Url, Login, Password ); end; procedure TFtpSenderMock.SetOnProgress(Value: TProgressEvent); begin FFtpSender.OnProgress := Value; end; procedure TFtpSenderMock.UploadFile(const FileName: String); begin FUploadFile_FileName := FileName; FFtpSender.UploadFile( FileName ); end; end.
unit uServer; {$mode objfpc}{$H+} {$DEFINE DEBUG}// Альтернатива -dDEBUG {$C+}// Альтернатива Включить Assert interface uses Classes, SysUtils, WinSock2, Windows, uBase, uModbus; type { TServer } TServer = class(TBase, IServer) private fHandle: THandle; // дескриптор окна обработки сообщения (принимает новый контроллер) fAcTcpBuilder: IAcTcpBuilder; fControllerPool: IControllerPool; fTcpConnection: ITcpConnection; // События нити // fEvents[0] используется для остановки нити // fEvents[1] связывается с событием FD_ACCEPT fEvents: array[0..1] of WSAEvent; // Флаг активности потока: 1 - активен, 0 - нет fActive: integer; // Указатель на поток событий на порту fEventLoop: TThreadId; private // Создание, закрытие, сброс событий на сокете procedure CreateEvents; procedure CloseEvents; procedure ResetEvents; protected function GetTcpConnection: ITcpConnection; procedure SetTcpConnection(const aTcpConnection: ITcpConnection); procedure SetAcTcpBuilder(const aAcTcpBuilder: IAcTcpBuilder); procedure SetControllerPool(const aControllerPool: IControllerPool); function GetHandle: THandle; procedure SetHandle(const aHandle: THandle); public procedure AfterConstruction; override; destructor Destroy; override; public constructor Create(const aAcTcpBuilder: IAcTcpBuilder; const aControllerPool: IControllerPool); overload; function Start: boolean; procedure Stop; function IsActive: boolean; property AcTcpBuilder: IAcTcpBuilder write SetAcTcpBuilder; property ControllerPoll: IControllerPool write SetControllerPool; property TcpConnection: ITcpConnection read GetTcpConnection write SetTcpConnection; property Handle: THandle read GetHandle write SetHandle; end; implementation const ERROR_WSA_CREATE_EVENT = 1; ERROR_WSA_EVENT_SELECT = 2; ERROR_THREAD_ARGUMENT = 3; ERROR_CREATE_EVENT_LOOP = 4; ERROR_ENUM_NETWORK_EVENT = 5; ERROR_UNKNOWN_EVENT = 6; ERROR_FD_ACCEPT = 7; ERROR_WSA_WAIT_FUNCTION = 8; ERROR_ACCEPT = 9; ERROR_CONNECTION = 10; resourcestring sERROR_WSA_CREATE_EVENT = 'Ошибка создания сокетного события'; sERROR_WSA_EVENT_SELECT = 'Ошибка связвания события с сокетом'; sERROR_THREAD_ARGUMENT = 'Аргумент потока равен nil'; sERROR_CREATE_EVENT_LOOP = 'Ошибка создания потока событий'; sERROR_ENUM_NETWORK_EVENT = 'Ошибка сброса события'; sERROR_UNKNOWN_EVENT = 'Неизвестное событие'; sERROR_FD_ACCEPT = 'Ошибка события Accept'; sERROR_WSA_WAIT_FUNCTION = 'Ошибка функции ожидания событий'; sERROR_ACCEPT = 'Ошибка подключения клиента'; sERROR_CONNECTION = 'Ошибка подключения'; function ListenPort(Parameter: Pointer): integer; var Server: TServer; NetEvents: TWSANetworkEvents; // Сокет, созданный для общения с подключившимся клиентом ClientSocket: TSocket; // Адрес подключившегося клиента ClientAddr: TSockAddr; ClientAddrLen: LongInt; ClientController: IController; begin Result := 0; if Parameter = nil then begin SetLastError(ERROR_THREAD_ARGUMENT); Exit; end; // Приведение указателя Server := TServer(Parameter); // Флаг активности Windows.InterLockedExchange(Server.fActive, 1); try // Основной цикл событий repeat // Ожидание событий case WSAWaitForMultipleEvents(2, @Server.fEvents, False, WSA_INFINITE, False) of // Событие FEvents[0] взведено - закрытие потока событий WSA_WAIT_EVENT_0: Break; // Событие FEvents[1] взведено - наступление события FD_ACCEPT WSA_WAIT_EVENT_0 + 1: begin // Сбрасываем событие if WSAEnumNetworkEvents(Server.TcpConnection.Sock, Server.fEvents[1], @NetEvents) = SOCKET_ERROR then begin Server.SetLastError(ERROR_ENUM_NETWORK_EVENT); Break; end; // Проверка на соответствие событию FD_ACCEPT if NetEvents.lNetworkEvents and FD_ACCEPT = 0 then begin Server.SetLastError(ERROR_UNKNOWN_EVENT); Break; end; // Проверка, не было ли ошибок if NetEvents.iErrorCode[FD_ACCEPT_BIT] <> 0 then begin Server.SetLastError(ERROR_FD_ACCEPT); Break; end; // Создаем сокетное соединение с клиентом ClientAddrLen := SizeOf(ClientAddr); // Проверяем наличие подключения ClientSocket := Accept(Server.TcpConnection.Sock, @ClientAddr, ClientAddrLen); if ClientSocket = INVALID_SOCKET then begin Server.SetLastError(ERROR_ACCEPT); if WSAGetLastError <> WSAEWOULDBLOCK then Continue; Break; end; // Новый контроллер if not Server.fControllerPool.ReplaceConnection(ClientSocket) then begin ClientController := Server.fAcTcpBuilder.GetController(ClientSocket); ClientController.Open; Server.fControllerPool.Add(ClientController); // Отправить сообщение дескриптору окна с указателем на интерфейс контроллера SendMessage(Server.Handle, WM_NEW_CLIENT, {%H-}Integer(Pointer(ClientController)), 0); end; end else begin Server.SetLastError(ERROR_WSA_WAIT_FUNCTION); Break; end; end; until False; finally // Флаг активности Windows.InterLockedExchange(Server.fActive, 0); end; end; { TServer } procedure TServer.AfterConstruction; begin inherited AfterConstruction; fErrors.Add(ERROR_WSA_CREATE_EVENT, sERROR_WSA_CREATE_EVENT); fErrors.Add(ERROR_WSA_EVENT_SELECT, sERROR_WSA_EVENT_SELECT); fErrors.Add(ERROR_THREAD_ARGUMENT, sERROR_THREAD_ARGUMENT); fErrors.Add(ERROR_CREATE_EVENT_LOOP, sERROR_CREATE_EVENT_LOOP); fErrors.Add(ERROR_ENUM_NETWORK_EVENT, sERROR_ENUM_NETWORK_EVENT); fErrors.Add(ERROR_UNKNOWN_EVENT, sERROR_UNKNOWN_EVENT); fErrors.Add(ERROR_FD_ACCEPT, sERROR_FD_ACCEPT); fErrors.Add(ERROR_WSA_WAIT_FUNCTION, sERROR_WSA_WAIT_FUNCTION); fErrors.Add(ERROR_ACCEPT, sERROR_ACCEPT); fErrors.Add(ERROR_CONNECTION, sERROR_CONNECTION); // Создание событий CreateEvents; end; destructor TServer.Destroy; begin Stop; CloseEvents; inherited Destroy; end; constructor TServer.Create(const aAcTcpBuilder: IAcTcpBuilder; const aControllerPool: IControllerPool); begin inherited Create; fAcTcpBuilder := aAcTcpBuilder; fControllerPool := aControllerPool; end; function TServer.Start: boolean; begin Result := False; {$IFDEF DEBUG} Assert(TcpConnection <> nil); Assert(TcpConnection.Port <> 0); Assert(fAcTcpBuilder <> nil); Assert(fControllerPool <> nil); {$ENDIF} // Вначале закрыть сокет Stop; // Открытие сокета if TcpConnection = nil then begin fLastError := ERROR_CONNECTION; Exit; end; TcpConnection.Open; if TcpConnection.Sock = INVALID_SOCKET then Exit; {$IFDEF DEBUG} Assert(fEvents[1] <> WSA_INVALID_HANDLE); {$ENDIF} // Привязывание сокета к событию if WSAEventSelect(TcpConnection.Sock, fEvents[1], FD_ACCEPT) = SOCKET_ERROR then begin fLastError := ERROR_WSA_EVENT_SELECT; Exit; end; // Создание слушающего потока fEventLoop := BeginThread(@ListenPort, Self); if fEventLoop = 0 then begin fLastError := ERROR_CREATE_EVENT_LOOP; Exit; end; Result := True; end; procedure TServer.Stop; const TIMEOUT_CLOSE = 5000; begin // Закрытие потока if fEventLoop <> 0 then begin WSASetEvent(FEvents[0]); WaitForThreadTerminate(fEventLoop, TIMEOUT_CLOSE); CloseThread(fEventLoop); fEventLoop := 0; // Сброс событий ResetEvents; end; // Закрытие сокета if TcpConnection <> nil then TcpConnection.Close; end; procedure TServer.CreateEvents; begin // События нити // fEvents[0] используется для остановки нити fEvents[0] := WSACreateEvent; if fEvents[0] = WSA_INVALID_HANDLE then begin fLastError := ERROR_WSA_CREATE_EVENT; Exit; end; // fEvents[1] связывается с событием FD_ACCEPT fEvents[1] := WSACreateEvent; if FEvents[1] = WSA_INVALID_HANDLE then begin fLastError := ERROR_WSA_CREATE_EVENT; Exit; end; end; procedure TServer.CloseEvents; begin WSACloseEvent(fEvents[0]); WSACloseEvent(fEvents[1]); end; procedure TServer.ResetEvents; begin WSAResetEvent(fEvents[0]); WSAResetEvent(fEvents[1]); end; procedure TServer.SetAcTcpBuilder(const aAcTcpBuilder: IAcTcpBuilder); begin fAcTcpBuilder := aAcTcpBuilder; end; procedure TServer.SetControllerPool(const aControllerPool: IControllerPool); begin fControllerPool := aControllerPool; end; function TServer.GetHandle: THandle; begin Result := fHandle; end; procedure TServer.SetHandle(const aHandle: THandle); begin if fHandle <> aHandle then fHandle := aHandle; end; function TServer.IsActive: boolean; begin Result := Windows.InterlockedCompareExchange(fActive, 0, 0) = 1; end; function TServer.GetTcpConnection: ITcpConnection; begin Result := fTcpConnection; end; procedure TServer.SetTcpConnection(const aTcpConnection: ITcpConnection); begin fTcpConnection := aTcpConnection; end; end.
//Only compile for the LINUX platform. {$IF NOT Defined(LINUX)} {$MESSAGE Fatal 'AT.Linux.Libc.pas only compiles for the LINUX platform.'} {$ENDIF} // ****************************************************************** // // Program Name : Angelic Tech Linux Library // Program Version: 2017 // Platform(s) : Linux // Framework : None // // Filename : AT.Linux.Libc.pas // File Version : 2017.04 // Date Created : 15-Apr-2017 // Author : Matthew Vesperman // // Description: // // Linux libc imports. // // Revision History: // // v1.00 : Initial version // // ****************************************************************** // // COPYRIGHT © 2017 - PRESENT Angelic Technology // ALL RIGHTS RESERVED WORLDWIDE // // ****************************************************************** /// <summary> /// Contains Linux libc import statements. /// </summary> unit AT.Linux.Libc; interface uses Posix.Base, // System.SysUtils, // Posix.Stdlib, // Posix.Fcntl, Posix.SysTypes; type TStreamHandle = Pointer; function _execv(const Command: MarshaledAString; const ArgV: Pointer): Integer; cdecl; external libc name _PU + 'execv'; function _fgets(ABuffer: Pointer; ASize: Int32; AStream: TStreamHandle): Pointer; cdecl; external libc name _PU + 'fgets'; function _fork(): pid_t; cdecl; external libc name _PU + 'fork'; function _pclose(AHandle: TStreamHandle): Int32; cdecl; external libc name _PU + 'pclose'; function _popen(const ACommand: MarshaledAString; const AType: MarshaledAString): TStreamHandle; cdecl; external libc name _PU + 'popen'; implementation end.
unit AutoScrollableMemo; interface uses Windows, Messages, StdCtrls, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs; type TAutoScrollableMemo = class (TMemo) private FAutoScrollable: Boolean; procedure OnWinCommandReceived(var Message: TWMCommand); message WM_COMMAND; protected procedure UpdateScrollBarsVisibility; procedure SetAutoScrollable(const AutoScrollable: Boolean); procedure SetScrollBars(Value: TScrollStyle); published property AutoScrollable: Boolean read FAutoScrollable write SetAutoScrollable; end; procedure Register; implementation uses AuxWindowsFunctionsUnit; { TAutoScrollableMemo } procedure TAutoScrollableMemo.OnWinCommandReceived(var Message: TWMCommand); begin if (Message.Ctl = Handle) and (Message.NotifyCode = EN_UPDATE) and FAutoScrollable then begin UpdateScrollBarsVisibility; end; inherited; end; procedure TAutoScrollableMemo.SetAutoScrollable(const AutoScrollable: Boolean); begin FAutoScrollable := AutoScrollable; UpdateScrollBarsVisibility; end; procedure TAutoScrollableMemo.SetScrollBars(Value: TScrollStyle); begin if not FAutoScrollable then inherited; end; procedure TAutoScrollableMemo.UpdateScrollBarsVisibility; var TextLength: Integer; begin TextLength := CalculateTextLength; Pare end; end.
{ JustOne v2.0 Modified by: Eric Pankoke email: epankoke@cencom.net Changes - Written for Delphi 2.0 - PerformAction was added - Previous version info moved to readme.txt This component is designed to prevent users from being able to open multiple instances of your applications designed with Delphi 2.0. Just drop the component into your form, tell it whether to reactivate the original instance or just send it a message, and you're ready to go. } unit Justone; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, DsgnIntf; type TJustOne = class(TComponent) private FAbout: string; FSendMsg: string; public FMessageID: DWORD; constructor Create(AOwner:TComponent); override; procedure Loaded; override; destructor Destroy; override; procedure GoToPreviousInstance; procedure ShowAbout; published property About: string read FAbout write FAbout stored False; property SendMsg: string read FSendMsg write FSendMsg; end; procedure Register; type PHWND = ^HWND; implementation {########################################################################} type TAboutProperty = class(TPropertyEditor) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; function GetValue:string; override; end; {########################################################################} procedure TAboutProperty.Edit; {Invoke the about dialog when clicking on ... in the Object Inspector} begin TJustOne(GetComponent(0)).ShowAbout; end; {########################################################################} function TAboutProperty.GetAttributes: TPropertyAttributes; {Make settings for just displaying a string in the ABOUT property in the Object Inspector} begin GetAttributes := [paDialog, paReadOnly]; end; {########################################################################} function TAboutProperty.GetValue: String; {Text in the Object Inspector for the ABOUT property} begin GetValue := '(About)'; end; {########################################################################} procedure TJustOne.ShowAbout; var msg: string; const carriage_return = chr(13); copyright_symbol = chr(169); begin msg := 'JustOne v2.0'; AppendStr(msg, carriage_return); AppendStr(msg, 'A Freeware component'); AppendStr(msg, carriage_return); AppendStr(msg, carriage_return); AppendStr(msg, 'Copyright '); AppendStr(msg, copyright_symbol); AppendStr(msg, ' 1995, 1996 by Steven L. Keyser'); AppendStr(msg, carriage_return); AppendStr(msg, 'e-mail 71214.3117@compuserve.com'); AppendStr(msg, carriage_return); AppendStr(msg, 'and Eric Pankoke (for v2.0 upgrade)'); AppendStr(msg, carriage_return); AppendStr(msg, 'e-mail epankoke@cencom.net'); AppendStr(msg, carriage_return); ShowMessage(msg); end; {########################################################################} procedure Register; {If you want, replace 'SLicK' with whichever component page you want JustOne to show up on.} begin RegisterComponents('PosControl2', [TJustOne]); RegisterPropertyEditor(TypeInfo(String), TJustOne, 'About', TAboutProperty); RegisterPropertyEditor(TypeInfo(string), TJustOne, 'SendMsg', TStringProperty); end; {########################################################################} procedure TJustOne.GotoPreviousInstance; begin PostMessage(hwnd_Broadcast, FMessageID, 0, 0); end; {########################################################################} constructor TJustOne.Create(AOwner:TComponent); begin inherited Create(AOwner); end; {########################################################################} procedure TJustOne.Loaded; var hMapping: HWND; tmp: PChar; begin inherited Loaded; GetMem(tmp, Length(FSendMsg) + 1); StrPCopy(tmp, FSendMsg); FMessageID := RegisterWindowMessage(tmp); FreeMem(tmp); hMapping := CreateFileMapping(HWND($FFFFFFFF), nil, PAGE_READONLY, 0, 32, 'JustOne Map'); if (hMapping <> NULL) and (GetLastError <> 0) then begin if not (csDesigning in ComponentState) then begin GotoPreviousInstance; halt; end; end; end; {########################################################################} destructor TJustOne.Destroy; begin inherited Destroy; end; {########################################################################} end.
{ Adapted from: https://github.com/torvalds/linux/blob/master/include/uapi/linux/input.h Commit: f729a1b0f8df7091cea3729fc0e414f5326e1163 } UNIT linux_input; {$PackRecords C} INTERFACE USES BaseUnix; // #include "input-event-codes.h" CONST EV_VERSION = $010001; TYPE pinput_event = ^input_event; input_event = packed record time: timeval; {NOTE: This may not be correct} typ: uint16; code: uint16; value: uint32; end; pinput_id = ^input_id; input_id = packed record bustype: uint16; vendor: uint16; product: uint16; version: uint16; end; pinput_absinfo = ^input_absinfo; input_absinfo = packed record value, minimum, maximum, fuzz, flat, resolution: uint32; end; pinput_keymap_entry = ^input_keymap_entry; input_keymap_entry = packed record flags, len: uint8; index: uint32; keycode: uint32; scancode: array[0..31] of uint8; end; pinput_mask = ^input_mask; input_mask = packed record typ, codes_size: uint32; codes_ptr: uint64; end; CONST ID_BUS = 0; ID_VENDOR = 1; ID_PRODUCT = 2; ID_VERSION = 3; BUS_PCI = $01; BUS_ISAPNP = $02; BUS_USB = $03; BUS_HIL = $04; BUS_BLUETOOTH = $05; BUS_VIRTUAL = $06; BUS_ISA = $10; BUS_I8042 = $11; BUS_XTKBD = $12; BUS_RS232 = $13; BUS_GAMEPORT = $14; BUS_PARPORT = $15; BUS_AMIGA = $16; BUS_ADB = $17; BUS_I2C = $18; BUS_HOST = $19; BUS_GSC = $1A; BUS_ATARI = $1B; BUS_SPI = $1C; BUS_RMI = $1D; BUS_CEC = $1E; BUS_INTEL_ISHTP = $1F; (* MT_TOOL types *) MT_TOOL_FINGER = $00; MT_TOOL_PEN = $01; MT_TOOL_PALM = $02; MT_TOOL_DIAL = $0a; MT_TOOL_MAX = $0f; CONST FF_STATUS_STOPPED = $00; FF_STATUS_PLAYING = $01; FF_STATUS_MAX = $01; TYPE ff_replay = record length, delay: uint16; end; ff_trigger = record button, interval: uint16; end; ff_envelope = record attack_length, attack_level, fade_length, fade_level: uint16; end; ff_constant_effect = record level: uint16; envelope: ff_envelope; end; ff_ramp_effect = record start_level, end_level: int16; envelope: ff_envelope; end; ff_condition_effect = record right_saturation, left_saturation: uint16; right_coeff, left_coeff: int16; deadband: uint16; center: int16; end; ff_periodic_effect = record waveform, period: uint16; magnitude, offset: int16; phase: uint16; envelope: ff_envelope; custom_len: uint32; custom_data: pint16; end; ff_rumble_effect = record strong_magnitude, weak_magnitude: uint16; end; CONST ffi_constant_effect = 0; ffi_ramp_effect = 1; ffi_periodic_effect = 2; ffi_condition_effect = 3; ffi_rumble_effect = 4; TYPE ff_effect = record typ: uint16; id: int16; direction: uint16; trigger: ff_trigger; replay: ff_replay; case cint of 0: ( constant: ff_constant_effect; ); 1: ( ramp: ff_ramp_effect; ); 2: ( periodic: ff_periodic_effect; ); 3: ( condition: array[0..1] of ff_condition_effect; ); 4: ( rumble: ff_rumble_effect; ); end; CONST FF_RUMBLE = $50; FF_PERIODIC = $51; FF_CONSTANT = $52; FF_SPRING = $53; FF_FRICTION = $54; FF_DAMPER = $55; FF_INERTIA = $56; FF_RAMP = $57; FF_EFFECT_MIN = FF_RUMBLE; FF_EFFECT_MAX = FF_RAMP; { Force feedback periodic effect types } FF_SQUARE = $58; FF_TRIANGLE = $59; FF_SINE = $5a; FF_SAW_UP = $5b; FF_SAW_DOWN = $5c; FF_CUSTOM = $5d; FF_WAVEFORM_MIN = FF_SQUARE; FF_WAVEFORM_MAX = FF_CUSTOM; FF_GAIN = $60; FF_AUTOCENTER = $61; FF_MAX_EFFECTS = FF_GAIN; FF_MAX = $7f; FF_CNT = FF_MAX + 1; IMPLEMENTATION END.
program exObjects; type Rectangle = object public length, width: integer; constructor init(l, w: integer); procedure setlength(l: integer); function getlength(): integer; procedure setwidth(w: integer); function getwidth(): integer; procedure draw; end; Square = object public length, width: integer; constructor init(l, w: integer); procedure setlength(l: integer); function getlength(): integer; procedure setwidth(w: integer); function getwidth(): integer; procedure draw; end; type var r1: Rectangle; pr1: ^Rectangle; constructor Rectangle.init(l, w: integer); begin length := l; width := w; end; procedure Rectangle.setlength(l: integer); begin length := l; end; procedure Rectangle.setwidth(w: integer); begin width :=w; end; function Rectangle.getlength(): integer; begin getlength := length; end; function Rectangle.getwidth(): integer; begin getwidth := width; end; procedure Rectangle.draw; var i, j: integer; begin i := 1; while i < length do begin j := 1; while j < self.width do begin write(' * '); j := j + 1; end; //writeln; i := i + 1; break; end; end; begin r1.init(3, 7); //writeln('Draw a rectangle:', r1.getlength(), ' by ' , r1.getwidth()); r1.draw; new(pr1, init(5, 4)); //writeln('Draw a rectangle:', pr1^.getlength(), ' by ',pr1^.getwidth()); pr1^.draw; pr1^.init(2, 9); //writeln('Draw a rectangle:', pr1^.getlength(), ' by ' ,pr1^.getwidth()); pr1^.draw; dispose(pr1); end;
unit aros_debug; {$MODE OBJFPC}{$H+} interface Uses Exec, AmigaDos, Utility; Const //* Tags for DecodeLocation() */ DL_Dummy = (TAG_USER + $03e00000); DL_ModuleName = (DL_Dummy + 1); DL_SegmentName = (DL_Dummy + 2); DL_SegmentPointer = (DL_Dummy + 3); DL_SegmentNumber = (DL_Dummy + 4); DL_SegmentStart = (DL_Dummy + 5); DL_SegmentEnd = (DL_Dummy + 6); DL_SymbolName = (DL_Dummy + 7); DL_SymbolStart = (DL_Dummy + 8); DL_SymbolEnd = (DL_Dummy + 9); DL_FirstSegment = (DL_Dummy + 10); //* Known debug information types */ DEBUG_NONE = 0; DEBUG_ELF = 1; DEBUG_PARTHENOPE = 2; DEBUG_HUNK = 3; Type //* ELF module debug information */ TELF_DebugInfo = record eh : pelfheader; sh : psheader; end; //* Kickstart module debug information (pointed to by KRN_DebugInfo ti_Data) */ PELF_ModuleInfo = ^TELF_ModuleInfo; TELF_ModuleInfo = record Next : pELF_ModuleInfo; //* Pointer to next module in list */ Name : PChar; //* Pointer to module name */ Type_ : Byte; //* DEBUG_ELF, for convenience */ eh : pelfheader; //* ELF file header */ sh : psheader; //* ELF section header */ end; //* Structure received as message of EnumerateSymbols hook */ PSymbolInfo = ^TSymbolInfo; TSymbolInfo = record si_Size : LongInt; //* Size of the structure */ si_ModuleName : STRPTR; si_SymbolName : STRPTR; si_SymbolStart : APTR; si_SymbolEnd : APTR; end; // Parthenope module debug information (pointed to by KRN_DebugInfo ti_Data) // // (This structure has the same layout as Parthenope's "module_t") // Parthenope_ModuleInfo = record m_node : TMinNode; m_name : STRPTR; m_str : STRPTR; m_lowest : ULONG; m_highest : ULONG; m_symbols : TMinList; end; Parthenope_Symbol = record s_node : TMinNode; s_name : STRPTR; s_lowest : ULONG; s_highest : ULONG; end; //* HUNK module debug information */ HUNK_DebugInfo = record dummy: APTR; end; Type cint = LongInt; pvoid = pointer; Const DEBUGNAME : pchar = 'debug.library'; Type PDebugLibrary = ^TDebugLibrary; TDebugLibrary = record db_lib : TLibrary; db_Modules : TMinList; db_ModSem : TSignalSemaphore; db_KernelBase : APTR; end; Var DebugBase : PDebugLibrary; Procedure RegisterModule(const name: pchar; segList: BPTR; debugType: ULONG; debugInfo: APTR); SysCall DebugBase 5; Procedure UnregisterModule(segList: BPTR); SysCall DebugBase 6; Function DecodeLocationA(addr: pvoid; tags: pTagItem): cint; SysCall DebugBase 7; Procedure EnumerateSymbolsA(handler: PHook; tags: PTagItem); SysCall DebugBase 8; Function DecodeLocation(addr: pvoid; const Tags: array of const): cint; Procedure EnumerateSymbols(handler: PHook; const Tags: array of const); implementation Uses tagsarray; Function DecodeLocation(addr: pvoid; const Tags: array of const): cint; var TagList: TTagsList; begin AddTags(TagList, Tags); DecodeLocation := DecodeLocationA(addr, GetTagPtr(TagList)); end; Procedure EnumerateSymbols(handler: PHook; const Tags: array of const); var TagList: TTagsList; begin AddTags(TagList, Tags); EnumerateSymbolsA(handler, GetTagPtr(TagList)); end; Initialization PLibrary(DebugBase) := OpenLibrary(DEBUGNAME, 0); Finalization; CloseLibrary(PLibrary(DebugBase)); end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit Server.Resources.Data; interface uses System.SysUtils, System.Classes, System.JSON, System.DateUtils, Data.DB, Variants, Windows, Datasnap.DBClient, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Stan.ExprFuncs, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, FireDAC.Comp.DataSet, FireDAC.Comp.Client, WiRL.Core.JSON, WiRL.Core.Registry, WiRL.Core.Attributes, WiRL.http.Accept.MediaType, WiRL.http.URL, WiRL.http.Request, WiRL.Core.MessageBody.Default, WiRL.Data.MessageBody.Default, WiRL.Core.Exceptions, WiRL.Data.Resolver, FireDAC.Phys.SQLiteDef; // In Delphi versions earlier than 10 Seattle please remove FireDAC.Phys.SQLiteDef type [Path('/main')] TMainModule = class(TDataModule) FDConnection: TFDConnection; qryEmployee: TFDQuery; qryEmployeeEMP_NO: TSmallintField; qryEmployeeFIRST_NAME: TStringField; qryEmployeeLAST_NAME: TStringField; qryEmployeePHONE_EXT: TStringField; qryEmployeeHIRE_DATE: TSQLTimeStampField; qryEmployeeDEPT_NO: TStringField; qryEmployeeJOB_CODE: TStringField; qryEmployeeJOB_GRADE: TSmallintField; qryEmployeeJOB_COUNTRY: TStringField; qryEmployeeSALARY: TBCDField; FDGUIxWaitCursor1: TFDGUIxWaitCursor; qryEmpNoGen: TFDQuery; procedure DataModuleCreate(Sender: TObject); private // [Context] FRequest: TWiRLRequest; public [GET, Path('/employee/')] function Employee(): TDataSet; [POST, Path('/employee/')] function InsertEmployee([BodyParam] Json: TJSONValue): TJSONObject; [PUT, Path('/employee/{Id}')] function UpdateEmployee([BodyParam] Json: TJSONValue): TJSONObject; [DELETE, Path('/employee/{Id}')] function DeleteEmployee([PathParam] Id: Integer; [BodyParam] Json: TJSONValue): TJSONObject; end; var MainModule: TMainModule; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TMainModule } function TMainModule.Employee: TDataSet; begin Result := qryEmployee; end; function TMainModule.InsertEmployee(Json: TJSONValue): TJSONObject; begin raise EWiRLNotImplementedException.Create('Not yet implemented'); end; procedure TMainModule.DataModuleCreate(Sender: TObject); const DatabaseName = 'data.db'; begin inherited; FDConnection.DriverName := 'SQLite'; FDConnection.Params.Add('Database=' + DatabaseName); FDConnection.Params.Add('SQLiteAdvanced=page_size=4096'); FDConnection.Connected := True; end; function TMainModule.DeleteEmployee(Id: Integer; Json: TJSONValue): TJSONObject; begin TWiRLResolver.DeleteDataSet(qryEmployee, Id); Result := TJSONObject.Create(TJSONPair.Create('success', TJSONTrue.Create)); end; function TMainModule.UpdateEmployee([BodyParam] Json: TJSONValue): TJSONObject; begin TWiRLResolver.UpdateDataSet(qryEmployee, Json); Result := TJSONObject.Create(TJSONPair.Create('success', TJSONTrue.Create)); end; initialization TWiRLResourceRegistry.Instance.RegisterResource<TMainModule>( function: TObject begin Result := TMainModule.Create(nil); end ); end.
{$ifdef license} (* Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder 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 HOLDER 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. *) {$endif} /// <summary> /// Simple global heap memory access. /// </summary> unit cwHeap; {$ifdef fpc}{$mode delphiunicode}{$endif} interface type IHeap = interface ['{9DB573AE-7D27-4096-A72B-DA08FEB2298E}'] /// <summary> /// Allocates a chunk of memory for use as a buffer. /// </summary> /// <param name="Size"> /// The amount of memory to allocate, in bytes.s /// </param> /// <returns> /// Returns a pointer to the newly allocated memory buffer, or else, /// returns nil if a memory buffer could not be allocated. /// </returns> function Allocate( const Size: nativeuint ): pointer; /// <summary> /// Deallocates a previously allocated memory buffer, which was allocated /// using the Allocate() method. This returns the memory buffer to the /// heap, and ultimately to the system. /// </summary> /// <param name="p"> /// A pointer to the memory buffer to deallocate. /// </param> /// <returns> /// Returns true if the memory was successfully released to the syetem, else false. /// </returns> function Deallocate( const P: pointer ): boolean; end; implementation end.
unit UCC_Progress; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, ControlProgressBar, UForms, ControlWorkingIndicator; type TCCProgress = class(TAdvancedForm) StatusBar: TCFProgressBar; StatusNote: TLabel; lblMax: TLabel; lblValue: TLabel; wiProcessing: TWorkingIndicator; private FDisabledTaskWindows: Pointer; protected procedure DoHide; override; procedure DoShow; override; public { Public declarations } constructor Create(AOwner: TComponent; ShowVals: Boolean; MinValue, MaxValue, Steps: Integer; const title: string); reintroduce; procedure BeforeDestruction; override; procedure SetProgressNote(const Note: String); procedure IncrementProgress; procedure IncrementBy(Amt: Integer); property Note: String write SetProgressNote; end; implementation {$R *.DFM} { TProgress } constructor TCCProgress.Create(AOwner: TComponent; ShowVals: Boolean; MinValue, MaxValue, Steps: Integer; const title: string); begin inherited create(AOwner); if Assigned(AOwner) and (AOwner is TWinControl) then begin Parent := TWinControl(AOwner); Left := Trunc((Parent.Width / 2) - (Width / 2)); Top := Trunc((Parent.Height / 4) - (Height / 2)); end; Caption := Title; lblValue.Visible := ShowVals; lblValue.Caption := IntToStr(MinValue); lblMax.Visible := ShowVals; lblMax.Caption := IntToStr(MaxValue); StatusBar.Min := MinValue; StatusBar.Max := MaxValue; StatusBar.Step := 1; Visible := True; Application.ProcessMessages; end; /// summary: Enables task windows when the progress bar is destroyed. procedure TCCProgress.BeforeDestruction; begin if Assigned(FDisabledTaskWindows) then begin EnableTaskWindows(FDisabledTaskWindows); FDisabledTaskWindows := nil; end; inherited; end; /// summary: Enables task windows when the progress bar hidden. procedure TCCProgress.DoHide; begin inherited; if Assigned(FDisabledTaskWindows) then begin EnableTaskWindows(FDisabledTaskWindows); FDisabledTaskWindows := nil; end; end; /// summary: Disables task windows when the progress bar is shown. procedure TCCProgress.DoShow; begin if not Assigned(FDisabledTaskWindows) then FDisabledTaskWindows := DisableTaskWindows(0); inherited; end; procedure TCCProgress.IncrementProgress; begin StatusBar.StepIt; lblValue.Caption := IntToStr(StatusBar.Position); Update; Application.ProcessMessages; end; procedure TCCProgress.IncrementBy(Amt: Integer); begin StatusBar.Position := StatusBar.Position + Amt; lblValue.Caption := IntToStr(StatusBar.Position); Update; Application.ProcessMessages; end; procedure TCCProgress.SetProgressNote(const Note: String); begin StatusNote.Caption := Note; Update; Application.ProcessMessages; end; end.
unit U_frmcadastroinstituicao; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons, StdCtrls, U_Utils, U_FrmCadastroBase, U_dtmcadastroInstituicao, U_Instituicao; type { Tfrmcadastroinstituicao } Tfrmcadastroinstituicao = class(TFrmCadastroBase) edtCodigo: TEdit; edtNome: TEdit; edtSigla: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; procedure btnCancelarClick(Sender: TObject); procedure btnIncluirClick(Sender: TObject); procedure btnPesquisarClick(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure edtCodigoExit(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); private instituicao :TInstituicao; public end; var frmcadastroinstituicao: Tfrmcadastroinstituicao; implementation {$R *.lfm} { Tfrmcadastroinstituicao } uses U_frmpesquisacadastroInstituicao; procedure Tfrmcadastroinstituicao.btnIncluirClick(Sender: TObject); begin edtCodigo.Text := FormatFloat('00',getCodigoValido('INSTITUICAO','COD_INSTITUICAO')); inherited; edtCodigo.Enabled:=False; edtCodigo.Color:=clInfoBk; edtNome.Enabled:= True; edtNome.Color:=clWhite; edtSigla.Enabled:= True; edtSigla.Color:=clWhite; edtSigla.SetFocus; end; procedure Tfrmcadastroinstituicao.btnPesquisarClick(Sender: TObject); begin try frmpesquisacadastroInstituicao := TfrmpesquisacadastroInstituicao.Create(Self); frmpesquisacadastroInstituicao.ShowModal; if frmpesquisacadastroInstituicao.gControle = tpAlterar then begin edtCodigo.Text := frmpesquisacadastroInstituicao.DSGrid.DataSet.FieldByName('CODIGO').AsString; edtCodigoExit(edtCodigo); end; finally FreeAndNil(frmpesquisacadastroInstituicao); end; end; procedure Tfrmcadastroinstituicao.btnSalvarClick(Sender: TObject); begin if (Trim(edtSigla.Text) = '') then begin MsgAlerta('Informe a Sigla!'); edtSigla.SetFocus; Exit; end; if (Trim(edtNome.Text) = '') then begin MsgAlerta('Informe o nome!'); edtNome.SetFocus; Exit; end; try instituicao := TInstituicao.Create; instituicao.codigo:= StrToInt(edtCodigo.Text); instituicao.sigla:= edtSigla.Text; instituicao.descicao:= edtNome.Text; if dtmcadastroInstituicao.salvarInstituicao(instituicao,gControle) then begin if gControle = tpNovo then MsgOk('Instituição cadastrado com sucesso!') else MsgOk('Instituição alterado com sucesso!'); end; finally FreeAndNil(instituicao); end; btnCancelarClick(btnCancelar); inherited; end; procedure Tfrmcadastroinstituicao.edtCodigoExit(Sender: TObject); begin if gControle = tpConsulta then begin if (Trim(edtCodigo.Text) <> '') then begin instituicao := dtmcadastroInstituicao.getInstituicao(StrToInt(edtCodigo.Text)); if (instituicao <> nil) then begin try edtCodigo.Text := formatfloat('00',instituicao.codigo); edtSigla.Text := instituicao.sigla; edtNome.Text := instituicao.descicao; controleAlterar; edtCodigo.Enabled:=False; edtCodigo.Color:=clInfoBk; if (instituicao.codigo > 0) then begin edtNome.Enabled:= True; edtNome.Color:=clWhite; edtSigla.Enabled:= True; edtSigla.Color:=clWhite; edtSigla.SetFocus; end; finally FreeAndNil(instituicao); end; end else begin MsgAlerta('Instituição não encontrado!'); btnCancelarClick(btnCancelar); end; end; end; end; procedure Tfrmcadastroinstituicao.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin if gControle = tpNovo then deletaCodigo('INSTITUICAO','COD_INSTITUICAO',StrToInt(edtCodigo.Text)); end; procedure Tfrmcadastroinstituicao.FormCreate(Sender: TObject); begin inherited; dtmcadastroInstituicao := TdtmcadastroInstituicao.Create(Self); end; procedure Tfrmcadastroinstituicao.FormDestroy(Sender: TObject); begin FreeAndNil(dtmcadastroInstituicao); end; procedure Tfrmcadastroinstituicao.FormShow(Sender: TObject); begin self.ActiveControl := edtCodigo; edtCodigo.SetFocus; end; procedure Tfrmcadastroinstituicao.btnCancelarClick(Sender: TObject); begin deletaCodigo('INSTITUICAO','COD_INSTITUICAO',StrToInt(edtCodigo.Text)); edtCodigo.Clear; edtCodigo.Enabled:= True; edtCodigo.Color:=clWhite; edtCodigo.SetFocus; edtSigla.Clear; edtSigla.Enabled:=False; edtSigla.Color:=clInfoBk; edtNome.Clear; edtNome.Enabled:=False; edtNome.Color:=clInfoBk; inherited; end; end.
unit UTestSpeed; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, CompGroup; type TForm1 = class(TForm) Image1: TImage; PaintBox1: TPaintBox; btnStrech: TButton; btnNormal: TButton; Timer1: TTimer; btnIncreament: TButton; btnExclusive: TButton; apColor: TAppearanceProxy; ColorDialog1: TColorDialog; procedure btnStrechClick(Sender: TObject); procedure btnNormalClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure btnIncreamentClick(Sender: TObject); procedure btnExclusiveClick(Sender: TObject); private { Private declarations } procedure TestDraw; public { Public declarations } StretchDraw : boolean; Increament : boolean; Index:integer; end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.btnStrechClick(Sender: TObject); begin StretchDraw := true; Increament := false; TestDraw; end; procedure TForm1.btnNormalClick(Sender: TObject); begin StretchDraw := false; Increament := false; TestDraw; end; procedure TForm1.TestDraw; begin Timer1.Enabled := true; Index := 1; with PaintBox1.Canvas do begin Brush.Color := apColor.Color; Brush.Style := bsSolid; FillRect(rect(0,0,PaintBox1.width,PaintBox1.Height)); end; end; const count = 8; procedure TForm1.Timer1Timer(Sender: TObject); var w : integer; gw,gh : integer; r : TRect; begin gw:= Image1.Picture.Graphic.width; gh:= Image1.Picture.Graphic.Height; if Increament then begin r := rect(Round((Index-1) * gw /Count),0,Round(Index * gw /Count),gh); PaintBox1.Canvas.CopyRect(r,Image1.Picture.Bitmap.Canvas,r); end else begin w := Round(Index * gw /Count); r := rect(0,0,w,gh); if StretchDraw then PaintBox1.Canvas.CopyRect(r,Image1.Picture.Bitmap.Canvas,r) else begin SetStretchBltMode(PaintBox1.Canvas.handle,STRETCH_DELETESCANS); BitBlt(PaintBox1.Canvas.handle,0,0,w,gh, Image1.Picture.Bitmap.Canvas.handle,0,0,SRCCOPY); end; end; inc(index); if Index>count then Timer1.Enabled:=false; end; procedure TForm1.btnIncreamentClick(Sender: TObject); begin Increament := true; TestDraw; end; procedure TForm1.btnExclusiveClick(Sender: TObject); var w : integer; gw,gh : integer; r : TRect; i : integer; begin with PaintBox1.Canvas do begin Brush.Color := apColor.Color;//clBtnFace; Brush.Style := bsSolid; FillRect(rect(0,0,PaintBox1.width,PaintBox1.Height)); end; gw:= Image1.Picture.Graphic.width; gh:= Image1.Picture.Graphic.Height; for i:=1 to count do begin r := rect(Round((I-1) * gw /Count),0,Round(I * gw /Count),gh); PaintBox1.Canvas.CopyRect(r,Image1.Picture.Bitmap.Canvas,r); Sleep(100); end; end; end.
unit Payment; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorDocument, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxPCdxBarPopupMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, Data.DB, cxDBData, cxCurrencyEdit, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, dsdAddOn, dsdGuides, dsdDB, Vcl.Menus, dxBarExtItems, dxBar, cxClasses, Datasnap.DBClient, dsdAction, Vcl.ActnList, cxPropertiesStore, cxButtonEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxTextEdit, Vcl.ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridCustomView, cxGrid, cxPC, dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPCPainter, dxSkinsdxBarPainter, ChoicePeriod, cxCheckBox, cxSplitter, dsdExportToXLSAction; type TPaymentForm = class(TAncestorDocumentForm) lblJuridical: TcxLabel; edJuridical: TcxButtonEdit; GuidesJuridical: TdsdGuides; cxLabel4: TcxLabel; edTotalSumm: TcxCurrencyEdit; cxLabel5: TcxLabel; edTotalCount: TcxCurrencyEdit; Income_InvNumber: TcxGridDBColumn; Income_Operdate: TcxGridDBColumn; Income_JuridicalName: TcxGridDBColumn; Income_StatusName: TcxGridDBColumn; Income_UnitName: TcxGridDBColumn; Income_NDS: TcxGridDBColumn; spSelectPrint: TdsdStoredProc; PrintItemsCDS: TClientDataSet; PrintHeaderCDS: TClientDataSet; dxBarControlContainerItem1: TdxBarControlContainerItem; dxBarControlContainerItem2: TdxBarControlContainerItem; deDateStart: TcxDateEdit; deDateEnd: TcxDateEdit; PeriodChoice: TPeriodChoice; RefreshDispatcher: TRefreshDispatcher; Id: TcxGridDBColumn; Income_ContractName: TcxGridDBColumn; Income_TotalSumm: TcxGridDBColumn; Income_PaySumm: TcxGridDBColumn; SummaPay: TcxGridDBColumn; BankAccountName: TcxGridDBColumn; BankName: TcxGridDBColumn; NeedPay: TcxGridDBColumn; actOpenBankAccount: TOpenChoiceForm; PrintItemsVATCDS: TClientDataSet; Income_PaymentDate: TcxGridDBColumn; Income_PayOrder: TcxGridDBColumn; SummaCorrBonus: TcxGridDBColumn; SummaCorrOther: TcxGridDBColumn; SummaCorrReturnOut: TcxGridDBColumn; mactSelectAll: TMultiAction; gpInsertUpdate_MovementItem_Payment_NeedPay: TdsdStoredProc; actInsertUpdate_MovementItem_Payment_NeedPay: TdsdExecStoredProc; dxBarButton1: TdxBarButton; actSelectAllAndRefresh: TMultiAction; spGet_Payment_Detail: TdsdStoredProc; spInsertUpdate_MovementFloat_TotalSummPayment: TdsdStoredProc; actGet_Payment_Detail: TdsdExecStoredProc; actInsertUpdate_MovementFloat_TotalSummPayment: TdsdExecStoredProc; spSelect_PaymentCorrSumm: TdsdStoredProc; PaymentCorrSummCDS: TClientDataSet; PaymentCorrSummDS: TDataSource; actSelect_PaymentCorrSumm: TdsdExecStoredProc; cxGrid1: TcxGrid; cxGridDBTableView1: TcxGridDBTableView; cxGridLevel1: TcxGridLevel; ContainerAmountBonus: TcxGridDBColumn; ContainerAmountReturnOut: TcxGridDBColumn; ContainerAmountOther: TcxGridDBColumn; CorrBonus: TcxGridDBColumn; LeftCorrBonus: TcxGridDBColumn; CorrReturnOut: TcxGridDBColumn; LeftCorrReturnOut: TcxGridDBColumn; CorrOther: TcxGridDBColumn; LeftCorrOther: TcxGridDBColumn; cxSplitter1: TcxSplitter; ContractNumber: TcxGridDBColumn; ContractStartDate: TcxGridDBColumn; ContractEndDate: TcxGridDBColumn; actRefreshLite: TdsdDataSetRefresh; spUpdateMI_NeedPay: TdsdStoredProc; actUpdateMI_NeedPay: TdsdExecStoredProc; macUpdateMI_NeedPay: TMultiAction; bbUpdateMI_NeedPay: TdxBarButton; actExportToXLSPrivat: TdsdExportToXLS; actExecStoredProcPrivat: TdsdExecStoredProc; ExportBankCDS: TClientDataSet; spExportBankPrivat: TdsdStoredProc; dxBarButton2: TdxBarButton; spExportBankPrivatFileName: TdsdStoredProc; spExportBankUkrximFileName: TdsdStoredProc; spExportBankUkrxim: TdsdStoredProc; actExportToXLSUkrxim: TdsdExportToXLS; actExecStoredProcUkrxim: TdsdExecStoredProc; dxBarButton3: TdxBarButton; cbPaymentFormed: TcxCheckBox; actExportToXLSConcord: TdsdExportToXLS; actExecStoredProcConcord: TdsdExecStoredProc; dxBarButton4: TdxBarButton; spExportBankConcordFileName: TdsdStoredProc; spExportBankConcord: TdsdStoredProc; isPartialPay: TcxGridDBColumn; ContainerAmountPartialSale: TcxGridDBColumn; CorrPartialSale: TcxGridDBColumn; LeftCorrPartialSale: TcxGridDBColumn; SummaCorrPartialPay: TcxGridDBColumn; cxLabel3: TcxLabel; edComment: TcxTextEdit; private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} initialization RegisterClass(TPaymentForm); end.
unit ListDiffAddGoods; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, System.DateUtils, Dialogs, StdCtrls, Mask, CashInterface, DB, Buttons, Gauges, cxGraphics, cxControls, cxLookAndFeels, Math, System.StrUtils, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxCurrencyEdit, cxClasses, cxPropertiesStore, dsdAddOn, dxSkinsCore, dxSkinsDefaultPainters, Datasnap.DBClient, Vcl.Menus, cxButtons, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxMaskEdit, Vcl.ExtCtrls, System.Actions, Vcl.ActnList, cxButtonEdit, ChoiceListDiff, dsdDB, dsdAction; type TListDiffAddGoodsForm = class(TForm) bbOk: TcxButton; bbCancel: TcxButton; ListDiffCDS: TClientDataSet; Label1: TLabel; Label2: TLabel; Label3: TLabel; ceAmount: TcxCurrencyEdit; meComent: TcxMaskEdit; Label4: TLabel; DiffKindCDS: TClientDataSet; Label5: TLabel; ListGoodsCDS: TClientDataSet; Label7: TLabel; Label8: TLabel; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; Label6: TLabel; Label9: TLabel; ActionList: TActionList; beDiffKind: TcxButtonEdit; actShowListDiff: TAction; TimerStart: TTimer; CheckCDS: TClientDataSet; spExistsRemainsGoods: TdsdStoredProc; actCustomerThresho_RemainsGoodsCash: TdsdOpenForm; DiffKindPriceCDS: TClientDataSet; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure ceAmountPropertiesChange(Sender: TObject); procedure lcbDiffKindPropertiesChange(Sender: TObject); procedure actShowListDiffExecute(Sender: TObject); procedure TimerStartTimer(Sender: TObject); private FDiffKindId : Integer; FAmountDay : Currency; FAmountDiffKind, FMaxOrderAmount, FPackages : Currency; FPrice, FNDS, FMCSValue : Currency; FGoodsId, FGoodsCode, FNDSKindId : Integer; FGoodsName : String; // Сохранение чека в локальной базе. function SaveLocal(AManagerId: Integer; AManagerName, ABayerName: String; AAmount : Currency): Boolean; public property Price : Currency read FPrice write FPrice; property NDS : Currency read FNDS write FNDS; property MCSValue : Currency read FMCSValue write FMCSValue; property NDSKindId : Integer read FNDSKindId write FNDSKindId; property GoodsId : Integer read FGoodsId write FGoodsId; property GoodsCode : Integer read FGoodsCode write FGoodsCode; property GoodsName : String read FGoodsName write FGoodsName; end; implementation {$R *.dfm} uses CommonData, LocalWorkUnit, MainCash2, ListDiff, PUSHMessage, VIPDialog; { TListDiffAddGoodsForm } procedure TListDiffAddGoodsForm.actShowListDiffExecute(Sender: TObject); begin if ChoiceListDiffExecute(DiffKindCDS, FDiffKindId) and (FDiffKindId <> 0) then begin if DiffKindCDS.Locate('Id', FDiffKindId, []) then begin beDiffKind.Text := DiffKindCDS.FieldByName('Name').AsString; if DiffKindCDS.FieldByName('DaysForSale').AsInteger > 0 then ShowPUSHMessage('ВНИМАНИЕ - ВЫ ОБЯЗАНЫ ДОБАВИТЬ В ЛИСТ ОТКАЗА ТОЛЬКО ТО КОЛ-ВО , КОТОРОЕ ВЫ ДОЛЖНЫ ПРОДАТЬ ЗА ' + DiffKindCDS.FieldByName('DaysForSale').AsString + ' ДНЕЙ.'#13#10#13#10 + 'ЕСЛИ ВЫ ЕГО НЕ ПРОДАДИТЕ ПО ОКОНЧАНИИ ПЕРИОДА - БУДУТ НАЛОЖЕНЫ ШТРАФНЫЕ САНКЦИИ В РАЗМЕРЕ 10% ОТ СУММЫ НЕ ПРОДАННЫХ ПОЗИЦИЙ.', mtWarning); ceAmount.SetFocus; end else Close; end else Close; end; procedure TListDiffAddGoodsForm.ceAmountPropertiesChange(Sender: TObject); var nAmount : Currency; begin Label8.Visible := False; if (FMaxOrderAmount = 0) and (FPackages = 0) then Exit; nAmount := ceAmount.Value; if nAmount < 0 then nAmount := 0; Label8.Caption := 'Кол-во ' + CurrToStr(nAmount + FAmountDiffKind) + ' ' + 'Poзн. цена,грн ' + CurrToStr(FPrice) + ' ' + 'Сумма,грн ' + CurrToStr(RoundTo((nAmount + FAmountDiffKind) * FPrice, - 2)) + IfThen (FMaxOrderAmount = 0, '', ' Макс. Сумма,грн ' + CurrToStr(FMaxOrderAmount)) + IfThen (FPackages = 0, '', ' Макс. кол-во уп. ' + CurrToStr(FMaxOrderAmount)); Label8.Visible := True; end; procedure TListDiffAddGoodsForm.FormClose(Sender: TObject; var Action: TCloseAction); var nAmount, nAmountDiffKind, nMaxOrderAmount, nPackages : Currency; bSend : boolean; ManagerID: Integer; ManagerName, BayerName: String; begin if ModalResult <> mrOk then Exit; nAmount := ceAmount.Value; if nAmount = 0 then begin Action := TCloseAction.caNone; ShowMessage('Должно быть число не равное 0...'); ceAmount.SetFocus; Exit; end; // Люба сказала отменить контролт 03.02.2020 // if (FAmountDay + nAmount) < 0 then // begin // if FAmountDay = 0 then // ShowMessage('Медикамент в течении дня не добавлялся в лист оказов.') // else ShowMessage('Вы пытаетест отменить с листа отказов больше чем добавлено.'#13#10 + // 'Можно вернуть не более ' + CurrToStr(FAmountDay)); // ceAmount.SetFocus; // Exit; // end; if FDiffKindId = 0 then begin Action := TCloseAction.caNone; ShowMessage('Вид отказа должен быть выбрано из списка...'); actShowListDiffExecute(Sender); Exit; end; if not ListGoodsCDS.FieldByName('ExpirationDate').IsNull then begin if ListGoodsCDS.FieldByName('ExpirationDate').AsDateTime < IncYear(Date, 1) then begin if not DiffKindCDS.FieldByName('isLessYear').AsBoolean then begin Action := TCloseAction.caNone; ShowMessage('По виду отказа <' + DiffKindCDS.FieldByName('Name').AsString + '> заказ товара со сроком годности менее года запрещен...'); ceAmount.SetFocus; Exit; end; end; end; nMaxOrderAmount := DiffKindCDS.FieldByName('MaxOrderUnitAmount').AsCurrency; nPackages := DiffKindCDS.FieldByName('Packages').AsCurrency; if (nAmount > 0) and (nMaxOrderAmount > 0) then begin nAmountDiffKind := 0; if not gc_User.Local then try MainCashForm.spSelect_CashListDiffGoods.Params.ParamByName('inGoodsId').Value := FGoodsId; MainCashForm.spSelect_CashListDiffGoods.Params.ParamByName('inDiffKindID').Value := FDiffKindId; MainCashForm.spSelect_CashListDiffGoods.Execute; if MainCashForm.CashListDiffCDS.Active and (MainCashForm.CashListDiffCDS.RecordCount = 1) then begin nAmountDiffKind := MainCashForm.CashListDiffCDS.FieldByName('AmountDiffKind').AsCurrency; end; Except end; WaitForSingleObject(MutexDiffCDS, INFINITE); try LoadLocalData(ListDiffCDS, ListDiff_lcl); if not ListDiffCDS.Active then begin CheckListDiffCDS; LoadLocalData(ListDiffCDS, ListDiff_lcl); end; finally ReleaseMutex(MutexDiffCDS); end; if ListDiffCDS.Active then begin ListDiffCDS.First; while not ListDiffCDS.Eof do begin if (ListDiffCDS.FieldByName('ID').AsInteger = FGoodsId) then begin if (StartOfTheDay(ListDiffCDS.FieldByName('DateInput').AsDateTime) = Date) then begin if not MainCashForm.CashListDiffCDS.Active or not ListDiffCDS.FieldByName('IsSend').AsBoolean then begin if (ListDiffCDS.FieldByName('DiffKindId').AsInteger = FDiffKindId) then nAmountDiffKind := nAmountDiffKind + ListDiffCDS.FieldByName('Amount').AsCurrency; end; end; end; ListDiffCDS.Next; end; end; if ((nAmountDiffKind + nAmount) > 1) and (((nAmountDiffKind + nAmount) * FPrice) > nMaxOrderAmount) then begin Action := TCloseAction.caNone; ShowMessage('Сумма заказа по позиции :'#13#10 + FGoodsName + #13#10'С видом отказа "' + DiffKindCDS.FieldByName('Name').AsString + '" превышает ' + CurrToStr(nMaxOrderAmount) + ' грн. ...'); ceAmount.SetFocus; Exit; end; end; if (nAmount > 0) and (nPackages > 0) then begin nAmountDiffKind := 0; if not gc_User.Local then try MainCashForm.spSelect_CashListDiffGoods.Params.ParamByName('inGoodsId').Value := FGoodsId; MainCashForm.spSelect_CashListDiffGoods.Params.ParamByName('inDiffKindID').Value := FDiffKindId; MainCashForm.spSelect_CashListDiffGoods.Execute; if MainCashForm.CashListDiffCDS.Active and (MainCashForm.CashListDiffCDS.RecordCount = 1) then begin nAmountDiffKind := MainCashForm.CashListDiffCDS.FieldByName('AmountDiffKind').AsCurrency; end; Except end; WaitForSingleObject(MutexDiffCDS, INFINITE); try LoadLocalData(ListDiffCDS, ListDiff_lcl); if not ListDiffCDS.Active then begin CheckListDiffCDS; LoadLocalData(ListDiffCDS, ListDiff_lcl); end; finally ReleaseMutex(MutexDiffCDS); end; if ListDiffCDS.Active then begin ListDiffCDS.First; while not ListDiffCDS.Eof do begin if (ListDiffCDS.FieldByName('ID').AsInteger = FGoodsId) then begin if (StartOfTheDay(ListDiffCDS.FieldByName('DateInput').AsDateTime) = Date) then begin if not MainCashForm.CashListDiffCDS.Active or not ListDiffCDS.FieldByName('IsSend').AsBoolean then begin if (ListDiffCDS.FieldByName('DiffKindId').AsInteger = FDiffKindId) then nAmountDiffKind := nAmountDiffKind + ListDiffCDS.FieldByName('Amount').AsCurrency; end; end; end; ListDiffCDS.Next; end; end; if ((nAmountDiffKind + nAmount) > 1) and ((nAmountDiffKind + nAmount) > nPackages) then begin Action := TCloseAction.caNone; ShowMessage('Количество заказа по позиции :'#13#10 + FGoodsName + #13#10'С видом отказа "' + DiffKindCDS.FieldByName('Name').AsString + '" превышает ' + CurrToStr(nPackages) + ' уп. ...'); ceAmount.SetFocus; Exit; end; end; if Pos('1303', DiffKindCDS.FieldByName('Name').AsString) > 0 then begin if MainCashForm.UnitConfigCDS.FieldByName('PartnerMedicalID').IsNull then begin Action := TCloseAction.caNone; ShowMessage('Аптека не подключена к СП по постановлению 1303'#13#10'Использование вида отказа <' + DiffKindCDS.FieldByName('Name').AsString + '> запрещено...'); beDiffKind.SetFocus; Exit; end; if ListGoodsCDS.FieldByName('PriceOOC1303').AsCurrency = 0 then begin Action := TCloseAction.caNone; ShowMessage('Товар <' + FGoodsName + '> не участвует в СП по постановлению 1303...'); beDiffKind.SetFocus; Exit; end; if FNDS = 20 then begin Action := TCloseAction.caNone; ShowMessage('Запрещено использовать товар <' + FGoodsName + '> с НДС 20% в СП по постановлению 1303...'); beDiffKind.SetFocus; Exit; end; if (ListGoodsCDS.FieldByName('PriceOOC1303').AsCurrency < ListGoodsCDS.FieldByName('JuridicalPrice').AsCurrency) and ((ListGoodsCDS.FieldByName('JuridicalPrice').AsCurrency / ListGoodsCDS.FieldByName('PriceOOC1303').AsCurrency * 100.0 - 100) > MainCashForm.UnitConfigCDS.FindField('DeviationsPrice1303').AsCurrency) then begin Action := TCloseAction.caNone; ShowMessage('Отпускная цена товара <' + FGoodsName + '> выше чем по реестру товаров соц. проекта 1303...'); beDiffKind.SetFocus; Exit; end; end; if DiffKindPriceCDS.Active then begin try DiffKindPriceCDS.Filtered := False; DiffKindPriceCDS.Filter := 'DiffKindId = ' + DiffKindCDS.FieldByName('Id').AsString + ' and MinPrice <= ' + CurrToStr(FPrice) + ' and MaxPrice > ' + CurrToStr(FPrice); DiffKindPriceCDS.Filtered := True; if DiffKindPriceCDS.RecordCount = 1 then begin if ((nAmountDiffKind + nAmount) > 1) and (DiffKindPriceCDS.FieldByName('Amount').AsCurrency > 0) and ((nAmountDiffKind + nAmount) > DiffKindPriceCDS.FieldByName('Amount').AsCurrency) then begin Action := TCloseAction.caNone; ShowMessage('Количество заказа по позиции :'#13#10 + FGoodsName + #13#10'С видом отказа "' + DiffKindCDS.FieldByName('Name').AsString + ' и ценой ' + CurrToStr(FPrice) + ' " превышает ' + CurrToStr(DiffKindPriceCDS.FieldByName('Amount').AsCurrency) + ' уп. ...'); ceAmount.SetFocus; Exit; end; if ((nAmountDiffKind + nAmount) > 1) and (DiffKindPriceCDS.FieldByName('Summa').AsCurrency > 0) and (((nAmountDiffKind + nAmount) * FPrice) > DiffKindPriceCDS.FieldByName('Summa').AsCurrency) then begin Action := TCloseAction.caNone; ShowMessage('Сумма заказа по позиции :'#13#10 + FGoodsName + #13#10'С видом отказа "' + DiffKindCDS.FieldByName('Name').AsString + ' и ценой ' + CurrToStr(FPrice) + '" превышает ' + CurrToStr(DiffKindPriceCDS.FieldByName('Summa').AsCurrency) + ' грн. ...'); ceAmount.SetFocus; Exit; end; end; finally DiffKindPriceCDS.Filtered := False; DiffKindPriceCDS.Filter := ''; end; end; if FGoodsId = 0 then begin Action := TCloseAction.caNone; ShowMessage('Ошибка Не выбран товар...'); Exit; end; if DiffKindCDS.FieldByName('isFindLeftovers').AsBoolean and (FPrice >= MainCashForm.UnitConfigCDS.FindField('CustomerThreshold').AsCurrency) then begin if not gc_User.Local then begin spExistsRemainsGoods.ParamByName('inGoodsId').Value := FGoodsId; spExistsRemainsGoods.ParamByName('outThereIs').Value := False; spExistsRemainsGoods.Execute; if spExistsRemainsGoods.ParamByName('outThereIs').Value then begin ShowMessage('Заказываемый товар есть в наличии по другим аптекам.'#13#10#13#10 + 'Менеджер по возможности создаст на вас перемещение либо разблокирует товар для заказа у поставщика.'); // actCustomerThresho_RemainsGoodsCash.GuiParams.ParamByName('GoodsId').Value := FGoodsId; // actCustomerThresho_RemainsGoodsCash.GuiParams.ParamByName('GoodsCode').Value := GoodsCDS.FieldByName('GoodsCode').AsInteger; // actCustomerThresho_RemainsGoodsCash.GuiParams.ParamByName('GoodsName').Value := FGoodsName; // actCustomerThresho_RemainsGoodsCash.GuiParams.ParamByName('Amount').Value := nAmount; // actCustomerThresho_RemainsGoodsCash.Execute; end; end; end; if DiffKindCDS.FieldByName('isFormOrder').AsBoolean then begin if not VIPDialogExecute(ManagerID, ManagerName, BayerName) then begin Action := TCloseAction.caNone; ceAmount.SetFocus; Exit; end; end; bSend := False; WaitForSingleObject(MutexDiffCDS, INFINITE); try try CheckListDiffCDS; LoadLocalData(ListDiffCDS, ListDiff_lcl); if not ListDiffCDS.Active then begin CheckListDiffCDS; LoadLocalData(ListDiffCDS, ListDiff_lcl); end; ListDiffCDS.Append; ListDiffCDS.FieldByName('ID').AsInteger := FGoodsId; ListDiffCDS.FieldByName('Amount').AsCurrency := nAmount; ListDiffCDS.FieldByName('Code').AsInteger := FGoodsCode; ListDiffCDS.FieldByName('Name').AsString := FGoodsName; ListDiffCDS.FieldByName('Price').AsCurrency := FPrice; ListDiffCDS.FieldByName('DiffKindId').AsVariant := FDiffKindId; ListDiffCDS.FieldByName('Comment').AsString := meComent.Text; ListDiffCDS.FieldByName('UserID').AsString := gc_User.Session; ListDiffCDS.FieldByName('UserName').AsString := gc_User.Login; ListDiffCDS.FieldByName('DateInput').AsDateTime := Now; ListDiffCDS.FieldByName('IsSend').AsBoolean := False; ListDiffCDS.Post; SaveLocalData(ListDiffCDS, ListDiff_lcl); if DiffKindCDS.FieldByName('isFormOrder').AsBoolean then SaveLocal(ManagerId, ManagerName, BayerName, nAmount); bSend := True; Except ON E:Exception do ShowMessage('Ошибка сохранения листа отказов:'#13#10 + E.Message); end; finally ReleaseMutex(MutexDiffCDS); // отправка сообщения о необходимости отправки листа отказов if bSend then PostMessage(HWND_BROADCAST, FM_SERVISE, 2, 4); end; end; procedure TListDiffAddGoodsForm.FormDestroy(Sender: TObject); begin if MainCashForm.CashListDiffCDS.Active then MainCashForm.CashListDiffCDS.Close; end; procedure TListDiffAddGoodsForm.FormShow(Sender: TObject); var AmountDiffUser, AmountDiff, AmountDiffPrev : currency; AmountIncome, AmountIncomeSend, PriceSaleIncome, Remains : currency; ListDate : Variant; S : string; nID : integer; begin if FGoodsId = 0 then Exit; FDiffKindId := 0; if MainCashForm.UnitConfigCDS.FieldByName('isReplaceSte2ListDif').AsBoolean then begin Label9.Caption := 'ШАГ 2. Добавить в заказ'; end; WaitForSingleObject(MutexDiffCDS, INFINITE); try try FAmountDay := 0; AmountDiffUser := 0; AmountDiff := 0; AmountDiffPrev := 0; AmountIncome := 0; AmountIncomeSend := 0; PriceSaleIncome := 0; ListDate := Null; if not gc_User.Local then try MainCashForm.spSelect_CashListDiffGoods.Params.ParamByName('inGoodsId').Value := FGoodsId; MainCashForm.spSelect_CashListDiffGoods.Params.ParamByName('inDiffKindID').Value := 0; MainCashForm.spSelect_CashListDiffGoods.Execute; if MainCashForm.CashListDiffCDS.Active and (MainCashForm.CashListDiffCDS.RecordCount = 1) then begin AmountDiffUser := MainCashForm.CashListDiffCDS.FieldByName('AmountDiffUser').AsCurrency; AmountDiff := MainCashForm.CashListDiffCDS.FieldByName('AmountDiff').AsCurrency; FAmountDay := MainCashForm.CashListDiffCDS.FieldByName('AmountDiff').AsCurrency; AmountDiffPrev := MainCashForm.CashListDiffCDS.FieldByName('AmountDiffPrev').AsCurrency; AmountIncome := MainCashForm.CashListDiffCDS.FieldByName('AmountIncome').AsCurrency; AmountIncomeSend := MainCashForm.CashListDiffCDS.FieldByName('AmountSendIn').AsCurrency; PriceSaleIncome := MainCashForm.CashListDiffCDS.FieldByName('PriceSaleIncome').AsCurrency; if not MainCashForm.CashListDiffCDS.FieldByName('ListDate').IsNull then ListDate := MainCashForm.CashListDiffCDS.FieldByName('ListDate').AsDateTime; end; Except end; WaitForSingleObject(MutexDiffKind, INFINITE); // только для формы2; защищаем так как есть в приложениее и сервисе try LoadLocalData(DiffKindCDS,DiffKind_lcl); if DiffKindCDS.Active then DiffKindCDS.FindField('Name').DisplayLabel := 'Вид отказа'; finally ReleaseMutex(MutexDiffKind); end; WaitForSingleObject(MutexDiffKind, INFINITE); // только для формы2; защищаем так как есть в приложениее и сервисе try LoadLocalData(DiffKindPriceCDS,DiffKindPrice_lcl); finally ReleaseMutex(MutexDiffKind); end; Remains := 0; try nID := MainCashForm.RemainsCDS.RecNo; MainCashForm.RemainsCDS.DisableControls; MainCashForm.RemainsCDS.Filtered := False; MainCashForm.RemainsCDS.First; while not MainCashForm.RemainsCDS.Eof do begin if MainCashForm.RemainsCDS.FieldByName('Id').AsInteger = FGoodsId then begin Remains := Remains + MainCashForm.RemainsCDS.FieldByName('Remains').AsCurrency + MainCashForm.RemainsCDS.FieldByName('Reserved').AsCurrency + MainCashForm.RemainsCDS.FieldByName('DeferredSend').AsCurrency; end; MainCashForm.RemainsCDS.Next; end; finally MainCashForm.RemainsCDS.Filtered := True; MainCashForm.RemainsCDS.RecNo := nID; MainCashForm.RemainsCDS.EnableControls; end; LoadLocalData(ListDiffCDS, ListDiff_lcl); if not ListDiffCDS.Active then begin CheckListDiffCDS; LoadLocalData(ListDiffCDS, ListDiff_lcl); end; if ListDiffCDS.Active then begin ListDiffCDS.First; while not ListDiffCDS.Eof do begin if (ListDiffCDS.FieldByName('ID').AsInteger = FGoodsId) then begin if (StartOfTheDay(ListDiffCDS.FieldByName('DateInput').AsDateTime) = Date) then begin if not MainCashForm.CashListDiffCDS.Active or not ListDiffCDS.FieldByName('IsSend').AsBoolean then begin if (ListDiffCDS.FieldByName('UserID').AsString = gc_User.Session) then AmountDiffUser := AmountDiffUser + ListDiffCDS.FieldByName('Amount').AsCurrency; AmountDiff := AmountDiff + ListDiffCDS.FieldByName('Amount').AsCurrency; FAmountDay := FAmountDay + ListDiffCDS.FieldByName('Amount').AsCurrency; end; end else if not MainCashForm.CashListDiffCDS.Active then AmountDiffPrev := AmountDiffPrev + ListDiffCDS.FieldByName('Amount').AsCurrency; end; ListDiffCDS.Next; end; end; WaitForSingleObject(MutexGoods, INFINITE); try LoadLocalData(ListGoodsCDS, Goods_lcl); finally ReleaseMutex(MutexGoods); end; if not ListGoodsCDS.Active then begin ShowMessage('Ошибка открытия прайсов поставщиков.'); Exit; end; if not ListGoodsCDS.Locate('Id', FGoodsId, []) then begin ListGoodsCDS.Close; ShowMessage('Ошибка медикамент не найден в прайсах поставщиков.'); Exit; end; // if ListGoodsCDS.FieldByName('isResolution_224').AsBoolean and // (Now < EncodeDateTime(2020, 04, 20, 16, 0, 0, 0)) then // begin // ListGoodsCDS.Close; // ShowMessage('Временная блокировка товара.'); // Exit; // end; S := ''; if AmountDiff <> 0 Then S := S + #13#10'Отказы сегодня: ' + CurrToStr(AmountDiff); if AmountDiffPrev <> 0 Then S := S + #13#10'Отказы вчера: ' + CurrToStr(AmountDiffPrev); if S = '' then S := #13#10'За последнии два дня отказы не найдены'; if ListDate <> Null then S := S + #13#10'Последний раз менеджер забрал заказ: ' + FormatDateTime('DD.mm.yyyy HH:NN', ListDate); if not MainCashForm.CashListDiffCDS.Active then S := #13#10'Работа автономно (Данные по кассе)' + S; S := 'Препарат: '#13#10 + FGoodsName + S; Label1.Caption := S; S := ''; if ListGoodsCDS.FieldByName('IsClose').AsBoolean then begin S := #13#10#13#10'ВНИМАНИЕ! Код закрыт для заказа МАРКЕТИНГОМ.'#13#10'См. аналог. товар (колонка "Закрыт для заказа")' + S; Label7.Font.Size := Label7.Font.Size - 2; end; if AmountDiffUser <> 0 Then S := #13#10#13#10'ВЫ УЖЕ ПОСТАВИЛИ СЕГОДНЯ - ' + CurrToStr(AmountDiffUser) + ' упк.'; if (AmountIncome > 0) or (AmountIncomeSend > 0) then begin S := S + #13#10#13#10'ТОВАР УЖЕ В ПУТИ: '; if AmountIncome > 0 then S := S + ' от поставщика: ' + CurrToStr(AmountIncome) + 'упк.'; if (AmountIncome > 0) and (AmountIncomeSend > 0) then S := S + ';'; if AmountIncomeSend > 0 then S := S + ' внутрен. перещение - ' + CurrToStr(AmountIncomeSend) + 'упк.'; end; S := S + #13#10#13#10'НТЗ = ' + CurrToStr(FMCSValue) + ' упк. ОСТАТОК = ' + CurrToStr(Remains) + ' упк.'; // if ListGoodsCDS.FieldByName('isResolution_224').AsBoolean then // begin // S := S + #13#10#13#10'ВНИМАНИЕ!!!! позиция из пост 224 - '#13#10' СТАВИТЬ в ЗАКАЗ из рассчета на 1день продаж!'; // Label7.Font.Size := Label7.Font.Size - 2; // end; S := S + #13#10#13#10'ВАМ ДЕЙСТВИТЕЛЬНО НУЖНО БОЛЬШЕ ?!'; Label7.Caption := S; Label7.Visible := Label7.Caption <> ''; if not ListGoodsCDS.FieldByName('ExpirationDate').IsNull then begin if ListGoodsCDS.FieldByName('ExpirationDate').AsDateTime < IncYear(Date, 1) then begin Label5.Caption := 'СРОК ГОДНОСТИ МЕНЕЕ ГОДА - ' + ListGoodsCDS.FieldByName('ExpirationDate').AsString; Label5.Font.Color := clRed; end else begin Label5.Caption := 'Срок годности - ' + ListGoodsCDS.FieldByName('ExpirationDate').AsString; Label5.Font.Color := clWindowText end; end else begin Label5.Caption := 'СРОК ГОДНОСТИ НЕ НАЙДЕН'; Label5.Font.Color := clRed; end; TimerStart.Enabled := True; Except ON E:Exception do ShowMessage('Ошибка открытия листа отказов:'#13#10 + E.Message); end; finally ReleaseMutex(MutexDiffCDS); if not ListGoodsCDS.Active then PostMessage(Handle, WM_CLOSE, 0, 0); end; end; procedure TListDiffAddGoodsForm.lcbDiffKindPropertiesChange(Sender: TObject); begin Label8.Visible := False; FMaxOrderAmount := 0; FPackages := 0; FAmountDiffKind := 0; if FDiffKindId = 0 then Exit; if not DiffKindCDS.Locate('Id', FDiffKindId, []) then Exit; FMaxOrderAmount := DiffKindCDS.FieldByName('MaxOrderUnitAmount').AsCurrency; FPackages := DiffKindCDS.FieldByName('Packages').AsCurrency; if (FMaxOrderAmount = 0) and (FPackages = 0) then Exit; if not gc_User.Local then try MainCashForm.spSelect_CashListDiffGoods.Params.ParamByName('inGoodsId').Value := FGoodsId; MainCashForm.spSelect_CashListDiffGoods.Params.ParamByName('inDiffKindID').Value := FDiffKindId; MainCashForm.spSelect_CashListDiffGoods.Execute; if MainCashForm.CashListDiffCDS.Active and (MainCashForm.CashListDiffCDS.RecordCount = 1) then begin FAmountDiffKind := MainCashForm.CashListDiffCDS.FieldByName('AmountDiffKind').AsCurrency; end; Except end; WaitForSingleObject(MutexDiffCDS, INFINITE); try LoadLocalData(ListDiffCDS, ListDiff_lcl); if not ListDiffCDS.Active then begin CheckListDiffCDS; LoadLocalData(ListDiffCDS, ListDiff_lcl); end; finally ReleaseMutex(MutexDiffCDS); end; if ListDiffCDS.Active then begin ListDiffCDS.First; while not ListDiffCDS.Eof do begin if (ListDiffCDS.FieldByName('ID').AsInteger = FGoodsId) then begin if (StartOfTheDay(ListDiffCDS.FieldByName('DateInput').AsDateTime) = Date) then begin if not MainCashForm.CashListDiffCDS.Active or not ListDiffCDS.FieldByName('IsSend').AsBoolean then begin if (ListDiffCDS.FieldByName('DiffKindId').AsInteger = FDiffKindId) then FAmountDiffKind := FAmountDiffKind + ListDiffCDS.FieldByName('Amount').AsCurrency; end; end; end; ListDiffCDS.Next; end; end; ceAmountPropertiesChange(Sender); end; procedure TListDiffAddGoodsForm.TimerStartTimer(Sender: TObject); begin TimerStart.Enabled := False; actShowListDiffExecute(Sender); end; // Сохранение чека в локальной базе. function TListDiffAddGoodsForm.SaveLocal(AManagerId: Integer; AManagerName, ABayerName: String; AAmount : Currency): Boolean; var UID: String; begin UID := ''; if CheckCDS.Active then CheckCDS.Close; CheckCDS.FieldDefs.Clear; CheckCDS.FieldDefs.Assign(MainCashForm.CheckCDS.FieldDefs); CheckCDS.CreateDataSet; CheckCDS.Append; CheckCDS.FieldByName('Id').AsInteger := 0; CheckCDS.FieldByName('ParentId').AsInteger := 0; CheckCDS.FieldByName('GoodsId').AsInteger := FGoodsId; CheckCDS.FieldByName('GoodsCode').AsInteger := FGoodsCode; CheckCDS.FieldByName('GoodsName').AsString := FGoodsName; CheckCDS.FieldByName('Amount').asCurrency := AAmount; CheckCDS.FieldByName('Price').asCurrency := FPrice; CheckCDS.FieldByName('Summ').asCurrency := GetSumm(AAmount, FPrice, True); CheckCDS.FieldByName('NDS').asCurrency := FNDS; CheckCDS.FieldByName('NDSKindId').AsInteger := FNDSKindId; CheckCDS.FieldByName('DiscountExternalID').AsVariant := Null; CheckCDS.FieldByName('DiscountExternalName').AsVariant := Null; CheckCDS.FieldByName('DivisionPartiesID').AsVariant := Null; CheckCDS.FieldByName('DivisionPartiesName').AsVariant :=Null; CheckCDS.FieldByName('isErased').AsBoolean := false; // ***20.07.16 CheckCDS.FieldByName('PriceSale').asCurrency := FPrice; CheckCDS.FieldByName('ChangePercent').asCurrency := 0; CheckCDS.FieldByName('SummChangePercent').asCurrency := 0; // ***19.08.16 CheckCDS.FieldByName('AmountOrder').asCurrency := 0; // ***10.08.16 CheckCDS.FieldByName('List_UID').AsString := GenerateGUID; // ***04.09.18 CheckCDS.FieldByName('Remains').asCurrency := 0; // ***31.03.19 CheckCDS.FieldByName('DoesNotShare').AsBoolean := False; // ***31.03.19 CheckCDS.FieldByName('isPresent').AsBoolean := False; CheckCDS.Post; MainCashForm.SaveLocal(CheckCDS, AManagerId, AManagerName, ABayerName, '', 'Не подтвержден', '', '', 0, '', '', 0, '', '', '', '', Date, 0, '', 0, 0, 0, 0, 0, 0, 0, 0, True, 0, '', 0, 0, 0, 0, '', '', '', '', '', 0, 0, False, False, false, false, 0, false, 0, false, false, false, 0, '', 0, '', 0, UID); end; end.
{$ifdef license} (* Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder 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 HOLDER 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. *) {$endif} unit cwIO.FileStream.Standard; {$ifdef fpc} {$mode delphiunicode} {$endif} interface uses Classes //[RTL] , cwIO , cwIO.UnicodeStream.Custom ; type TFileStream = class( TCustomUnicodeStream, IStream, IUnicodeStream ) private fFilePath: string; fSysFileStream: classes.TFileStream; protected procedure Clear; override; function Read( const p: pointer; const Count: nativeuint ): nativeuint; override; function Write( const p: pointer; const Count: nativeuint ): nativeuint; override; function getSize: nativeuint; override; function getPosition: nativeuint; override; procedure setPosition( const newPosition: nativeuint ); override; public constructor Create( const Filepath: string; const ReadOnly: boolean ); reintroduce; destructor Destroy; override; end; implementation uses sysutils //[RTL] , cwTypes ; procedure TFileStream.Clear; begin {$ifdef fpc} fSysFileStream.Free; {$else} fSysFileStream.DisposeOf; {$endif} fSysFileStream := nil; if FileExists(fFilePath) then begin DeleteFile(fFilePath); end; fSysFileStream := classes.TFileStream.Create(fFilePath{$ifdef fpc}.AsAnsiString{$endif},fmCreate); end; constructor TFileStream.Create( const Filepath: string; const ReadOnly: boolean ); begin inherited Create; fFilepath := FilePath; if ReadOnly then begin fSysFileStream := classes.TFileStream.Create(fFilepath{$ifdef fpc}.AsAnsiString{$endif},fmOpenRead); end else begin if FileExists(FilePath) then begin fSysFileStream := classes.TFileStream.Create(fFilepath{$ifdef fpc}.AsAnsiString{$endif},fmOpenReadWrite); end else begin fSysFileStream := classes.TFileStream.Create(fFilepath{$ifdef fpc}.AsAnsiString{$endif},fmCreate); end; end; end; destructor TFileStream.Destroy; begin {$ifdef fpc} fSysFileStream.Free; {$else} fSysFileStream.DisposeOf; {$endif} inherited; end; function TFileStream.getPosition: nativeuint; begin Result := fSysFileStream.Position; end; function TFileStream.getSize: nativeuint; begin Result := fSysFileStream.Size; end; function TFileStream.Read(const p: pointer; const Count: nativeuint): nativeuint; begin Result := fSysfileStream.Read(p^,Count); end; procedure TFileStream.setPosition(const newPosition: nativeuint); begin fSysFileStream.Position := newPosition; end; function TFileStream.Write(const p: pointer; const Count: nativeuint): nativeuint; begin Result := fSysFileStream.Write(p^,Count); end; end.
unit UExternalFunctionTests; interface uses Classes, dwsXPlatformTests, dwsComp, dwsErrors, dwsExprList, dwsCompiler, dwsExprs, dwsExternalFunctions; type TExternalFunctionTests = class(TTestCase) private FTests : TStringList; FCompiler : TDelphiWebScript; FUnit: TdwsUnit; procedure RegisterExternalRoutines(const manager : IdwsExternalFunctionsManager); procedure FreeBoxedString(ExternalObject: TObject); public procedure SetUp; override; procedure TearDown; override; procedure Execution; procedure Compilation; published procedure Test; end; implementation uses SysUtils, dwsXPlatform, dwsSymbols, dwsUtils, dwsDataContext; { TExternalFunctionTests } procedure TExternalFunctionTests.Compilation; var source : TStringList; i : Integer; prog : IdwsProgram; begin source:=TStringList.Create; try for i:=0 to FTests.Count-1 do begin source.LoadFromFile(FTests[i]); prog:=FCompiler.Compile(source.Text); CheckEquals('', prog.Msgs.AsInfo, FTests[i]); end; finally source.Free; end; end; type TBoxedString = class value: string; end; procedure Blank; begin end; procedure Ints3(a, b, c: integer); begin assert(a = 1); assert(b = 5); assert(c = 6); end; procedure TestString(a: integer; b: string); begin assert(a = 5); assert(b = 'Testing'); end; procedure TestStringExc(a: integer; b: string); begin TestString(a, b); Abort; end; procedure TestBool(a: integer; b: boolean); begin assert(a = 5); assert(b = true); end; procedure TestStack(a, b, c, d: integer); begin assert(a = 1); assert(b = 5); assert(c = 12); assert(d = -57); end; procedure TestFloat(a: integer; b: double); begin assert(a = 1); assert(b = 0.5); end; procedure TestObject(a: integer; b: TBoxedString); begin assert(a = 1); assert(b.value = 'Boxed String'); end; procedure TestObjectExc(a: integer; b: TBoxedString); begin TestObject(a, b); Abort; end; function TestReturnInt(a, b: integer): integer; begin result := a + b; end; function TestReturnObject: TBoxedString; begin result := TBoxedString.Create; result.value := 'Boxed String'; end; procedure TestArray(a: integer; b: TStringDynArray); begin assert(a = 1); assert(length(b) = 3); assert(b[0] = 'Testing'); assert(b[1] = 'testing'); assert(b[2] = '123'); end; procedure TExternalFunctionTests.RegisterExternalRoutines(const manager : IdwsExternalFunctionsManager); begin manager.RegisterExternalFunction('Blank', @Blank); manager.RegisterExternalFunction('Ints3', @Ints3); manager.RegisterExternalFunction('TestString', @TestString); manager.RegisterExternalFunction('TestStringExc', @TestStringExc); manager.RegisterExternalFunction('TestBool', @TestBool); manager.RegisterExternalFunction('TestStack', @TestStack); manager.RegisterExternalFunction('TestFloat', @TestFloat); manager.RegisterExternalFunction('TestObject', @TestObject); manager.RegisterExternalFunction('TestObjectExc', @TestObjectExc); manager.RegisterExternalFunction('TestReturnInt', @TestReturnInt); manager.RegisterExternalFunction('TestReturnObject', @TestReturnObject); manager.RegisterExternalFunction('TestArray', @TestArray); end; procedure ExtractStringArray(const source: IDataContext; var output {TStringDynArray}); var i: integer; result: TStringDynArray absolute output; begin SetLength(result, source.DataLength); for i := 0 to source.DataLength - 1 do result[i] := source.AsString[i]; end; procedure TExternalFunctionTests.Execution; var source, expectedResult : TStringList; i : Integer; prog : IdwsProgram; exec : IdwsProgramExecution; manager : IdwsExternalFunctionsManager; resultText, resultsFileName : String; begin source:=TStringList.Create; expectedResult:=TStringList.Create; try for i:=0 to FTests.Count-1 do begin source.LoadFromFile(FTests[i]); manager:=TExternalFunctionManager.Create; // TODO: IdwsExternalFunctionsManager being low-level // it shouldn't be exposed at the TDelphiWebScript level // (need to have a TComponent property be exposed there) FCompiler.Compiler.ExternalFunctionsManager:=manager; manager.RegisterTypeMapping('TStringDynArray', TTypeLookupData.Create(@ExtractStringArray, TypeInfo(TStringDynArray))); prog:=FCompiler.Compile(source.Text); CheckEquals('', prog.Msgs.AsInfo, FTests[i]); // TODO: ideally should happen before compilation // and registration should be able to be program-independent RegisterExternalRoutines(manager); exec:=prog.Execute; // TODO: make compiler program independent from manager FCompiler.Compiler.ExternalFunctionsManager:=nil; resultText:=exec.Result.ToString; if exec.Msgs.Count>0 then resultText:=resultText+#13#10'>>>> Error(s): '#13#10+exec.Msgs.AsInfo; resultsFileName:=ChangeFileExt(FTests[i], '.txt'); if FileExists(resultsFileName) then begin expectedResult.LoadFromFile(resultsFileName); CheckEquals(expectedResult.Text, resultText, FTests[i]); end else CheckEquals('', resultText, FTests[i]); CheckEquals('', exec.Msgs.AsInfo, FTests[i]); end; finally expectedResult.Free; source.Free; end; end; procedure TExternalFunctionTests.SetUp; var tbs: TdwsClass; arr: TdwsArray; begin FTests:=TStringList.Create; CollectFiles(ExtractFilePath(ParamStr(0))+'External'+PathDelim, '*.pas', FTests); FCompiler:=TDelphiWebScript.Create(nil); FUnit := TdwsUnit.Create(FCompiler); FUnit.ParseName := pnAlways; FUnit.UnitName := 'Helper'; FUnit.script := FCompiler; tbs := FUnit.Classes.Add; tbs.Name := 'TBoxedString'; tbs.OnCleanUp := self.FreeBoxedString; arr := FUnit.Arrays.Add; arr.Name := 'TStringDynArray'; arr.IsDynamic := true; arr.DataType := 'string'; FUnit.ImplicitUse := true; end; procedure TExternalFunctionTests.TearDown; begin FCompiler.Free; FTests.Free; end; procedure TExternalFunctionTests.FreeBoxedString(ExternalObject: TObject); begin ExternalObject.free; end; procedure TExternalFunctionTests.Test; begin Compilation; Execution; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterTest('dwsExternalFunctionTests', TExternalFunctionTests); end.
unit point; interface uses Windows; //tell if a point is between (0, 0) and (w-1, h-1) function Collision(x, y: integer; w, h : integer; size : integer = 0): boolean; overload; function Collision(var p: Tpoint; w, h : integer; size : integer = 0): boolean; overload; function manhattan(var start, finish : Tpoint): integer; function pointCmp(a, b : Tpoint): boolean; //returns the direction from p1 to p2 (ex : (4, 4)->(15, -15) = (1, -1)) // (only accurate for horizontal, vertical and diagonal moves) function Tpoint_way(var p1, p2 : Tpoint): Tpoint; function TpointToStr(var p: Tpoint): string; function TpDist2(var p1, p2 : Tpoint): integer; implementation uses Sysutils, Mymath; function Collision(x, y: integer; w, h : integer; size : integer = 0): boolean; var add : integer; begin add := half(size); Result := (x >= add) and (y >= add) and (x + add < w) and (y + add < h); end; function Collision(var p: Tpoint; w, h : integer; size : integer = 0): boolean; var add : integer; begin add := half(size); Result := (p.x >= add) and (p.y >= add) and (p.x + add < w) and (p.y + add < h); end; function manhattan(var start, finish : Tpoint): integer; begin Result := int_abs(finish.x - start.x) + int_abs(finish.y - start.y); end; function pointCmp(a, b : Tpoint): boolean; begin Result := (a.x = b.x) and (a.y = b.y); end; function Tpoint_way(var p1, p2 : Tpoint): Tpoint; begin Result.x := intComp(p2.x, p1.x); Result.y := intComp(p2.y, p1.y); end; function TpointToStr(var p: Tpoint): string; begin Result := IntToStr(p.x) + ', ' + IntToStr(p.y); end; function TpDist2(var p1, p2 : Tpoint): integer; begin Result := pow2(int_abs(p1.x - p2.x)) + pow2(int_abs(p1.y - p2.y)); end; end.
unit RepositorioUsuario; interface uses DB, Repositorio, Auditoria; type TRepositorioUsuario = class(TRepositorio) protected procedure ExecutaDepoisDeSalvar(Objeto: TObject); override; protected function Get (Dataset :TDataSet) :TObject; overload; override; function GetNomeDaTabela :String; override; function GetIdentificador(Objeto :TObject) :Variant; override; function GetRepositorio :TRepositorio; override; protected function SQLGet :String; override; function SQLSalvar :String; override; function SQLGetAll :String; override; function SQLRemover :String; override; function SQLGetExiste(campo: String): String; override; protected function IsInsercao(Objeto :TObject) :Boolean; override; protected procedure SetParametros (Objeto :TObject ); override; procedure SetIdentificador(Objeto :TObject; Identificador :Variant); override; //============================================================================== // Auditoria //============================================================================== protected procedure SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); override; procedure SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); override; procedure SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); override; end; implementation uses Usuario, FabricaRepositorio, DiretorioBackup, SysUtils, Variants; { TRepositorioUsuario } procedure TRepositorioUsuario.ExecutaDepoisDeSalvar(Objeto: TObject); var nX :Integer; Usuario :TUsuario; Repositorio :TRepositorio; begin Usuario := (Objeto as TUsuario); if (not Assigned(Usuario.DiretoriosBackup)) or (Usuario.DiretoriosBackup.Count <= 0) then exit; try Repositorio := TFabricaRepositorio.GetRepositorio(TDiretorioBackup.ClassName); for nX := 0 to (Usuario.DiretoriosBackup.Count-1) do begin Repositorio.Salvar(Usuario.DiretoriosBackup.Items[0]); end; finally FreeAndNil(Repositorio); end; end; function TRepositorioUsuario.Get(Dataset: TDataSet): TObject; var Usuario :TUsuario; begin Usuario := TUsuario.Create; Usuario.Codigo := self.FQuery.FieldByName('codigo').AsInteger; Usuario.Nome := self.FQuery.FieldByName('nome').AsString; Usuario.Login := self.FQuery.FieldByName('login').AsString; Usuario.Senha := self.FQuery.FieldByName('senha').AsString; Usuario.CodPerfil := self.FQuery.FieldByName('cod_Perfil').AsInteger; Usuario.Bloqueado := (Dataset.FieldByName('bloqueado').AsString = 'S'); Usuario.Codigo_departamento := self.FQuery.FieldByName('codigo_departamento').AsInteger; result := Usuario; end; function TRepositorioUsuario.GetIdentificador(Objeto: TObject): Variant; begin result := TUsuario(Objeto).Codigo; end; function TRepositorioUsuario.GetNomeDaTabela: String; begin result := 'USUARIOS'; end; function TRepositorioUsuario.GetRepositorio: TRepositorio; begin result := TRepositorioUsuario.Create; end; function TRepositorioUsuario.IsInsercao(Objeto: TObject): Boolean; begin result := (TUsuario(Objeto).Codigo <= 0); end; procedure TRepositorioUsuario.SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); var UAntigo, UNovo :TUsuario; begin UAntigo := (AntigoObjeto as TUsuario); UNovo := (Objeto as TUsuario); if (UAntigo.Nome <> UNovo.Nome) then Auditoria.AdicionaCampoAlterado('nome', UAntigo.Nome, UNovo.Nome); if (UAntigo.Login <> UNovo.Login) then Auditoria.AdicionaCampoAlterado('login', UAntigo.Login, UNovo.Login); if (UAntigo.Senha <> UNovo.Senha) then Auditoria.AdicionaCampoAlterado('senha', UAntigo.Senha, UNovo.Senha); if (UAntigo.CodPerfil <> UNovo.CodPerfil) then Auditoria.AdicionaCampoAlterado('cod_perfil', IntToStr(UAntigo.CodPerfil), IntToStr(UNovo.CodPerfil)); if (UAntigo.Bloqueado <> UNovo.Bloqueado) and UAntigo.Bloqueado then Auditoria.AdicionaCampoAlterado('bloqueado', 'S', 'N') else if (UAntigo.Bloqueado <> UNovo.Bloqueado) and (not UAntigo.Bloqueado) then Auditoria.AdicionaCampoAlterado('bloqueado', 'N', 'S'); if (UAntigo.Codigo_departamento <> UNovo.Codigo_departamento) then Auditoria.AdicionaCampoAlterado('codigo_departamento', IntToStr(UAntigo.Codigo_departamento), IntToStr(UNovo.Codigo_departamento)); end; procedure TRepositorioUsuario.SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); var Usuario :TUsuario; begin Usuario := (Objeto as TUsuario); Auditoria.AdicionaCampoExcluido('codigo', IntToStr(Usuario.Codigo)); Auditoria.AdicionaCampoExcluido('nome', Usuario.Nome); Auditoria.AdicionaCampoExcluido('login', Usuario.Login); Auditoria.AdicionaCampoExcluido('senha', Usuario.Senha); Auditoria.AdicionaCampoExcluido('cod_perfil', IntToStr(Usuario.CodPerfil)); if Usuario.Bloqueado then Auditoria.AdicionaCampoExcluido('bloqueado', 'S') else Auditoria.AdicionaCampoExcluido('bloqueado', 'N'); Auditoria.AdicionaCampoExcluido('codigo_departamento', IntToStr(Usuario.Codigo_departamento)); end; procedure TRepositorioUsuario.SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); var Usuario :TUsuario; begin Usuario := (Objeto as TUsuario); Auditoria.AdicionaCampoIncluido('codigo', IntToStr(Usuario.Codigo)); Auditoria.AdicionaCampoIncluido('nome', Usuario.Nome); Auditoria.AdicionaCampoIncluido('login', Usuario.Login); Auditoria.AdicionaCampoIncluido('senha', Usuario.Senha); Auditoria.AdicionaCampoIncluido('cod_perfil', IntToStr(Usuario.CodPerfil)); if Usuario.Bloqueado then Auditoria.AdicionaCampoIncluido('bloqueado', 'S') else Auditoria.AdicionaCampoIncluido('bloqueado', 'N'); Auditoria.AdicionaCampoIncluido('codigo_departamento', IntToStr(Usuario.Codigo_departamento)); end; procedure TRepositorioUsuario.SetIdentificador(Objeto: TObject; Identificador: Variant); begin TUsuario(Objeto).Codigo := Integer(Identificador); end; procedure TRepositorioUsuario.SetParametros(Objeto :TObject); var Usuario :TUsuario; nX :Integer; RepositorioDiretoriosBackup :TRepositorio; begin Usuario := (Objeto as TUsuario); if (Usuario.Codigo > 0) then inherited SetParametro('codigo', Usuario.Codigo) else inherited LimpaParametro('codigo'); inherited SetParametro('nome', Usuario.Nome); inherited SetParametro('login', Usuario.Login); inherited SetParametro('senha', Usuario.Senha); inherited SetParametro('cod_Perfil', Usuario.CodPerfil); if Usuario.Bloqueado then inherited SetParametro('bloqueado', 'S') else inherited SetParametro('bloqueado', 'N'); inherited SetParametro('codigo_departamento', Usuario.Codigo_departamento); RepositorioDiretoriosBackup := nil; if ( Assigned(Usuario.DiretoriosBackup) and (Usuario.DiretoriosBackup.Count > 0)) then begin try RepositorioDiretoriosBackup := TFabricaRepositorio.GetRepositorio(TDiretorioBackup.ClassName); for nX := 0 to (Usuario.DiretoriosBackup.Count-1) do begin TDiretorioBackup(Usuario.DiretoriosBackup.Items[nX]).Usuario := Usuario; // Isso aqui colocar no ADD. RepositorioDiretoriosBackup.Salvar(Usuario.DiretoriosBackup.Items[nX]); end; finally FreeAndNil(RepositorioDiretoriosBackup); end; end; end; function TRepositorioUsuario.SQLGet: String; begin result := 'select * from usuarios where codigo = :codigo '; end; function TRepositorioUsuario.SQLGetAll: String; begin result := 'select * from usuarios'; end; function TRepositorioUsuario.SQLGetExiste(campo: String): String; begin result := 'select '+ campo +' from usuarios where '+ campo +' = :ncampo'; end; function TRepositorioUsuario.SQLRemover: String; begin result := ' delete from usuarios where codigo = :codigo '; end; function TRepositorioUsuario.SQLSalvar: String; begin result := 'update or insert into usuarios (codigo, nome, login, senha, cod_Perfil, bloqueado, codigo_departamento)'+ ' values (:codigo, :nome, :login, :senha, :cod_Perfil, :bloqueado, :codigo_departamento)'; end; end.
unit Unit_Cript; interface uses Windows, Dialogs; const CountTest = 10; SerialNumberArray : array [0..CountTest] of Cardinal = (746067712, // ---- СН - Винчестер Виталий 122297812, // ---- СН - Винчестер Пашин 2, 3, 4, 5, 6, 7, 794204000, 3563790268, //-----СН - Инсталл SDRom 2603380172); procedure cript; function Get_SerialNumberCdRom():Cardinal; function Get_SerialNumberDiskC():Cardinal; var GLobalErrorOffset : extended; implementation Function CompareSerialNumber(SerialNumber : Cardinal): Boolean; Const Max_Path = 255; var MyStr : pChar; DriveList : array [0..20] of String; DriveLetter : PChar; VolumeName, FileSystemName : array [0..Max_Path-1] of Char; VolumeSerialNo : Cardinal; MaxComponentLength, FileSystemFlags : DWORD; i : Integer; Count : Integer; begin Result := false; GetMem(MyStr, Max_Path); //------- Получаю список Драйвов ------------------------- GetLogicalDriveStrings(Max_Path,MyStr); Count := 0; for i:=0 to Max_Path-1 do begin if (MyStr[i] >= 'a') and (MyStr[i] <= 'z') or ((MyStr[i] >= 'A') and (MyStr[i] <= 'Z')) then begin DriveList[Count] := MyStr[i]+MyStr[i+1]+MyStr[i+2] + #0; Count := Count + 1; end; if (MyStr[i] = #0) and (MyStr[i+1] = #0) then Break; end; FreeMem(MyStr, Max_Path); //------- Получаю СН ------------------------- GetMem(DriveLetter,4); for i:= 0 to Count - 1 do begin DriveLetter[0] := DriveList[i][1]; DriveLetter[1] := DriveList[i][2]; DriveLetter[2] := DriveList[i][3]; DriveLetter[3] := DriveList[i][4]; if (DriveLetter[0] <> 'a') and (DriveLetter[0] <> 'A') and (DriveLetter[0] <> 'b') and (DriveLetter[0] <> 'B') then try GetVolumeInformation(DriveLetter, VolumeName, MAX_PATH, @VolumeSerialNo, MaxComponentLength, FileSystemFlags, FileSystemName, MAX_PATH); if VolumeSerialNo = SerialNumber then begin //StrSerialNumber := IntToHex(HiWord(VolumeSerialNo),4)+ '-' + IntToHex(LoWord(VolumeSerialNo),4); Result := true; end; except end; end; FreeMem(DriveLetter,4); //-------------------------------- end; // *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function Get_SerialNumberCdRom(): Cardinal; Const Max_Path = 255; var MyStr : pChar; DriveList : array [0..20] of String; DriveLetter : PChar; VolumeName, FileSystemName : array [0..Max_Path-1] of Char; VolumeSerialNo : Cardinal; MaxComponentLength, FileSystemFlags : DWORD; i : Integer; Count : Integer; begin Result := 0; GetMem(MyStr, Max_Path); //------- Получаю список Драйвов ------------------------- GetLogicalDriveStrings(Max_Path,MyStr); Count := 0; for i:=0 to Max_Path-1 do begin if (MyStr[i] >= 'a') and (MyStr[i] <= 'z') or ((MyStr[i] >= 'A') and (MyStr[i] <= 'Z')) then begin DriveList[Count] := MyStr[i]+MyStr[i+1]+MyStr[i+2] + #0; Count := Count + 1; end; if (MyStr[i] = #0) and (MyStr[i+1] = #0) then Break; end; FreeMem(MyStr, Max_Path); //------- Получаю СН ------------------------- GetMem(DriveLetter,4); for i:= 0 to Count - 1 do begin DriveLetter[0] := DriveList[i][1]; DriveLetter[1] := DriveList[i][2]; DriveLetter[2] := DriveList[i][3]; DriveLetter[3] := DriveList[i][4]; if GetDriveType (DriveLetter) = 5 then try GetVolumeInformation(DriveLetter, VolumeName, MAX_PATH, @VolumeSerialNo, MaxComponentLength, FileSystemFlags, FileSystemName, MAX_PATH); Result := VolumeSerialNo; Break; except end; end; FreeMem(DriveLetter,4); //-------------------------------- end; // *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function Get_SerialNumberDiskC(): Cardinal; Const Max_Path = 255; var MyStr : pChar; DriveList : array [0..20] of String; DriveLetter : PChar; VolumeName, FileSystemName : array [0..Max_Path-1] of Char; VolumeSerialNo : Cardinal; MaxComponentLength, FileSystemFlags : DWORD; i : Integer; Count : Integer; begin Result := 0; GetMem(MyStr, Max_Path); //------- Получаю список Драйвов ------------------------- GetLogicalDriveStrings(Max_Path,MyStr); Count := 0; for i:=0 to Max_Path-1 do begin if (MyStr[i] >= 'a') and (MyStr[i] <= 'z') or ((MyStr[i] >= 'A') and (MyStr[i] <= 'Z')) then begin DriveList[Count] := MyStr[i]+MyStr[i+1]+MyStr[i+2] + #0; Count := Count + 1; end; if (MyStr[i] = #0) and (MyStr[i+1] = #0) then Break; end; FreeMem(MyStr, Max_Path); //------- Получаю СН ------------------------- GetMem(DriveLetter,4); for i:= 0 to Count - 1 do begin DriveLetter[0] := DriveList[i][1]; DriveLetter[1] := DriveList[i][2]; DriveLetter[2] := DriveList[i][3]; DriveLetter[3] := DriveList[i][4]; if (DriveLetter[0] = 'c') or (DriveLetter[0] = 'C') then try GetVolumeInformation(DriveLetter, VolumeName, MAX_PATH, @VolumeSerialNo, MaxComponentLength, FileSystemFlags, FileSystemName, MAX_PATH); Result := VolumeSerialNo; Break; except end; end; FreeMem(DriveLetter,4); //-------------------------------- end; // *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure cript; var flag : Boolean; i : Integer; //StrSerialNumber : String; begin //********* Проверям Компакт Диск ********************* repeat flag := false; //--------------------------------------------------- for i := 0 to CountTest do begin if CompareSerialNumber(SerialNumberArray[i]) then flag := true; // ---- Серийный номер Винчестера на Работе end; //-------------------------------------------------- if not flag then if MessageDLG('Вставте компютер инсталяционный диск', mtError, [mbCancel,mbRetry],0) = idCancel then ExitProcess(0); until flag; // ******************************************************** end; begin GLobalErrorOffset :=1 ; end.
unit Config_u; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ComCtrls, ExtCtrls, Registry, Advanced; type TdlgConfig = class(TForm) btnOk: TBitBtn; btnCancel: TBitBtn; pcMain: TPageControl; tgGeneral: TTabSheet; gbInterface: TGroupBox; cbToolBarCaptions: TCheckBox; cbRowSelect: TCheckBox; rgViewStyle: TRadioGroup; tbFolders: TTabSheet; gbTempDir: TGroupBox; edTempDir: TEdit; BitBtn1: TBitBtn; tsView: TTabSheet; gbFileTypes: TGroupBox; edFileExts: TEdit; tsSecurity: TTabSheet; gbExcludeFiles: TGroupBox; cbEnableMode: TCheckBox; edExcludeExts: TEdit; tsIntegration: TTabSheet; gbFolders: TGroupBox; Label1: TLabel; Label2: TLabel; edDefaultFolder: TEdit; btnBrows: TBitBtn; edDefaultExtractDir: TEdit; btnBrows1: TBitBtn; gbAssociation: TGroupBox; cbAssociate: TCheckBox; procedure FormCreate(Sender: TObject); private { Private declarations } public Procedure WriteParams; Procedure ReadParams; { Public declarations } end; var dlgConfig: TdlgConfig; Const Section='Config'; implementation {$R *.dfm} Procedure TdlgConfig.WriteParams; Var RegIni:TRegIniFile; Index:Byte; Begin RegIni:=TRegIniFile.Create('Software\MADMAN Software\WinMZF'); RegIni.RootKey:=HKEY_CURRENT_USER; RegIni.WriteBool(Section,'ShowToolBarCaptions',dlgConfig.cbToolBarCaptions.Checked); RegIni.WriteBool(Section,'RowSelect',dlgConfig.cbRowSelect.Checked); RegIni.WriteInteger(Section,'ViewStyle',dlgConfig.rgViewStyle.ItemIndex); RegIni.WriteString(Section,'DefArchFolder',dlgConfig.edDefaultFolder.Text); RegIni.WriteString(Section,'DefExtractFolder',dlgConfig.edDefaultExtractDir.Text); RegIni.WriteString(Section,'TempDir',dlgConfig.edTempDir.Text); RegIni.WriteString(Section,'UnpackFor',dlgConfig.edFileExts.Text); RegIni.WriteBool(Section,'EnableSecurity',dlgConfig.cbEnableMode.Checked); RegIni.WriteString(Section,'ExcludeExt',dlgCOnfig.edExcludeExts.Text); RegIni.WriteBool(Section,'Associate',dlgCOnfig.cbAssociate.Checked); RegIni.Free; End; procedure TdlgConfig.FormCreate(Sender: TObject); begin Caption:=ReadFromLanguage('Windows','wndConfig',Caption); tgGeneral.Caption:=ReadFromLanguage('Tabs','tbGeneral',tgGeneral.Caption); tbFolders.Caption:=ReadFromLanguage('Tabs','tbFolders',tbFolders.Caption); tsView.Caption:=ReadFromLanguage('Tabs','tbView',tsView.Caption); tsSecurity.Caption:=ReadFromLanguage('Tabs','tbSecurity',tsSecurity.Caption); tsIntegration.Caption:=ReadFromLanguage('Tabs','tbIntegration',tsIntegration.Caption); gbInterface.Caption:=ReadFromLanguage('Labels','lbInterface',gbInterface.Caption); cbToolBarCaptions.Caption:=ReadFromLanguage('Labels','lbShowCaptions',cbToolBarCaptions.Caption); cbRowSelect.Caption:=ReadFromLanguage('Labels','lbRowSelect',cbRowSelect.Caption); rgViewStyle.Caption:=ReadFromLanguage('Labels','lbViewStyle',rgViewStyle.Caption); gbFolders.Caption:=ReadFromLanguage('Labels','lbDefExtractFolder',gbFolders.Caption); Label2.Caption:=ReadFromLanguage('Labels','lbDefExtractFolder',Label2.Caption); Label1.Caption:=ReadFromLanguage('Labels','lbDefFolder',Label1.Caption); gbTempDir.Caption:=ReadFromLanguage('Labels','lbTempDir',gbTempDir.Caption); gbFileTypes.Caption:=ReadFromLanguage('Labels','lbFileTypes',gbFileTypes.Caption); gbExcludeFiles.Caption:=ReadFromLanguage('Labels','lbExcludeFiles',gbExcludeFiles.Caption); cbEnableMode.Caption:=ReadFromLanguage('Labels','lbEnableSecurity',cbEnableMode.Caption); btnCancel.Caption:=ReadFromLanguage('Buttons','btnCancel',btnCancel.Caption); rgViewStyle.Items[0]:=ReadFromLanguage('Menu','mnuReport',rgViewStyle.Items[0]); rgViewStyle.Items[1]:=ReadFromLanguage('Menu','mnuList',rgViewStyle.Items[1]); rgViewStyle.Items[2]:=ReadFromLanguage('Menu','mnuSmallIcons',rgViewStyle.Items[2]); rgViewStyle.Items[3]:=ReadFromLanguage('Menu','mnuBigIcons',rgViewStyle.Items[3]); gbAssociation.Caption:=ReadFromLanguage('Labels','lbAssociation',gbAssociation.Caption); cbAssociate.Caption:=ReadFromLanguage('Labels','lbAssociate',cbAssociate.Caption); end; Procedure TdlgConfig.ReadParams; var RegIni:TRegIniFile; Index:Byte; begin RegIni:=TRegIniFile.Create('Software\MADMAN Software\WinMZF'); RegIni.RootKey:=HKEY_CURRENT_USER; dlgConfig.cbToolBarCaptions.Checked:=RegIni.ReadBool(Section,'ShowToolBarCaptions',True); dlgConfig.cbRowSelect.Checked:=RegIni.ReadBool(Section,'RowSelect',True); dlgConfig.rgViewStyle.ItemIndex:=RegIni.ReadInteger(Section,'ViewStyle',0); dlgConfig.edDefaultFolder.Text:=RegIni.ReadString(Section,'DefArchFolder',GetSystemPath(TSystemPath(0))); dlgConfig.edDefaultExtractDir.Text:=RegIni.ReadString(Section,'DefExtractFolder',GetSystemPath(TSystemPath(0))); dlgConfig.edTempDir.Text:=RegIni.ReadString(Section,'TempDir',GetTempDir); dlgConfig.edFileExts.Text:=RegIni.ReadString(Section,'UnpackFor','*.exe;*.com;*.htm;*.bat;*.html'); dlgConfig.cbEnableMode.Checked:=RegIni.ReadBool(Section,'EnableSecurity',False); dlgConfig.edExcludeExts.Enabled:=dlgConfig.cbEnableMode.Checked; dlgCOnfig.edExcludeExts.Text:=RegIni.ReadString(Section,'ExcludeExt','*.exe;*.com;*.bat'); dlgCOnfig.cbAssociate.Checked:=RegIni.ReadBool(Section,'Associate',False); if RegIni.ReadBool(Section,'Associate',False) then RegisterApplication; RegIni.Free; end; end.
program re (input, output); type tRefListe = ^tListe; tListe = record info : integer; next : tRefListe end; var Liste, MaxZeig : tRefListe; function ZeigListMax (inRefAnfang : tRefListe) : tRefListe; { bestimmt rekursiv einen Zeiger auf das Listenelement mit der groessten Zahl } var rekMax : tRefListe; { Hilfsvariable, die auf das rekursiv bestimmte Maximum der Listenelemente ab dem zweiten Listenelement zeigt } begin if inRefAnfang = nil then { Rekursionsabbruch } ZeigListMax := nil else begin rekMax := ZeigListMax (inRefAnfang^.next); if rekMax = nil then ZeigListMax := inRefAnfang else if inRefAnfang^.info < rekMax^.info then ZeigListMax := rekMax else ZeigListMax := inRefAnfang end { if } end; { ZeigListMax } procedure LiesListe(var outListe : tRefListe); { Liest eine (evtl. leere) Liste ein und gibt deren Anfangszeiger outListe zurueck. } var Anzahl : integer; i : integer; neueZahl : integer; Listenanfang, Listenende : tRefListe; begin Listenanfang := nil; repeat write ('Wie viele Zahlen wollen Sie eingeben? '); readln (Anzahl); until Anzahl >= 0; write ('Bitte geben Sie ', Anzahl, ' Zahlen ein: '); { Liste aufbauen } for i := 1 to Anzahl do begin read (neueZahl); if Listenanfang = nil then begin new (Listenanfang); Listenanfang^.next := nil; Listenanfang^.info := neueZahl; Listenende := Listenanfang; end else begin new (Listenende^.next); Listenende := Listenende^.next; Listenende^.next := nil; Listenende^.info := neueZahl end { if Liste = nil } end; { for } outListe := Listenanfang; writeln end; { LiesListe } begin LiesListe (Liste); { Die zu testende Funktion wird zweimal aufgerufen, damit tatsaechlich ein Fehler auftritt, wenn die Liste durch den Aufruf zerstoert wird. } MaxZeig := ZeigListMax (Liste); MaxZeig := ZeigListMax (Liste); if MaxZeig = nil then writeln('Leere Eingabefolge!') else writeln ('Das Maximum ist ', MaxZeig^.info, '.') end. { testeZeigListMax }
unit TrackEditor; interface uses Controls, Classes, Windows, Graphics, Messages, Board, Intersect, Tracks, TrackItems, TrackPainter, SegmentProperties; type TteEditMode = ( bmSelect, bmStrip, bmSegment, bmDonut ); TteEditorModeChange = procedure( Sender : TObject; Mode : TteEditMode ) of object; TbeTrackMouseMoveTask = ( mtNone, mtDrawSelectionRectangle, mtDrawStrip, mtDrawSegment, mtDragEndStrip, mtDragEndSegment, mtMoveSelected ); TbeDrawMode = ( dmNormal, dmSelected, dmXOR ); TveArrowMove = ( amNone, amUp, amDown, amLeft, amRight ); TteMouseMove = procedure( X_DIV, Y_DIV : integer ) of object; // ************************************************* // ************************************************* type TteTrackEditor = class( TCustomControl ) protected Tracks : TbeTracks; Painter : TteTrackEditPainter; // editing variables FEditMode : TteEditMode; MouseMoveTask : TbeTrackMouseMoveTask; MouseMoveItem : TteTrack; DrawMode : TbeDrawMode; // LeftX, TopY are board coords in screen pixels at top, left of the canvas LeftX : integer; TopY : integer; BoardHeightScreenPixels : integer; BoardWidthScreenPixels : integer; // extra pixels to scroll so actual board edge is clearly displayed ScrollBorder : integer; // simple properties //.. draw selection rectangle, etc with this line width FDrawLineWidth : integer; // property handlers // procedure SetEditMode( AEditMode : TbeEditMode ); // ** Mouse Down/Move/Up State Machine Vars ** // Where mouse went down as float and DIVs MouseDownCellCoords : TFloatPoint; MouseDownCellCoords_D : TPoint; // where mouse went down in screen pixels ClickOriginalClient : TPoint; // X,Y distance from where the mouse went down LastDeltaXCells_D, LastDeltaYCells_D : integer; // Selection rectangle in Divs ClickSelectedItemsRect_D : TRect; // selection rectangle in screen units SelectionClientRect : TRect; // when dragging items or selections, move in these steps DragGrid_1000 : integer; // Reference to Strip or Segment that we are in process of drawing DrawStrip : TteStrip; DrawSegment : TteSegment; // ** Events ** FOnChangeMode : TteEditorModeChange; FOnMouseMove : TteMouseMove; FStripColor : TColor; FSelectionColor : TColor; FBoardColor : TColor; // form for entering segment changes SegmentPropertiesForm : TSegmentPropertiesForm; // ** Scrolling ** procedure Recalculate; procedure SetVertScroll; procedure SetHorzScroll; procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL; procedure WMHScroll(var Msg: TWMHScroll); message WM_HSCROLL; procedure CreateParams(var Params: TCreateParams); override; procedure Resize; override; // EraseBackgroud - doesn't seem to make any visible difference whether we // let Windows erase the background or prevent it. procedure EraseBackground(var Msg: TWMEraseBkgnd); message WM_ERASEBKGND; // mouse procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; function ClickxyToCells( ClickX, ClickY : integer) : TFloatPoint; function ClickxyToCells_D( ClickX, ClickY : integer) : TPoint; function SnapToGrid( value : integer ) : integer; procedure SnapCircleToGrid( var Centre : TPoint; Radius : integer ); procedure PullCellInsideBoard( var Cell : TPoint ); function DragAtGrid( value : integer ) : integer; function StripFollowMouse( Strip : TteStrip; MouseX_D, MouseY_D : integer ) : boolean; function SegmentFollowMouse( Segment : TteSegment; MouseX_D, MouseY_D : integer ) : boolean; // keyboard procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure ArrowMoveSelected( Direction : TveArrowMove ); procedure DeleteSelectedItems; procedure SelectAll; // message handlers procedure WMGetDlgCode(var message: TMessage); message WM_GETDLGCODE; // Canvas, Pen, Brush procedure SetCanvasUnselected; procedure SetCanvasSelected; procedure SetCanvasXORTrack; procedure SetCanvasXORRectangle; procedure CanvasSettingsToPainter; // Painting procedure PaintSelected; procedure PaintTrack( Track : TteTrack ); procedure PaintRect( RectDivs : TRect ); // procedure MakeDirty; function GetDirty : boolean; procedure SetDirty( Value : boolean ); // property function GetPixelsPerCell : integer; procedure SetPixelsPerCell( Value : integer ); procedure SetEditMode( Mode : TteEditMode ); public // segment drawing settings SegmentWidth_D : integer; SnapGrid_D : integer; ConstrainedSegments : boolean; // events property OnMouseMove : TteMouseMove read FOnMouseMove write FOnMouseMove; { property OnMouseClickItem : TMouseClickItem read FOnMouseClickItem write FOnMouseClickItem; } property OnChangeMode : TteEditorModeChange read FOnChangeMode write FOnChangeMode; property EditMode : TteEditMode read FEditMode write SetEditMode; property Dirty : boolean read GetDirty write SetDirty; // display colors property StripColor : TColor read FStripColor write FStripColor; property BoardColor : TColor read FBoardColor write FBoardColor; property SelectionColor : TColor read FSelectionColor write FSelectionColor; // editing mode variables // property EditMode : TbeEditMode read FEditMode write SetEditMode; property PixelsPerCell : integer read GetPixelsPerCell write SetPixelsPerCell; property DrawLineWidth : integer read FDrawLineWidth write FDrawLineWidth; procedure LoadFromBoard( Board : TbrBoard ); procedure SaveToBoard( Board : TbrBoard ); procedure Paint; override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses Forms, SysUtils, Math, Rectangles, ClipbrdTracks; const DIVS_PER_CELL = 1000; DIVS_PER_HALF_CELL = 500; { Found this: http://stackoverflow.com/questions/6363954/best-way-to-do-non-flickering-segmented-graphics-updates-in-delphi } // *********************************************** // INITIALISATION & FINALISATION // *********************************************** constructor TteTrackEditor.Create(AOwner: TComponent); begin inherited Create(AOwner); // csOpaque means the control completely fills its client rectangle. // ControlStyle := ControlStyle + [csOpaque]; Tracks := TbeTracks.Create; Painter := TteTrackEditPainter.Create; SegmentPropertiesForm := TSegmentPropertiesForm.Create( self ); // SegmentPropertiesForm.Parent := self; //..scroll border is a little bit of "extra scroll" that lets user see // a small blank area around the board edge. 4 pixels at 96 ppi resolution. ScrollBorder := Screen.PixelsPerInch div 10; // initialise color scheme here FStripColor := clBlack; FSelectionColor := clRed; FBoardColor := clWhite; SegmentWidth_D := 250; SnapGrid_D := 500; end; destructor TteTrackEditor.Destroy; begin Painter.Free; Tracks.Free; inherited; end; procedure TteTrackEditor.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.Style := Params.Style or WS_VSCROLL or WS_HSCROLL {or WS_BORDER}; end; // Handle a Windows Message to request arrow key messages sent to this // TWinControl as well as ordinary key messages procedure TteTrackEditor.WMGetDlgCode(var message: TMessage); begin { Remy Lebeau : I call the base class handler first, so that it can assign default settings, to which you are then simply adding DLGC_WANTARROWS. TCustomControl::Dispatch(&AMsg); AMsg.Result |= DLGC_WANTARROWS; } message.Result := DLGC_WANTARROWS; end; procedure TteTrackEditor.LoadFromBoard( Board : TbrBoard ); begin Tracks.LoadFromBoard( Board ); Recalculate; // << thia should be somewhere else end; procedure TteTrackEditor.SaveToBoard( Board : TbrBoard ); begin Tracks.SaveToBoard( Board ); end; // ******************************************* // PROPERTY HANDLERS // ******************************************* // ****** GET / SET DISPLAY SCALE ****** function TteTrackEditor.GetPixelsPerCell : integer; begin result := Painter.PixelsPerCell; end; const MAX_PIXELS_PER_CELL = 40; MIN_PIXELS_PER_CELL = 4; procedure TteTrackEditor.SetPixelsPerCell( Value : integer ); begin if Value > MAX_PIXELS_PER_CELL then begin Value := MAX_PIXELS_PER_CELL; end else if Value < MIN_PIXELS_PER_CELL then begin Value := MIN_PIXELS_PER_CELL; end; //FPixelsPerCell := Value; Painter.PixelsPerCell := Value; Recalculate; end; procedure TteTrackEditor.SetEditMode( Mode : TteEditMode ); //const // ModeToShape : array[TbeEditMode] of TcCursorShape = // ( bmSelect, bmStrip, bmSegment ); begin FEditMode := Mode; if Mode = bmSelect then begin Cursor := crDefault; end; { else begin Cursor := CursorMinder.GetCursor( ModeToShape[Mode] ); end; } // raise event if assigned( FOnChangeMode ) then begin FOnChangeMode( self, Mode ); end; end; { const ModeToShape : array[TCmoEditMode] of TcCursorShape = ( csSelect, csLine, csPin ); begin FEditMode := Mode; if Mode = emSelect then begin Cursor := crDefault; end else begin Cursor := CursorMinder.GetCursor( ModeToShape[Mode] ); end; // raise event if assigned( FOnChangeMode ) then begin FOnChangeMode( self, Mode ); end; } // ************************************************** // SCROLLING // ************************************************** // *** POSITION HORIZONTAL SCROLLBAR *** procedure TteTrackEditor.SetHorzScroll; var ScrollInfo : TScrollInfo; LeftScroll, RightScroll : integer; begin // At full left scroll, screen left shows -0.5 minus a little bit extra LeftScroll := -(PixelsPerCell div 2) - ScrollBorder; // At full right scroll, screen right shows board right plus a little RightScroll := BoardWidthScreenPixels + Scrollborder - ClientWidth; if LeftX < LeftScroll then begin LeftX := LeftScroll; end else if LeftX > RightScroll then begin LeftX := RightScroll; end; // if whole board will fit on screen, scroll to left if BoardWidthScreenPixels + Scrollborder + Scrollborder <= ClientWidth then begin LeftX := LeftScroll; end; ScrollInfo.cbSize := sizeof(TScrollInfo); ScrollInfo.fMask := SIF_POS or SIF_RANGE or SIF_PAGE; ScrollInfo.nMin := LeftScroll; ScrollInfo.nMax := BoardWidthScreenPixels + ScrollBorder; ScrollInfo.nPage := ClientWidth; ScrollInfo.nPos := LeftX; ScrollInfo.nTrackPos := 0; SetScrollInfo( handle, SB_HORZ, ScrollInfo, TRUE ); end; // *** POSITION VERTICAL SCROLLBAR *** procedure TteTrackEditor.SetVertScroll; var ScrollInfo : TScrollInfo; UpScroll, DownScroll : integer; begin // At full up scroll, screen top shows -0.5 minus a little bit extra UpScroll := -(PixelsPerCell div 2) - ScrollBorder; // At full right scroll, screen right shows board right plus a little DownScroll := BoardHeightScreenPixels + Scrollborder - ClientHeight; if TopY < UpScroll then begin TopY := UpScroll; end else if TopY > DownScroll then begin TopY := DownScroll; end; // if whole board will fit on screen, scroll up if BoardHeightScreenPixels + Scrollborder + Scrollborder <= ClientHeight then begin TopY := UpScroll; end; ScrollInfo.cbSize := sizeof(TScrollInfo); ScrollInfo.fMask := SIF_POS or SIF_RANGE or SIF_PAGE; ScrollInfo.nMin := UpScroll; ScrollInfo.nMax := BoardHeightScreenPixels + ScrollBorder; ScrollInfo.nPage := ClientHeight; ScrollInfo.nPos := TopY; ScrollInfo.nTrackPos := 0; SetScrollInfo( handle, SB_VERT, ScrollInfo, TRUE ); end; procedure TteTrackEditor.WMVScroll(var Msg: TWMVScroll); begin case Msg.ScrollCode of // SB_THUMBPOSITION updates when mouse released after moving scrollbar SB_THUMBPOSITION {, SB_THUMBTRACK} : begin TopY := Msg.Pos; end; // SB_THUMBTRACK gives continuous tracking SB_THUMBTRACK : begin ScrollWindowEx( handle, 0, TopY - Msg.Pos, nil, nil, 0, nil, SW_INVALIDATE); // ScrollWindowEx( handle, 0, TopY - Msg.Pos, nil, nil, 0, nil, 0 ); TopY := Msg.Pos; SetVertScroll; exit; end; SB_LINEDOWN : begin Inc( TopY, 20 ); end; SB_LINEUP : begin Dec( TopY, 20 ); end; SB_PAGEDOWN : begin Inc( TopY, ClientHeight -1 ); end; SB_PAGEUP : begin Dec( TopY, ClientHeight -1 ); end else begin exit; end; end; SetVertScroll; InvalidateRect( handle, ClientRect, False ); // PostMessage(hwnd, WM_MYMESSAGE, 0, 0); end; procedure TteTrackEditor.WMHScroll(var Msg: TWMHScroll); begin case Msg.ScrollCode of // SB_THUMBPOSITION updates when mouse released after moving scrollbar SB_THUMBPOSITION : begin LeftX := Msg.Pos; end; // SB_THUMBTRACK gives continuous tracking SB_THUMBTRACK : begin ScrollWindowEx( handle, LeftX - Msg.Pos, 0, nil, nil, 0, nil, SW_INVALIDATE); LeftX := Msg.Pos; SetHorzScroll; exit; end; SB_LINERIGHT : begin Inc( LeftX, 20 ); end; SB_LINELEFT : begin Dec( LeftX, 20 ); end; SB_PAGERIGHT : begin Inc( LeftX, ClientWidth -1 ); end; SB_PAGELEFT : begin Dec( LeftX, ClientWidth -1 ); end else begin exit; end; end; SetHorzScroll; InvalidateRect( handle, ClientRect, False ); end; // Window resized procedure TteTrackEditor.Resize; begin Recalculate; end; procedure TteTrackEditor.Recalculate; begin BoardHeightScreenPixels := Tracks.Height * PixelsPerCell; BoardWidthScreenPixels := Tracks.Width * PixelsPerCell; SetVertScroll; SetHorzScroll; end; // Tell Windows not to erase backgroud - we will do it. // GDI calls this Preview first displays, and when resizing the window // Can't see any visible difference whether we do this or not. procedure TteTrackEditor.EraseBackground(var Msg: TWMEraseBkgnd); begin // tell Windows we have handled background drawing Msg.Result := 1; end; // ********************************************** // DIRTY (ALTERED) // ********************************************** procedure TteTrackEditor.MakeDirty; begin Tracks.Dirty := True; end; function TteTrackEditor.GetDirty : boolean; begin result := Tracks.Dirty; end; procedure TteTrackEditor.SetDirty( Value : boolean ); begin Tracks.Dirty := Value; end; // ********************************************** // KEYBOARD // ********************************************** procedure TteTrackEditor.KeyDown(var Key: Word; Shift: TShiftState); begin if Key = VK_LEFT then begin ArrowMoveSelected( amLeft ); Key := 0; end else if KEY = VK_UP then begin ArrowMoveSelected( amUp ); Key := 0; end else if KEY = VK_RIGHT then begin ArrowMoveSelected( amRight ); Key := 0; end else if KEY = VK_DOWN then begin ArrowMoveSelected( amDown ); Key := 0; end else if Key = VK_DELETE then begin DeleteSelectedItems; end else if Key = VK_ESCAPE then begin EditMode := bmSelect; end; end; procedure TteTrackEditor.KeyPress(var Key: Char); const // WM_CHAR messages come through to TWinControl.KeyPress // Windows encodes Ctrl Key in combination with a letter key // as a WM_CHAR key containing standard ASCII control characters // which range from 0x01 (Ctrl-A), Ox02 (Ctrl-B), through 0x1A (Ctrl-Z) CTRL_A = char(1); // Select All CTRL_C = char(3); // Copy CTRL_V = char($16); // Paste CTRL_X = char($18); // Cut CTRL_Z = char($1A); // Undo CTRL_Y = char($19); // Redo begin case Key of CTRL_A : SelectAll; CTRL_C : CopySelectedTracksToClipboard( Tracks ); CTRL_V : begin SetCanvasUnselected; PaintSelected; PasteTracksFromClipboard( Tracks ); SetCanvasSelected; PaintSelected; end; CTRL_Z : begin Tracks.Undo; Paint; end; CTRL_Y : begin Tracks.Redo; Paint; end; end; end; // Select All Tracks procedure TteTrackEditor.SelectAll; begin Tracks.SelectAll; SetCanvasSelected; PaintSelected; end; // ** Move Selected Items in Requested Direction ** // NOTE: based on TveEditor.ArrowMoveSelected() in Editor.pas - refer // to that functn. for Undo & Screen refresh code. procedure TteTrackEditor.ArrowMoveSelected( Direction : TveArrowMove ); var SelectedCount : integer; BoardRect : TRect; ItemsBoundarySource_D : TRect; Delta_D : integer; deltaX, deltaY : integer; begin // must have something selected! SelectedCount := Tracks.GetSelectedCount; if SelectedCount <= 0 then begin exit; end; // get rectangle of board area BoardRect := Tracks.BoardRect_D; // get rectangle enclosing selected items ItemsBoundarySource_D := Tracks.GetSelectedItemsBoundary_D; // work out how far to move the selected items //.. If any strips in selection, only move by whole cells if Tracks.GetSelectedTypeCount( TteStrip ) > 0 then begin Delta_D := DIVS_PER_CELL; end // else move by snap else begin Delta_D := SnapGrid_D; end; // see if rectangle can be moved 1 in desired direction // This code assumes we do not move in both x and y directions! case Direction of amRight : begin if ItemsBoundarySource_D.BottomRight.x + Delta_D > BoardRect.Right then begin exit; end; deltaX := Delta_D; deltaY := 0; end; amLeft : begin if (ItemsBoundarySource_D.TopLeft.x - Delta_D) < BoardRect.Left then begin exit; end; deltaX := -Delta_D; deltaY := 0; end; amDown : begin if ItemsBoundarySource_D.BottomRight.y + Delta_D > BoardRect.Bottom then begin exit; end; deltaX := 0; deltaY := Delta_D; end; amUp : begin if ItemsBoundarySource_D.TopLeft.y - Delta_D < BoardRect.Top then begin exit; end; deltaX := 0; deltaY := -Delta_D; end else begin exit; end; end; // move items Tracks.SnapshotSelectedItems; Tracks.MoveSelectedItems_D( deltaX, deltaY ); Tracks.StoreSnaphotSelectedAsUndo; // redraw source area to clean up PaintRect( ItemsBoundarySource_D ); // redraw items in new position - most of these items were probably redrawn // in code line above, since they continue to overlap the source area SetCanvasSelected; PaintSelected; MakeDirty; end; procedure TteTrackEditor.DeleteSelectedItems; begin Tracks.DeleteSelectedItemsWithUndo; // now show the changes Paint; MakeDirty; end; // ********************************************** // SNAP GRID & DRAG GRID // ********************************************** // Pull A Coordinate or Displacement in DIVS to snap grid function TteTrackEditor.SnapToGrid( value : integer ) : integer; begin result := SnapGrid_D * Round( value / SnapGrid_D ); end; // Pull a circle to snap grid inside the board boundaries procedure TteTrackEditor.SnapCircleToGrid( var Centre : TPoint; Radius : integer ); var BoardRect : TRect; LeftLimit_D, RightLimit_D : integer; TopLimit_D, BottomLimit_D : integer; begin // get rectangle of board area BoardRect := Tracks.BoardRect_D; // *** HANDLE X COORD LeftLimit_D := BoardRect.Left + Radius; RightLimit_D := BoardRect.Right - Radius; // pull X coord onto board if Centre.X > RightLimit_D then begin Centre.X := RightLimit_D; end else if Centre.X < LeftLimit_D then begin Centre.x := LeftLimit_D; end; // snap X coord Centre.X := SnapGrid_D * Round( Centre.X / SnapGrid_D ); // if X coord snapped outside the board, pull it back if Centre.X > RightLimit_D then begin dec( Centre.X, SnapGrid_D ); end else if Centre.X < LeftLimit_D then begin inc( Centre.X, SnapGrid_D ); end; // *** HANDLE Y COORD TopLimit_D := BoardRect.Top + Radius; BottomLimit_D := BoardRect.Bottom - Radius; // pull Y coord onto board if Centre.Y > BottomLimit_D then begin Centre.Y := BottomLimit_D; end else if Centre.Y < TopLimit_D then begin Centre.Y := TopLimit_D; end; // snap Y coord Centre.Y := SnapGrid_D * Round( Centre.Y / SnapGrid_D ); // if Y coord snapped outside the board, pull it back if Centre.Y > BottomLimit_D then begin dec( Centre.Y, SnapGrid_D ); end else if Centre.Y < LeftLimit_D then begin inc( Centre.Y, SnapGrid_D ); end; end; // Pull A Coordinate in DIVS to drag grid function TteTrackEditor.DragAtGrid( value : integer ) : integer; begin result := DragGrid_1000 * Round( value / DragGrid_1000 ); end; // Pull Cell Coords Inside Board Edges procedure TteTrackEditor.PullCellInsideBoard( var Cell : TPoint ); begin Cell.X := Max( Cell.X, 0 ); Cell.X := Min( Cell.X, Tracks.Width -1 ); Cell.Y := Max( Cell.Y, 0 ); Cell.Y := Min( Cell.Y, Tracks.Height -1 ); end; // ********************************************** // STRIP & SEGMENT PLACING // ********************************************** // Make the strip finish follow the mouse - return TRUE if strip finish moved function TteTrackEditor.StripFollowMouse( Strip : TteStrip; MouseX_D, MouseY_D : integer ) : boolean; var DeltaX_D, DeltaY_D : integer; TempPoint : TPoint; begin // how far mouse is from Strip.Start DeltaX_D := MouseX_D - (Strip.Start.X * DIVS_PER_CELL); DeltaY_D := MouseY_D - (Strip.Start.Y * DIVS_PER_CELL); // work out if we have a horizontal strip or vertical and calculate // new strip Finish coords (leave Start Coords unchanged) // We add DIVS_PER_HALF_CELL to get rounding of the integer division result // if horizontal if abs( DeltaX_D ) > abs( DeltaY_D ) then begin TempPoint.X := Strip.Start.X + Round( DeltaX_D / DIVS_PER_CELL ); TempPoint.Y := Strip.Start.Y; // keep strip within board boundaries if TempPoint.X < 0 then begin TempPoint.X := 1; end else if TempPoint.X >= Tracks.Width then begin TempPoint.X := Tracks.Width -1; end; end // else vertical else begin TempPoint.X := Strip.Start.X; TempPoint.Y := Strip.Start.Y + Round( DeltaY_D / DIVS_PER_CELL ); // keep strip within board boundaries if TempPoint.Y < 0 then begin TempPoint.Y := 1; end else if TempPoint.Y >= Tracks.Height then begin TempPoint.Y := Tracks.Height -1; end; end; // work out return value - TRUE = changed result := (TempPoint.X <> Strip.Finish.X) or (TempPoint.Y <> Strip.Finish.Y); // move changes into the strip Strip.Finish := TempPoint; end; // Make the segment follow the mouse - return TRUE if segment finish moved function TteTrackEditor.SegmentFollowMouse( Segment : TteSegment; MouseX_D, MouseY_D : integer ) : boolean; var DeltaX_D, DeltaY_D : integer; TempPoint : TPoint; MagDx, MagDy : integer; TrackDelta_DIV : integer; const // 100 * tan(22.5 degrees) tan22p5x100 = 41; begin // how far mouse is from Segment.Start DeltaX_D := MouseX_D - Segment.Start_1000.X; DeltaY_D := MouseY_D - Segment.Start_1000.Y; // zero length if (DeltaX_D = 0) and (DeltaY_D = 0) then begin TempPoint.X := Segment.Start_1000.X; TempPoint.Y := Segment.Start_1000.Y; end // UNCONSTRAINED SEGMENTS CODE - SEGEMENTS AT ANY ANGLE else if not ConstrainedSegments then begin TempPoint.X := Segment.Start_1000.X + DeltaX_D; TempPoint.Y := Segment.Start_1000.Y + DeltaY_D; SnapCircleToGrid( TempPoint, Segment.Width_1000 div 2 ); end // CONSTRAINED SEGMENTS CODE - SEGEMENTS AT 45 DEGREE INCREMENTS else begin // calculate some useful values MagDx := abs( DeltaX_D ); MagDy := abs( DeltaY_D ); // if vertical (mouse at less than 22.5 degrees from the vertical if (MagDy > 0) and (((MagDx * 100) div MagDy) < tan22p5x100) then begin // do vertical TempPoint.x := Segment.Start_1000.X; TempPoint.y := Segment.Start_1000.Y + DeltaY_D; SnapCircleToGrid( TempPoint, Segment.Width_1000 div 2 ); end // if horizontal (mouse at less than 22.5 degrees the horizontal else if (MagDx > 0) and (((MagDy * 100) div MagDx) < tan22p5x100) then begin // do horizontal TempPoint.x := Segment.Start_1000.X + DeltaX_D; TempPoint.y := Segment.Start_1000.Y; SnapCircleToGrid( TempPoint, Segment.Width_1000 div 2 ); end // at this point in code, our line is not vertical or horizontal, so it // must be either 45 / 225 degrees or 135 / 315 degrees. // Note: Tests in the lines above ensure that neither dX or dY is zero // at this point in the code. So no divide by zero errors! // if 45 / 225 degrees else if (DeltaY_D / DeltaX_D) > 0 then begin // do 45 / 225 degrees, where deltaX = deltaY : both positive or negative // calculate deltaX_div as average of the two - in grid multiple TrackDelta_DIV := SnapToGrid((DeltaX_D + DeltaY_D) DIV 2); TempPoint.x := Segment.Start_1000.X + TrackDelta_DIV; TempPoint.y := Segment.Start_1000.Y + TrackDelta_DIV; // snap to a grid point far enough inside the board so that // segment radius is entirely inside the board SnapCircleToGrid( TempPoint, Segment.Width_1000 div 2 ); // in case Snap moved X or Y, make deltaX=deltaY again if abs(TempPoint.X - Segment.Start_1000.X) < abs(TempPoint.Y - Segment.Start_1000.Y) then begin TempPoint.Y := Segment.Start_1000.Y + (TempPoint.X - Segment.Start_1000.X); end else if abs(TempPoint.X - Segment.Start_1000.X) > abs(TempPoint.Y - Segment.Start_1000.Y) then begin TempPoint.X := Segment.Start_1000.X + (TempPoint.Y - Segment.Start_1000.Y); end; end // else 135 / 315 degrees else begin // do 135 / 315 degrees, where deltaX = -(deltaY) : opposite sign //.. this could be positive or negative TrackDelta_DIV := SnapToGrid((DeltaX_D - DeltaY_D) DIV 2); TempPoint.x := Segment.Start_1000.X + TrackDelta_DIV; TempPoint.y := Segment.Start_1000.Y - TrackDelta_DIV; SnapCircleToGrid( TempPoint, Segment.Width_1000 div 2 ); // in case Snap moved X or Y, make deltaX=-deltaY again if abs(TempPoint.X - Segment.Start_1000.X) < abs(TempPoint.Y - Segment.Start_1000.Y) then begin TempPoint.Y := Segment.Start_1000.Y - (TempPoint.X - Segment.Start_1000.X); end else if abs(TempPoint.X - Segment.Start_1000.X) > abs(TempPoint.Y - Segment.Start_1000.Y) then begin TempPoint.X := Segment.Start_1000.X - (TempPoint.Y - Segment.Start_1000.Y); end; end; end; // work out return value - TRUE = changed result := (TempPoint.X <> Segment.Finish_1000.X) or (TempPoint.Y <> Segment.Finish_1000.Y); // move changes into the strip Segment.Finish_1000 := TempPoint; end; // ********************************************** // MOUSE // ********************************************** procedure TteTrackEditor.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var ClickedItem : TteTrack; procedure SetDragGrid; begin // work out whether fine movement is possible - or only coarse if (ClickedItem is TteStrip) or (Tracks.GetSelectedTypeCount( TteStrip ) > 0) then begin DragGrid_1000 := DIVS_PER_CELL; end else begin DragGrid_1000 := SnapGrid_D; end; end; var TempPoint : TPoint; begin // focus makes this control receive keyboard input if CanFocus then begin SetFocus; end; // Find where on the board we clicked MouseDownCellCoords := ClickxyToCells( X, Y ); MouseDownCellCoords_D := ClickxyToCells_D( X, Y ); // Find the track clicked on ClickedItem := Tracks.ClickedItem( MouseDownCellCoords ); // ********************************* // *** Right click returns to bmSelect **** // ********************************* // if right click if Button = mbRight then begin EditMode := bmSelect; // if a segment is under the mouse, show right click menu if ClickedItem is TteSegment then begin // remove existing selection DrawMode := dmNormal; PaintSelected; Tracks.ClearSelectedItems; // Select new item DrawMode := dmSelected; PaintTrack( ClickedItem ); ClickedItem.Selected := True; // record original segment rectangle ClickSelectedItemsRect_D := ClickedItem.GetPaintRect_D; // show segment properties form and let user change start, end, width SegmentPropertiesForm.Segment := TteSegment( ClickedItem ); SegmentPropertiesForm.BoardRect_D := Tracks.BoardRect_D; SegmentPropertiesForm.ShowModal; // repaint area containing both original and edited segment ExtendRectangle( ClickSelectedItemsRect_D, ClickedItem.GetPaintRect_D ); PaintRect( ClickSelectedItemsRect_D ); MakeDirty; end; // finished MouseMoveTask := mtNone; exit; end; // ********************************* // *** edit mode = bmStrip **** // ********************************* if EditMode = bmStrip then begin // create new strip DrawStrip := Tracks.AddNewStrip; DrawStrip.Selected := False; // set strip to single cell - in whole cell coords TempPoint.X := Round( MouseDownCellCoords.x ); TempPoint.Y := Round( MouseDownCellCoords.y ); PullCellInsideBoard( TempPoint ); DrawStrip.Start := TempPoint; DrawStrip.Finish := TempPoint; // prepare for XOR image to follow mouse SetCanvasXORTrack; PaintTrack( DrawStrip ); MouseMoveTask := mtDrawStrip; // no other repaint exit; end // ********************************* // *** edit mode = bmSegment **** // ********************************* else if EditMode = bmSegment then begin // create new segment DrawSegment := Tracks.AddNewSegment; DrawSegment.Selected := False; DrawSegment.Width_1000 := SegmentWidth_D; // set segment to zero length at mouse position TempPoint.X := MouseDownCellCoords_D.X; TempPoint.Y := MouseDownCellCoords_D.Y; SnapCircleToGrid( TempPoint, SegmentWidth_D div 2 ); DrawSegment.Start_1000 := TempPoint; DrawSegment.Finish_1000 := TempPoint; // prepare for XOR image to follow mouse SetCanvasXORTrack; PaintTrack( DrawSegment ); MouseMoveTask := mtDrawSegment; // no other repaint exit; end // ********************************* // *** edit mode = bmDonut **** // ********************************* else if EditMode = bmDonut then begin // MouseMoveTask := mtDrawSegment; ?? DrawDonut? end else begin // ********************************* // *** edit mode = bmSelect **** // ********************************* // *** if SHIFT key is down - means size a track or drag one end of a track *** if ssShift in Shift then begin // Clear all selected items - SHIFT-DRAG will act only on one track DrawMode := dmNormal; PaintSelected; Tracks.ClearSelectedItems; // Find the track under the mouse and make it selected. if ClickedItem <> nil then begin // item should show as selected after end is dragged ClickedItem.Selected := True; // record the item paint rectangle before movement in cell units ClickSelectedItemsRect_D := ClickedItem.GetPaintRect_D; // if we have a strip, drag the end of it if ClickedItem is TteStrip then begin // we will be altering this strip during time mouse stays down DrawStrip := TteStrip( ClickedItem ); // get ClickedItem.Finish to be the end nearest nearest mouse DrawStrip.MakeFinishNearestPoint( MouseDownCellCoords ); // move strip end to be near mouse, depending on free/45 degree // angle mode StripFollowMouse( DrawStrip, MouseDownCellCoords_D.X, MouseDownCellCoords_D.Y ); // prepare for XOR image to follow mouse SetCanvasXORTrack; PaintTrack( DrawStrip ); MouseMoveTask := mtDragEndStrip; // record for undo DrawStrip.TakeSnapshot; // no other repaint exit; end else if ClickedItem is TteSegment then begin // we will be altering this segment during time mouse stays down DrawSegment := TteSegment( ClickedItem ); // get ClickedItem.Finish to be the end nearest nearest mouse DrawSegment.MakeFinishNearestPoint( MouseDownCellCoords ); // move strip end to be near mouse, depending on free/45 degree // angle mode SegmentFollowMouse( DrawSegment, MouseDownCellCoords_D.X, MouseDownCellCoords_D.Y ); // prepare for XOR image to follow mouse SetCanvasXORTrack; PaintTrack( DrawSegment ); MouseMoveTask := mtDragEndSegment; // record for undo DrawSegment.TakeSnapshot; // no other repaint exit; end end; end // if nothing clicked on else if ClickedItem = nil then begin // if Ctrl not down, empty selection if not (ssCtrl in Shift) then begin SetCanvasUnselected; PaintSelected; Tracks.ClearSelectedItems; end; // prepare to draw selection rectangle when mouse moves SetCanvasXORRectangle; // record where we started ?? ClickOriginalClient.X := X; ClickOriginalClient.Y := Y; // initialise selection rectangle in screen units SelectionClientRect.Left := X; SelectionClientRect.Top := Y; SelectionClientRect.Right := X; SelectionClientRect.Bottom := Y; MouseMoveTask := mtDrawSelectionRectangle; // don't do paint exit; end // at this point we have an item under the mouse ClickedItem // *** if CTRL key is down *** else if ssCTRL in Shift then begin // Invert the selection of the item under the mouse if ClickedItem <> nil then begin if ClickedItem.Selected then begin ClickedItem.Selected := False; DrawMode := dmNormal; end else begin ClickedItem.Selected := True; DrawMode := dmSelected; end; // redraw the clicked item PaintTrack( ClickedItem ); end; // Enter “None” mode – no dragging to follow. MouseMoveTask := mtNone; // no other repaints exit; end // else we are clicking on a track or tracks, in anticipation that // they will be dragged by the mouse else begin // work out how much the drag grid will be (movement increment) SetDragGrid; // If one of the items under the mouse is already selected, then // enter the DragTracks mode. Don't add anything to the selection if Tracks.SelectedTracksUnderMouse( MouseDownCellCoords ) then begin // Set up for drag MouseMoveTask := mtMoveSelected; SetCanvasXORTrack; // record the border of the selected items ClickSelectedItemsRect_D := Tracks.GetSelectedItemsBoundary_D; end // else item under the mouse is not selected, so select that one item // and prepare for it to be dragged // select the item under the mouse for dragging else begin // remove existing selection DrawMode := dmNormal; PaintSelected; Tracks.ClearSelectedItems; // Select new item DrawMode := dmSelected; PaintTrack( ClickedItem ); ClickedItem.Selected := True; // set up for drag MouseMoveTask := mtMoveSelected; SetCanvasXORTrack; // record the border of the selected item ClickSelectedItemsRect_D := Tracks.GetSelectedItemsBoundary_D; end; // record for undo Tracks.SnapshotSelectedItems; // distance we have moved from mouse down LastDeltaXCells_D := 0; LastDeltaYCells_D := 0; end; end; end; procedure TteTrackEditor.MouseMove(Shift: TShiftState; X, Y: Integer); var MouseMoveCellCoords_D : TPoint; DeltaXCells_D, DeltaYCells_D : integer; BoardRect_D : TRect; LatestMoveX, LatestMoveY : integer; const // 100 * tan(22.5 degrees) tan22p5x100 = 41; begin // Find where on the board is the mouse in DIVS MouseMoveCellCoords_D := ClickxyToCells_D( X, Y ); // mouse move event if assigned( FOnMouseMove ) then begin FOnMouseMove( SnapToGrid( MouseMoveCellCoords_D.X ), SnapToGrid( MouseMoveCellCoords_D.Y ) ); end; // Nothing was started by a mouse down? then exit if MouseMoveTask = mtNone then begin exit; end; // find total distance mouse has moved since it went down in DIVS DeltaXCells_D := MouseMoveCellCoords_D.x - MouseDownCellCoords_D.x; DeltaYCells_D := MouseMoveCellCoords_D.y - MouseDownCellCoords_D.y; // get boundaries of the board BoardRect_D := Tracks.BoardRect_D; if MouseMoveTask = mtDrawSelectionRectangle then begin // XOR draw over previous selection rectangle Canvas.MoveTo( SelectionClientRect.Left, SelectionClientRect.Top ); Canvas.LineTo( SelectionClientRect.Right, SelectionClientRect.Top ); Canvas.LineTo( SelectionClientRect.Right, SelectionClientRect.Bottom ); Canvas.LineTo( SelectionClientRect.Left, SelectionClientRect.Bottom ); Canvas.LineTo( SelectionClientRect.Left, SelectionClientRect.Top ); // adjust rectangle to new mouse position SelectionClientRect.Right := X; SelectionClientRect.Bottom := Y; // XOR draw latest selection rectangle Canvas.MoveTo( SelectionClientRect.Left, SelectionClientRect.Top ); Canvas.LineTo( SelectionClientRect.Right, SelectionClientRect.Top ); Canvas.LineTo( SelectionClientRect.Right, SelectionClientRect.Bottom ); Canvas.LineTo( SelectionClientRect.Left, SelectionClientRect.Bottom ); Canvas.LineTo( SelectionClientRect.Left, SelectionClientRect.Top ); end else if MouseMoveTask = mtDrawStrip then begin // XOR paint strip at old location to remove it PaintTrack( DrawStrip ); // move strip end to be near mouse, depending on free/45 degree // angle mode StripFollowMouse( DrawStrip, MouseMoveCellCoords_D.x, MouseMoveCellCoords_D.y ); // draw strip at new location PaintTrack( DrawStrip ); // no other repaint exit; end else if MouseMoveTask = mtDrawSegment then begin // XOR paint strip at old location to remove it PaintTrack( DrawSegment ); // move strip end to be near mouse, depending on free/45 degree // angle mode SegmentFollowMouse( DrawSegment, MouseMoveCellCoords_D.x, MouseMoveCellCoords_D.y ); // draw strip at new location PaintTrack( DrawSegment ); // no other repaint exit; end else if MouseMoveTask = mtDragEndStrip then begin // XOR paint strip at old location to remove it PaintTrack( DrawStrip ); // move strip end to be near mouse, depending on free/45 degree // angle mode StripFollowMouse( DrawStrip, MouseMoveCellCoords_D.x, MouseMoveCellCoords_D.y ); // draw strip at new location PaintTrack( DrawStrip ); // no other repaint exit; end else if MouseMoveTask = mtDragEndSegment then begin // XOR paint strip at old location to remove it PaintTrack( DrawSegment ); // move strip end to be near mouse, depending on free/45 degree // angle mode SegmentFollowMouse( DrawSegment, MouseMoveCellCoords_D.x, MouseMoveCellCoords_D.y ); // draw strip at new location PaintTrack( DrawSegment ); // no other repaint exit; end else if MouseMoveTask = mtMoveSelected then begin // limit movement to left if ClickSelectedItemsRect_D.TopLeft.x + DeltaXCells_D < BoardRect_D.TopLeft.x then begin DeltaXCells_D := BoardRect_D.TopLeft.x - ClickSelectedItemsRect_D.TopLeft.x; DeltaXCells_D := DragAtGrid( DeltaXCells_D ); if ClickSelectedItemsRect_D.TopLeft.x + DeltaXCells_D < BoardRect_D.TopLeft.x then begin Inc( DeltaXCells_D, DragGrid_1000 ); end; end; // limit movement to right if ClickSelectedItemsRect_D.BottomRight.x + DeltaXCells_D > BoardRect_D.BottomRight.x then begin DeltaXCells_D := BoardRect_D.BottomRight.x - ClickSelectedItemsRect_D.BottomRight.x; DeltaXCells_D := DragAtGrid( DeltaXCells_D ); if ClickSelectedItemsRect_D.BottomRight.x + DeltaXCells_D > BoardRect_D.BottomRight.x then begin Dec( DeltaXCells_D, DragGrid_1000 ); end; end; // limit movement to top if ClickSelectedItemsRect_D.TopLeft.y + DeltaYCells_D < BoardRect_D.TopLeft.y then begin DeltaYCells_D := BoardRect_D.TopLeft.y - ClickSelectedItemsRect_D.TopLeft.y; DeltaYCells_D := DragAtGrid( DeltaYCells_D ); if ClickSelectedItemsRect_D.TopLeft.y + DeltaYCells_D < BoardRect_D.TopLeft.y then begin Inc( DeltaYCells_D, DragGrid_1000 ); end; end; // limit movement to bottom if ClickSelectedItemsRect_D.BottomRight.y + DeltaYCells_D > BoardRect_D.BottomRight.y then begin DeltaYCells_D := BoardRect_D.BottomRight.y - ClickSelectedItemsRect_D.BottomRight.y; DeltaYCells_D := DragAtGrid( DeltaYCells_D ); if ClickSelectedItemsRect_D.BottomRight.y + DeltaYCells_D > BoardRect_D.BottomRight.y then begin Dec( DeltaYCells_D, DragGrid_1000 ); end; end; // snap to grid DeltaXCells_D := DragAtGrid( DeltaXCells_D ); DeltaYCells_D := DragAtGrid( DeltaYCells_D ); // work out the displacement needed to move the selected components // to their new position LatestMoveX := DeltaXCells_D - LastDeltaXCells_D; LatestMoveY := DeltaYCells_D - LastDeltaYCells_D; // if no displacement, do nothing if (LatestMoveX = 0) and (LatestMoveY = 0) then begin exit; end; // erase BoardItems at old location PaintSelected; // move the selected components to the new position Tracks.MoveSelectedItems_D( LatestMoveX, LatestMoveY ); // record distance we have moved from original mouse down LastDeltaXCells_D := DeltaXCells_D; LastDeltaYCells_D := DeltaYCells_D; //show movement PaintSelected; end; end; procedure TteTrackEditor.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var SelectionRect : TAlignedFloatRect; ItemPaintRect_D : TRect; begin if MouseMoveTask = mtDrawSelectionRectangle then begin // erase rectangle at old old location by XOR drawing Canvas.MoveTo( SelectionClientRect.Left, SelectionClientRect.Top ); Canvas.LineTo( SelectionClientRect.Right, SelectionClientRect.Top ); Canvas.LineTo( SelectionClientRect.Right, SelectionClientRect.Bottom ); Canvas.LineTo( SelectionClientRect.Left, SelectionClientRect.Bottom ); Canvas.LineTo( SelectionClientRect.Left, SelectionClientRect.Top ); // get rectangle in standard format NormalizeRect( SelectionClientRect ); // convert rectangle to TAlignedFloatRect SelectionRect.TopLeft := ClickxyToCells( SelectionClientRect.Left, SelectionClientRect.Top ); SelectionRect.BottomRight := ClickxyToCells( SelectionClientRect.Right, SelectionClientRect.Bottom ); // select items inside selection rectangle Tracks.SelectInsideRect( SelectionRect ); // paint selected SetCanvasSelected; PaintSelected; MouseMoveTask := mtNone; exit; end else if MouseMoveTask = mtDrawStrip then begin // save for Undo Tracks.RegisterNewTrackForUndo(DrawStrip); // Redraw Strip SetCanvasUnselected; PaintTrack( DrawStrip ); MouseMoveTask := mtNone; MakeDirty; exit; end else if MouseMoveTask = mtDrawSegment then begin // save for Undo Tracks.RegisterNewTrackForUndo(DrawSegment); // Redraw Segment SetCanvasUnselected; PaintTrack( DrawSegment ); MouseMoveTask := mtNone; MakeDirty; exit; end else if MouseMoveTask = mtDragEndStrip then begin // make an undo record Tracks.StoreSnaphotSelectedAsUndo; // repaint the rectangle that contains the strip // in both its before-edit and after-edit forms // current paint rect of item ItemPaintRect_D := DrawStrip.GetPaintRect_D; // combine before and after movement rects ExtendRectangle( ItemPaintRect_D, ClickSelectedItemsRect_D ); // stop XOR drawing SetCanvasUnselected; PaintRect( ItemPaintRect_D ); MouseMoveTask := mtNone; MakeDirty; exit; end else if MouseMoveTask = mtDragEndSegment then begin // make an undo record Tracks.StoreSnaphotSelectedAsUndo; // repaint the rectangle that contains the strip // in both its before-edit and after-edit forms // current paint rect of item ItemPaintRect_D := DrawSegment.GetPaintRect_D; // combine before and after movement rects ExtendRectangle( ItemPaintRect_D, ClickSelectedItemsRect_D ); // stop XOR drawing SetCanvasUnselected; PaintRect( ItemPaintRect_D ); MouseMoveTask := mtNone; MakeDirty; exit; end else if MouseMoveTask = mtMoveSelected then begin // erase XOR drawing //PaintSelected; // make an undo record Tracks.StoreSnaphotSelectedAsUndo; // paint destination SetCanvasSelected; PaintSelected; // repaint the source rectangle so item is "not there" SetCanvasUnselected; //- PaintRect does this automatically PaintRect( ClickSelectedItemsRect_D ); MouseMoveTask := mtNone; MakeDirty; exit; end; end; // **** MouseClickXY to Cell Coords XY **** function TteTrackEditor.ClickxyToCells( ClickX, ClickY : integer ) : TFloatPoint; begin result.x := ((ClickX + LeftX) / PixelsPerCell); result.y := ((ClickY + TopY) / PixelsPerCell); end; function TteTrackEditor.ClickxyToCells_D( ClickX, ClickY : integer) : TPoint; var FPoint : TFloatPoint; begin FPoint := ClickxyToCells( ClickX, ClickY ); result.x := round( FPoint.x * DIVS_PER_CELL ); result.Y := round( FPoint.y * DIVS_PER_CELL ); // result.x := ((ClickX + LeftX) * DIVS_PER_CELL) div PixelsPerCell; // result.y := ((ClickY + TopY) * DIVS_PER_CELL) div PixelsPerCell; end; // ***************************************** // SETUP CANVAS PEN, TEXT, BRUSH // ***************************************** procedure TteTrackEditor.SetCanvasUnselected; begin DrawMode := dmNormal; Canvas.Pen.Mode := pmCopy; end; procedure TteTrackEditor.SetCanvasSelected; begin DrawMode := DmSelected; end; procedure TteTrackEditor.SetCanvasXORTrack; begin DrawMode := dmXOR; end; procedure TteTrackEditor.SetCanvasXORRectangle; begin // Canvas.Pen.Style := psDot; Canvas.Pen.Style := psSolid; Canvas.Pen.Mode := pmXOr; Canvas.Pen.Color := clYellow; Canvas.Pen.Width := FDrawLineWidth; // Canvas.Pen.Width := PixelsPerCell div 4; Canvas.Brush.Color := clWhite; end; procedure TteTrackEditor.CanvasSettingsToPainter; begin case DrawMode of dmNormal: begin Painter.StripColor := FStripColor; Painter.XOR_Mode := False; end; dmSelected: begin Painter.StripColor := FSelectionColor; Painter.XOR_Mode := False; end; dmXOR: begin Painter.StripColor := FSelectionColor; Painter.XOR_Mode := True; end; end; end; // *********************************************** // PAINTING // *********************************************** // Painting procedure TteTrackEditor.PaintSelected; var i : integer; Track : TteTrack; begin CanvasSettingsToPainter; // ** Paint Selected Items Painter.Clear; for i := 0 to Tracks.Count - 1 do begin Track := Tracks[i]; if Track.Selected then begin { if Track.InsideRect then begin end; } Track.Paint( Painter ); end; end; Painter.Paint( Canvas ); end; procedure TteTrackEditor.PaintTrack( Track : TteTrack ); begin CanvasSettingsToPainter; Painter.Clear; Track.Paint( Painter ); Painter.Paint( Canvas ); end; // ********************************************* // PAINT MESSAGE HANDLER // ********************************************* // Called in response to WM_PAINT, and also explicitly. // Fills out the clipping rectangle supplied by WM_PAINT procedure TteTrackEditor.Paint; var BoardRectPx : TRect; RightRectPx : TRect; BelowRectPx : TRect; ClipRect : TRect; RefreshBoardRectDivs : TRect; RefreshBoardRectPx : TRect; begin ClipRect := Canvas.ClipRect; // calculate where Board Rectangle lies on window in screen pixels BoardRectPx.Left := 0; BoardRectPx.Top := 0; BoardRectPx.Right := BoardWidthScreenPixels - LeftX; BoardRectPx.Bottom := BoardHeightScreenPixels - TopY; // *** Repaint window area to right and below board - if inside cliprect { --------------------- | BOARD | RIGHT | |--------|----------| | BELOW | -------------------- } // area to right of board RightRectPx.Left := BoardRectPx.Right; RightRectPx.Right := Width; RightRectPx.Top := 0; RightRectPx.Bottom := BoardRectPx.Bottom; // if requires a repaint, repaint the whole area to the right if RectanglesOverlap( ClipRect, RightRectPx ) then begin Canvas.Pen.Color := clBtnFace; Canvas.Brush.Color := clBtnFace; Canvas.Rectangle( RightRectPx.Left, RightRectPx.Top, RightRectPx.Right, RightRectPx.Bottom); end; // area below board BelowRectPx.Left := 0; BelowRectPx.Right := Width; BelowRectPx.Top := BoardRectPx.Bottom; BelowRectPx.Bottom := Height; // if requires a repaint, repaint the whole area below if RectanglesOverlap( ClipRect, BelowRectPx ) then begin Canvas.Pen.Color := clBtnFace; Canvas.Brush.Color := clBtnFace; Canvas.Rectangle( BelowRectPx.Left, BelowRectPx.Top, BelowRectPx.Right, BelowRectPx.Bottom); end; // Calculate the Board Area in screen pixels that Needs a Repaint if not IntersectRect( RefreshBoardRectPx, BoardRectPx, ClipRect ) then begin // ClipRect area does not include the board & tracks asm nop end; exit; end; // RefreshBoardRectPx := ClipRect;// BoardRectPx; // offset Screen Redraw Rectangle to remove any scrolling and give us // a rectangle relative to the board RefreshBoardRectPx.Left := RefreshBoardRectPx.Left + LeftX; RefreshBoardRectPx.Right := RefreshBoardRectPx.Right + LeftX; RefreshBoardRectPx.Top := RefreshBoardRectPx.Top + TopY; RefreshBoardRectPx.Bottom := RefreshBoardRectPx.Bottom + TopY; // convert repaint Board area into Board Cell Units RefreshBoardRectDivs.Left := (RefreshBoardRectPx.Left * DIVS_PER_CELL) DIV PixelsPerCell; RefreshBoardRectDivs.Right := (RefreshBoardRectPx.Right * DIVS_PER_CELL) DIV PixelsPerCell; RefreshBoardRectDivs.Top := (RefreshBoardRectPx.Top * DIVS_PER_CELL) DIV PixelsPerCell; RefreshBoardRectDivs.Bottom := (RefreshBoardRectPx.Bottom * DIVS_PER_CELL) DIV PixelsPerCell; // Paint Board Area PaintRect( RefreshBoardRectDivs ); end; // ********************************************* // PAINT BOARD RECTANGLE // ********************************************* // Called with board rectangle to paint as parameter, defined in DIVS. // Redraws the background rectangle, then finds all tracks overlapping that // rectangle and draws them. procedure TteTrackEditor.PaintRect( RectDivs : TRect ); var i : integer; Track : TteTrack; SelectedCount : integer; ScreenRectPx : TRect; begin { // ** increase the draw area box by one cell on each side, so that // integer division truncation does not leave us a pixel undersize ScreenRectPx.Left := ScreenRectPx.Left - DIVS_PER_CELL; ScreenRectPx.Right := ScreenRectPx.Right + DIVS_PER_CELL; ScreenRectPx.Top := ScreenRectPx.Top - DIVS_PER_CELL; ScreenRectPx.Bottom := ScreenRectPx.Bottom + DIVS_PER_CELL; } // convert repaint Board area into Board Cell Units ScreenRectPx.Left := (RectDivs.Left * PixelsPerCell div DIVS_PER_CELL); ScreenRectPx.Right := (RectDivs.Right * PixelsPerCell div DIVS_PER_CELL); ScreenRectPx.Top := (RectDivs.Top * PixelsPerCell div DIVS_PER_CELL); ScreenRectPx.Bottom := (RectDivs.Bottom * PixelsPerCell div DIVS_PER_CELL); // calculate screen rectangle to erase. // Note: we paint +1 pixel larger, to account for rounding errors. // In particular THUMBTRACK painting leaves debris without this. ScreenRectPx.Left := ScreenRectPx.Left - LeftX - 1; ScreenRectPx.Right := ScreenRectPx.Right - LeftX + 1; ScreenRectPx.Top := ScreenRectPx.Top - TopY - 1; ScreenRectPx.Bottom := ScreenRectPx.Bottom - TopY + 1; // ** paint the board repaint area Canvas.Pen.Color := FBoardColor; Canvas.Brush.Color := FBoardColor; Canvas.Rectangle( ScreenRectPx ); // ** Painter will take over drawing on the canvas CanvasSettingsToPainter; // ** get unselected items to register primitives (lines, circles etc) Painter.Clear; for i := 0 to Tracks.Count - 1 do begin Track := Tracks[i]; if not Track.Selected then begin if Track.OverlapsPaintRect_D( RectDivs ) then begin Track.Paint( Painter ); end; end; end; // ** paint unselected Painter.LeftX := LeftX; Painter.TopY := TopY; Painter.StripColor := FStripColor; Painter.Paint( Canvas ); // ** get selected items to register primitives (lines, circles etc) Painter.Clear; for i := 0 to Tracks.Count - 1 do begin Track := Tracks[i]; if Track.Selected then begin if Track.OverlapsPaintRect_D( RectDivs ) then begin Track.Paint( Painter ); end; end; end; // ** paint selected // we ignore DrawMode because Paint and PaintRect always draw without XOR Painter.StripColor := FSelectionColor; Painter.Paint( Canvas ); //display some stuff for debug exit; SelectedCount := Tracks.GetSelectedCount; Canvas.TextOut( 20, 20, Format( '%d', [SelectedCount] )); Canvas.TextOut( 20, 30, Format( '%f,%f', [MouseDownCellCoords.x, MouseDownCellCoords.y] )); end; end.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.ORM.RestServer Description : Rest ORM Server allows access by http, httpapi or websockets Author : Kike Pérez Version : 1.9 Created : 02/06/2017 Modified : 08/05/2019 This file is part of QuickORM: https://github.com/exilon/QuickORM Uses Synopse mORMot framework. Copyright (C) 2017 Arnaud Bouchez Synopse Informatique - https://synopse.info *************************************************************************** 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 Quick.ORM.RestServer; {$i QuickORM.inc} {$INCLUDE synopse.inc} interface uses Classes, SysUtils, SynCommons, mORMot, mORMotSQLite3, mORMotDB, mORMotHttpServer, SynSQLite3Static, SynDBODBC, SynCrtSock, SynBidirSock, Quick.ORM.Engine, Quick.ORM.Server.Base, Quick.ORM.DataBase, Quick.ORM.Security, Quick.ORM.Server.Config; type TCustomORMServer = TSQLRestServerDB; TORMServerClass = class of TCustomORMServer; TIPRestriction = class private fDefaultSecurityRule : TSecurityAccess; fExcludedIPFromDefaultRule : TArrayOfRawUTF8; public constructor Create; destructor Destroy; override; published property DefaultSecurityRule : TSecurityAccess read fDefaultSecurityRule write fDefaultSecurityRule; property ExcludedIPFromDefaultRule : TArrayOfRawUTF8 read fExcludedIPFromDefaultRule write fExcludedIPFromDefaultRule; end; TORMHTTPServer = class(TSQLHttpServer) private fIPRestriction : TIPRestriction; fAPIKeys : TArrayOfRawUTF8; fOnIPRestrictedTry : TIPRestrictedTryEvent; fOnApiKeyBeforeAccess : TApiKeyBeforeAccessEvent; fOnApiKeyAfterAccess : TApiKeyAfterAccessEvent; protected function Request(Ctxt: THttpServerRequest): cardinal; override; function BeforeServiceExecute(Ctxt: TSQLRestServerURIContext; const Method: TServiceMethod) : Boolean; public property IPRestriction : TIPRestriction read fIPRestriction write fIPRestriction; property APIKeys : TArrayOfRawUTF8 read fAPIKeys write fAPIKeys; property OnIPRestrictedTry : TIPRestrictedTryEvent read fOnIPRestrictedTry write fOnIPRestrictedTry; property OnApiKeyBeforeAccess : TApiKeyBeforeAccessEvent read fOnApiKeyBeforeAccess write fOnApiKeyBeforeAccess; property OnApiKeyAfterAccess : TApiKeyAfterAccessEvent read fOnApiKeyAfterAccess write fOnApiKeyAfterAccess; end; THTTPServerOptions = class private fBinding : TIPBinding; fAuthMode : TAuthMode; fProtocol : TSrvProtocol; fConnectionTimeout : Integer; fCORSAllowedDomains : RawUTF8; fWSEncryptionKey : RawUTF8; fNamedPipe : RawUTF8; fIPRestriction : TIPRestriction; fAPIKeys : TArrayOfRawUTF8; public property Binding : TIPBinding read fBinding write fBinding; property AuthMode : TAuthMode read fAuthMode write fAuthMode; property Protocol : TSrvProtocol read fProtocol write fProtocol; property ConnectionTimeout : Integer read fConnectionTimeout write fConnectionTimeout; property CORSAllowedDomains : RawUTF8 read fCORSAllowedDomains write fCORSAllowedDomains; property WSEncryptionKey : RawUTF8 read fWSEncryptionKey write fWSEncryptionKey; property NamedPipe : RawUTF8 read fNamedPipe write fNamedPipe; property IPRestriction : TIPRestriction read fIPRestriction write fIPRestriction; property APIKeys : TArrayOfRawUTF8 read fAPIKeys write fAPIKeys; constructor Create; destructor Destroy; override; end; TORMService = class public fMethodClass : TInterfacedClass; fMethodInterface : TGUID; fInstanceImplementation : TServiceInstanceImplementation; fResultAsXMLIfRequired : Boolean; fEnabled : Boolean; public property MethodClass : TInterfacedClass read fMethodClass write fMethodClass; property MethodInterface : TGUID read fMethodInterface write fMethodInterface; property InstanceImplementation : TServiceInstanceImplementation read fInstanceImplementation write fInstanceImplementation; property ResultAsXMLIfRequired : Boolean read fResultAsXMLIfRequired write fResultAsXMLIfRequired; property Enabled : Boolean read fEnabled write fEnabled; constructor Create; end; {$IFDEF FPC} TProc = procedure; {$ENDIF} TORMRestServer = class(TORMBaseServer) private fHTTPServer : TORMHTTPServer; fService : TORMService; fHTTPOptions : THTTPServerOptions; fCustomORMServerClass : TORMServerClass; fConfigFile : TORMRestServerConfig; procedure LoadConfig; procedure ReloadConfig; procedure GetDefinedServerConfig; public ORM : TSQLRestServer; property CustomORMServerClass : TORMServerClass read fCustomORMServerClass write fCustomORMServerClass; property Service : TORMService read fService write fService; property HTTPOptions : THTTPServerOptions read fHTTPOptions write fHTTPOptions; constructor Create(cFullMemoryMode : Boolean = False); override; destructor Destroy; override; function Connect : Boolean; overload; override; function Connect(DoCustomDB : TProc) : Boolean; overload; end; implementation {TIPRestriction Class} constructor TIPRestriction.Create; begin fDefaultSecurityRule := TSecurityAccess.saAllowed; fExcludedIPFromDefaultRule := []; end; destructor TIPRestriction.Destroy; begin if Assigned(fExcludedIPFromDefaultRule) then fExcludedIPFromDefaultRule := []; inherited; end; {THTTPServer Class} constructor THTTPServerOptions.Create; begin inherited; fBinding := TIPBinding.Create; fBinding.IP := '127.0.0.1'; fBinding.Port := 8090; fProtocol := spHTTP_Socket; fCORSAllowedDomains := '*'; fConnectionTimeout := DEF_CONNECTION_TIMEOUT; fWSEncryptionKey := DEF_ENCRYPTIONKEY; fNamedPipe := DEF_NAMEDPIPE; fIPRestriction := TIPRestriction.Create; end; destructor THTTPServerOptions.Destroy; begin if Assigned(fBinding) then fBinding.Free; if Assigned(fIPRestriction) then fIPRestriction.Free; inherited; end; {TORMService Class} constructor TORMService.Create; begin inherited; fMethodClass := nil; //fMethodInterface := nil; fInstanceImplementation := sicShared; fResultAsXMLIfRequired := False; fEnabled := False; end; {TORMHTTPServer Class} function MatchArray(const aValue : string; const aAValues : TArrayOfRawUTF8) : Boolean; var lValue : string; begin Result := False; for lValue in aAValues do begin if AnsiSameStr(lValue,AValue) then begin Result := True; Break; end; end; end; function TORMHTTPServer.Request(Ctxt: THttpServerRequest): cardinal; var ClientIP : RawUTF8; ip : RawUTF8; CanAccess : Boolean; apikey : string; begin try ClientIP := FindIniNameValue(pointer(Ctxt.InHeaders),'REMOTEIP: '); except Result := HTTP_FORBIDDEN; Exit; end; //check default behaviour if fIPRestriction.DefaultSecurityRule = TSecurityAccess.saAllowed then CanAccess := True else CanAccess := False; //check if ip included in exception list if MatchArray(ClientIP,fIPRestriction.fExcludedIPFromDefaultRule) then CanAccess := not CanAccess; if CanAccess then begin //check if apikey required if High(fAPIKeys) > -1 then begin apikey := GetQueryParam(Ctxt.URL,'apikey'); CanAccess := MatchArray(apikey,fAPIKeys); if Assigned(fOnApiKeyBeforeAccess) then fOnApiKeyBeforeAccess(apikey,CanAccess); if Assigned(fOnApiKeyAfterAccess) then fOnApiKeyAfterAccess(apikey,CanAccess); end; end else if Assigned(fOnIPRestrictedTry) then fOnIPRestrictedTry(ClientIP); if CanAccess then Result := inherited Request(Ctxt) else Result := HTTP_FORBIDDEN; end; function TORMHTTPServer.BeforeServiceExecute(Ctxt: TSQLRestServerURIContext; const Method: TServiceMethod): Boolean; var ClientIP : RawUTF8; CanAccess : Boolean; apikey : string; begin try ClientIP := Ctxt.RemoteIP; except Result := False; Exit; end; //check default behaviour if fIPRestriction.DefaultSecurityRule = TSecurityAccess.saAllowed then CanAccess := True else CanAccess := False; //check if ip included in exception list if MatchArray(ClientIP,fIPRestriction.fExcludedIPFromDefaultRule) then CanAccess := not CanAccess; if CanAccess then begin //check if apikey required if High(fAPIKeys) > -1 then begin apikey := GetQueryParam(Ctxt.URI,'apikey'); CanAccess := MatchArray(apikey,fAPIKeys); if Assigned(fOnApiKeyBeforeAccess) then fOnApiKeyBeforeAccess(apikey,CanAccess); if Assigned(fOnApiKeyAfterAccess) then fOnApiKeyAfterAccess(apikey,CanAccess); end; end else if Assigned(fOnIPRestrictedTry) then fOnIPRestrictedTry(ClientIP); if CanAccess then Result := True else Result := False; end; {TORMRestServer Class} constructor TORMRestServer.Create(cFullMemoryMode : Boolean = False); begin inherited Create(cFullMemoryMode); fHTTPOptions := THTTPServerOptions.Create; fService := TORMService.Create; fService.Enabled := False; fCustomORMServerClass := nil; fConfigFile := TORMRestServerConfig.Create; fConfigFile.OnLoadConfig := Self.LoadConfig; fConfigFile.OnConfigChanged := Self.ReloadConfig; //fConfigFile.Load; loads on connect end; destructor TORMRestServer.Destroy; begin if Assigned(fHTTPServer) then fHTTPServer.Free; if Assigned(ORM) then ORM.Free; if Assigned(fHTTPOptions) then fHTTPOptions.Free; if Assigned(fService) then fService.Free; if Assigned(fConfigFile) then fConfigFile.Free; //deletes registration //if fHTTPMode = TSQLHttpServerOptions.useHttpApi then THttpApiServer.AddUrlAuthorize(faRootURI,'8080',false,'+',True); inherited; end; procedure TORMRestServer.LoadConfig; begin //read base config file fields of Base class ReadBaseConfigFile(fConfigFile); //read custom config file field NeedsRestart := False; //after ReadBaseConfigFile to avoid restart on first Load fHTTPOptions.IPRestriction.DefaultSecurityRule := fConfigFile.DefaultSecurityRule; fHTTPOptions.IPRestriction.ExcludedIPFromDefaultRule := fConfigFile.IPRestrictionExcludedIP; fHTTPOptions.APIKeys := fConfigFile.APIKeys; fHTTPOptions.Binding.IP := fConfigFile.ServerHost; fHTTPOptions.Binding.Port := fConfigFile.ServerPort; end; procedure TORMRestServer.ReloadConfig; var cNeedsRestart : Boolean; begin if Assigned(OnReloadConfig) then OnReloadConfig; //determines if changes on configfile need restart server if (fConfigfile.ServerHost <> fHTTPOptions.Binding.IP) or (fConfigfile.ServerPort <> fHTTPOptions.Binding.Port) then cNeedsRestart := True; //apply new values LoadConfig; // NeedsRestart := cNeedsRestart; //restart server to apply changes if (NeedsRestart) and (ConfigFile.RestartServerIfChanged) then begin if Assigned(OnRestart) then OnRestart; Connect; Security.ApplySecurity; NeedsRestart := False; end; end; procedure TORMRestServer.GetDefinedServerConfig; begin fConfigFile.ServerHost := fHTTPOptions.fBinding.IP; fConfigFile.ServerPort := fHTTPOptions.fBinding.Port; fConfigFile.DefaultSecurityRule := fHTTPOptions.IPRestriction.fDefaultSecurityRule; fConfigFile.IPRestrictionExcludedIP := fHTTPOptions.IPRestriction.fExcludedIPFromDefaultRule; fConfigFile.APIKeys := fHTTPOptions.APIKeys; fConfigFile.DBFilename := DataBase.DBFileName; end; function TORMRestServer.Connect : Boolean; begin Result := Connect(nil); end; function TORMRestServer.Connect(DoCustomDB : TProc) : Boolean; var ServiceFactoryServer: TServiceFactoryServer; ProxyPort : Integer; DBIndex : TDBIndex; DBMapping : TDBMappingField; begin //load config file if ConfigFile.Enabled then begin Self.GetDefinedServerConfig; fConfigFile.Load; end; //clear if previosly connected if Assigned(fHTTPServer) then FreeAndNil(fHTTPServer); if Assigned(ORM) then FreeAndNil(ORM); if Assigned(DataBase.SQLProperties) then DataBase.SQLProperties.Free; if Assigned(Security.ServiceFactoryServer) then Security.ServiceFactoryServer.Free; //check if port config provided in params by proxy (to work as a service in Azure) if ParamCount > 0 then begin if (TryStrToInt(ParamStr(1),ProxyPort)) and (ProxyPort > 0) then begin fHTTPOptions.Binding.IP := '127.0.0.1'; fHTTPOptions.Binding.Port := ProxyPort; end; end; //if needs Authentication if fHTTPOptions.AuthMode <> TAuthMode.amNoAuthentication then// in [TAuthMode.amDefault,TAuthMode.amSimple,TAuthMode.amHttpBasic] then begin Security.Enabled := True; DataBase.IncludedClasses := DataBase.IncludedClasses + [TORMAuthUser] + [TORMAuthGroup]; end else Security.Enabled := False; if Assigned(DataBase.Model) then DataBase.Model.Free; DataBase.Model := TSQLModel.Create(DataBase.IncludedClasses, DataBase.aRootURI); if DataBase.FullMemoryMode then begin if fCustomORMServerClass <> nil then ORM := fCustomORMServerClass.Create(DataBase.Model,False) else begin if DataBase.IncludedClasses = nil then ORM := TSQLRestServerFullMemory.CreateWithOwnModel([]) else ORM := TSQLRestServerFullMemory.Create(DataBase.Model,False); end; end else begin if not Assigned(DoCustomDb) then begin case DataBase.DBType of dtSQLite : begin if fCustomORMServerClass = nil then ORM := TSQLRestServerDB.Create(DataBase.Model,DataBase.DBFileName,Security.Enabled) else ORM := fCustomORMServerClass.Create(DataBase.Model,DataBase.DBFileName,Security.Enabled); end; dtMSSQL : begin DataBase.SQLProperties := //TOleDBMSSQL2008ConnectionProperties.Create(fDataBase.SQLConnection.ServerName,fDataBase.SQLConnection.DataBase,fDataBase.SQLConnection.Username,fDataBase.SQLConnection.UserPass); //TODBCConnectionProperties.Create('','Driver={SQL Server Native Client 10.0} ;Database='+DataBase.SQLConnection.DataBase+';'+ // 'Server='+DataBase.SQLConnection.ServerName+';UID='+DataBase.SQLConnection.Username+';Pwd='+DataBase.SQLConnection.UserPass+';MARS_Connection=yes','',''); TODBCConnectionProperties.Create('',DataBase.SQLConnection.GetConnectionString,'',''); VirtualTableExternalRegisterAll(DataBase.Model,DataBase.SQLProperties); try for DBMapping in DataBase.DBMappingFields do begin DataBase.Model.Props[DBMapping.SQLRecordClass].ExternalDB.MapField(DBMapping.InternalFieldName,DBMapping.ExternalFieldName); end; except on E : Exception do raise Exception.CreateFmt('Error mapping fields! (%s)',[e.Message]); end; if fCustomORMServerClass = nil then ORM := TSQLRestServerDB.Create(DataBase.Model,SQLITE_MEMORY_DATABASE_NAME,Security.Enabled,'') else ORM := fCustomORMServerClass.Create(DataBase.Model,SQLITE_MEMORY_DATABASE_NAME,Security.Enabled,'') end; end; end else DoCustomDb; end; //create tables ORM.CreateMissingTables; //create indexes for DBIndex in DataBase.DBIndexes do begin if DBIndex.FieldNames.Count > 1 then ORM.CreateSQLMultiIndex(DBIndex.SQLRecordClass,DBIndex.FieldNames,DBIndex.Unique) else ORM.CreateSQLIndex(DBIndex.SQLRecordClass,DBIndex.FieldNames,DBIndex.Unique); end; //assigns ORM to security class Security.SetORMServer(ORM); //fHTTPServer := TSQLHttpServer.Create(IntToStr(fHTTPServerOptions.Binding.Port),[ORM],'+',fHTTPServerOptions.Protocol); //if fHTTPMode = TSQLHttpServerOptions.useHttpApi then THttpApiServer.AddUrlAuthorize(faRootURI,IntToStr(fBinding.Port),false,fBinding.Host{+})); //netsh http show urlacl //Authmode initialization case fHTTPOptions.AuthMode of amNoAuthentication: begin //Nothing to do end; amSimple: //TSQLRestServerAuthenticationNone (uses User/pass but not signature Authentication) begin ORM.AuthenticationRegister(TSQLRestServerAuthenticationNone); end; amDefault: //TSQLRestServerAuthenticationDefault begin ORM.AuthenticationRegister(TSQLRestServerAuthenticationDefault); end; amHttpBasic: //TSQLRestServerAuthenticationHttpBasic begin ORM.AuthenticationRegister(TSQLRestServerAuthenticationHttpBasic); end; // TSQLRestServerAuthenticationSSPI {$IFDEF MSWINDOWS} amSSPI: begin ORM.AuthenticationRegister(TSQLRestServerAuthenticationSSPI); end; {$endif} else begin //DeInitialize(); raise Exception.Create('Authentication mode not available!'); end; end; //service initialization if fService.Enabled then begin ServiceFactoryServer := ORM.ServiceDefine(fService.MethodClass, [fService.fMethodInterface], fService.InstanceImplementation); ServiceFactoryServer.SetOptions([], [optErrorOnMissingParam]); if (not Security.Enabled) or (Security.PublicServices) then ServiceFactoryServer.ByPassAuthentication := True; //determines if service will return XML if client only accepts XML ServiceFactoryServer.ResultAsXMLObjectIfAcceptOnlyXML := fService.ResultAsXMLIfRequired; end; //protocol initialization if Assigned(fHTTPServer) then fHTTPServer.Free; case fHTTPOptions.Protocol of spHTTP_Socket: begin fHTTPServer := TORMHTTPServer.Create(fHTTPOptions.Binding.Port.ToString, [ORM], '+', useHttpSocket); THttpServer(fHTTPServer.HttpServer).ServerKeepAliveTimeOut := fHTTPOptions.ConnectionTimeout; end; { // require manual URI registration, we will not use this option in this test project, because this option // should be used with installation program that will unregister all used URIs during sofware uninstallation. HTTPsys: begin HTTPServer := TSQLHttpServer.Create(AnsiString(Options.Port), [RestServer], '+', useHttpApi); THttpServer(fHTTPServer.HttpServer).ServerKeepAliveTimeOut := SERVER_CONNECTION_TIMEOUT; end; } spHTTPsys: begin fHTTPServer := TORMHTTPServer.Create(fHTTPOptions.Binding.Port.ToString, [ORM], '+', HTTP_DEFAULT_MODE); THttpServer(fHTTPServer.HttpServer).ServerKeepAliveTimeOut := fHTTPOptions.fConnectionTimeout; end; spHTTPsys_SSL: begin fHTTPServer := TORMHTTPServer.Create(fHTTPOptions.Binding.Port.ToString, [ORM], '+', HTTP_DEFAULT_MODE, 32, TSQLHttpServerSecurity.secSSL); THttpServer(fHTTPServer.HttpServer).ServerKeepAliveTimeOut := fHTTPOptions.fConnectionTimeout; end; spHTTPsys_AES: begin fHTTPServer := TORMHTTPServer.Create(fHTTPOptions.Binding.Port.ToString, [ORM], '+', HTTP_DEFAULT_MODE, 32, TSQLHttpServerSecurity.secSynShaAes); THttpServer(fHTTPServer.HttpServer).ServerKeepAliveTimeOut := fHTTPOptions.fConnectionTimeout; end; spHTTP_WebSocket: begin fHTTPServer := TORMHTTPServer.Create(fHTTPOptions.Binding.Port.ToString, [ORM], '+', useBidirSocket); TWebSocketServerRest(fHTTPServer.HttpServer).ServerKeepAliveTimeOut := fHTTPOptions.fConnectionTimeout; end; spWebSocketBidir_JSON: begin fHTTPServer := TORMHTTPServer.Create(fHTTPOptions.Binding.Port.ToString, [ORM], '+', useBidirSocket); TWebSocketServerRest(fHTTPServer.HttpServer).ServerKeepAliveTimeOut := fHTTPOptions.fConnectionTimeout; { WebSocketServerRest := } fHTTPServer.WebSocketsEnable(ORM, '', True); end; spWebSocketBidir_Binary: begin fHTTPServer := TORMHTTPServer.Create(fHTTPOptions.Binding.Port.ToString, [ORM], '+', useBidirSocket); TWebSocketServerRest(fHTTPServer.HttpServer).ServerKeepAliveTimeOut := fHTTPOptions.fConnectionTimeout; { WebSocketServerRest := } fHTTPServer.WebSocketsEnable(ORM, '', false); end; spWebSocketBidir_BinaryAES: begin fHTTPServer := TORMHTTPServer.Create(fHTTPOptions.Binding.Port.ToString, [ORM], '+', useBidirSocket); TWebSocketServerRest(fHTTPServer.HttpServer).ServerKeepAliveTimeOut := fHTTPOptions.fConnectionTimeout; { WebSocketServerRest := } fHTTPServer.WebSocketsEnable(ORM, fHTTPOptions.WSEncryptionKey, false); end; spNamedPipe: begin if not ORM.ExportServerNamedPipe('\\.\pipe\' + fHTTPOptions.NamedPipe) then Exception.Create('Unable to register server with named pipe channel.'); end; else begin raise Exception.Create('Protocol not available!'); end; end; if fHTTPOptions.Protocol <> spNamedPipe then fHTTPServer.AccessControlAllowOrigin := fHTTPOptions.CORSAllowedDomains; //ip restriction if Assigned(fHTTPOptions.IPRestriction) then fHTTPServer.IPRestriction := fHTTPOptions.IPRestriction; //apikey access fHTTPServer.APIKeys := fHTTPOptions.APIKeys; //checks if default security needs to apply Security.SetDefaultSecurity; //assigns ServiceFactory to Security class if fService.Enabled then begin Security.ServiceFactoryServer := ServiceFactoryServer; //check every service authorization before execute ServiceFactoryServer.OnMethodExecute := fHTTPServer.BeforeServiceExecute; end; //apply security settings Security.ApplySecurity; Result := True; if Assigned(OnConnectionSuccess) then OnConnectionSuccess; end; end.
{* ***************************************************************************** PROYECTO FACTURACION ELECTRONICA Copyright (C) 2010-2014 - Bambú Code SA de CV - Ing. Luis Carrasco Esta clase representa la implementación para timbrado de CFDI del proveedor Comercio Digital (http://www.comercio-digital.com.mx) Este archivo pertenece al proyecto de codigo abierto de Bambú Code: http://bambucode.com/codigoabierto La licencia de este código fuente se encuentra en: http://github.com/bambucode/tfacturaelectronica/blob/master/LICENCIA > 11-24-2013 Integración con PAC creada por Ing. Pablo Torres TecSisNet.net (Cd. Juárez, Chihuahua) ***************************************************************************** *} unit PACComercioDigital; interface uses HTTPSend, SynaCode, Classes, xmldom, XMLIntf, msxmldom, XMLDoc, SysUtils, ProveedorAutorizadoCertificacion, FacturaTipos, FETimbreFiscalDigital, ComprobanteFiscal, FeCFDv32, FeCFD, FECancelaComercioDigital; type ECDNoPeticionVacia = class(Exception); // Error código 001 ECDTamanoPeticionGrande = class(Exception); // Error código 002 ECDTamanoPeticionHTTPIncorrecta = class(Exception); // Error código 003 ECDUsuarioContrasenaInvalida = class(Exception); // Error código 700,702,703,708 ECDRFCObligacionesInvalidas = class(Exception); // Error código 803 ECDServicioCancelacionNoDisponible = class(Exception); // Error código 900,945,946 ECDRespuestaIncorrectaCancelacionSat = class(Exception); // Error código 949,950 ECDErrorInternoPac = class(Exception); // Error código 332,333,334,910,951 ECDErrorFolioPreviamenteCancelado = class(Exception); // Error código 202 ECDErrorFolioNoCorrespondeEmisor = class(Exception); // Error código 203 ECDErrorFolioNoAplicaCancelacion = class(Exception); // Error código 204 ECDErrorFolioNoExiste = class(Exception); // Error código 205 {$REGION 'Documentation'} /// <summary> /// Implementa el servicio de timbrado para CFDI del proveedor "Comercio /// Digital" (<see href="http://www.comercio-digital.com.mx" />) /// </summary> {$ENDREGION} TPACComercioDigital = class(TProveedorAutorizadoCertificacion) private fCredenciales : TFEPACCredenciales; fDocumentoXMLTimbrado : TXMLDocument; fDocumentoXMLCancelado : TXMLDocument; function getNombre() : string; override; function ObtenerURLTimbrado: String; function ObtenerURLCancelacion: String; procedure ProcesarCodigoDeError(aRespuestaDePAC: String); function RealizarPeticionREST(const URL : string; const aDocumentoXML: TTipoComprobanteXML): TTipoComprobanteXML; function RealizarCancelacionREST(const URL : string; const aDocumentoXML: TTipoComprobanteXML): TTipoComprobanteXML; function ValidarXML(const xmlFile : TFileName) : String; //unicamente valida la estructura del xml solo se usaria para desarrollo public constructor Create(); destructor Destroy(); override; procedure AfterConstruction; override; procedure AsignarCredenciales(const aCredenciales: TFEPACCredenciales); override; function CancelarDocumento(const aDocumento: TTipoComprobanteXML): Boolean; override; function TimbrarDocumento(const aDocumento: TTipoComprobanteXML): TFETimbre; override; property Nombre: String read getNombre; end; const _URL_API_TIMBRADO = 'http://pruebas.comercio-digital.mx/timbre/timbrar.aspx?rfc=%s&pwd=%s'; _URL_API_CANCELAR = 'http://pruebas.comercio-digital.mx/cancela/uuid.aspx'; _URL_API_CANCELAR_PRM = '?rfc=%s&pwd=%s'; implementation uses FacturaReglamentacion; function TPACComercioDigital.getNombre() : string; begin Result := 'Comercio Digital'; end; destructor TPACComercioDigital.Destroy(); begin // Al ser una interface el objeto TXMLDocument se libera automaticamente por Delphi al dejar de ser usado // aunque para asegurarnos hacemos lo siguiente: inherited; end; procedure TPACComercioDigital.AfterConstruction; begin inherited; fDocumentoXMLTimbrado := TXMLDocument.Create(nil); fDocumentoXMLTimbrado.Active := True; fDocumentoXMLCancelado := TXMLDocument.Create(nil); fDocumentoXMLCancelado.Active := True; end; procedure TPACComercioDigital.AsignarCredenciales(const aCredenciales: TFEPACCredenciales); begin fCredenciales := aCredenciales; end; function TPACComercioDigital.ObtenerURLTimbrado: String; begin // TODO: Pasar por URL encode estos parametros Result := Format(_URL_API_TIMBRADO, [fCredenciales.RFC, fCredenciales.Clave]); end; function TPACComercioDigital.ObtenerURLCancelacion: String; begin // TODO: Pasar por URL encode estos parametros Result := Format(_URL_API_CANCELAR+_URL_API_CANCELAR_PRM, [fCredenciales.RFC, fCredenciales.Clave]); end; //unicamente valida la estructura del xml solo se usaria para desarrollo procedure TPACComercioDigital.ProcesarCodigoDeError(aRespuestaDePAC: String); var mensajeExcepcion: string; Const _ERROR_CD_PETICION_VACIA = '001'; _ERROR_CD_TAMANO_PETICION_GRANDE = '002'; _ERROR_CD_PETICION_HTTP_INCORRECTA = '003'; _ERROR_CD_USUARIO_CONTRASENA_INVALIDA = '700'; _ERROR_CD_USUARIO_CONTRASENA_INVALIDA_1 = '702'; _ERROR_CD_USUARIO_CONTRASENA_INVALIDA_3 = '703'; _ERROR_CD_USUARIO_CONTRASENA_INVALIDA_8 = '708'; _ERROR_CD_RFC_CON_OBLIGACIONES_INVALIDAS = '306'; _ERROR_CD_SERVICIO_CANCELACION_NO_DISPONIBLE = '900'; _ERROR_CD_SERVICIO_CANCELACION_NO_DISPONIBLE_1 = '945'; _ERROR_CD_SERVICIO_CANCELACION_NO_DISPONIBLE_2 = '946'; _ERROR_CD_RESPUESTA_INCORRECTA_CANCELACION_SAT = '949'; _ERROR_CD_RESPUESTA_INCORRECTA_CANCELACION_SAT_1 = '950'; _ERROR_CD_ERROR_INTERNO_PAC = '332'; _ERROR_CD_ERROR_INTERNO_PAC_1 = '333'; _ERROR_CD_ERROR_INTERNO_PAC_2 = '334'; _ERROR_CD_ERROR_INTERNO_PAC_3 = '910'; _ERROR_CD_ERROR_INTERNO_PAC_4 = '951'; _ERROR_CD_FOLIO_PREVIAMENTE_CANCELADO = '202'; _ERROR_CD_FOLIO_NO_CORRESPONDE_RFC_EMISOR = '203'; _ERROR_CD_FOLIO_NO_APLICA_CANCELACION = '204'; _ERROR_CD_FOLIO_NO_EXISTE = '205'; begin // if AnsiPos(_ECODEX_FUERA_DE_SERVICIO, mensajeExcepcion) > _NO_ECONTRADO then // raise EPACServicioNoDisponibleException.Create(mensajeExcepcion, 0, True); // // if AnsiPos(_ERROR_SAT_XML_INVALIDO, mensajeExcepcion) > _NO_ECONTRADO then // raise ETimbradoXMLInvalidoException.Create(mensajeExcepcion, 301, False); // // if AnsiPos(_ERROR_SAT_SELLO_EMISOR_INVALIDO, mensajeExcepcion) > _NO_ECONTRADO then // raise ETimbradoSelloEmisorInvalidoException.Create(mensajeExcepcion, 302, False); // // if AnsiPos(_ERROR_SAT_CERTIFICADO_NO_CORRESPONDE, mensajeExcepcion) > _NO_ECONTRADO then // raise ETimbradoCertificadoNoCorrespondeException.Create(mensajeExcepcion, 303, False); // // if AnsiPos(_ERROR_SAT_CERTIFICADO_REVOCADO, mensajeExcepcion) > _NO_ECONTRADO then // raise ETimbradoCertificadoRevocadoException.Create(mensajeExcepcion, 304, False); // // if AnsiPos(_ERROR_SAT_FECHA_EMISION_SIN_VIGENCIA, mensajeExcepcion) > _NO_ECONTRADO then // raise ETimbradoFechaEmisionSinVigenciaException.Create(mensajeExcepcion, 305, False); // // if AnsiPos(_ERROR_SAT_LLAVE_NO_CORRESPONDE, mensajeExcepcion) > _NO_ECONTRADO then // raise ETimbradoLlaveInvalidaException.Create(mensajeExcepcion, 306, False); // // if AnsiPos(_ERROR_SAT_PREVIAMENTE_TIMBRADO, mensajeExcepcion) > _NO_ECONTRADO then // raise ETimbradoPreviamenteException.Create(mensajeExcepcion, 307, False); // // if AnsiPos(_ERROR_SAT_CERTIFICADO_NO_FIRMADO_POR_SAT, mensajeExcepcion) > _NO_ECONTRADO then // raise ETimbradoCertificadoApocrifoException.Create(mensajeExcepcion, 308, False); // // if AnsiPos(_ERROR_SAT_FECHA_FUERA_DE_RANGO, mensajeExcepcion) > _NO_ECONTRADO then // raise ETimbradoFechaGeneracionMasDe72HorasException.Create(mensajeExcepcion, 401, False); // // if AnsiPos(_ERROR_SAT_REGIMEN_EMISOR_NO_VALIDO, mensajeExcepcion) > _NO_ECONTRADO then // raise ETimbradoRegimenEmisorNoValidoException.Create(mensajeExcepcion, 402, False); // // if AnsiPos(_ERROR_SAT_FECHA_EMISION_EN_EL_PASADO, mensajeExcepcion) > _NO_ECONTRADO then // raise ETimbradoFechaEnElPasadoException.Create(mensajeExcepcion, 403, False); // // if AnsiPos(_ECODEX_RFC_NO_CORRESPONDE, mensajeExcepcion) > _NO_ECONTRADO then // raise EPACTimbradoRFCNoCorrespondeException.Create('El RFC del documento y el del emisor no corresponden', 0, False); // // if AnsiPos(_ECODEX_VERSION_NO_SOPORTADA, mensajeExcepcion) > _NO_ECONTRADO then // raise EPACTimbradoVersionNoSoportadaPorPACException.Create('Esta version de CFDI no es soportada por ECODEX:' + // mensajeExcepcion, 0, False); // Si llegamos aqui y no se ha lanzado ningun otro error lanzamos el error genérico de PAC // con la propiedad reintentable en verdadero para que el cliente pueda re-intentar el proceso anterior // raise EPACErrorGenericoException.Create(mensajeExcepcion, 0, True); /// errores generados de este pac if AnsiPos(_ERROR_CD_PETICION_VACIA, aRespuestaDePAC) > -1 then raise ECDNoPeticionVacia.Create(aRespuestaDePAC+' Petición Vacia'); if AnsiPos(_ERROR_CD_TAMANO_PETICION_GRANDE, aRespuestaDePAC) > -1 then raise ECDTamanoPeticionGrande.Create(aRespuestaDePAC+' Tamaño de la petición demasiado grande'); if AnsiPos(_ERROR_CD_PETICION_HTTP_INCORRECTA, aRespuestaDePAC) > -1 then raise ECDTamanoPeticionHTTPIncorrecta.Create(aRespuestaDePAC+' Petición de HTTP incorrecta'); if AnsiPos(_ERROR_CD_USUARIO_CONTRASENA_INVALIDA, aRespuestaDePAC) > -1 then raise ECDUsuarioContrasenaInvalida.Create(aRespuestaDePAC+' Usuario o contraseña invalida'); if AnsiPos(_ERROR_CD_USUARIO_CONTRASENA_INVALIDA_1, aRespuestaDePAC) > -1 then raise ECDUsuarioContrasenaInvalida.Create(aRespuestaDePAC+' Usuario o contraseña invalida'); if AnsiPos(_ERROR_CD_USUARIO_CONTRASENA_INVALIDA_3, aRespuestaDePAC) > -1 then raise ECDUsuarioContrasenaInvalida.Create(aRespuestaDePAC+' Usuario o contraseña invalida'); if AnsiPos(_ERROR_CD_USUARIO_CONTRASENA_INVALIDA_8, aRespuestaDePAC) > -1 then raise ECDUsuarioContrasenaInvalida.Create(aRespuestaDePAC+' Usuario o contraseña invalida'); if AnsiPos(_ERROR_CD_RFC_CON_OBLIGACIONES_INVALIDAS, aRespuestaDePAC) > -1 then raise ECDRFCObligacionesInvalidas.Create(aRespuestaDePAC+' El RFC no cuenta con obligaciones validas en la Lista de Contribuyentes Obligados'); if AnsiPos(_ERROR_CD_SERVICIO_CANCELACION_NO_DISPONIBLE, aRespuestaDePAC) > -1 then raise ECDServicioCancelacionNoDisponible.Create(aRespuestaDePAC+' Servicio de cancelacion del SAT no disponible (intentar mas tarde)'); if AnsiPos(_ERROR_CD_SERVICIO_CANCELACION_NO_DISPONIBLE_1, aRespuestaDePAC) > -1 then raise ECDServicioCancelacionNoDisponible.Create(aRespuestaDePAC+' Servicio de cancelacion del SAT no disponible (intentar mas tarde)'); if AnsiPos(_ERROR_CD_SERVICIO_CANCELACION_NO_DISPONIBLE_2, aRespuestaDePAC) > -1 then raise ECDServicioCancelacionNoDisponible.Create(aRespuestaDePAC+' Servicio de cancelacion del SAT no disponible (intentar mas tarde)'); if AnsiPos(_ERROR_CD_RESPUESTA_INCORRECTA_CANCELACION_SAT, aRespuestaDePAC) > -1 then raise ECDRespuestaIncorrectaCancelacionSat.Create(aRespuestaDePAC+' Respuesta incompleta del servicio de cancelacion del SAT (se recomienda reintentar)'); if AnsiPos(_ERROR_CD_RESPUESTA_INCORRECTA_CANCELACION_SAT_1, aRespuestaDePAC) > -1 then raise ECDRespuestaIncorrectaCancelacionSat.Create(aRespuestaDePAC+' Respuesta incompleta del servicio de cancelacion del SAT (se recomienda reintentar)'); if AnsiPos(_ERROR_CD_ERROR_INTERNO_PAC, aRespuestaDePAC) > -1 then raise ECDErrorInternoPac.Create(aRespuestaDePAC+' Error Interno en el servicio de Cancelación'); if AnsiPos(_ERROR_CD_ERROR_INTERNO_PAC_1, aRespuestaDePAC) > -1 then raise ECDErrorInternoPac.Create(aRespuestaDePAC+' Error Interno en el servicio de Cancelación'); if AnsiPos(_ERROR_CD_ERROR_INTERNO_PAC_2, aRespuestaDePAC) > -1 then raise ECDErrorInternoPac.Create(aRespuestaDePAC+' Error Interno en el servicio de Cancelación'); if AnsiPos(_ERROR_CD_ERROR_INTERNO_PAC_3, aRespuestaDePAC) > -1 then raise ECDErrorInternoPac.Create(aRespuestaDePAC+' Error Interno en el servicio de Cancelación'); if AnsiPos(_ERROR_CD_ERROR_INTERNO_PAC_4, aRespuestaDePAC) > -1 then raise ECDErrorInternoPac.Create(aRespuestaDePAC+' Error Interno en el servicio de Cancelación'); if AnsiPos(_ERROR_CD_FOLIO_PREVIAMENTE_CANCELADO, aRespuestaDePAC) > -1 then raise ECDErrorFolioPreviamenteCancelado.Create(aRespuestaDePAC+' Folio Fiscal Previamente cancelado'); if AnsiPos(_ERROR_CD_FOLIO_NO_CORRESPONDE_RFC_EMISOR, aRespuestaDePAC) > -1 then raise ECDErrorFolioNoCorrespondeEmisor.Create(aRespuestaDePAC+' Folio Fiscal no corresponde a RFC Emisor y de quien solicita Cancelación'); if AnsiPos(_ERROR_CD_FOLIO_NO_APLICA_CANCELACION, aRespuestaDePAC) > -1 then raise ECDErrorFolioNoAplicaCancelacion.Create(aRespuestaDePAC+' No aplica cancelación'); if AnsiPos(_ERROR_CD_FOLIO_NO_EXISTE, aRespuestaDePAC) > -1 then raise ECDErrorFolioNoExiste.Create(aRespuestaDePAC+' Folio Fiscal no existe'); // Si llegamos aqui y no se ha lanzado ningun otro error lanzamos el error genérico de PAC // con la propiedad reintentable en verdadero para que el cliente pueda re-intentar el proceso anterior raise EPACErrorGenericoException.Create(mensajeExcepcion, 0, 0, True); end; function TPACComercioDigital.ValidarXML(const xmlFile : TFileName) : String; begin fDocumentoXMLTimbrado.ParseOptions := [poResolveExternals, poValidateOnParse]; try fDocumentoXMLTimbrado.LoadFromFile(xmlFile) ; fDocumentoXMLTimbrado.Active := true; //esto valida result := ''; except on EX : EDOMParseError do begin Result:='XML Invalido: ' + Ex.Message ; end; end; end; function TPACComercioDigital.RealizarPeticionREST(const URL: string; const aDocumentoXML: TTipoComprobanteXML): TTipoComprobanteXML; var HTTP: THTTPSend; resultadoAPI : TStringStream; respuestaDeServidor: TStrings; llamadoExitoso: Boolean; begin // TODO: Cambiar este codigo para no depender de Synapse {$IF Compilerversion >= 20} resultadoAPI := TStringStream.Create(aDocumentoXML,TEncoding.UTF8 ); {$ELSE} resultadoAPI := TStringStream.Create(aDocumentoXML); {$IFEND} HTTP := THTTPSend.Create; respuestaDeServidor := TStringList.Create; try // Copiamos el documento XML al Memory Stream resultadoAPI.WriteString(aDocumentoXML); HTTP.Document.CopyFrom(resultadoAPI, 0); llamadoExitoso:=HTTP.HTTPMethod('POST', URL); if llamadoExitoso then begin respuestaDeServidor.LoadFromStream(HTTP.Document); Result := respuestaDeServidor.Text; end else raise Exception.Create('Error al timbrar en API:' + HTTP.ResultString); finally HTTP.Free; respuestaDeServidor.Free; resultadoAPI.Free; end; end; function TPACComercioDigital.RealizarCancelacionREST(const URL: string; const aDocumentoXML: TTipoComprobanteXML): TTipoComprobanteXML; function EncodeF(const Archivo: string): {$IF Compilerversion >= 20} UnicodeString {$ELSE} UTF8String {$IFEND}; function MemoryStreamToString(M: TMemoryStream): UTF8string; //extraida de http://stackoverflow.com/questions/732666/converting-tmemorystream-to-string-in-delphi-2009 begin SetString(Result, PChar(M.Memory), M.Size div SizeOf(Char)); end; var {$IF Compilerversion >= 20} stream : TStringStream; {$ELSE} stream : TMemoryStream; {$IFEND} begin try {$IF Compilerversion >= 20} stream := TStringStream.Create; stream.LoadFromFile(Archivo); result := EncodeBase64(stream.DataString); {$ELSE} stream := TMemoryStream.Create; stream.LoadFromFile(Archivo); result := EncodeBase64(MemoryStreamToString(stream)); {$IFEND} finally stream.Free; end; end; function ExtraerUUID(const aDocumentoTimbrado: TTipoComprobanteXML) : String; const _LONGITUD_UUID = 36; begin Result:=Copy(aDocumentoTimbrado, AnsiPos('UUID="', aDocumentoTimbrado) + 6, _LONGITUD_UUID); end; var HTTP: THTTPSend; {$IF Compilerversion >= 20} resultadoAPI : TStringStream; {$ELSE} resultadoAPI : TMemoryStream; {$IFEND} respuestaDeServidor: TStrings; llamadoExitoso: Boolean; Res: TStrings; begin // TODO: Cambiar este codigo para no depender de Synapse HTTP := THTTPSend.Create; respuestaDeServidor := TStringList.Create; Res:= TStringList.Create; try res.Add('POST '+_URL_API_CANCELAR+' HTTP/1.1'); res.Add('Content-Type: text/plain'); res.Add('Host: pruebas.comercio-digital.mx'); res.Add('Content-Length: 3285'); res.Add('Connection: Keep-Alive'); res.Add(''); res.Add('RFC ='+EncodeURL(fCredenciales.RFC)); res.Add('UUID='+ExtraerUUID(aDocumentoXML)); res.Add('USER='+EncodeURL(fCredenciales.RFC)); res.Add('PWDW='+EncodeURL(fCredenciales.Clave)); res.Add('CERT='+EncodeF(fCredenciales.Certificado.Ruta)); res.Add('KEYF='+EncodeF(fCredenciales.Certificado.LlavePrivada.Ruta)); res.Add('PWDK='+EncodeURL(fCredenciales.Certificado.LlavePrivada.Clave)); res.Add('ACUS=SI'); {$IF Compilerversion >= 20} resultadoAPI := TStringStream.Create; {$ELSE} resultadoAPI := TMemoryStream.Create; {$IFEND} Res.SaveToStream(resultadoAPI); HTTP.Document.LoadFromStream(resultadoAPI); llamadoExitoso:=HTTP.HTTPMethod('POST', URL); if llamadoExitoso then begin respuestaDeServidor.LoadFromStream(HTTP.Document); Result := respuestaDeServidor.Text; end else raise Exception.Create('Error al cancelar en API:' + HTTP.ResultString); finally HTTP.Free; respuestaDeServidor.Free; resultadoAPI.Free; Res.Free; end; end; function TPACComercioDigital.TimbrarDocumento(const aDocumento: TTipoComprobanteXML): TFETimbre; var respuestaCadena: TTipoComprobanteXML; nodoXMLTimbre : IFEXMLtimbreFiscalDigital; begin try // Paso 1. Mandamos solicitar el timbre por medio del API Rest de Comercio Digital respuestaCadena := RealizarPeticionREST(ObtenerURLTimbrado(), aDocumento); // Checamos haber recibido el timbrado correctamente if Copy(Trim(respuestaCadena),1,4)='<tfd' then Begin {$IF Compilerversion >= 20} fDocumentoXMLTimbrado.XML.Text:=respuestaCadena; {$ELSE} fDocumentoXMLTimbrado.XML.Text:=UTF8Encode(respuestaCadena); {$IFEND} fDocumentoXMLTimbrado.Active:=True; nodoXMLTimbre := GetTimbreFiscalDigital(fDocumentoXMLTimbrado); // Asignamos las propiedades del Timbre que vamos a regresar Result.Version:=nodoXMLTimbre.Version; Result.UUID:=nodoXMLTimbre.UUID; Result.FechaTimbrado:=TFEReglamentacion.DeFechaHoraISO8601(nodoXMLTimbre.FechaTimbrado); Result.SelloCFD:=nodoXMLTimbre.SelloCFD; Result.NoCertificadoSAT:=nodoXMLTimbre.NoCertificadoSAT; Result.SelloSAT:=nodoXMLTimbre.SelloSAT; Result.XML := nodoXMLTimbre.XML; end else ProcesarCodigoDeError(respuestaCadena); except On E:Exception do begin // TODO: Procesar correctamente los diferentes tipos de errores raise; end; end; end; function TPACComercioDigital.CancelarDocumento(const aDocumento: TTipoComprobanteXML): Boolean; var Respuesta: TTipoComprobanteXML; NodoCancelacion: IFEXMLAcuseType; begin try // Paso 1. Mandamos solicitar la cancelación por medio del API Rest de Comercio Digital respuesta := RealizarCancelacionREST(ObtenerURLCancelacion(),aDocumento); // Paso 2. Checamos haber recibido la cancelación correctamente {$IF Compilerversion >= 20} fDocumentoXMLCancelado.XML.Text:=respuesta; {$ELSE} fDocumentoXMLCancelado.XML.Text:=UTF8Encode(respuesta); {$IFEND} fDocumentoXMLCancelado.Active:=True; nodoCancelacion := GetAcuse(fDocumentoXMLCancelado); // Paso 3. Validamos haber recibido la cancelación correctamente if nodoCancelacion.Folios.EstatusUUID<>201 then ProcesarCodigoDeError(IntToStr(nodoCancelacion.Folios.EstatusUUID)) else Result:= True; except On E:Exception do begin // TODO: Procesar correctamente los diferentes tipos de errores raise; end; end; end; constructor TPACComercioDigital.Create; begin inherited; end; end.
unit rsDefs; interface uses SysUtils, Classes, TypInfo, RTTI, Generics.Collections; type TTokenKind = ( tkNone, //symbols tkIdentifier, tkAssign, tkColon, tkSem, tkEquals, tkNotEqual, tkLessThan, tkLessEqual, tkGreaterThan, tkGreaterEqual, tkPlus, tkMinus, tkTimes, tkDivide, tkComma, tkDot, tkDotDot, tkOpenParen, tkCloseParen, tkOpenBracket, tkCloseBracket, tkInt, tkFloat, tkChar, tkString, //keywords tkAnd, tkArray, tkAs, tkBegin, tkBreak, tkCase, tkClass, tkConst, tkContinue, tkConstructor, tkDefault, tkDestructor, tkDiv, tkDo, tkDownTo, tkElse, tkEnd, tkExcept, tkExit, {tkExternal,} tkFinally, tkFor, tkForward, tkFunction, tkGoto, tkIf, tkIn, tkImplementation, tkInherited, tkInterface, tkIs, tkLabel, tkMod, tkNil, tkNot, tkObject, tkOf, tkOn, tkOr, tkOut, tkOverride, tkPrivate, tkProcedure, tkProperty, tkProtected, tkPublic, tkProgram, tkRaise, tkRepeat, tkRecord, tkSet, tkShl, tkShr, tkThen, tkTo, tkTry, tkType, tkUnit, tkUntil, tkUses, tkVar, tkVirtual, tkWhile, tkXor, tkEof, tkError); TToken = record private FKind: TTokenKind; // FText: string; // FOrigText: string; FRow: integer; FColumn: integer; FStart: PChar; FLength: integer; function GetOrigText: string; public constructor Create(kind: TTokenKind; row, column, length: integer; start: PChar); function GetText: string; property kind: TTokenKind read FKind write FKind; // property text: string read GetText; property origText: string read GetOrigText; property row: integer read FRow; property Column: integer read FColumn; end; TKeywordPair = record keyword: string; token: TTokenKind; end; TSyntaxKind = (skValue, skBinOp, skUnOp, skBoolOp, skVariable, skType, skCall, skDeref, skReturn, skLabel, skJump, skBlock, skAssign, skTryF, skTryE, skFinally, skExcept, skELoad, skTryCall, skRaise, skSwallow, skElem, skDot, skCast, skArrayProp, skArray); TBinOpKind = (opPlus, opMinus, opMult, opDiv, opDivide, opMod, opAnd, opOr, opXor, opShl, opShr, opAs); TBoolOpKind = (opGreaterEqual, opLessEqual, opGreaterThan, opLessThan, opEquals, opNotEqual, opIn, opIs, opBoolAnd, opBoolOr, opBoolXor); TUnOpKind = (opNeg, opNot, opInc, opDec, opExis); TSymbolKind = (syConst, syVariable, syLabel, syProp, syProc, syType, syEnum, syUnit); TBlockSyntax = class; TSymbol = class private function GetFullName: string; protected FName: string; FFullName: string; FKind: TSymbolKind; //in case any descendants need interfaces function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function ResolveFullName: string; virtual; constructor Create(const name: string; kind: TSymbolKind); public property name: string read FName; property fullName: string read GetFullName; property kind: TSymbolKind read FKind; end; ISymbolTable = interface function GetItem(const Key: string): TSymbol; procedure SetItem(const Key: string; const Value: TSymbol); procedure Add(const Key: string; const Value: TSymbol); function Values: TEnumerable<TSymbol>; function TryGetValue(const Key: string; out Value: TSymbol): Boolean; function ContainsKey(const Key: string): Boolean; function ExtractPair(const Key: string): TPair<string,TSymbol>; function KeysWhereValue(filter: TPredicate<TSymbol>): TStringList; function Where(filter: TFunc<string, TSymbol, boolean>): TList<TPair<string, TSymbol>>; procedure Clear; function Count: integer; property Items[const Key: string]: TSymbol read GetItem write SetItem; default; end; TConstSymbol = class(TSymbol) private FValue: TValue; public constructor Create(const name: string; const value: TValue); property value: TValue read FValue; end; TTypeSymbol = class(TSymbol) private FTypeInfo: PTypeInfo; protected function GetTypeInfo: PTypeInfo; virtual; public constructor Create(const name: string); function CanDerefDot: boolean; virtual; function CanDerefArray: boolean; virtual; function GetSymbolTable: ISymbolTable; virtual; function HasTypeInfo: boolean; property TypeInfo: PTypeInfo read GetTypeInfo; end; TVarSymbol = class(TSymbol) private FType: TTypeSymbol; FIndex: integer; FParent: TSymbol; protected function ResolveFullName: string; override; public constructor Create(const name: string; aType: TTypeSymbol; parent: TSymbol); property &Type: TTypeSymbol read FType; property index: integer read FIndex; property parent: TSymbol read FParent; end; TFieldSymbol = class(TVarSymbol) private FVisibility: TMemberVisibility; public constructor Create(const name: string; aType: TTypeSymbol; visibility: TMemberVisibility; parent: TSymbol); property visibility: TMemberVisibility read FVisibility; end; TParamSymbol = class(TVarSymbol) private FFlags: TParamFlags; public constructor Create(const name: string; aType: TTypeSymbol; flags: TParamFlags); destructor Destroy; override; property flags: TParamFlags read FFlags; end; IParamList = interface procedure Insert(Index: Integer; const Value: TParamSymbol); function Count: integer; function Last: TParamSymbol; procedure SetOwnsObjects(value: boolean); function GetItem(Index: Integer): TParamSymbol; procedure SetItem(Index: Integer; const Value: TParamSymbol); function GetEnumerator: TEnumerator<TParamSymbol>; function Add(const Value: TParamSymbol): Integer; procedure AddRange(Collection: IParamList); property OwnsObjects: boolean write SetOwnsObjects; property Items[Index: Integer]: TParamSymbol read GetItem write SetItem; default; end; TPropSymbol = class(TVarSymbol) private FVisibility: TMemberVisibility; FClassScope: boolean; FParamList: IParamList; FReadSpec: TSymbol; FWriteSpec: TSymbol; FPropInfo: PPropInfo; procedure VerifyReadWriteCompat; public constructor Create(const name: string; &type: TTypeSymbol; visibility: TMemberVisibility; classScope: boolean; const paramList: IParamList; readSpec, writeSpec: TSymbol; parent: TSymbol); overload; constructor Create(const name: string; visibility: TMemberVisibility; info: PPropInfo; parent: TSymbol); overload; property visibility: TMemberVisibility read FVisibility; property classScope: boolean read FClassScope; property paramList: IParamList read FParamList; property readSpec: TSymbol read FReadSpec; property writeSpec: TSymbol read FWriteSpec; end; TProcSymbol = class(TVarSymbol) private FVisibility: TMemberVisibility; FClassScope: boolean; FParamList: IParamList; FForwarded: boolean; FSymbolTable: ISymbolTable; FSyntax: TBlockSyntax; procedure SetSyntax(const Value: TBlockSyntax); public constructor Create(const name: string; &type: TTypeSymbol; visibility: TMemberVisibility; classScope: boolean; const paramList: IParamList; forwarded: boolean; parent: TSymbol); destructor Destroy; override; procedure Define; property visibility: TMemberVisibility read FVisibility; property classScope: boolean read FClassScope; property paramList: IParamList read FParamList; property forwarded: boolean read FForwarded; property symbolTable: ISymbolTable read FSymbolTable; property syntax: TBlockSyntax read FSyntax write SetSyntax; end; TClassTypeSymbol = class(TTypeSymbol) private FForward: boolean; FParentType: TClassTypeSymbol; FSymbols: ISymbolTable; FExportSymbols: ISymbolTable; FMetaclass: TClass; procedure SetParent(const Value: TClassTypeSymbol); procedure CheckUnique(const name, kind: string); procedure AddSymbol(const name: string; visibility: TMemberVisibility; value: TVarSymbol; var counter: integer); procedure SetMetaclass(const Value: TClass); protected FFieldCount: integer; FPropCount: integer; FArrayPropCount: integer; FMethodCount: integer; FDefaultProperty: TPropSymbol; public constructor Create(const name: string); constructor CreateFwd(const name: string); procedure Define; procedure AddField(const name: string; &type: TTypeSymbol; visibility: TMemberVisibility); procedure AddProp(const name: string; &type: TTypeSymbol; visibility: TMemberVisibility; classScope: boolean; paramList: IParamList; readSpec, writeSpec: TSymbol); overload; procedure AddProp(info: TRttiInstanceProperty); overload; procedure AddMethod(const name: string; &type: TTypeSymbol; visibility: TMemberVisibility; classScope: boolean; paramList: IParamList); function DefineMethod(const name: string): TProcSymbol; function SymbolLookup(const name: string): TSymbol; function DescendsFrom(ancestor: TClassTypeSymbol): boolean; overload; function DescendsFrom(metaclass: TClass): boolean; overload; function CanDerefDot: boolean; override; function CanDerefArray: boolean; override; function GetSymbolTable: ISymbolTable; override; property forwarded: boolean read FForward; property parent: TClassTypeSymbol read FParentType write SetParent; property metaclass: TClass read FMetaclass write SetMetaclass; property fieldCount: integer read FFieldCount; property propCount: integer read FPropCount; property methodCount: integer read FMethodCount; property defaultProperty: TPropSymbol read FDefaultProperty; end; TArrayTypeSymbol = class(TTypeSymbol) private FBaseType: TTypeSymbol; FUBound: integer; FLBound: integer; public constructor Create(lBound, uBound: integer; baseType: TTypeSymbol); function CanDerefArray: boolean; override; property lBound: integer read FLBound; property ubound: integer read FUBound; property baseType: TTypeSymbol read FBaseType; end; TProcTypeSymbol = class(TTypeSymbol) private FParams: IParamList; FRetval: TTypeSymbol; FMethod: boolean; public constructor Create(const name: string; retval: TTypeSymbol; const params: IParamList; isMethod: boolean); property retval: TTypeSymbol read FRetval; property params: IParamList read FParams; property isMethod: boolean read FMethod; end; TLabelSymbol = class(TSymbol) private FUsed: boolean; public constructor Create(const name: string); procedure Use; property Used: boolean read FUsed; end; TSyntax = class; TUnitSymbol = class(TSymbol) private FPublicTable: ISymbolTable; FPrivateTable: ISymbolTable; FExternal: boolean; FLineMap: TDictionary<TSyntax, integer>; FDependencies: TStringList; public constructor Create(name: string; const publicTable, privateTable: ISymbolTable; isExternal: boolean = false); destructor Destroy; override; function SymbolLookup(const name: string): TSymbol; function Procs: TList<TProcSymbol>; procedure AddDependency(const name: string); property LineMap: TDictionary<TSyntax, integer> read FLineMap; property publics: ISymbolTable read FPublicTable; property privates: ISymbolTable read FPrivateTable; property IsExternal: boolean read FExternal; property Dependencies: TStringList read FDependencies; end; TSyntax = class private FKind: TSyntaxKind; public constructor Create(kind: TSyntaxKind); property kind: TSyntaxKind read FKind; end; TTypedSyntax = class(TSyntax) private FSem: integer; protected function GetType: TTypeSymbol; virtual; abstract; public function GetSelfValue: TVarSymbol; virtual; property &type: TTypeSymbol read GetType; property sem: integer read FSem write FSem; end; TValueSyntax = class(TTypedSyntax) private FValue: TValue; protected function GetType: TTypeSymbol; override; public constructor Create(const value: TValue); overload; constructor Create(const value: TToken); overload; constructor Create(); overload; property value: TValue read FValue; end; TBinOpSyntax = class(TTypedSyntax) private FOp: TBinOpKind; FRight: TTypedSyntax; FLeft: TTypedSyntax; protected function GetType: TTypeSymbol; override; public constructor Create(op: TBinOpKind; left, right: TTypedSyntax); destructor Destroy; override; procedure ResetLeft(value: TTypedSyntax); procedure ResetRight(value: TTypedSyntax); property op: TBinOpKind read FOp; property left: TTypedSyntax read FLeft; property right: TTypedSyntax read FRight; end; TBoolOpSyntax = class(TTypedSyntax) private FOp: TBoolOpKind; FRight: TTypedSyntax; FLeft: TTypedSyntax; protected function GetType: TTypeSymbol; override; public constructor Create(op: TBoolOpKind; left, right: TTypedSyntax); destructor Destroy; override; property op: TBoolOpKind read FOp; property left: TTypedSyntax read FLeft; property right: TTypedSyntax read FRight; end; TUnOpSyntax = class(TTypedSyntax) private FOp: TUnOpKind; FSub: TTypedSyntax; protected function GetType: TTypeSymbol; override; public constructor Create(op: TUnOpKind; sub: TTypedSyntax); destructor Destroy; override; procedure resetSub(value: TTypedSyntax); property op: TUnOpKind read FOp; property sub: TTypedSyntax read FSub; end; TVariableSyntax = class(TTypedSyntax) private FSymbol: TVarSymbol; protected function GetType: TTypeSymbol; override; public constructor Create(symbol: TVarSymbol); function GetSelfValue: TVarSymbol; override; property symbol: TVarSymbol read FSymbol; end; TTypeRefSyntax = class(TTypedSyntax) private FClass: TClassTypeSymbol; protected function GetType: TTypeSymbol; override; public constructor Create(base: TClassTypeSymbol); property &class: TClassTypeSymbol read FClass; end; TSyntaxList = class(TObjectList<TSyntax>); TBlockSyntax = class(TSyntax) private FChildren: TSyntaxList; public constructor Create; destructor Destroy; override; procedure Add(value: TSyntax); property children: TSyntaxList read FChildren; end; TAssignmentSyntax = class(TSyntax) private FRValue: TTypedSyntax; FLValue: TTypedSyntax; public constructor Create(lValue, rValue: TTypedSyntax); destructor Destroy; override; property lValue: TTypedSyntax read FLValue; property rValue: TTypedSyntax read fRValue; end; TLabelSyntax = class(TSyntax) private FName: string; public constructor Create(const name: string); property name: string read FName; end; TJumpSyntax = class(TSyntax) private FName: string; FConditional: boolean; public constructor Create(const name: string; conditional: boolean = false); property name: string read FName; property conditional: boolean read FConditional; //conditional jump jumps if BR = *false*, because that means that the //check failed and we're jumping over the success case end; TCallSyntax = class(TTypedSyntax) private FProc: TProcSymbol; FParams: TList<TTypedSyntax>; FSelfSymbol: TTypedSyntax; procedure SetSelf(const Value: TTypedSyntax); protected function GetType: TTypeSymbol; override; public constructor Create(proc: TProcSymbol; const params: TList<TTypedSyntax>); destructor Destroy; override; function GetSelfValue: TVarSymbol; override; procedure ClearSelf; property proc: TProcSymbol read FProc; property params: TList<TTypedSyntax> read FParams; property SelfSymbol: TTypedSyntax read FSelfSymbol write SetSelf; end; TDotSyntax = class(TTypedSyntax) private FLeft: TTypedSyntax; FRight: TTypedSyntax; protected function GetType: TTypeSymbol; override; public constructor Create(left, right: TTypedSyntax); destructor Destroy; override; function GetSelfValue: TVarSymbol; override; property left: TTypedSyntax read FLeft; property right: TTypedSyntax read FRight; end; TArrayPropSyntax = class(TTypedSyntax) private FSymbol: TVarSymbol; FBase: TDotSyntax; FParams: TList<TTypedSyntax>; protected function GetType: TTypeSymbol; override; public constructor Create(base: TDotSyntax; subscript: TTypedSyntax); destructor Destroy; override; function GetSelfValue: TVarSymbol; override; property base: TDotSyntax read FBase; property params: TList<TTypedSyntax> read FParams; end; TTryCallSyntax = class(TSyntax) private FJump: string; FRet: string; public constructor Create(const jump, ret: string); property jump: string read FJump; property ret: string read FRet; end; TFinallySyntax = class(TSyntax) private FRet: string; public constructor Create(const ret: string); property ret: string read FRet; end; TExceptBlockData = record cls: TClassTypeSymbol; sym: TVarSymbol; block: TBlockSyntax; end; TExceptSyntax = class(TSyntax) private FRet: string; public constructor Create(const ret: string); property ret: string read FRet; end; TExceptionLoadSyntax = class(TSyntax) private FSymbol: TVarSymbol; public constructor Create(sym: TVarSymbol); property symbol: TVarSymbol read FSymbol; end; TRaiseSyntax = class(TSyntax) private FObject: TVariableSyntax; public constructor Create(obj: TVariableSyntax); property obj: TVariableSyntax read FObject; end; TElemSyntax = class(TTypedSyntax) private FSymbol: TVarSymbol; FLeft: TTypedSyntax; FRight: TTypedSyntax; protected function GetType: TTypeSymbol; override; public constructor Create(left, right: TTypedSyntax); destructor Destroy; override; function GetSelfValue: TVarSymbol; override; property Left: TTypedSyntax read FLeft; property Right: TTypedSyntax read FRight; property symbol: TVarSymbol read FSymbol; end; TCastSyntax = class(TTypedSyntax) private FBase: TTypedSyntax; FType: TTypeSymbol; protected function GetType: TTypeSymbol; override; public constructor Create(base: TTypedSyntax; &type: TTypeSymbol); destructor Destroy; override; property Base: TTypedSyntax read FBase; end; TArraySyntax = class(TTypedSyntax) private FChildren: TBlockSyntax; FType: TTypeSymbol; function IsConstant: boolean; protected function GetType: TTypeSymbol; override; public constructor Create; destructor Destroy; override; procedure Add(value: TTypedSyntax); procedure Finalize; property subvalues: TBlockSyntax read FChildren; property constant: boolean read IsConstant; end; EParseError = class(Exception); TTokenQueue = TQueue<TToken>; TBlockList = class(TObjectList<TBlockSyntax>); function GetKeyword(const name: string): TTokenKind; function CreateSymbolTable(ownsObjects: boolean): ISymbolTable; function EmptyParamList(owns: boolean = true): IParamList; procedure AddNativeType(nativeType: TRttiType; new: TTypeSymbol); function NativeTypeDefined(value: TRttiType): boolean; function TypeOfNativeType(value: PTypeInfo): TTypeSymbol; function TypeOfRttiType(value: TRttiType): TTypeSymbol; function TypeOfValue(const value: TValue): TTypeSymbol; function BooleanType: TTypeSymbol; function FindNativeType(const name: string): TTypeSymbol; function MakeArrayPropType(base: TTypeSymbol): TTypeSymbol; procedure AddArrayType(value: TArrayTypeSymbol); procedure ResetTables; procedure CheckCompatibleTypes(left, right: TTypeSymbol; exact: boolean = false); procedure EnsureCompatibleTypes(left: TTypeSymbol; var right: TTypedSyntax; exact: boolean = false); implementation uses SyncObjs, rsEnex; var ParserFormatSettings: TFormatSettings; //minor hack type real = extended; function CheckCompatibleArrayTypes(left, right: TTypeSymbol): TTypeSymbol; forward; function MakeArrayType(base: TTypeSymbol): TTypeSymbol; forward; { TToken } constructor TToken.Create(kind: TTokenKind; row, column, length: integer; start: PChar); begin FKind := kind; FRow := row; FColumn := column; FStart := start; FLength := length; end; function TToken.GetOrigText: string; begin SetLength(result, FLength); Move(FStart^, result[1], FLength * sizeof(char)); end; function TToken.GetText: string; var otext: string; begin oText := GetOrigText; case kind of tkIdentifier: result := UpperCase(oText); tkChar: result := oText; tkString: result := AnsiDequotedStr(oText, ''''); else result := oText; end; end; { TSyntax } constructor TSyntax.Create(kind: TSyntaxKind); begin FKind := kind; end; { TValueSyntax } constructor TValueSyntax.Create(const value: TValue); begin inherited create(skValue); FValue := value; end; constructor TValueSyntax.Create(const value: TToken); begin case value.kind of tkInt: Create(StrToInt(value.GetText)); tkFloat: Create(TValue.From<Real>(StrToFloat(value.GetText, ParserFormatSettings))); tkChar, tkString: Create(value.GetText); else assert(false); end; end; constructor TValueSyntax.Create; begin Create(TValue.Empty); end; function TValueSyntax.GetType: TTypeSymbol; begin result := TypeOfValue(FValue); end; { TBinOpSyntax } constructor TBinOpSyntax.Create(op: TBinOpKind; left, right: TTypedSyntax); begin if (left.kind = skValue) and (right.kind <> skValue) and (op in [opPlus, opMult, opAnd, opOr, opXor]) and (left.&type.TypeInfo.Kind <> tkUString) then Create(op, right, left) else begin inherited Create(skBinOp); FOp := op; FLeft := left; FRight := right; end; end; destructor TBinOpSyntax.Destroy; begin FLeft.Free; FRight.Free; inherited Destroy; end; function TBinOpSyntax.GetType: TTypeSymbol; begin result := FLeft.GetType; //TODO: check for left: integer, right: float case end; procedure TBinOpSyntax.ResetLeft(value: TTypedSyntax); begin FLeft := value; end; procedure TBinOpSyntax.ResetRight(value: TTypedSyntax); begin FRight := value; end; { TBoolOpSyntax } function InvertBoolOp(op: TBoolOpKind): TBoolOpKind; begin case op of opGreaterEqual: result := opLessThan; opLessEqual: result := opGreaterThan; opGreaterThan: result := opLessEqual; opLessThan: result := opGreaterEqual; opEquals: result := opNotEqual; opNotEqual: result := opEquals; opBoolXor: result := opBoolXor; else raise EParseError.Create('Invalid boolean operation'); end; end; constructor TBoolOpSyntax.Create(op: TBoolOpKind; left, right: TTypedSyntax); begin if (left.kind = skValue) and (right.kind <> skValue) and (op in [opGreaterEqual, opLessEqual, opGreaterThan, opLessThan, opEquals, opNotEqual, opBoolXor]) then Create(InvertBoolOp(op), right, left) else begin inherited Create(skBoolOp); FOp := op; FLeft := left; FRight := right; end; end; destructor TBoolOpSyntax.Destroy; begin FLeft.Free; FRight.Free; inherited Destroy; end; function TBoolOpSyntax.GetType: TTypeSymbol; begin result := BooleanType; end; { TSymbol } constructor TSymbol.Create(const name: string; kind: TSymbolKind); begin FName := name; FKind := kind; end; function TSymbol.GetFullName: string; begin if FFullName = '' then FFullName := resolveFullName; result := FFullName end; function TSymbol.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; function TSymbol.ResolveFullName: string; begin result := FName; end; function TSymbol._AddRef: Integer; begin result := -1; end; function TSymbol._Release: Integer; begin result := -1; end; { TConstSymbol } constructor TConstSymbol.Create(const name: string; const value: TValue); begin if value.Kind = tkEnumeration then inherited Create(name, syEnum) else inherited Create(name, syConst); FValue := value; end; { TVarSymbol } constructor TVarSymbol.Create(const name: string; aType: TTypeSymbol; parent: TSymbol); begin inherited Create(name, syVariable); FName := name; FType := aType; FParent := parent; end; function TVarSymbol.ResolveFullName: string; begin if assigned(FParent) then result := FParent.fullName + '.' + UpperCase(FName) else result := UpperCase(FName); end; { TVariableSyntax } constructor TVariableSyntax.Create(symbol: TVarSymbol); begin assert(assigned(symbol)); inherited Create(skVariable); FSymbol := symbol; end; function TVariableSyntax.GetSelfValue: TVarSymbol; begin if FSymbol.&Type is TClassTypeSymbol then result := FSymbol { else if FSymbol.parent is TClassTypeSymbol then result := FSymbol.parent } else result := nil; end; function TVariableSyntax.GetType: TTypeSymbol; begin result := FSymbol.FType; end; { TUnitSymbol } procedure TUnitSymbol.AddDependency(const name: string); begin FDependencies.Add(name); end; constructor TUnitSymbol.Create(name: string; const publicTable, privateTable: ISymbolTable; isExternal: boolean = false); begin inherited Create(name, syUnit); FPublicTable := publicTable; FPrivateTable := privateTable; FExternal := isExternal; FLineMap := TDictionary<TSyntax, integer>.Create; FDependencies := TStringList.Create; end; destructor TUnitSymbol.Destroy; begin FDependencies.Free; FLineMap.Free; inherited Destroy; end; function TUnitSymbol.Procs: TList<TProcSymbol>; var cls: TClassTypeSymbol; classes: TList<TClassTypeSymbol>; exportSymbols: TList<TProcSymbol>; begin result := TEnex.Select<TSymbol, TProcSymbol>(self.privates.Values); classes := TEnex.Select<TSymbol, TClassTypeSymbol>(self.privates.Values); try for cls in classes do begin exportSymbols := TEnex.Select<TSymbol, TProcSymbol>(cls.FExportSymbols.Values); try result.addRange(exportSymbols); finally exportSymbols.Free; end; end; finally classes.Free; end; end; function TUnitSymbol.SymbolLookup(const name: string): TSymbol; begin if not FPublicTable.TryGetValue(name, result) then raise EParseError.CreateFmt('Symbol %s not found', [name]) end; { TUnOpSyntax } constructor TUnOpSyntax.Create(op: TUnOpKind; sub: TTypedSyntax); begin inherited Create(skUnOp); FOp := op; FSub := sub; end; destructor TUnOpSyntax.Destroy; begin FSub.Free; inherited Destroy; end; function TUnOpSyntax.GetType: TTypeSymbol; begin result := FSub.GetType; end; procedure TUnOpSyntax.resetSub(value: TTypedSyntax); begin FSub := value; end; { TTypeSymbol } function TTypeSymbol.CanDerefArray: boolean; begin result := false; end; function TTypeSymbol.CanDerefDot: boolean; begin result := false; end; constructor TTypeSymbol.Create(const name: string); begin inherited Create(name, syType); end; function TTypeSymbol.GetSymbolTable: ISymbolTable; begin raise EParseError.CreateFmt('Internal error: no symbol table available for type "%s"', [FName]); end; function TTypeSymbol.GetTypeInfo: PTypeInfo; begin if FTypeInfo = nil then raise EInsufficientRtti.CreateFmt('TypeInfo has not been generated for %s yet.', [FName]) else result := FTypeInfo; end; function TTypeSymbol.HasTypeInfo: boolean; begin result := assigned(FTypeInfo); end; { TClassTypeSymbol } constructor TClassTypeSymbol.Create(const name: string); begin inherited Create(name); FExportSymbols := CreateSymbolTable(false); FSymbols := CreateSymbolTable(true); end; constructor TClassTypeSymbol.CreateFwd(const name: string); begin Create(name); FForward := true; end; function TClassTypeSymbol.CanDerefArray: boolean; begin result := assigned(FDefaultProperty); end; function TClassTypeSymbol.CanDerefDot: boolean; begin result := true; end; procedure TClassTypeSymbol.CheckUnique(const name, kind: string); begin if FSymbols.ContainsKey(name) then raise EParseError.CreateFmt('Duplicate %s name %s', [kind, name]); end; procedure TClassTypeSymbol.AddSymbol(const name: string; visibility: TMemberVisibility; value: TVarSymbol; var counter: integer); var uName: string; begin uName := UpperCase(name); FSymbols.Add(uName, value); if visibility <> mvPrivate then FExportSymbols.Add(uName, value); inc(counter); value.FIndex := counter; value.FParent := self; end; procedure TClassTypeSymbol.AddField(const name: string; &type: TTypeSymbol; visibility: TMemberVisibility); begin CheckUnique(name, 'field'); AddSymbol(name, visibility, TFieldSymbol.Create(name, &type, visibility, self), FFieldCount); end; procedure TClassTypeSymbol.AddMethod(const name: string; &type: TTypeSymbol; visibility: TMemberVisibility; classScope: boolean; paramList: IParamList); var selfType: TTypeSymbol; begin CheckUnique(name, 'method'); //TODO: modify this to allow for overloading if classScope then selfType := nil else selfType := self; if paramList = nil then ParamList := EmptyParamList; paramList.Insert(0, TParamSymbol.Create('self', selfType, [])); AddSymbol(name, visibility, TProcSymbol.Create(name, &type, visibility, classScope, paramList, true, self), FMethodCount); end; procedure TClassTypeSymbol.AddProp(info: TRttiInstanceProperty); begin CheckUnique(name, 'property'); AddSymbol(info.Name, info.Visibility, TPropSymbol.Create(info.Name, info.Visibility, info.PropInfo, self), FPropCount); inc(FPropCount); end; procedure TClassTypeSymbol.AddProp(const name: string; &type: TTypeSymbol; visibility: TMemberVisibility; classScope: boolean; paramList: IParamList; readSpec, writeSpec: TSymbol); var counter: PInteger; begin if assigned(paramList) and (paramList.count > 0) then counter := @FArrayPropCount else counter := @FPropCount; CheckUnique(name, 'property'); AddSymbol(name, visibility, TPropSymbol.Create(name, &type, visibility, classScope, paramList, readSpec, writeSpec, self), counter^); inc(counter^); end; procedure TClassTypeSymbol.Define; begin assert(FForward); FForward := false; end; function TClassTypeSymbol.DefineMethod(const name: string): TProcSymbol; begin try result := FSymbols[name] as TProcSymbol; except raise EParseError.CreateFmt('Undefined method: %s.%s.', [FName, name]); end; if result.forwarded then result.Define else raise EParseError.CreateFmt('Method redeclared: %s.%s.', [FName, name]); end; function TClassTypeSymbol.DescendsFrom(ancestor: TClassTypeSymbol): boolean; var current: TClassTypeSymbol; begin current := self; while (current <> ancestor) and assigned(current) do current := current.FParentType; result := current = ancestor; end; function TClassTypeSymbol.DescendsFrom(metaclass: TClass): boolean; var current: TClassTypeSymbol; begin current := self; while (current.metaclass <> metaclass) and assigned(current) do current := current.FParentType; result := current.metaclass = metaclass; end; function TClassTypeSymbol.GetSymbolTable: ISymbolTable; begin result := FSymbols; end; procedure TClassTypeSymbol.SetMetaclass(const Value: TClass); begin assert(FMetaclass = nil); FMetaclass := Value; end; procedure TClassTypeSymbol.SetParent(const Value: TClassTypeSymbol); begin assert(FParentType = nil); FParentType := Value; FFieldCount := value.FFieldCount; FPropCount := value.FPropCount; FMethodCount := value.FMethodCount; end; function TClassTypeSymbol.SymbolLookup(const name: string): TSymbol; begin if not FSymbols.TryGetValue(name, result) then raise EParseError.CreateFmt('Symbol %s not found', [name]) end; { TFieldSymbol } constructor TFieldSymbol.Create(const name: string; aType: TTypeSymbol; visibility: TMemberVisibility; parent: TSymbol); begin FVisibility := visibility; inherited Create(name, aType, parent); end; { TParamSymbol } constructor TParamSymbol.Create(const name: string; aType: TTypeSymbol; flags: TParamFlags); begin inherited Create(name, aType, nil); FFlags := flags; end; destructor TParamSymbol.Destroy; begin inherited; end; { TPropSymbol } constructor TPropSymbol.Create(const name: string; &type: TTypeSymbol; visibility: TMemberVisibility; classScope: boolean; const paramList: IParamList; readSpec, writeSpec: TSymbol; parent: TSymbol); begin inherited Create(name, &type, parent); FKind := syProp; FVisibility := visibility; FClassScope := classScope; FParamList := paramList; FReadSpec := readSpec; FWriteSpec := writeSpec; VerifyReadWriteCompat; end; constructor TPropSymbol.Create(const name: string; visibility: TMemberVisibility; info: PPropInfo; parent: TSymbol); begin inherited Create(name, TypeOfNativeType(info.PropType^), parent); FVisibility := visibility; FKind := syProp; FPropinfo := info; end; procedure TPropSymbol.VerifyReadWriteCompat; var match: boolean; i: integer; left, right: TParamSymbol; begin assert(assigned(FReadSpec) or (assigned(FWriteSpec))); if assigned(FReadSpec) then begin if FParamList.Count > 0 then begin match := (FReadSpec is TProcSymbol) and (TProcSymbol(FReadSpec).FParamList.Count = FParamList.Count + 1) and AnsiSameText(TProcSymbol(FReadSpec).FParamList[0].name, 'self'); if Match then begin for i := 0 to FParamList.Count - 1 do begin left := FParamList[i]; right:= TProcSymbol(FReadSpec).FParamList[i + 1]; CheckCompatibleTypes(left.FType, right.FType, true); match := match and (left.flags = right.flags); end; match := match and (TProcSymbol(FReadSpec).&type = (self.&type as TArrayTypeSymbol).baseType); end; end else if FReadSpec is TFieldSymbol then match := TFieldSymbol(FReadSpec).&Type = self.&Type else match := false; //TODO: implement this if not match then raise EParseError.Create('Read specifier must match property type'); end; if assigned(FWriteSpec) then begin if FParamList.Count > 0 then begin match := (FWriteSpec is TProcSymbol) and (TProcSymbol(FWriteSpec).FParamList.Count = FParamList.Count + 2) and AnsiSameText(TProcSymbol(FWriteSpec).FParamList[0].name, 'self'); if Match then begin for i := 0 to FParamList.Count - 1 do begin left := FParamList[i]; right:= TProcSymbol(FWriteSpec).FParamList[i + 1]; CheckCompatibleTypes(left.FType, right.FType, true); match := match and (left.flags = right.flags); end; match := match and (TProcSymbol(FWriteSpec).paramList.Last.&Type = (self.&type as TArrayTypeSymbol).baseType); end; end else if FWriteSpec is TFieldSymbol then match := TFieldSymbol(FWriteSpec).&Type = self.&Type else match := false; //TODO: implement this if not match then raise EParseError.Create('Write specifier must match property type'); end; end; { TProcSymbol } constructor TProcSymbol.Create(const name: string; &type: TTypeSymbol; visibility: TMemberVisibility; classScope: boolean; const paramList: IParamList; forwarded: boolean; parent: TSymbol); var param: TParamSymbol; begin inherited Create(name, &type, parent); FKind := syProc; FVisibility := visibility; FClassScope := classScope; if assigned(paramList) then for param in paramList do param.FParent := self; FParamList := paramList; FSymbolTable := CreateSymbolTable(true); FForwarded := forwarded; end; destructor TProcSymbol.Destroy; begin FSyntax.Free; inherited Destroy; end; procedure TProcSymbol.Define; begin assert(FForwarded); FForwarded := false; end; procedure TProcSymbol.SetSyntax(const Value: TBlockSyntax); begin assert(FSyntax = nil); FSyntax := Value; end; { TArrayTypeSymbol } function TArrayTypeSymbol.CanDerefArray: boolean; begin result := true; end; constructor TArrayTypeSymbol.Create(lBound, uBound: integer; baseType: TTypeSymbol); begin inherited Create('ARRAYOF*' + baseType.name); FLBound := lBound; FUBound := uBound; FBaseType := baseType; end; { TLabelSymbol } constructor TLabelSymbol.Create(const name: string); begin inherited Create(name, syLabel); end; procedure TLabelSymbol.Use; begin if FUsed then raise EParseError.CreateFmt('Label %s reused', [FName]); FUsed := true; end; { TProcTypeSymbol } constructor TProcTypeSymbol.Create(const name: string; retval: TTypeSymbol; const params: IParamList; isMethod: boolean); begin inherited Create(name); FRetval := retval; FParams := params; FMethod := isMethod; end; { TTypedSyntax } function TTypedSyntax.GetSelfValue: TVarSymbol; begin result := nil; end; { TBlockSyntax } constructor TBlockSyntax.Create; begin inherited Create(skBlock); FChildren := TSyntaxList.Create; FChildren.OwnsObjects := true; end; destructor TBlockSyntax.Destroy; begin FChildren.free; inherited Destroy; end; procedure TBlockSyntax.Add(value: TSyntax); begin FChildren.Add(value); end; { TAssignmentSyntax } constructor TAssignmentSyntax.Create(lValue, rValue: TTypedSyntax); begin inherited Create(skAssign); FLValue := lValue; FRValue := rValue; end; destructor TAssignmentSyntax.Destroy; begin FLValue.Free; FRValue.Free; inherited; end; { TLabelSyntax } constructor TLabelSyntax.Create(const name: string); begin inherited Create(skLabel); FName := name; end; { TJumpSyntax } constructor TJumpSyntax.Create(const name: string; conditional: boolean = false); begin inherited Create(skJump); FName := name; FConditional := conditional; end; { TCallSyntax } constructor TCallSyntax.Create(proc: TProcSymbol; const params: TList<TTypedSyntax>); begin inherited Create(skCall); FProc := proc; FParams := params; end; destructor TCallSyntax.Destroy; begin FSelfSymbol.Free; FParams.Free; inherited; end; function TCallSyntax.GetSelfValue: TVarSymbol; begin if FProc.FType is TClassTypeSymbol then result := FProc else result := nil; end; function TCallSyntax.GetType: TTypeSymbol; begin result := FProc.FType; end; procedure TCallSyntax.SetSelf(const Value: TTypedSyntax); begin assert(FSelfSymbol = nil); FSelfSymbol := Value; end; procedure TCallSyntax.ClearSelf; begin assert(assigned(FSelfSymbol)); FreeAndNil(FSelfSymbol); end; { TTryCallSyntax } constructor TTryCallSyntax.Create(const jump, ret: string); begin inherited Create(skTryCall); FJump := jump; FRet := ret; end; { TFinallySyntax } constructor TFinallySyntax.Create(const ret: string); begin inherited Create(skFinally); FRet := ret; end; { TExceptSyntax } constructor TExceptSyntax.Create(const ret: string); begin inherited Create(skExcept); FRet := ret; end; { TRaiseSyntax } constructor TRaiseSyntax.Create(obj: TVariableSyntax); begin inherited Create(skRaise); FObject := obj; end; { TElemSyntax } constructor TElemSyntax.Create(left, right: TTypedSyntax); var lName, rName: string; begin assert(left.kind in [skVariable, skDot]); inherited Create(skElem); FLeft := left; FRight := right; if (left.kind = skVariable) then lName := TVariableSyntax(FLeft).FSymbol.name else lName := (TDotSyntax(FLeft).FRight as TVariableSyntax).FSymbol.name; case right.kind of skVariable: rName := TVariableSyntax(FRight).FSymbol.name; skValue: rName := TValueSyntax(FRight).FValue.ToString; skElem: rName := TElemSyntax(FRight).FSymbol.name; skArrayProp: rName := TArrayPropSyntax(FRight).FSymbol.name; else assert(false); end; FSymbol := TVarSymbol.Create(format('%s[%s]', [lName, rName]), self.GetType, nil); end; destructor TElemSyntax.Destroy; begin FSymbol.Free; FLeft.Free; FRight.Free; inherited Destroy; end; function TElemSyntax.GetSelfValue: TVarSymbol; begin if FSymbol.FType is TClassTypeSymbol then result := FSymbol else result := nil; end; function TElemSyntax.GetType: TTypeSymbol; begin result := (FLeft.&type as TArrayTypeSymbol).FBaseType end; { TTypeRefSyntax } constructor TTypeRefSyntax.Create(base: TClassTypeSymbol); begin inherited Create(skType); FClass := base; end; function TTypeRefSyntax.GetType: TTypeSymbol; begin result := FClass; end; { TExceptionLoadSyntax } constructor TExceptionLoadSyntax.Create(sym: TVarSymbol); begin inherited Create(skELoad); FSymbol := sym; end; { TDotSyntax } constructor TDotSyntax.Create(left, right: TTypedSyntax); begin inherited Create(skDot); FLeft := left; FRight := right; if FRight.kind = skCall then TCallSyntax(FRight).ClearSelf; end; destructor TDotSyntax.Destroy; begin FLeft.Free; FRight.Free; inherited; end; function TDotSyntax.GetSelfValue: TVarSymbol; begin result := FRight.GetSelfValue; end; function TDotSyntax.GetType: TTypeSymbol; begin result := FRight.&type; end; { TCastSyntax } constructor TCastSyntax.Create(base: TTypedSyntax; &type: TTypeSymbol); begin inherited Create(skCast); FBase := base; FType := &type; end; destructor TCastSyntax.Destroy; begin FBase.Free; inherited Destroy; end; function TCastSyntax.GetType: TTypeSymbol; begin result := FType; end; { TArrayPropSyntax } constructor TArrayPropSyntax.Create(base: TDotSyntax; subscript: TTypedSyntax); var lName, rName: string; begin inherited Create(skArrayProp); FBase := base; FParams := TObjectList<TTypedSyntax>.Create; FParams.Add(subscript); lName := (base.FRight as TVariableSyntax).FSymbol.name; case subscript.kind of skVariable: rName := TVariableSyntax(subscript).FSymbol.name; skValue: rName := TValueSyntax(subscript).FValue.ToString; skElem: rName := TElemSyntax(subscript).FSymbol.name; skArrayProp: rName := TArrayPropSyntax(subscript).FSymbol.name; else assert(false); end; FSymbol := TVarSymbol.Create(format('%s[%s]', [lName, rName]), self.GetType, nil); end; destructor TArrayPropSyntax.Destroy; begin FSymbol.Free; FParams.Free; FBase.Free; inherited Destroy; end; function TArrayPropSyntax.GetSelfValue: TVarSymbol; begin result := FSymbol; end; function TArrayPropSyntax.GetType: TTypeSymbol; begin result := (((FBase.FRight as TVariableSyntax).FSymbol as TPropSymbol).FType as TArrayTypeSymbol).basetype; end; { TArraySyntax } constructor TArraySyntax.Create; begin inherited Create(skArray); FChildren := TBlockSyntax.Create; end; destructor TArraySyntax.Destroy; begin FChildren.Free; inherited Destroy; end; procedure TArraySyntax.Finalize; var baseType, newType: TTypeSymbol; i: integer; begin if FChildren.children.count = 0 then begin FType := TypeOfNativeType(nil); Exit; end; baseType := (FChildren.children[0] as TTypedSyntax).&type; for i := 1 to FChildren.children.Count - 1 do begin newType := CheckCompatibleArrayTypes(baseType, (FChildren.children[i] as TTypedSyntax).&type); if newType = nil then raise EParseError.CreateFmt('Incompatible types: %s and %s', [baseType, (FChildren.children[i] as TTypedSyntax).&type]) else baseType := newType; end; FType := MakeArrayType(baseType); end; function TArraySyntax.GetType: TTypeSymbol; begin assert(assigned(FType)); result := FType; end; function TArraySyntax.IsConstant: boolean; var i: integer; begin result := true; for i := 0 to FChildren.children.Count - 1 do result := result and (FChildren.children[i].kind = skValue); end; procedure TArraySyntax.Add(value: TTypedSyntax); begin FChildren.Add(value); end; { Classless } type TSymbolTable = class(TObjectDictionary<string, TSymbol>, ISymbolTable) private FRefCount: integer; function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function GetItem(const Key: string): TSymbol; procedure SetItem(const Key: string; const Value: TSymbol); function Values: TEnumerable<TSymbol>; function Where(filter: TFunc<string, TSymbol, boolean>): TList<TPair<string, TSymbol>>; function KeysWhereValue(filter: TPredicate<TSymbol>): TStringList; function Count: integer; public destructor Destroy; override; end; TParamList = class(TObjectList<TParamSymbol>, IParamList) private FRefCount: integer; function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function Count: integer; procedure SetOwnsObjects(value: boolean); function GetItem(Index: Integer): TParamSymbol; procedure SetItem(Index: Integer; const Value: TParamSymbol); function GetEnumerator: TEnumerator<TParamSymbol>; procedure AddRange(Collection: IParamList); end; function CreateSymbolTable(ownsObjects: boolean): ISymbolTable; begin if ownsObjects then result := TSymbolTable.Create([doOwnsValues]) else result := TSymbolTable.Create; end; function EmptyParamList(owns: boolean = true): IParamList; begin result := TParamList.Create; result.OwnsObjects := owns; end; function CheckSubtype(left, right: TTypeSymbol): boolean; begin result := false; if (left = TypeOfNativeType(TypeInfo(Real))) and (right = TypeOfNativeType(TypeInfo(Integer))) then result := true else if (left is TClassTypeSymbol) then begin if (right is TClassTypeSymbol) then result := TClassTypeSymbol(right).DescendsFrom(TClassTypeSymbol(left)) else if right = TypeOfNativeType(nil) then result := true; end; //TODO: add more rules end; function CheckCompatibleArrayTypes(left, right: TTypeSymbol): TTypeSymbol; begin if (left = right) or CheckSubtype(left, right) then result := left else if CheckSubtype(right, Left) then result := right else result := nil; end; procedure CheckCompatibleTypes(left, right: TTypeSymbol; exact: boolean); var good: boolean; begin assert(assigned(left)); if right = nil then raise EParseError.CreateFmt('Incompatible types: "%s" and "Procedure or untyped value"', [left.name]); good := false; if left = right then good := true else if not exact then good := CheckSubtype(left, right); if not good then raise EParseError.CreateFmt('Incompatible types: "%s" and "%s"', [left.name, right.name]); end; procedure EnsureCompatibleTypes(left: TTypeSymbol; var right: TTypedSyntax; exact: boolean = false); begin CheckCompatibleTypes(left, right.&type, exact); if exact then Exit; if left <> right.&type then right := TCastSyntax.Create(right, left); end; var LContext: TRttiContext; Sync: TMultiReadExclusiveWriteSynchronizer; LTypeTable: TDictionary<TRttiType, TTypeSymbol>; LArrayPropTable: TObjectDictionary<string, TTypeSymbol>; LArrayTypeTable: TDictionary<string, TTypeSymbol>; LFreeList: TObjectList<TTypeSymbol>; procedure AddNativeType(nativeType: TRttiType; new: TTypeSymbol); begin LTypeTable.Add(nativeType, new); end; function NativeTypeDefined(value: TRttiType): boolean; begin result := LTypeTable.ContainsKey(value); end; function TypeOfRttiType(value: TRttiType): TTypeSymbol; begin result := LTypeTable[value]; end; function TypeOfNativeType(value: PTypeInfo): TTypeSymbol; begin result := TypeOfRttiType(LContext.GetType(value)); end; function TypeOfValue(const value: TValue): TTypeSymbol; begin result := TypeOfNativeType(value.TypeInfo); end; var LBoolType: TTypeSymbol = nil; function BooleanType: TTypeSymbol; begin if not assigned(LBoolType) then LBoolType := TypeOfNativeType(TypeInfo(boolean)); result := LBoolType; end; function FindNativeType(const name: string): TTypeSymbol; begin result := TEnex.FirstWhereOrDefault<TTypeSymbol>(LTypeTable.Values, function(value: TTypeSymbol): boolean begin result := AnsiSameText(value.Name, name); end, nil); if result = nil then raise EParseError.CreateFmt('Type "%s" has not been imported.', [name]); end; procedure AddArrayType(value: TArrayTypeSymbol); begin if LArrayTypeTable.ContainsKey(UpperCase(value.name)) then raise EParseError.Create('Duplicate array type'); LArrayTypeTable.Add(UpperCase(value.name), value); end; function MakeArrayType(base: TTypeSymbol): TTypeSymbol; var name: string; begin name := 'ARRAYOF*' + UpperCase(base.name); TMonitor.Enter(LArrayTypeTable); try if not LArrayTypeTable.TryGetValue(name, Result) then begin result := TArrayTypeSymbol.Create(0, 0, base); LArrayTypeTable.Add(name, result); LFreeList.Add(result); end; finally TMonitor.Exit(LArrayTypeTable); end; end; function MakeArrayPropType(base: TTypeSymbol): TTypeSymbol; var name: string; begin name := 'ARRAYPROP*' + UpperCase(base.name); TMonitor.Enter(LArrayPropTable); try if not LArrayPropTable.TryGetValue(name, Result) then begin result := TArrayTypeSymbol.Create(0, 0, base); LArrayPropTable.Add(name, result) end; finally TMonitor.Exit(LArrayPropTable); end; end; procedure ResetTables; begin LTypeTable.Free; LArrayTypeTable.Free; LArrayPropTable.Free; LFreeList.Free; LTypeTable := TObjectDictionary<TRttiType, TTypeSymbol>.Create([doOwnsValues]); LArrayPropTable := TObjectDictionary<string, TTypeSymbol>.Create([doOwnsValues]); LArrayTypeTable := TDictionary<string, TTypeSymbol>.Create(); LFreeList := TObjectList<TTypeSymbol>.Create(true); LBoolType := nil; end; const KEYWORD_COUNT = 63; KEYWORD_TABLE: array[1..KEYWORD_COUNT] of TKeywordPair = ( (keyword: 'AND'; token: tkAnd), (keyword: 'ARRAY'; token: tkArray), (keyword: 'AS'; token: tkAs), (keyword: 'BEGIN'; token: tkBegin), (keyword: 'BREAK'; token: tkBreak), (keyword: 'CASE'; token: tkCase), (keyword: 'CLASS'; token: tkClass), (keyword: 'CONST'; token: tkConst), (keyword: 'CONSTRUCTOR'; token: tkConstructor), (keyword: 'CONTINUE'; token: tkContinue), (keyword: 'DESTRUCTOR'; token: tkDestructor), (keyword: 'DIV'; token: tkDiv), (keyword: 'DO'; token: tkDo), (keyword: 'DOWNTO'; token: tkDownTo), (keyword: 'ELSE'; token: tkElse), (keyword: 'END'; token: tkEnd), (keyword: 'EXCEPT'; token: tkExcept), (keyword: 'EXIT'; token: tkExit), {(keyword: 'EXTERNAL'; token: tkExternal),} (keyword: 'FINALLY'; token: tkFinally), (keyword: 'FOR'; token: tkFor), (keyword: 'FORWARD'; token: tkForward), (keyword: 'FUNCTION'; token: tkFunction), (keyword: 'GOTO'; token: tkGoto), (keyword: 'IF'; token: tkIf), (keyword: 'IMPLEMENTATION'; token: tkImplementation), (keyword: 'IN'; token: tkIn), (keyword: 'INHERITED'; token: tkInherited), (keyword: 'INTERFACE'; token: tkInterface), (keyword: 'IS'; token: tkIs), (keyword: 'LABEL'; token: tkLabel), (keyword: 'MOD'; token: tkMod), (keyword: 'NIL'; token: tkNil), (keyword: 'NOT'; token: tkNot), (keyword: 'OBJECT'; token: tkObject), (keyword: 'OF'; token: tkOf), (keyword: 'ON'; token: tkOn), (keyword: 'OR'; token: tkOr), (keyword: 'OUT'; token: tkOut), (keyword: 'OVERRIDE'; token: tkOverride), (keyword: 'DEFAULT'; token: tkDefault), (keyword: 'PRIVATE'; token: tkPrivate), (keyword: 'PROCEDURE'; token: tkProcedure), (keyword: 'PROGRAM'; token: tkProgram), (keyword: 'PROPERTY'; token: tkProperty), (keyword: 'PROTECTED'; token: tkProtected), (keyword: 'PUBLIC'; token: tkPublic), (keyword: 'RAISE'; token: tkRaise), (keyword: 'RECORD'; token: tkRecord), (keyword: 'REPEAT'; token: tkRepeat), (keyword: 'SET'; token: tkSet), (keyword: 'SHL'; token: tkShl), (keyword: 'SHR'; token: tkShr), (keyword: 'THEN'; token: tkThen), (keyword: 'TO'; token: tkTo), (keyword: 'TRY'; token: tkTry), (keyword: 'TYPE'; token: tkType), (keyword: 'UNIT'; token: tkUnit), (keyword: 'UNTIL'; token: tkUntil), (keyword: 'USES'; token: tkUses), (keyword: 'VAR'; token: tkVar), (keyword: 'VIRTUAL'; token: tkVirtual), (keyword: 'WHILE'; token: tkWhile), (keyword: 'XOR'; token: tkXor)); //turned "keywords" chr and ord into compiler magic functions var LKeywords: TDictionary<string, TTokenKind>; function GetKeyword(const name: string): TTokenKind; begin if not LKeywords.TryGetValue(name, result) then result := tkIdentifier; end; var pair: TKeywordPair; { TSymbolTable } function TSymbolTable.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; function TSymbolTable._AddRef: Integer; begin Result := TInterlocked.Increment(FRefCount); end; function TSymbolTable._Release: Integer; begin Result := TInterlocked.Decrement(FRefCount); if Result = 0 then Destroy; end; function TSymbolTable.Count: integer; begin result := inherited Count; end; destructor TSymbolTable.Destroy; var list: TStringList; key: string; pair: TPair<string, TSymbol>; begin list := TStringList.Create; try for pair in self do if pair.Value.FKind = syType then list.Add(pair.Key); for key in list do self.ExtractPair(key); finally list.Free; end; inherited; end; function TSymbolTable.GetItem(const Key: string): TSymbol; begin result := self[key]; end; procedure TSymbolTable.SetItem(const Key: string; const Value: TSymbol); begin self[key] := value; end; function TSymbolTable.Values: TEnumerable<TSymbol>; begin result := inherited Values; end; function TSymbolTable.KeysWhereValue(filter: TPredicate<TSymbol>): TStringList; var pair: TPair<string, TSymbol>; begin result := TStringList.Create; try for pair in self do if filter(pair.Value) then result.Add(pair.Key); except result.Free; raise; end; end; function TSymbolTable.Where( filter: TFunc<string, TSymbol, boolean>): TList<TPair<string, TSymbol>>; var pair: TPair<string, TSymbol>; begin result := TList<TPair<string, TSymbol>>.Create; try for pair in self do if filter(pair.Key, pair.Value) then result.Add(pair); except result.Free; raise; end; end; { TParamList } procedure TParamList.AddRange(Collection: IParamList); var param: TParamSymbol; begin for param in collection do add(param); end; function TParamList.Count: integer; begin result := inherited Count; end; function TParamList.GetEnumerator: TEnumerator<TParamSymbol>; begin result := inherited GetEnumerator; end; function TParamList.GetItem(Index: Integer): TParamSymbol; begin result := self[index]; end; procedure TParamList.SetItem(Index: Integer; const Value: TParamSymbol); begin self[index] := value; end; procedure TParamList.SetOwnsObjects(value: boolean); begin self.OwnsObjects := value; end; function TParamList.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; function TParamList._AddRef: Integer; begin Result := TInterlocked.Increment(FRefCount); end; function TParamList._Release: Integer; begin Result := TInterlocked.Decrement(FRefCount); if Result = 0 then Destroy; end; initialization LKeywords := TDictionary<string, TTokenKind>.Create; for pair in KEYWORD_TABLE do lKeywords.Add(pair.keyword, pair.token); LTypeTable := TObjectDictionary<TRttiType, TTypeSymbol>.Create([doOwnsValues]); LArrayPropTable := TObjectDictionary<string, TTypeSymbol>.Create([doOwnsValues]); LArrayTypeTable := TDictionary<string, TTypeSymbol>.Create(); Sync := TMultiReadExclusiveWriteSynchronizer.Create; LFreeList := TObjectList<TTypeSymbol>.Create(true); ParserFormatSettings := FormatSettings; ParserFormatSettings.DecimalSeparator := '.'; finalization Sync.Free; lKeywords.Free; LTypeTable.Free; LArrayTypeTable.Free; LArrayPropTable.Free; LFreeList.Free; end.
{$I XLib.inc } Unit XECtrls; Interface Uses Classes, Graphics, Controls, DB, DBCtrls, ExtCtrls, Messages, XCtrls, EtvList, EtvContr, EtvLook, EtvGrid, XMisc, EtvRxCtl; type { TXEDBRadioGroup } TXEDBRadioGroup = class(TDBRadioGroup) private procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; protected procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; end; { TXDEBRadioGroup } TXEDBCheckBox = class(TDBCheckBox) private procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; protected procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; end; { TXEDBEdit } TXEDBEdit = class(TEtvDBEdit) private procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; end; { TXEDBDateEdit } TXEDBDateEdit = class(TEtvDBDateEdit) private procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; end; { TXEDBCombo } TXEDBCombo=class(TEtvDBCombo) private procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; end; TXEDBMemo = class(TDBMemo) private procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; end; { TXEDBLookupCombo } TXEDBLookupCombo = class(TEtvDBLookupCombo) private FIsContextOpen: Boolean; FStoreDataSet: TDataSet; FStoreColor: TColor; FStoreHeadColor:TColor; procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS; protected procedure ReadState(Reader: TReader); override; procedure Paint; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure XOnTimer(Sender: TObject); public constructor Create(AOwner: TComponent); override; end; { TXEDBInplaceLookUpCombo } TXEDBInplaceLookUpCombo = class(TEtvInplaceLookupCombo) private FIsContextOpen: Boolean; FStoreDataSet: TDataSet; FStoreColor: TColor; FStoreHeadColor:TColor; procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS; protected procedure ReadState(Reader: TReader); override; procedure Paint; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure SetHideFlag(Value: Boolean); procedure XOnTimer(Sender: TObject); public constructor Create(AOwner: TComponent); override; end; { TXEDbGrid } TXEDbGrid = class(TEtvDbGrid) private FIsStoredDataSource: Boolean; FStoredDataSource: TDataSource; FStoredControlSource: TDataSource; FStoredColumn: Integer; procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS; procedure WMChangePageSource(var Msg: TMessage); message WM_ChangePageSource; procedure WMChangeControlSource(var Msg: TMessage); message WM_ChangeControlSource; procedure ReadDataSource(Reader: TReader); procedure WriteDataSource(Writer: TWriter); function GetDataSource: TDataSource; procedure SetDataSource(Value: TDataSource); procedure ReadIsDataSource(Reader: TReader); procedure WriteIsDataSource(Writer: TWriter); protected function CreateInplaceLookupCombo:TEtvInplaceLookupCombo; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure DefineProperties(Filer: TFiler);override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure ColEnter; override; public MarkGridColor: TColor; MarkGridFontColor: TColor; constructor Create(AOwner: TComponent); override; procedure SetDefaultGridColor(Sender: TObject; Field: TField; var Color: TColor); procedure SetDefaultGridFont(Sender: TObject; Field: TField; Font: TFont); procedure FormatColumns(AsInDataBase: boolean); published property DataSource read GetDataSource write SetDataSource stored False; end; var XNotifyEvent: TXNotifyEvent; Implementation Uses TypInfo, Windows, Dialogs, Forms, DBTables, DBGrids, LnTables, EtvBor, LnkSet, EtvDB, FVisDisp, EtvPopup, SysUtils, XTFC, XDBTFC, XForms, XDBMisc, LnkMisc, EtvTemp, EtvOther, TlsForm, ETVPas; var aTick: byte; { TXEDBCheckBox } Procedure TXEDBCheckBox.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; KeyReturn(Self,Key,Shift); end; Procedure TXEDBCheckBox.WMSetFocus(var Message: TWMSetFocus); begin XNotifyEvent.GoSpellChild(GetParentForm(Self), xeChangeParams, DataSource, opInsert); // CreateCaret(Handle, 0, Font.Size div 2, Height); // ShowCaret(Handle); end; procedure TXEDBCheckBox.Notification(AComponent: TComponent; Operation: TOperation); begin if AComponent is TXNotifyEvent then case TXNotifyEvent(AComponent).SpellEvent of xeGetFirstXControl: TXNotifyEvent(AComponent).GoEqual(Self, Operation); xeIsThisLink: if Assigned(DataSource) and (DataSource = TXNotifyEvent(AComponent).SpellChild) then begin TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; xeSetParams: begin if Operation = opInsert then begin TXEDBLookupCombo(TXNotifyEvent(AComponent).SpellChild).KeyValue:=Self.Text; TDBLookupComboBoxBorland(TXNotifyEvent(AComponent).SpellChild).FDataList.KeyValue:=Self.Text; end else begin Field.AsString:= TDBLookupComboBoxBorland(TXNotifyEvent(AComponent).SpellChild).FDataList.KeyValue; end; TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; end else Inherited Notification(AComponent, Operation); end; { TXEDBRadioGroup } Procedure TXEDBRadioGroup.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; KeyReturn(Self,Key,Shift); end; Procedure TXEDBRadioGroup.WMSetFocus(var Message: TWMSetFocus); begin XNotifyEvent.GoSpellChild(GetParentForm(Self), xeChangeParams, DataSource, opInsert); end; procedure TXEDBRadioGroup.Notification(AComponent: TComponent; Operation: TOperation); begin if AComponent is TXNotifyEvent then case TXNotifyEvent(AComponent).SpellEvent of xeGetFirstXControl: TXNotifyEvent(AComponent).GoEqual(Self, Operation); xeIsThisLink: if Assigned(DataSource) and (DataSource = TXNotifyEvent(AComponent).SpellChild) then begin TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; xeSetParams: begin if Operation = opInsert then begin TXEDBLookupCombo(TXNotifyEvent(AComponent).SpellChild).KeyValue:=Self.Text; TDBLookupComboBoxBorland(TXNotifyEvent(AComponent).SpellChild).FDataList.KeyValue:=Self.Text; end else begin Field.AsString:= TDBLookupComboBoxBorland(TXNotifyEvent(AComponent).SpellChild).FDataList.KeyValue; end; TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; end else Inherited Notification(AComponent, Operation); end; { TXEDBEdit } Procedure TXEDBEdit.WMSetFocus(var Message: TWMSetFocus); (* const FirstFFF:boolean=true; I: integer=0; var FFF: TextFile; UUU: String; *) begin Inherited; {****************************************************** if FirstFFF then begin AssignFile(FFF,'c:\temp\tempik.tmp'); Rewrite(FFF); FirstFFF:=false; end else begin AssignFile(FFF,'c:\temp\tempik.tmp'); Append(FFF); end; Inc(I); if Assigned(DataSource) then UUU:=DataSource.Name else UUU:='нет'; writeln(FFF,IntToStr(I)+' '+UUU); CloseFile(FFF); {******************************************************} XNotifyEvent.GoSpellChild(GetParentForm(Self), xeChangeParams, DataSource, opInsert); CreateCaret(Handle, 0, Font.Size div 4, Abs(Font.Height)+4); ShowCaret(Handle); end; Procedure TXEDBEdit.Notification(AComponent: TComponent; Operation: TOperation); begin if AComponent is TXNotifyEvent then case TXNotifyEvent(AComponent).SpellEvent of xeGetFirstXControl: TXNotifyEvent(AComponent).GoEqual(Self, Operation); xeIsThisLink: if Assigned(DataSource) and (DataSource = TXNotifyEvent(AComponent).SpellChild) then begin TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; xeSetParams: begin if Operation = opInsert then begin TXEDBLookupCombo(TXNotifyEvent(AComponent).SpellChild).KeyValue:=Self.Text; TDBLookupComboBoxBorland(TXNotifyEvent(AComponent).SpellChild).FDataList.KeyValue:=Self.Text; end else begin Field.AsString:= TDBLookupComboBoxBorland(TXNotifyEvent(AComponent).SpellChild).FDataList.KeyValue; end; TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; end else Inherited Notification(AComponent, Operation); end; { TXEDBDateEdit } Procedure TXEDBDateEdit.WMSetFocus(var Message: TWMSetFocus); begin Inherited; XNotifyEvent.GoSpellChild(GetParentForm(Self), xeChangeParams, DataSource, opInsert); CreateCaret(Handle, 0, Font.Size div 4, Abs(Font.Height)+4); ShowCaret(Handle); end; Procedure TXEDBDateEdit.Notification(AComponent: TComponent; Operation: TOperation); begin if AComponent is TXNotifyEvent then case TXNotifyEvent(AComponent).SpellEvent of xeGetFirstXControl: TXNotifyEvent(AComponent).GoEqual(Self, Operation); xeIsThisLink: if Assigned(DataSource)and (DataSource = TXNotifyEvent(AComponent).SpellChild) then begin TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; end else Inherited Notification(AComponent, Operation); end; { TXEDBCombo } Procedure TXEDBCombo.WMSetFocus(var Message: TWMSetFocus); begin Inherited; XNotifyEvent.GoSpellChild(GetParentForm(Self), xeChangeParams, DataSource, opInsert); end; Procedure TXEDBCombo.Notification(AComponent: TComponent; Operation: TOperation); begin if AComponent is TXNotifyEvent then case TXNotifyEvent(AComponent).SpellEvent of xeGetFirstXControl: TXNotifyEvent(AComponent).GoEqual(Self, Operation); xeIsThisLink: if Assigned(DataSource)and (DataSource = TXNotifyEvent(AComponent).SpellChild) then begin TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; end else Inherited Notification(AComponent, Operation); end; Procedure TXEDBMemo.WMSetFocus(var Message: TWMSetFocus); begin Inherited; XNotifyEvent.GoSpellChild(GetParentForm(Self), xeChangeParams, DataSource, opInsert); CreateCaret(Handle, 0, Font.Size div 4, Abs(Font.Height)+4); ShowCaret(Handle); end; Procedure TXEDBMemo.Notification(AComponent: TComponent; Operation: TOperation); begin if AComponent is TXNotifyEvent then case TXNotifyEvent(AComponent).SpellEvent of xeGetFirstXControl: TXNotifyEvent(AComponent).GoEqual(Self, Operation); xeIsThisLink: if Assigned(DataSource) and (DataSource = TXNotifyEvent(AComponent).SpellChild) then begin TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; end else Inherited Notification(AComponent, Operation); end; { common procedures } Procedure XEDBSetLookupMode(Self: TDBLookupControl; Value: Boolean); begin with TDBLookupControlBorland(Self) do if FLookupMode <> Value then if Value then begin FMasterField:=GetFieldProperty(FDataField.DataSet, Self, FDataField.KeyFields); FLookupSource.DataSet:=FDataField.LookupDataSet; FKeyFieldName:=FDataField.LookupKeyFields; FLookupMode:=True; FListLink.DataSource:=FLookupSource; end else begin FListLink.DataSource:=nil; FLookupMode:=False; FKeyFieldName:=''; FLookupSource.DataSet:=nil; FMasterField:=FDataField; end; end; Procedure XEDBDataLinkRecordChanged(Self: TDBLookupComboBox); begin with Self, TDBLookupControlBorland(Self) do if FMasterField <> nil then KeyValue:= FMasterField.Value else KeyValue:=Null; end; Procedure XEDBChangeDataField(Self: TDBLookupComboBox; Field: TField); begin XEDBSetLookupMode(Self, False); TDBLookupControlBorland(Self).FDataField:=Field; XEDBSetLookupMode(Self, True); XEDBDataLinkRecordChanged(Self); end; Procedure XEDBPaint(Self: TEtvCustomDBLookupCombo; FIsContextOpen: Boolean; FStoreColor, FStoreHeadColor: TColor); begin if not FIsContextOpen then with TDBLookupComboBoxBorland(self).FDataList do begin Color:=FStoreColor; Self.HeadColor:=FStoreHeadColor; end; end; { Lev 17.04.99 The Begin } procedure XEDBSetIsContextOpen(Self: TEtvCustomDBLookupCombo; AValue: Boolean; var FIsContextOpen: Boolean; FStoreColor, FStoreHeadColor: TColor; FStoreDataSet: TDataSet); var LC:TDBLookupControlBorland; OldTag: Integer; LS: TLinkSource; begin LC:=TDBLookupControlBorland(Self); if (FIsContextOpen<>AValue) and Assigned(FStoreDataSet) then try {with LC.FDataField do} if AValue then begin if FStoreDataSet is TLinkQuery then LS:=TLinkQuery(FStoreDataSet).LinkSource else LS:=TLinkTable(FStoreDataSet).LinkSource; if LC.FLookUpMode then begin // Для исключения лишней работы в обработчиках конкретных DataSet'ов OldTag:=LC.FDataField.DataSet.Tag; LC.FDataField.DataSet.Tag:=99; // LC.FDataField.DataSet.DisableControls; TFieldBorland(LC.FDataField).FLookupDataSet:=LS.LikeQuery; end else LC.FlistLink.DataSource.DataSet:=LS.LikeQuery; if LC.FLookUpMode then XEDBChangeDataField(Self, LC.FDataField); Self.Color:=clLime or clSilver; TDBLookupComboBoxBorland(self).FDataList.Color:=clLime or clSilver; if Assigned(Self.Field) and (Self.Field is TEtvLookField) then TEtvLookField(Self.Field).HeadColor:=clYellow else Self.HeadColor:=clYellow; {Self.Field.HeadColor:=clYellow;} // После закрытия по таймеру всех таблиц надо открыть Query if not LS.LikeQuery.Active then LS.LikeQuery.Open; Self.HeadLineStr:='Выборка по "'+LS.LikePatterns[0]+'" - '+IntToStr(LS.LikeQuery.RecordCount)+' записей'; (* if LC.FlookUpMode then LC.FDataField.DataSet.EnableControls; FIsContextOpen:=True; *) end else begin if LC.FLookUpMode then begin // Для исключения лишней работы в обработчиках конкретных DataSet'ов OldTag:=LC.FDataField.DataSet.Tag; LC.FDataField.DataSet.Tag:=99; // LC.FDataField.DataSet.DisableControls; TFieldBorland(LC.FDataField).FLookupDataSet:=FStoreDataSet; end else LC.FlistLink.DataSource.DataSet:=FStoreDataSet; if LC.FLookUpMode then XEDBChangeDataField(Self,LC.FDataField); LC.FListLink.DataSet.Locate(LC.FListField.FieldName,TDBLookupComboBoxBorland(self). FDataList.KeyValue, [loCaseInsensitive, loPartialKey]); Self.HeadLineStr:=''; if Assigned(Self.Field) and (Self.Field is TEtvLookField) then TEtvLookField(Self.Field).HeadColor:=FStoreHeadColor else Self.HeadColor:=FStoreHeadColor; Self.Color:=FStoreColor; (* if LC.FlookUpMode then LC.FDataField.DataSet.EnableControls; FIsContextOpen:=False; *) end; finally if LC.FlookUpMode then begin LC.FDataField.DataSet.EnableControls; // Для исключения лишней работы в обработчиках конкретных DataSet'ов LC.FDataField.DataSet.Tag:=OldTag; end; FIsContextOpen:=aValue; end; end; { Lev 17.04.99 The End } Procedure XEDBContextUse(Self: TEtvCustomDBLookupCombo; var FIsContextOpen: Boolean; FStoreColor, FStoreHeadColor: TColor; FStoreDataSet: TDataSet); begin XEDBSetIsContextOpen(Self, Not FIsContextOpen, FIsContextOpen, FStoreColor, FStoreHeadColor, FStoreDataSet); end; { Lev 17.04.99 The Begin } Procedure XEDBContextCreate(Self: TEtvCustomDBLookupCombo; Const AStr:String; var FIsContextOpen: Boolean; FStoreColor, FStoreHeadColor: TColor; var FStoreDataSet: TDataSet); var LinkSet: TLinkSource; LC:TDBLookupControlBorland; LDataSet: TDataSet; { LookUpDataSet } LResultField: String; { LookUpResultField } OldTag: integer; begin LC:=TDBLookupControlBorland(Self); if not((Assigned(LC.FDataField) and LC.FDataField.Lookup) or (Assigned(LC.FlistLink.DataSource) and (LC.FListFieldName<>'') and (LC.FKeyFieldName<>''))) then Exit; { Инициализация LookupDataSet'а и LookUpResultField'ов } if LC.FLookupMode then begin LDataSet:=LC.FDataField.LookUpDataSet; {LResultField:=TEtvLookField(LC.FDataField).LookUpResultField;} LResultField:=LC.FDataField.LookUpResultField; if TEtvLookField(Self.Field).LookupFilterField<>'' then LResultField:=LResultField+';'+TEtvLookField(Self.Field).LookupFilterField; end else begin LDataSet:=LC.FListLink.DataSource.DataSet; LResultField:=LC.FListFieldName; end; if FIsContextOpen then if FStoreDataSet is TLinkQuery then LinkSet:=TLinkQuery(FStoreDataSet).LinkSource else LinkSet:=TLinkTable(FStoreDataSet).LinkSource else if LDataSet is TLinkQuery then LinkSet:=TLinkQuery(LDataSet).LinkSource else LinkSet:=TLinkTable(LDataSet).LinkSource; if Assigned(LinkSet) then {with LC.FDataField do} begin LinkSet.CreateLikeQuery(LDataSet); if LC.FLookUpMode then begin OldTag:=LC.FDataField.DataSet.Tag; LC.FDataField.DataSet.Tag:=99; LC.FDataField.DataSet.DisableControls; end; if not FIsContextOpen then FStoreDataSet:=LDataSet; if LinkSet.ChangeLikeQuery(FStoreDataSet, LResultField, AStr) then FIsContextOpen:=False; XEDBContextUse(Self, FIsContextOpen, FStoreColor, FStoreHeadColor, FStoreDataSet); if LC.FLookUpMode then begin LC.FDataField.DataSet.EnableControls; LC.FDataField.DataSet.Tag:=OldTag; end; end; end; { Lev 17.04.99 The End } Procedure XEDBContextInit(Self: TEtvCustomDBLookupCombo; var FIsContextOpen: Boolean; FStoreColor, FStoreHeadColor: TColor; FStoreDataSet: TDataSet); begin Self.Color:=FStoreColor; Self.HeadColor:=FStoreHeadColor; XEDBSetIsContextOpen(Self, False, FIsContextOpen, FStoreColor, FStoreHeadColor, FStoreDataSet); end; type TXEPopupDataList = class(TEtvPopupDataList) end; Function XEDBNotContextSearchKey(Self: TEtvCustomDBLookupCombo; var Key: Char; var FIsContextOpen{, Flag}: Boolean; FStoreColor, FStoreHeadColor: TColor; var FStoreDataSet: TDataSet): boolean; var s:string; aSearchOptions: TLocateOptions; aFSearchTextOfDataList: String; begin Result:=True; if Self.ListVisible then with Self, TDBLookupControlBorland(Self) do {TDBLookupControlBorland(TDBLookupComboBoxBorland(self).FDataList)} if (FListField<>nil) and (FListField.FieldKind=fkData) and ((FListField.DataType=ftString) or ((FListField.DataType in [ftInteger,ftSmallInt,ftAutoInc]) and (Key in [{Char(VK_Back),}#0,#27,'0'..'9']))) then {Lev 30/04/97} case Key of #27: if FIsContextOpen then begin XEDBContextInit(Self,FIsContextOpen,FStoreColor,FStoreHeadColor,FStoreDataSet); Invalidate; Result:=False; end; (* #27: FSearchText := ''; Char(VK_Back): begin S:=FSearchText; Delete(S,Length(S),1); TDBLookupControlBorland(self).FSearchText:=S; TDBLookupControlBorland(TDBLookupComboBoxBorland(self).FDataList).FSearchText:=S; Invalidate; Result:=False; end; *) #0,#8,#32..#255: if FListActive and not ReadOnly and ((FDataLink.DataSource = nil) or (FMasterField<>nil) and FMasterField.CanModify) then begin aFSearchTextOfDataList:=TDBLookupControlBorland(TDBLookupComboBoxBorland(Self).FDataList).FSearchText; if Length(FSearchText)<32 then begin if Key=#8 then S:=Copy(aFSearchTextOfDataList,1,Length(aFSearchTextOfDataList)-1) else begin S:=aFSearchTextOfDataList; if Key<>#0 then S:=S+Key end; {S:=AnsiUpperCase(S);} if Length(aFSearchTextOfDataList)=0 then aSearchOptions:=[loPartialKey{, loCaseInsensitive}] else aSearchOptions:=[loPartialKey{, loCaseInsensitive}]; if (Key=#0) and (S<>'') and FListLink.DataSet.Locate(FListField.FieldName,S,aSearchOptions) then begin // Меняем первую букву на Заглавную или наобоброт, что первое нашли... if Key<>#8 then S:=Copy(FListField.AsString,1,Length(aFSearchTextOfDataList){+1}); {TXEDBLookupCombo(Self).SelectKeyValue(FKeyField.Value);} TXEPopupDataList(TDBLookupComboBoxBorland(Self).FDataList).SelectCurrent; {SelectKeyValue(FKeyField.Value);} { FSearchText := S; TDBLookupControlBorland(TDBLookupComboBoxBorland(self).FDataList).FSearchText:=S;} end; if FListField.DataType in [ftInteger, ftSmallInt, ftAutoInc] then if Length(FSearchText)<8 then begin { FSearchText := S;} TDBLookupControlBorland(TDBLookupComboBoxBorland(Self).FDataList).FSearchText:=S; end else else begin FSearchText:=S; TDBLookupControlBorland(TDBLookupComboBoxBorland(Self).FDataList).FSearchText:=S; end; Invalidate; Result:=False; end; end; end; { case } end; Procedure XEDBSetContextKey(Self: TEtvCustomDBLookupCombo; var FIsContextOpen: Boolean; FStoreColor, FStoreHeadColor: TColor; var FStoreDataSet: TDataSet); begin if Self.ListVisible then with Self, TDBLookupControlBorland(self) do if (FListField<>nil) and (FListField.FieldKind=fkData) then begin if TDBLookupControlBorland(TDBLookupComboBoxBorland(self).FDataList).FSearchText<>'' then XEDBContextCreate(Self, TDBLookupControlBorland(TDBLookupComboBoxBorland(Self). FDataList).FSearchText, FIsContextOpen, FStoreColor, FStoreHeadColor, FStoreDataSet) else begin XEDBContextUse(Self, FIsContextOpen, FStoreColor, FStoreHeadColor, FStoreDataSet); if FIsContextOpen then begin if FStoreDataSet is TLinkQuery then TDBLookupControlBorland(TDBLookupComboBoxBorland(self).FDataList).FSearchText:= TLinkQuery(FStoreDataSet).LinkSource.LikePatterns[0] else TDBLookupControlBorland(TDBLookupComboBoxBorland(self).FDataList).FSearchText:= TLinkTable(FStoreDataSet).LinkSource.LikePatterns[0]; end; end; Invalidate; end; end; { TXEDBLookupCombo } Constructor TXEDBLookupCombo.Create(AOwner: TComponent); begin Inherited; FStoreDataSet:=nil; FIsContextOpen:=False; FStoreColor:=Color; EtvLookTimer.OnTimer:=XOnTimer; EtvLookTimer.Interval:=1; {FStoreHeadColor:=HeadColor;} end; Procedure TXEDBLookupCombo.ReadState(Reader: TReader); begin Inherited ReadState(Reader); FStoreColor:=Color; {FStoreHeadColor:=HeadColor;} end; Procedure TXEDBLookupCombo.Paint; begin XEDBPaint(Self, FIsContextOpen, FStoreColor, FStoreHeadColor); Inherited Paint; end; Procedure TXEDBLookupCombo.XOnTimer(Sender: TObject); var aKey:Char; begin Inc(aTick); if aTick>0 then begin try {Вызов функции поиска в Lookup'е} aKey:=#0; KeyPress(aKey); finally EtvLookTimer.Enabled:=false; aTick:=0; end; end; end; Procedure TXEDBLookupCombo.KeyPress(var Key: Char); begin if XEDBNotContextSearchKey(Self, Key, FIsContextOpen, FStoreColor, FStoreHeadColor, FStoreDataSet) then Inherited KeyPress(Key); if Self.ListVisible then begin EtvLookTimer.Enabled := false ; EtvLookTimer.Enabled := true ; end; end; Function XEDBSystemLookup: Boolean; begin if TXEDBLookupCombo(SystemMenuItemObject).ListVisible then with TXEDBLookupCombo(SystemMenuItemObject) do begin XEDBSetContextKey(TXEDBLookupCombo(SystemMenuItemObject), FIsContextOpen, FStoreColor, FStoreHeadColor, FStoreDataSet); Result:=True; end else Result:=False; end; Procedure SetOpenReturnControl(AField: TField; ADataSource: TDataSource; AOwner: TComponent); var LinkSet{, FormLinkSet}: TLinkSource; DBF1: TDBFormControl; begin if Assigned(AField) then begin if AField.LookupDataSet is TLinkQuery then LinkSet:=TLinkQuery(AField.LookupDataSet).LinkSource; if AField.LookupDataSet is TLinkTable then LinkSet:=TLinkTable(AField.LookupDataSet).LinkSource; {if (ADataSource is TLinkSource) then FormLinkSet:=TLinkSource(ADataSource) else FormLinkSet:=nil;} if Assigned(LinkSet) then begin { if Assigned(FormLinkSet) then begin FormLinkSet.IsCheckPostedMode:=False; end;} {!} { XNotifySelect.GoSpellSelect(LinkSet,xeSetParams, AField, AOwner, opInsert);} if (AOwner is TXForm) and (TXForm(AOwner).FormControl is TDBFormControl) then begin DBF1:= GetLinkedDBFormControl(LinkSet); if Assigned(DBF1) then begin DBF1.SelectedField:= AField; DBF1.ReturnForm:= TForm(AOwner); TDBFormControl(TXForm(AOwner).FormControl).OpenReturnControl:= DBF1; end; end; {!} (* if (XNotifySelect.SpellEvent=xeNone) and (AOwner is TXForm) then with TXForm(AOwner) do { if Assigned(XFormLink) and Assigned(XFormLink.LinkControl) then TFormControl(XFormLink.LinkControl).OpenReturnControl:=TFormControl(XNotifySelect.SpellSelect);} if Assigned(FormControl) then TFormControl(FormControl).OpenReturnControl:=TFormControl(XNotifySelect.SpellSelect); *) end; end; end; Procedure ClearOpenReturnControl(AOwner: TComponent); begin if AOwner is TXForm then with TXForm(AOwner) do { if Assigned(XFormLink) and Assigned(XFormLink.LinkControl) then TFormControl(XFormLink.LinkControl).OpenReturnControl:=Nil;} if Assigned(FormControl) then TFormControl(FormControl).OpenReturnControl:=nil; end; Procedure TXEDBLookupCombo.WMSetFocus(var Message: TWMSetFocus); var LinkSet, FormLinkSet: TLinkSource; ADataSet: TDataSet; AField: TField; DBF1: TDBFormControl; begin Inherited; FStoreColor:=Color; FStoreHeadColor:=GetHeadColor; SystemMenuItemObject:=Self; SystemMenuItemProc:=XEDBSystemLookup; XNotifyEvent.GoSpellChild(GetParentForm(Self), xeChangeParams, DataSource, opInsert); if Assigned(TDBLookupControlBorland(Self).FDataField) then if TDBLookupControlBorland(Self).FDataField.Lookup then begin if (TDBLookupControlBorland(Self).FDataField.LookupDataSet is TLinkQuery) then LinkSet:=TLinkQuery(TDBLookupControlBorland(Self).FDataField.LookupDataSet).LinkSource; if (TDBLookupControlBorland(Self).FDataField.LookupDataSet is TLinkTable) then LinkSet:=TLinkTable(TDBLookupControlBorland(Self).FDataField.LookupDataSet).LinkSource; if Assigned(LinkSet) then begin {! XNotifySelect.GoSpellSelect(LinkSet,xeSetParams,TDBLookupControlBorland(Self).FDataField, Owner, opRemove); } {!} DBF1:= GetLinkedDBFormControl(LinkSet); if Assigned(DBF1) and (DBF1.ReturnForm=Owner) then begin LinkSet.IsSetReturn:= False; DBF1.ReturnForm:=nil; if LinkSet.IsReturnValue then begin LinkSet.IsReturnValue:=False; ADataSet:=TDBLookupControlBorland(Self).FDataField.LookupDataSet; if IsLinkDataSet(ADataSet) then begin if ADataSet is TLinkQuery then AField:=TLinkQuery(ADataSet).LinkSource.Declar.FindField( TDBLookupControlBorland(Self).FDataField.LookupKeyFields) else AField:=TLinkTable(ADataSet).LinkSource.Declar.FindField( TDBLookupControlBorland(Self).FDataField.LookupKeyFields); SelectKeyValue(AField.Value); end; if (DataSource is TLinkSource) then FormLinkSet:=TLinkSource(DataSource) else FormLinkSet:=nil; if Assigned(FormLinkSet) then begin FormLinkSet.PostChecked:=True; end; end; end; end; end; SetOpenReturnControl(TDBLookupControlBorland(Self).FDataField, DataSource, Owner); end; { Lev. Time Of Correction 18.04.99 The Begin } Procedure TXEDBLookupCombo.WMKillFocus(var Message: TWMKillFocus); begin if (Assigned(TDBLookupControlBorland(Self).FDataField) or (Assigned(TDBLookupControlBorland(Self).FlistLink.DataSource) and (TDBLookupControlBorland(Self).FListFieldName<>'') and (TDBLookupControlBorland(Self).FKeyFieldName<>''))) and FIsContextOpen then XEDBContextInit(Self, FIsContextOpen, FStoreColor, FStoreHeadColor, FStoreDataSet); ClearOpenReturnControl(Owner); SystemMenuItemObject:=nil; SystemMenuItemProc:=nil; Inherited; end; { Lev. Time Of Correction 18.04.99 The Begin } Procedure TXEDBLookupCombo.KeyDown(var Key: Word; Shift: TShiftState); var Priz1: Boolean; LC:TDBLookupControlBorland; OldTag: integer; LDataSet: TDataSet; { LookUpDataSet } LResultField: String; { LookUpResultField } begin case Key of Word('F'): if (ssCtrl in Shift) then begin Key:=0; XEDBSetContextKey(Self, FIsContextOpen, FStoreColor, FStoreHeadColor, FStoreDataSet); end; { Word('S'): if (ssCtrl in Shift) and TDBLookupControlBorland(Self).FDataField.Lookup and (TDBLookupControlBorland(Self).FDataField.LookupDataSet is TLinkQuery) then begin Key:=0; if Owner is TXForm then with TXForm(Owner) do if Assigned(XFormLink) and Assigned(XFormLink.LinkControl) then if Assigned(TFormControl(XFormLink.LinkControl).OpenReturnControl) then TFormControl(XFormLink.LinkControl).OpenReturnControl.ReturnExecute; end; } (* Бред Льва Михайловича Word('S'): if (ssShift in Shift) {True} then begin Key:=0; with TDBFormControl(TXForm(Screen.ActiveForm).FormControl) do with TToolsForm(FormTools.Tools.ToolsForm) do if ReturnOpenBtn.Enabled then begin ReturnSubOpen; SubSetFocus; end; {FormTools.Tools.SubClick(TToolsForm(FormTools.Tools.ToolsForm).ReturnOpenBtn);} {OpenReturnControl.ReturnExecute;} end; *) Word('Z'): if (ssCtrl in Shift) then if not (ssShift in Shift) then Key:= 0 else try LC:=TDBLookupControlBorland(Self); { Инициализация LookupDataSet'а и LookUpResultField'ов } if LC.FLookupMode then begin LDataSet:=LC.FDataField.LookUpDataSet; LResultField:=TEtvLookField(LC.FDataField).LookUpResultField; end else begin LDataSet:=LC.FListLink.DataSource.DataSet; LResultField:=LC.FListFieldName; end; // Для исключения лишней работы в обработчиках конкретных DataSet'ов if Assigned(Self.DataSource) then begin OldTag:=Self.DataSource.DataSet.Tag; Self.DataSource.DataSet.Tag:=99; end; if (Assigned(LC.FDataField) and LC.FDataField.Lookup and not(foAutoDropDownWidth in TEtvLookField(LC.FDataField).Options)) or (Assigned(LC.FlistLink.DataSource) and (LC.FListFieldName<>'') and (LC.FKeyFieldName<>'')) and IsLinkDataSet(LDataSet) then begin Key:=0; Cursor:=crHourGlass; Priz1:= ListVisible; if Priz1 then CloseUp(False); ChangeLookQueryField(LC.FDataField,LC,LDataSet,LResultField); if Assigned(LC.FDataField) then XEDBChangeDataField(Self, LC.FDataField); DoEnter; LC.SetFocus; if Priz1 then DropDown; Cursor:=crDefault; end; finally if Assigned(Self.DataSource) then Self.DataSource.DataSet.Tag:=OldTag; end; end; Inherited KeyDown(Key, Shift); end; { Lev. Time of Correction 18.04.99 The End } Procedure TXEDBLookupCombo.KeyUp(var Key: Word; Shift: TShiftState); begin (* Inherited; case Key of Word('S'): if (ssCtrl in Shift) {True} then begin Key:=0; with TDBFormControl(TXForm(Screen.ActiveForm).FormControl) do with TToolsForm(FormTools.Tools.ToolsForm) do if ReturnOpenBtn.Enabled then begin ReturnSubOpen; SubSetFocus; end; end; end; *) end; Procedure TXEDBLookupCombo.Notification(AComponent: TComponent; Operation: TOperation); begin if AComponent is TXNotifyEvent then case TXNotifyEvent(AComponent).SpellEvent of xeIsLookField: begin if TDBLookupControlBorland(Self).FDataField is TEtvLookField then TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; xeSetSource: begin if (not Assigned(ListSource)) and (not Assigned(DataSource)) then ListSource:=TDataSource(TXNotifyEvent(AComponent).SpellChild); TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; xeSetParams: begin if Operation=opInsert then begin ListField:=TLnTable(TXNotifyEvent(AComponent).SpellChild).IndexFieldNames; KeyField:=TLnTable(TXNotifyEvent(AComponent).SpellChild).IndexFieldNames; DropDown; end; TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; xeGetFirstXControl: TXNotifyEvent(AComponent).GoEqual(Self, Operation); xeIsThisLink: if Assigned(DataSource) and (DataSource = TXNotifyEvent(AComponent).SpellChild) then TXNotifyEvent(AComponent).SpellEvent:=xeNone; end else Inherited Notification(AComponent, Operation); end; {TXEDBInplaceLookupCombo} Constructor TXEDBInplaceLookupCombo.Create(AOwner: TComponent); begin Inherited; FStoreDataSet:=nil; FIsContextOpen:=False; FStoreColor:=Color; FStoreHeadColor:=HeadColor; EtvLookTimer.OnTimer:=XOnTimer; EtvLookTimer.Interval:=1; end; Procedure TXEDBInplaceLookupCombo.XOnTimer(Sender: TObject); var aKey:Char; begin Inc(aTick); if aTick>0 then begin try {Вызов функции поиска в Lookup'е} aKey:=#0; KeyPress(aKey); finally EtvLookTimer.Enabled:=false; aTick:=0; end; end; end; Procedure TXEDBInplaceLookupCombo.ReadState(Reader: TReader); begin Inherited ReadState(Reader); FStoreColor:=Color; {FStoreHeadColor:=HeadColor;} end; Procedure TXEDBInplaceLookupCombo.Paint; begin XEDBPaint(Self, FIsContextOpen, FStoreColor, FStoreHeadColor); Inherited Paint; end; Procedure TXEDBInplaceLookupCombo.KeyPress(var Key: Char); begin if XEDBNotContextSearchKey(Self, Key, FIsContextOpen, FStoreColor, FStoreHeadColor, FStoreDataSet) then Inherited KeyPress(Key); if Self.ListVisible then begin EtvLookTimer.Enabled := false ; EtvLookTimer.Enabled := true ; end; end; Function XEDBSystemLookupInplace: Boolean; begin if TXEDBInplaceLookupCombo(SystemMenuItemObject).ListVisible then with TXEDBInplaceLookupCombo(SystemMenuItemObject) do begin SetHideFlag(False); XEDBSetContextKey(TXEDBInplaceLookupCombo(SystemMenuItemObject), FIsContextOpen, FStoreColor, FStoreHeadColor, FStoreDataSet); SetHideFlag(True); Result:=True; end else Result:=False; end; Procedure TXEDBInplaceLookupCombo.WMSetFocus(var Message: TWMSetFocus); var LinkSet, FormLinkSet: TLinkSource; ADataSet: TDataSet; AField: TField; DBF1: TDBFOrmControl; begin Inherited; SystemMenuItemObject:=Self; SystemMenuItemProc:=XEDBSystemLookupInplace; if Assigned(TDBLookupControlBorland(Self).FDataField) then begin if TDBLookupControlBorland(Self).FDataField.Lookup then begin if (TDBLookupControlBorland(Self).FDataField.LookupDataSet is TLinkQuery) then LinkSet:=TLinkQuery(TDBLookupControlBorland(Self).FDataField.LookupDataSet).LinkSource; if (TDBLookupControlBorland(Self).FDataField.LookupDataSet is TLinkTable) then LinkSet:=TLinkTable(TDBLookupControlBorland(Self).FDataField.LookupDataSet).LinkSource; if Assigned(LinkSet) then begin { XNotifySelect.GoSpellSelect(LinkSet,xeSetParams,TDBLookupControlBorland(Self).FDataField, Owner, opRemove);} DBF1:= GetLinkedDBFormControl(LinkSet); if Assigned(DBF1) and (DBF1.ReturnForm=Owner) then begin LinkSet.IsSetReturn:= False; DBF1.ReturnForm:=nil; if LinkSet.IsReturnValue then begin LinkSet.IsReturnValue:=False; ADataSet:=TDBLookupControlBorland(Self).FDataField.LookupDataSet; if IsLinkDataSet(ADataSet) then begin if ADataSet is TLinkQuery then AField:=TLinkQuery(ADataSet).LinkSource.Declar.FindField( TDBLookupControlBorland(Self).FDataField.LookupKeyFields) else AField:=TLinkTable(ADataSet).LinkSource.Declar.FindField( TDBLookupControlBorland(Self).FDataField.LookupKeyFields); SelectKeyValue(AField.Value); end; if (DataSource is TLinkSource) then FormLinkSet:=TLinkSource(DataSource) else FormLinkSet:=nil; if Assigned(FormLinkSet) then begin FormLinkSet.PostChecked:=True; end; end; end; end; end; end; end; Procedure TXEDBInplaceLookupCombo.WMKillFocus(var Message: TWMKillFocus); begin if Assigned(TDBLookupControlBorland(Self).FDataField) then XEDBContextInit(Self, FIsContextOpen, FStoreColor, FStoreHeadColor, FStoreDataSet); SystemMenuItemObject:=nil; SystemMenuItemProc:=nil; Visible:=false; Inherited; end; Procedure TXEDBInplaceLookupCombo.SetHideFlag(Value: Boolean); begin TXEDBGrid(Lookup).EtvAutoHide:=Value; end; Procedure TXEDBInplaceLookupCombo.KeyDown(var Key: Word; Shift: TShiftState); var Priz1: Boolean; LC:TDBLookupControlBorland; begin case Key of Word('F'),VK_RETURN: if ((ssCtrl in Shift) and (Key=Word('F'))) or ((Key=VK_Return) and (FIsContextOpen=true)) then begin Key:=0; SetHideFlag(False); XEDBSetContextKey(Self, FIsContextOpen, FStoreColor, FStoreHeadColor, FStoreDataSet); SetHideFlag(True); end; { Word('S'): if (ssCtrl in Shift) and TDBLookupControlBorland(Self).FDataField.Lookup and (TDBLookupControlBorland(Self).FDataField.LookupDataSet is TLinkQuery) then begin Key:=0; if Owner is TXForm then with TXForm(Owner) do if Assigned(XFormLink) and Assigned(XFormLink.LinkControl) then if Assigned(TFormControl(XFormLink.LinkControl).OpenReturnControl) then TFormControl(XFormLink.LinkControl).OpenReturnControl.ReturnExecute; end; } Word('Z'): if (ssCtrl in Shift) then if not (ssShift in Shift) then Key:= 0 else begin LC:=TDBLookupControlBorland(Self); if LC.FDataField.Lookup and IsLinkDataSet(LC.FDataField.LookupDataSet) {and (not (foAutoDropDownWidth in TEtvLookField(LC.FDataField).Options))} then begin Key:=0; SetHideFlag(False); Cursor:=crHourGlass; Priz1:= ListVisible; // Меняем значение Tag=Word('Z'), для дальнейшей обработки Tag:=Word('Z'); if Priz1 then CloseUp(False); if Tag<>0 then Tag:=0; ChangeLookQueryField(LC.FDataField,nil, LC.FDataField.LookUpDataSet,TEtvLookField(Self.Field).LookupResultField); XEDBChangeDataField(Self, LC.FDataField); DoEnter; LC.SetFocus; if Priz1 then DropDown; Cursor:=crDefault; SetHideFlag(True); end; end; end; Inherited KeyDown(Key, Shift); end; { TXEDbGrid } Constructor TXEDBGrid.Create(AOwner: TComponent); begin Inherited Create(AOwner); FStoredDataSource:=nil; FStoredControlSource:=nil; FStoredColumn:= 0; FIsStoredDataSource:= False; MarkGridFontColor:=clPurple; GridAcceptKey:=true; end; procedure TXEDBGrid.SetDefaultGridColor(Sender: TObject; Field: TField; var Color: TColor); Const MaxChars=70; var aCharBuffer: array[0..MaxChars] of Char; i: integer; begin {FillChar(aCharBuffer,MaxChars,#0);} Move(Field.DataSet.ActiveBuffer^,aCharBuffer,MaxChars); {Заменяем символ #0 на пробел } for i:=0 to MaxChars do if aCharBuffer[i]=#0 then Inc(aCharBuffer[i],32); if Pos('ИТОГО',AnsiUpperCase(aCharBuffer))>0 then Color:=$00B4FEFE else if Pos('ВСЕГО',AnsiUpperCase(aCharBuffer))>0 then Color:=$00D5FFFE else if Pos('+ ',aCharBuffer)>0 then Color:=$00D2F2F7//$00F4F5D8 else Color:=TXEDBGrid(Sender).Color; {if Copy(ClientBuildingGrodnoRealDeclarClientName.AsString,1,5)='Всего' then Color:=$00D5FFFE;} // $00FFF8E6; //$00CCEACC;//$00C6FDD8;//$00C6CDFD;//$00A0CD8F;//$00C6DDA4 end; procedure TXEDBGrid.SetDefaultGridFont(Sender: TObject; Field: TField; Font: TFont); Const MaxChars=255; var aCharBuffer: array[0..MaxChars] of Char; i: byte; begin Move(Field.DataSet.ActiveBuffer^,aCharBuffer,MaxChars); {Заменяем символ #0 на пробел } for i:=0 to MaxChars do if aCharBuffer[i]=#0 then Inc(aCharBuffer[i],32); if (Pos('ИТОГО',AnsiUpperCase(aCharBuffer))>0) or (Pos('ВСЕГО',AnsiUpperCase(aCharBuffer))>0) then begin Font.Style:=[fsBold]; Font.Color:=MarkGridFontColor; end end; Procedure TXEDBGrid.FormatColumns(AsInDataBase: boolean); var i,j:integer; begin if Assigned(DataSource) then begin SetMinLengthFieldsByDataSet(TDBDataSet(DataSource.DataSet),AsInDataBase); { Корректировка ширины столбцов с учетом итоговой строки } if Assigned(fListTotal) then for i:=0 to ListTotal.Count-1 do for j:=0 to Columns.Count-1 do if (AnsiUpperCase(Columns[j].FieldName)=AnsiUpperCase( TItemTotal(ListTotal[i]).FieldName)) and (TItemTotal(ListTotal[i]).Value<>'') and (Length(TItemTotal(ListTotal[i]).Value)>Columns[j].Field.DisplayWidth) then Columns[j].Field.DisplayWidth:=Length(TItemTotal(ListTotal[i]).Value); end; {for i:=0 to Columns.Count-1 do Columns[i].Visible:=Columns[i].Field.Visible;} Columns.RebuildColumns; i:=Columns.Count-1; while i>=0 do begin if Assigned(Columns[i].Field) and not Columns[i].Field.Visible then Columns[i].Destroy; Dec(i) end; end; Procedure TXEDBGrid.WMSetFocus(var Message: TWMSetFocus); var LinkSet, FormLinkSet: TLinkSource; ADataSet: TDataSet; AField: TField; DBF1: TDBFormControl; begin Inherited; HideEditor; XNotifyEvent.GoSpellChild(GetParentForm(Self), xeChangeParams, DataSource, opInsert); if Assigned(Columns[SelectedIndex].Field) then begin if (IsEtvField=efLookup) then begin if (Columns[SelectedIndex].Field.LookupDataSet is TLinkQuery) then LinkSet:=TLinkQuery(Columns[SelectedIndex].Field.LookupDataSet).LinkSource; if (Columns[SelectedIndex].Field.LookupDataSet is TLinkTable) then LinkSet:=TLinkTable(Columns[SelectedIndex].Field.LookupDataSet).LinkSource; if Assigned(LinkSet) then begin { XNotifySelect.GoSpellSelect(LinkSet,xeSetParams,Columns[SelectedIndex].Field, Owner, opRemove);} DBF1:= GetLinkedDBFormControl(LinkSet); if Assigned(DBF1) and (DBF1.ReturnForm=Owner) then begin LinkSet.IsSetReturn:= False; DBF1.ReturnForm:=nil; if LinkSet.IsReturnValue then begin LinkSet.IsReturnValue:=False; ADataSet:=Columns[SelectedIndex].Field.LookupDataSet; if IsLinkDataSet(ADataSet) then begin if ADataSet is TLinkQuery then AField:=TLinkQuery(ADataSet).LinkSource.Declar.FindField( Columns[SelectedIndex].Field.LookupKeyFields) else AField:=TLinkTable(ADataSet).LinkSource.Declar.FindField( Columns[SelectedIndex].Field.LookupKeyFields); if DataLink.Edit then DataSource.DataSet.FindField( Columns[SelectedIndex].Field.KeyFields).Value:=AField.Value; end; if (DataSource is TLinkSource) then FormLinkSet:=TLinkSource(DataSource) else FormLinkSet:=nil; if Assigned(FormLinkSet) then FormLinkSet.PostChecked:=True; end; end; end; end; end; if IsEtvField=efLookup then SetOpenReturnControl(Columns[SelectedIndex].Field, DataSource, Owner); end; Procedure TXEDBGrid.WMKillFocus(var Message: TWMKillFocus); begin Inherited; end; Procedure TXEDBGrid.ColEnter; var Priz: Boolean; begin Priz:=IsEtvField=efLookup; Inherited; if (IsEtvField=efLookup) or Priz then begin XNotifyEvent.GoSpellChild(GetParentForm(Self), xeChangeParams, DataSource, opInsert); if IsEtvField=efLookup then SetOpenReturnControl(Columns[SelectedIndex].Field, DataSource, Owner) else ClearOpenReturnControl(Owner); end; end; procedure TXEDBGrid.Notification(AComponent: TComponent; Operation: TOperation); var aTotals: TStringList; i: Integer; begin (*** TEST!!! Writeln(FFFF,'TXEDBGrid.Notification #1 :',AComponent.Name); ***) if AComponent is TXNotifyEvent then case TXNotifyEvent(AComponent).SpellEvent of xeSumExecute: {if TLinkSource(DataSource).IsDeclar then } begin if Operation=opInsert then begin ListTotal.ClearFull; {! TLinkSource(DataSource).LinkMaster.Calc.Dataset:= DataSource.Dataset;} TAggregateLink(TXNotifyEvent(AComponent).SpellChild).Calc.Dataset:= DataSource.Dataset; aTotals:=CalcFieldTotals(DataSource.DataSet, TLinkSource(DataSource).TableName, TLinkSource(DataSource).DatabaseName{'AO_GKSM_InProgram'}, TAggregateLink(TXNotifyEvent(AComponent).SpellChild).Calc.SumCalc { TLinkSource(DataSource).DeclarLink.Calc.SumCalc} {TLinkSource(DataSource).LinkMaster.Calc.SumCalc}); if Assigned(aTotals) then begin // Ситуация при вставке записи в MasterTable Lev 03.05.2010 for i:=0 to aTotals.Count-1 do SetItemTotal(TField(aTotals.Objects[i]).FieldName, aTotals[i]); Total:= True; aTotals.Free; end else Total:=false; end else Total:= False; TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; xeIsLookField: begin if IsEtvField=efLookup then TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; xeSetSource: begin if not Assigned(DataSource) then begin DataSource:=TDataSource(TXNotifyEvent(AComponent).SpellChild); if Assigned(DataSource.DataSet) then DataSource.DataSet.Active:=(Operation=opInsert) and TLinkSource(DataSource).Active; end; TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; xeGetFirstXControl: TXNotifyEvent(AComponent).GoEqual(Self, Operation); xeIsThisLink: if Assigned(DataSource)and (DataSource = TXNotifyEvent(AComponent).SpellChild) then begin TXNotifyEvent(AComponent).SpellEvent:=xeNone; end; end else Inherited; (*** TEST!!! Writeln(FFFF,'TXEDBGrid.Notification #2 :',AComponent.Name); ***) end; Function TXEDBGrid.GetDataSource: TDataSource; begin if FIsStoredDataSource then Result:=FStoredDataSource else Result:=Inherited DataSource; end; Procedure TXEDBGrid.SetDataSource(Value: TDataSource); begin if FIsStoredDataSource then FStoredDataSource:=Value else Inherited DataSource:=Value; end; Procedure TXEDBGrid.ReadIsDataSource(Reader: TReader); begin FIsStoredDataSource:=Reader.ReadBoolean; end; Procedure TXEDBGrid.WriteIsDataSource(Writer: TWriter); begin Writer.WriteBoolean(FIsStoredDataSource); end; Function TXEDBGrid.CreateInplaceLookupCombo:TEtvInplaceLookupCombo; begin Result:=TXEDBInplaceLookupCombo.Create(Self); end; Procedure TXEDBGrid.ReadDataSource(Reader: TReader); begin Reader.ReadIdent; end; Procedure TXEDBGrid.WriteDataSource(Writer: TWriter); var S: String; begin if DataSource.Owner<>Owner then S:=DataSource.Owner.Name+'.' else S:=''; Writer.WriteIdent(S+DataSource.Name); end; Procedure TXEDBGrid.DefineProperties(Filer: TFiler); begin Filer.DefineProperty('IsStoredDataSource', ReadIsDataSource, WriteIsDataSource, True{FIsStoredDataSource}); Filer.DefineProperty('DataSource', ReadDataSource, WriteDataSource, Assigned(DataSource)); Inherited; end; Procedure TXEDBGrid.WMChangePageSource(var Msg: TMessage); begin if Msg.WParam=0 then begin if not Assigned(FStoredDataSource) then begin FStoredDataSource:=DataSource; FStoredColumn:=SelectedIndex; Inherited DataSource:=nil; end; FIsStoredDataSource:=True; end else begin FIsStoredDataSource:=False; if Assigned(FStoredDataSource) then begin DataSource:=FStoredDataSource; SelectedIndex:=FStoredColumn; FStoredDataSource:=nil; end; end; end; Procedure TXEDBGrid.WMChangeControlSource(var Msg: TMessage); var wSource, lSource: TDataSource; begin lSource:= TDataSource(Msg.lParam); wSource:= TDataSource(Msg.wParam); if Assigned(lSource) then begin if wSource=DataSource then begin FStoredControlSource:= DataSource; DataSource:= lSource; end; end else if wSource=FStoredControlSource then begin DataSource:= FStoredControlSource; FStoredControlSource:=nil; end; end; Procedure TXEDBGrid.KeyDown(var Key: Word; Shift: TShiftState); var EtvField:TEtvLookField; begin case Key of { Word('S'): if (ssCtrl in Shift) and (IsEtvField=efLookup) and (Columns[SelectedIndex].Field.LookupDataSet is TLinkQuery) then begin Key:=0; if Owner is TXForm then with TXForm(Owner) do if Assigned(XFormLink) and Assigned(XFormLink.LinkControl) then if Assigned(TFormControl(XFormLink.LinkControl).OpenReturnControl) then TFormControl(XFormLink.LinkControl).OpenReturnControl.ReturnExecute; end; } Word('Z'): if (ssCtrl in Shift) then if not (ssShift in Shift) then Key:=0 else if IsEtvField=efLookup then begin EtvField:=TEtvLookField(Columns[SelectedIndex].Field); if IsLinkDataSet(EtvField.LookupDataSet) and not(foAutoDropDownWidth in EtvField.Options) then begin Key:=0; Cursor:=crHourGlass; ChangeLookQueryField(EtvField,nil,EtvField.LookUpDataSet,EtvField.LookUpResultField); Cursor:=crDefault; end; end; end; Inherited KeyDown(Key, Shift); end; { Mixer } Function GetXELookup(AOwner: TComponent): TWinControl; begin Result:=TXEDBLookupCombo.Create(AOwner); { Result:=TDBLookupComboBox.Create(AOwner);} end; Procedure SetXELookupField(AControl: TWinControl; AField: TField; aDataSource: TDataSource); var aLookField: TField; begin with TDBLookupComboBox(AControl) do begin if ChangeToLookField(aField, aLookField) then aField:=aLookField; DataField:=AField.FieldName; DataSource:=ADataSource; end; end; Procedure SetXELookupKeyValue(AControl: TWinControl; AValue: String); begin TDBLookupComboBox(AControl).KeyValue:=AValue; end; Function GetXEEdit(AOwner: TComponent): TWinControl; begin Result:=TXEDBEdit.Create(AOwner); end; Procedure SetXEEditField(AControl: TWinControl; AField: TField; ADataSource: TDataSource); begin TDBEdit(AControl).DataField:=AField.FieldName; TDBEdit(AControl).DataSource:=ADataSource; end; Procedure SetXEEditKeyValue(AControl: TWinControl; AValue: String); begin TDBEdit(AControl).Text:=AValue; end; type TControlSelf=class(TControl) end; Function GetXEOtherDBEdit(aOwner:TComponent; Field:TField):TControl; begin Result:= TXEDBEdit.Create(aOwner); TControlSelf(Result).PopupMenu:=PopupMenuEtvDBFieldControls; end; Function GetXEOtherDBDateEdit(aOwner:TComponent; Field:TField):TControl; begin Result:= TXEDBDateEdit.Create(aOwner); TControlSelf(Result).PopupMenu:=PopupMenuEtvDBFieldControls; end; Function GetXEOtherDBComboBox(aOwner:TComponent; Field:TField):TControl; begin Result:=nil; if Field is TEtvListField then begin Result:= TXEDBCombo.Create(aOwner); TControlSelf(Result).PopupMenu:=PopupMenuEtvDBFieldControls; end; end; Function GetXEOtherDBMemo(aOwner:TComponent; Field:TField):TControl; begin Result:= TXEDBMemo.Create(aOwner); TControlSelf(Result).PopupMenu:=PopupMenuEtvDBFieldControls; end; Function GetXEOtherDBLookupComboBox(aOwner:TComponent; Field:TField):TControl; begin Result:= TXEDBLookupCombo.Create(aOwner); TControlSelf(Result).PopupMenu:=PopupMenuEtvDBFieldControls; end; Initialization DFGetLookCombo:=GetXELookup; DFSetLookField:=SetXELookupField; DFSetLookKeyValue:=SetXELookupKeyValue; DFGetDBEdit:=GetXEEdit; DFSetDBEditField:=SetXEEditField; DFSetDBEditKeyValue:=SetXEEditKeyValue; XNotifyEvent:=TXNotifyEvent.Create(nil); CreateOtherDBEdit:= GetXEOtherDBEdit; CreateOtherDBDateEdit:= GetXEOtherDBDateEdit; CreateOtherDBIntEdit:= GetXEOtherDBComboBox; CreateOtherDBMemo:= GetXEOtherDBMemo; CreateOtherDBLookupComboBox:= GetXEOtherDBLookupComboBox; finalization DFGetLookCombo:=nil; DFSetLookField:=nil; DFSetLookKeyValue:=nil; DFGetDBEdit:=nil; DFSetDBEditField:=nil; DFSetDBEditKeyValue:=nil; XNotifyEvent.Free; XNotifyEvent:=nil; CreateOtherDBEdit:=nil; CreateOtherDBDateEdit:=nil; CreateOtherDBIntEdit:=nil; CreateOtherDBMemo:=nil; CreateOtherDBLookupComboBox:=nil; end.
unit Model.Services.ProductOrder; interface uses Model.Services.Interfaces, Model.Entities.ProductOrder, Data.DB, Model.Components.Connections.interfaces, Model.Components.Connections, System.SysUtils; type TModelServicesProductOrder = class(TInterfacedObject,IModelServicesProductOrder<TModelEntitiesProductOrder>) private FConnection:IModelComponentsConnectionsGeneric; FDataSource:TDataSource; FDisplayAttValueTotal:TProc<Currency>; FDisplayClearFieldsProduct:TProc; FEntity:TModelEntitiesProductOrder; function CountValueTotal(DataSet:TDataSet):Currency; public constructor Create; destructor Destroy;override; class function New : IModelServicesProductOrder<TModelEntitiesProductOrder>; function &Abort:IModelServicesProductOrder<TModelEntitiesProductOrder>; function Add:IModelServicesProductOrder<TModelEntitiesProductOrder>; function Cancel:IModelServicesProductOrder<TModelEntitiesProductOrder>; function DataSource(aValue:TDataSource):IModelServicesProductOrder<TModelEntitiesProductOrder>; function DisplayAttFieldsOrder(aDisplay: TProc): IModelServicesProductOrder<TModelEntitiesProductOrder>; function DisplayAttValueTotal(aDisplay:TProc<Currency>):IModelServicesProductOrder<TModelEntitiesProductOrder>; function DisplayClearFieldsProduct(aDisplay:TProc):IModelServicesProductOrder<TModelEntitiesProductOrder>; function Get(aId:Integer):IModelServicesProductOrder<TModelEntitiesProductOrder>; function Remove(aValue:Integer):IModelServicesProductOrder<TModelEntitiesProductOrder>; function Save:IModelServicesProductOrder<TModelEntitiesProductOrder>; function This:TModelEntitiesProductOrder; function TotalOrder:Currency; function Update:IModelServicesProductOrder<TModelEntitiesProductOrder>; end; implementation { TModelServicesOrder } function TModelServicesProductOrder.Abort: IModelServicesProductOrder<TModelEntitiesProductOrder>; begin Result := Self; FConnection.RollbackTrasaction; end; function TModelServicesProductOrder.Add : IModelServicesProductOrder<TModelEntitiesProductOrder>; begin Result := Self; // if(FConnection.DataSet.RecordCount <= 0)then; // FConnection.StartTransaction; FConnection .Close .SQLClear .SQLAdd('INSERT INTO PEDIDOS_PRODUTOS(NUMERO_PEDIDO,CODIGO_PRODUTO,QUANTIDADE,') .SQLAdd('VLR_UNITARIO,VLR_TOTAL)') .SQLAdd('VALUES(:NUMERO_PEDIDO,:CODIGO_PRODUTO,:QUANTIDADE,') .SQLAdd(':VLR_UNITARIO,:VLR_TOTAL)') .ParamByName('NUMERO_PEDIDO',FEntity.CodigoPedido) .ParamByName('CODIGO_PRODUTO',FEntity.CodigoProduto) .ParamByName('QUANTIDADE',FEntity.Quantidade) .ParamByName('VLR_UNITARIO',FEntity.ValorUnitario) .ParamByName('VLR_TOTAL',FEntity.ValorTotal) .ExecSQL; end; function TModelServicesProductOrder.Cancel: IModelServicesProductOrder<TModelEntitiesProductOrder>; begin Result := Self; FConnection .Close .SQLClear .SQLAdd('DELETE FROM PEDIDOS_PRODUTOS ') .SQLAdd('WHERE NUMERO_PEDIDO = :NUMERO_PEDIDO') .ParamByName('NUMERO_PEDIDO',FEntity.CodigoPedido) .ExecSQL; end; function TModelServicesProductOrder.CountValueTotal(DataSet:TDataSet):Currency; var LValue:Currency; begin LValue := 0; DataSet.First; while not(DataSet.Eof) do begin LValue := LValue + DataSet.FieldByName('VLR_TOTAL').AsCurrency; DataSet.Next; end; DataSet.First; Result := LValue; end; constructor TModelServicesProductOrder.Create; begin if not Assigned(FConnection) then FConnection := TModelComponentsConnections.New.Connection; FEntity := TModelEntitiesProductOrder.Create; end; function TModelServicesProductOrder.DataSource( aValue: TDataSource): IModelServicesProductOrder<TModelEntitiesProductOrder>; begin Result := Self; FDataSource := aValue; FDataSource.DataSet := FConnection.DataSet; end; destructor TModelServicesProductOrder.Destroy; begin FEntity.Free; inherited; end; function TModelServicesProductOrder.DisplayAttFieldsOrder( aDisplay: TProc): IModelServicesProductOrder<TModelEntitiesProductOrder>; begin end; function TModelServicesProductOrder.DisplayAttValueTotal( aDisplay: TProc<Currency>): IModelServicesProductOrder<TModelEntitiesProductOrder>; begin Result := Self; FDisplayAttValueTotal := aDisplay; end; function TModelServicesProductOrder.DisplayClearFieldsProduct( aDisplay: TProc): IModelServicesProductOrder<TModelEntitiesProductOrder>; begin Result := Self; FDisplayClearFieldsProduct := aDisplay; end; function TModelServicesProductOrder.Get( aId: Integer): IModelServicesProductOrder<TModelEntitiesProductOrder>; begin Result := Self; FConnection .Close .SQLClear .SQLAdd('SELECT PEDIDOS_PRODUTOS.CODIGO_PRODUTO,PRODUTOS.DESCRICAO,PEDIDOS_PRODUTOS.QUANTIDADE,') .SQLAdd('PEDIDOS_PRODUTOS.VLR_UNITARIO,PEDIDOS_PRODUTOS.VLR_TOTAL,AUTOINCREM FROM PEDIDOS_PRODUTOS') .SQLAdd('LEFT JOIN PRODUTOS ON PRODUTOS.CODIGO = PEDIDOS_PRODUTOS.CODIGO_PRODUTO') .SQLAdd('WHERE NUMERO_PEDIDO = :NUMERO_PEDIDO') .ParamByName('NUMERO_PEDIDO',aId) .Open; if Assigned(FDisplayClearFieldsProduct)then FDisplayClearFieldsProduct(); if Assigned(FDisplayAttValueTotal)then FDisplayAttValueTotal(CountValueTotal(FConnection.DataSet)); end; class function TModelServicesProductOrder.New: IModelServicesProductOrder<TModelEntitiesProductOrder>; begin Result := Self.Create; end; function TModelServicesProductOrder.Remove( aValue: Integer): IModelServicesProductOrder<TModelEntitiesProductOrder>; begin Result := Self; FConnection .Close .SQLClear .SQLAdd('DELETE FROM PEDIDOS_PRODUTOS ') .SQLAdd('WHERE AUTOINCREM = :AUTOINCREM') .ParamByName('AUTOINCREM',aValue) .ExecSQL; end; function TModelServicesProductOrder.Save: IModelServicesProductOrder<TModelEntitiesProductOrder>; begin Result := Self; FConnection.CommitTrasaction; end; function TModelServicesProductOrder.This: TModelEntitiesProductOrder; begin Result := FEntity; end; function TModelServicesProductOrder.TotalOrder: Currency; begin end; function TModelServicesProductOrder.Update: IModelServicesProductOrder<TModelEntitiesProductOrder>; begin Result := Self; if(FConnection.DataSet.RecordCount <= 0)then; FConnection.StartTransaction; FConnection .Close .SQLClear .SQLAdd('UPDATE PEDIDOS_PRODUTOS SET QUANTIDADE = :QUANTIDADE,') .SQLAdd('VLR_UNITARIO = :VLR_UNITARIO,VLR_TOTAL = :VLR_TOTAL') .SQLAdd('WHERE AUTOINCREM = :AUTOINCREMNTO') .ParamByName('AUTOINCREMNTO',FEntity.Seq) .ParamByName('QUANTIDADE',FEntity.Quantidade) .ParamByName('VLR_UNITARIO',FEntity.ValorUnitario) .ParamByName('VLR_TOTAL',FEntity.ValorTotal) .ExecSQL; end; end.
// // Created by the DataSnap proxy generator. // 20/10/2018 16:45:41 // unit Unit2; interface uses System.JSON, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.DBXJSONReflect; type TServerMethods1Client = class(TDSAdminClient) private FDataSetProvider1GetTableNameCommand: TDBXCommand; FEchoStringCommand: TDBXCommand; FReverseStringCommand: TDBXCommand; FGetClientesCommand: TDBXCommand; FGetClientesJSONCommand: TDBXCommand; FGravarCommand: TDBXCommand; public constructor Create(ADBXConnection: TDBXConnection); overload; constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; procedure DataSetProvider1GetTableName(Sender: TObject; DataSet: TDataSet; var TableName: string); function EchoString(Value: string): string; function ReverseString(Value: string): string; function GetClientes: string; function GetClientesJSON: TJSONArray; procedure Gravar(Value: string); end; implementation procedure TServerMethods1Client.DataSetProvider1GetTableName(Sender: TObject; DataSet: TDataSet; var TableName: string); begin if FDataSetProvider1GetTableNameCommand = nil then begin FDataSetProvider1GetTableNameCommand := FDBXConnection.CreateCommand; FDataSetProvider1GetTableNameCommand.CommandType := TDBXCommandTypes.DSServerMethod; FDataSetProvider1GetTableNameCommand.Text := 'TServerMethods1.DataSetProvider1GetTableName'; FDataSetProvider1GetTableNameCommand.Prepare; end; if not Assigned(Sender) then FDataSetProvider1GetTableNameCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FDataSetProvider1GetTableNameCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FDataSetProvider1GetTableNameCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Sender), True); if FInstanceOwner then Sender.Free finally FreeAndNil(FMarshal) end end; FDataSetProvider1GetTableNameCommand.Parameters[1].Value.SetDBXReader(TDBXDataSetReader.Create(DataSet, FInstanceOwner), True); FDataSetProvider1GetTableNameCommand.Parameters[2].Value.SetWideString(TableName); FDataSetProvider1GetTableNameCommand.ExecuteUpdate; TableName := FDataSetProvider1GetTableNameCommand.Parameters[2].Value.GetWideString; end; function TServerMethods1Client.EchoString(Value: string): string; begin if FEchoStringCommand = nil then begin FEchoStringCommand := FDBXConnection.CreateCommand; FEchoStringCommand.CommandType := TDBXCommandTypes.DSServerMethod; FEchoStringCommand.Text := 'TServerMethods1.EchoString'; FEchoStringCommand.Prepare; end; FEchoStringCommand.Parameters[0].Value.SetWideString(Value); FEchoStringCommand.ExecuteUpdate; Result := FEchoStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.ReverseString(Value: string): string; begin if FReverseStringCommand = nil then begin FReverseStringCommand := FDBXConnection.CreateCommand; FReverseStringCommand.CommandType := TDBXCommandTypes.DSServerMethod; FReverseStringCommand.Text := 'TServerMethods1.ReverseString'; FReverseStringCommand.Prepare; end; FReverseStringCommand.Parameters[0].Value.SetWideString(Value); FReverseStringCommand.ExecuteUpdate; Result := FReverseStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.GetClientes: string; begin if FGetClientesCommand = nil then begin FGetClientesCommand := FDBXConnection.CreateCommand; FGetClientesCommand.CommandType := TDBXCommandTypes.DSServerMethod; FGetClientesCommand.Text := 'TServerMethods1.GetClientes'; FGetClientesCommand.Prepare; end; FGetClientesCommand.ExecuteUpdate; Result := FGetClientesCommand.Parameters[0].Value.GetWideString; end; function TServerMethods1Client.GetClientesJSON: TJSONArray; begin if FGetClientesJSONCommand = nil then begin FGetClientesJSONCommand := FDBXConnection.CreateCommand; FGetClientesJSONCommand.CommandType := TDBXCommandTypes.DSServerMethod; FGetClientesJSONCommand.Text := 'TServerMethods1.GetClientesJSON'; FGetClientesJSONCommand.Prepare; end; FGetClientesJSONCommand.ExecuteUpdate; Result := TJSONArray(FGetClientesJSONCommand.Parameters[0].Value.GetJSONValue(FInstanceOwner)); end; procedure TServerMethods1Client.Gravar(Value: string); begin if FGravarCommand = nil then begin FGravarCommand := FDBXConnection.CreateCommand; FGravarCommand.CommandType := TDBXCommandTypes.DSServerMethod; FGravarCommand.Text := 'TServerMethods1.Gravar'; FGravarCommand.Prepare; end; FGravarCommand.Parameters[0].Value.SetWideString(Value); FGravarCommand.ExecuteUpdate; end; constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection); begin inherited Create(ADBXConnection); end; constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); begin inherited Create(ADBXConnection, AInstanceOwner); end; destructor TServerMethods1Client.Destroy; begin FDataSetProvider1GetTableNameCommand.DisposeOf; FEchoStringCommand.DisposeOf; FReverseStringCommand.DisposeOf; FGetClientesCommand.DisposeOf; FGetClientesJSONCommand.DisposeOf; FGravarCommand.DisposeOf; inherited; end; end.
unit IdTestSocketHandle; interface uses IdSocketHandle, IdStack, IdTest, IdSys; type TIdTestSocketHandle = class(TIdTest) published procedure TestSocketFree; end; implementation procedure TIdTestSocketHandle.TestSocketFree; //used to be a bug with incorrect freeing critical section, then using it. var s:TIdSocketHandle; begin TIdStack.IncUsage; s:=TIdSocketHandle.Create(nil); try s.AllocateSocket; finally Sys.FreeAndNil(s); TIdStack.DecUsage; end; end; initialization TIdTest.RegisterTest(TIdTestSocketHandle); end.
unit uFizzBuzz; interface type IFizzBuzz = interface function escreverSaida(aluno: Integer): string; function getFizz(aluno: Integer; saida: string): string; function getBuzz(aluno: Integer; saida: string): string; function getFizzBuzz(aluno: Integer; saida: string): string; end; TFizzBuzz = class(TInterfacedObject, IFizzBuzz) private function escreverSaida(aluno: Integer): string; function getFizz(aluno: Integer; saida: string): string; function getBuzz(aluno: Integer; saida: string): string; function getFizzBuzz(aluno: Integer; saida: string): string; public class function new(): IFizzBuzz; end; implementation uses System.SysUtils ,uFizzBuzzCore; class function TFizzBuzz.new(): IFizzBuzz; begin Result := Self.Create(); end; function TFizzBuzz.escreverSaida(aluno: Integer): string; begin Result := IntToStr(aluno); Result := Self.getFizz(aluno, Result); Result := Self.getBuzz(aluno, Result); Result := Self.getFizzBuzz(aluno, Result); end; function TFizzBuzz.getFizz(aluno: Integer; saida: string): string; begin Result := TFizzBuzzCore.new().getSaida(aluno, 3, saida, 'Fizz'); end; function TFizzBuzz.getBuzz(aluno: Integer; saida: string): string; begin Result := TFizzBuzzCore.new().getSaida(aluno, 5, saida, 'Buzz'); end; function TFizzBuzz.getFizzBuzz(aluno: Integer; saida: string): string; begin Result := TFizzBuzzCore.new().getSaida(aluno, 15, saida, 'FizzBuzz'); end; end.
unit untQueryType; interface uses Classes, FireDAC.Comp.Client, System.Generics.Collections, SysUtils; type TQueryType = class(TFDQuery) private FSizes: Integer; FSizesStr: string; FFieldsSize: LongInt; FCampos: TList<string>; //function GetName: TComponentName; //function GetObjectName: string; virtual; //procedure SetName(const Value: TComponentName); protected procedure Loaded; override; procedure LoadSizes(Stream: TStream); virtual; procedure SaveSizes(Stream: TStream); virtual; procedure LoadSizesStr(Stream: TStream); virtual; procedure SaveSizesStr(Stream: TStream); virtual; procedure LoadFieldsSize(Stream: TStream); virtual; procedure SaveFieldsSize(Stream: TStream); virtual; procedure LoadFields(Stream: TStream); virtual; procedure SaveFields(Stream: TStream); virtual; procedure DefineProperties(Filer: TFiler); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SetPosition(ALeft, ATop: Integer); function Campos: TList<string>; end; implementation uses untFuncoes; { TQueryType } function TQueryType.Campos: TList<string>; begin if Self.FCampos = nil then Self.FCampos := TList<string>.Create; Result := Self.FCampos; end; constructor TQueryType.Create(AOwner: TComponent); begin inherited Create(AOwner); end; procedure TQueryType.DefineProperties(Filer: TFiler); begin inherited DefineProperties(Filer); Filer.DefineBinaryProperty('Sizes', LoadSizes, SaveSizes, True); Filer.DefineBinaryProperty('SizesStr', LoadSizesStr, SaveSizesStr, True); Filer.DefineBinaryProperty('FieldsSize', LoadFieldsSize, SaveFieldsSize, True); Filer.DefineBinaryProperty('ListaCampos', LoadFields, SaveFields, True); end; destructor TQueryType.Destroy; begin FreeAndNil(Self.FCampos); inherited Destroy; end; procedure TQueryType.SetPosition(ALeft, ATop: Integer); var NewDesignInfo: LongRec; begin NewDesignInfo.Hi := Word(ATop); NewDesignInfo.Lo := Word(ALeft); Self.DesignInfo := Longint(NewDesignInfo); end; procedure TQueryType.Loaded; begin inherited Loaded; end; procedure TQueryType.LoadFields(Stream: TStream); var i, iPosIni, iSizeCampo, iContCampos: Integer; sCampos: string; begin Self.Campos.Clear; SetString(sCampos, PChar(nil), Self.FFieldsSize); Stream.Read(PChar(sCampos)^, Self.FFieldsSize * SizeOf('A')); iPosIni := 1; iContCampos := StrToInt(Copy(Self.FSizesStr, 1, 8)); for i := 0 to Pred(iContCampos) do begin iSizeCampo := StrToInt(Copy(Self.FSizesStr, (i + 1) * 8 + 1, 8)); Self.Campos.Add(Copy(sCampos, iPosIni, iSizeCampo)); iPosIni := iPosIni + iSizeCampo; end; end; procedure TQueryType.LoadFieldsSize(Stream: TStream); begin Stream.Read(Self.FFieldsSize, SizeOf(Self.FFieldsSize)); end; procedure TQueryType.LoadSizes(Stream: TStream); begin Stream.Read(Self.FSizes, SizeOf(Self.FSizes)); end; procedure TQueryType.LoadSizesStr(Stream: TStream); begin SetString(Self.FSizesStr, PChar(nil), Self.FSizes); Stream.Read(PChar(Self.FSizesStr)^, Self.FSizes * SizeOf('A')); end; procedure TQueryType.SaveFields(Stream: TStream); var i: Integer; iSize: LongInt; sCampos: string; begin sCampos := EmptyStr; for i := 0 to Self.Fields.Count - 1 do sCampos := sCampos + TFunc.ComponentToString(Self.Fields.Fields[i]); iSize := Length(sCampos); Stream.Write(PChar(sCampos)^, iSize * SizeOf(sCampos[1])); end; procedure TQueryType.SaveFieldsSize(Stream: TStream); var i: Integer; sCampos: string; begin sCampos := EmptyStr; for i := 0 to Self.Fields.Count - 1 do sCampos := sCampos + TFunc.ComponentToString(Self.Fields.Fields[i]); Self.FFieldsSize := Length(sCampos); Stream.Write(Self.FFieldsSize, Sizeof(Self.FFieldsSize)); end; procedure TQueryType.SaveSizes(Stream: TStream); var i: Integer; begin Self.FSizesStr := Format('%.8d', [Self.Fields.Count]); for i := 0 to Self.Fields.Count - 1 do Self.FSizesStr := Self.FSizesStr + Format('%.8d', [Length(TFunc.ComponentToString(Self.Fields.Fields[i]))]); Self.FSizes := Length(Self.FSizesStr); Stream.Write(FSizes, Sizeof(Self.FSizes)); end; procedure TQueryType.SaveSizesStr(Stream: TStream); begin Stream.Write(PChar(Self.FSizesStr)^, Self.FSizes * SizeOf('A')); end; end.
unit BuilderPizzaExample.Builder.Product.PizzaPepperoni; interface uses BuilderPizzaExample.Builder.Base.IPizzaBuilder, BuilderPizzaExample.Builder.Base.PizzaBuilderBase, BuilderPizzaExample.Domain.Edge, BuilderPizzaExample.Domain.ValueObject.PizzaSize, BuilderPizzaExample.Domain.Pizza, BuilderPizzaExample.Processors.ICalculatePrice; type TPizzaPepperoni = class(TPizzaBuilderBase, IPizzaBuilder) protected private public procedure PrepareEdge(AEdge: TEdge); procedure PrepareBatter(APizzaSize: TPizzaSize); procedure InsertIngredients(); procedure DefineTimeOnStove(); class function New(ACalculatePrice: ICalculatePrice) : TPizzaPepperoni; end; implementation uses BuilderPizzaExample.Domain.ValueObject.PizzaType, BuilderPizzaExample.Domain.ValueObject.IngredientsType, BuilderPizzaExample.Util.Utils; { TPizzaPepperoni } procedure TPizzaPepperoni.DefineTimeOnStove; begin FPizza.TimeOnStove := 20; end; procedure TPizzaPepperoni.InsertIngredients; begin FPizza.Flavor := TUtils.IIF(FPizza.WithEdge, 'Pepperoni With Edge', 'Pepperoni Without Edge'); FPizza.AddIngredient(TIngredientsType.Pepperoni); FPizza.AddIngredient(TIngredientsType.Olive); FPizza.AddIngredient(TIngredientsType.Onion); FPizza.AddIngredient(TIngredientsType.Cheddar); FPizza.AddIngredient(TIngredientsType.Salami); end; class function TPizzaPepperoni.New(ACalculatePrice: ICalculatePrice): TPizzaPepperoni; begin Result := Self.Create(ACalculatePrice); end; procedure TPizzaPepperoni.PrepareBatter(APizzaSize: TPizzaSize); begin Init; FPizza.WithEdge := False; FPizza.PizzaType := TPizzaType.Salty; FPizza.PizzaSize := APizzaSize; end; procedure TPizzaPepperoni.PrepareEdge(AEdge: TEdge); begin FPizza.WithEdge := True; FPizza.Edge := AEdge; end; end.
{*******************************************************} { } { Delphi FireMonkey Notification Service } { } { Implementation Notification Center for iOS } { } { Copyright(c) 2012-2013 Embarcadero Technologies, Inc. } { } {*******************************************************} // Reference on programm guide in Apple developer center: // https://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction/Introduction.html unit FMX.Notification.iOS; interface procedure RegisterNotificationService; procedure UnregisterNotificationService; implementation uses FMX.Notification, FMX.Platform, FMX.Helpers.iOS, FMX.Messages, FMX.Forms, System.SysUtils, System.Classes, System.Generics.Collections, Macapi.ObjectiveC, iOSapi.Foundation, iOSapi.CocoaTypes, iOSapi.UIKit; type { TNotificationCenterCocoa } TNotificationCenterCocoa = class sealed (TInterfacedObject, IFMXNotificationCenter) strict private FDelayedNotifications: TObjectList<TNotification>; FApplicationLoaded: Boolean; { Subscriptions } FSubscriptionNotificationReceivedID: Integer; FSubscriptionFormsLoadedID: Integer; { Creation and manipulation with notifications } function CreateNativeNotification(const ANotification: TNotification): UILocalNotification; function ConvertNativeToDelphiNotification(const ANotification: UILocalNotification): TNotification; function FindNativeNotification(const AID: string; var ANotification: UILocalNotification): Boolean; { Global External event } procedure DoReceiveLocalNotification(const Sender: TObject; const M: TMessage); procedure DidFormsLoad(const Sender: TObject; const M: TMessage); { Delayed notifications } procedure SendDelayedNotifications; procedure ClearDelayedNotifications; public constructor Create; destructor Destroy; override; { IFMXNotificationCenter } function GetCurrentNotifications: TNotifications; function FindNotification(const AName: string): TNotification; procedure ScheduleNotification(const ANotification: TNotification); procedure PresentNotification(const ANotification: TNotification); procedure CancelNotification(const AName: string); overload; procedure CancelNotification(const ANotification: TNotification); overload; procedure CancelAllNotifications; procedure SetIconBadgeNumber(const ACount: Integer); function GetIconBadgeNumber: Integer; procedure ResetIconBadgeNumber; end; var NotificationCenter: TNotificationCenterCocoa; procedure RegisterNotificationService; begin NotificationCenter := TNotificationCenterCocoa.Create; TPlatformServices.Current.AddPlatformService(IFMXNotificationCenter, NotificationCenter); end; procedure UnregisterNotificationService; begin TPlatformServices.Current.RemovePlatformService(IFMXNotificationCenter); NotificationCenter := nil; end; {$REGION 'TNotificationCenterCocoa'} procedure TNotificationCenterCocoa.CancelAllNotifications; begin SharedApplication.cancelAllLocalNotifications; end; function TNotificationCenterCocoa.FindNativeNotification(const AID: string; var ANotification: UILocalNotification): Boolean; function FindInScheduledNotifications: UILocalNotification; var Notifications: NSArray; NativeNotification: UILocalNotification; Found: Boolean; I: NSUInteger; UserInfo: NSDictionary; begin Notifications := SharedApplication.scheduledLocalNotifications; Found := False; I := 0; while (I < Notifications.count) and not Found do begin NativeNotification := TUILocalNotification.Wrap(Notifications.objectAtIndex(I)); UserInfo := NativeNotification.userInfo; if Assigned(UserInfo) and (UTF8ToString(TNSString.Wrap(UserInfo.valueForKey(NSSTR('id'))).UTF8String) = AID) then Found := True else Inc(I); end; if Found then Result := NativeNotification else Result := nil; end; begin // We are searching notification in two list: // 1. Notifications, which have not displayed in Notification Center // 2. Notifications, which already displayed ANotification := FindInScheduledNotifications; Result := Assigned(ANotification); end; function TNotificationCenterCocoa.FindNotification( const AName: string): TNotification; var NativeNotification: UILocalNotification; begin if FindNativeNotification(AName, NativeNotification) then Result := ConvertNativeToDelphiNotification(NativeNotification) else Result := nil; end; function TNotificationCenterCocoa.GetCurrentNotifications: TNotifications; var Notifications: NSArray; NativeNotification: UILocalNotification; I: Integer; begin Notifications := SharedApplication.scheduledLocalNotifications; SetLength(Result, Notifications.count); for I := 0 to Integer(Notifications.count) - 1 do begin NativeNotification := TUILocalNotification.Wrap(Notifications.objectAtIndex(I)); Result[I] := ConvertNativeToDelphiNotification(NativeNotification) end; end; procedure TNotificationCenterCocoa.CancelNotification(const AName: string); var NativeNotification: UILocalNotification; begin if FindNativeNotification(AName, NativeNotification) then SharedApplication.cancelLocalNotification(NativeNotification); end; procedure TNotificationCenterCocoa.CancelNotification(const ANotification: TNotification); begin if not Assigned(ANotification) then Exit; CancelNotification(ANotification.Name); end; procedure TNotificationCenterCocoa.ClearDelayedNotifications; begin FDelayedNotifications.Clear; end; constructor TNotificationCenterCocoa.Create; begin FSubscriptionNotificationReceivedID := TMessageManager.DefaultManager.SubscribeToMessage(TMessage<UILocalNotification>, DoReceiveLocalNotification); FSubscriptionFormsLoadedID := TMessageManager.DefaultManager.SubscribeToMessage(TFormsCreatedMessage, DidFormsLoad); FDelayedNotifications := TObjectList<TNotification>.Create; FApplicationLoaded := ApplicationState = TApplicationState.asRunning; end; function TNotificationCenterCocoa.CreateNativeNotification(const ANotification: TNotification): UILocalNotification; var NativeNotification: UILocalNotification; UserInfo: NSDictionary; GMTDateTime: TDateTime; begin NativeNotification := TUILocalNotification.Create; if not ANotification.Name.IsEmpty then begin // Set unique identificator UserInfo := TNSDictionary.Wrap(TNSDictionary.OCClass.dictionaryWithObject( (NSSTR(ANotification.Name) as ILocalObject).GetObjectID, (NSSTR('id') as ILocalObject).GetObjectID)); NativeNotification.setUserInfo(UserInfo); end; // Get GMT time and set notification fired date GMTDateTime := GetGMTDateTime(ANotification.FireDate); NativeNotification.setTimeZone(TNSTimeZone.Wrap(TNSTimeZone.OCClass.defaultTimeZone)); NativeNotification.setFireDate(DateTimeToNSDate(GMTDateTime)); NativeNotification.setApplicationIconBadgeNumber(ANotification.Number); NativeNotification.setAlertBody(NSSTR(ANotification.AlertBody)); NativeNotification.setAlertAction(NSSTR(ANotification.AlertAction)); NativeNotification.setHasAction(ANotification.HasAction); if ANotification.EnableSound then NativeNotification.setSoundName(UILocalNotificationDefaultSoundName) else NativeNotification.setSoundName(nil); Result := NativeNotification; end; destructor TNotificationCenterCocoa.Destroy; begin { Unsibscribe } TMessageManager.DefaultManager.Unsubscribe(TMessage<UILocalNotification>, FSubscriptionNotificationReceivedID); TMessageManager.DefaultManager.Unsubscribe(TFormsCreatedMessage, FSubscriptionFormsLoadedID); { Destroying } ClearDelayedNotifications; FDelayedNotifications.DisposeOf; inherited Destroy; end; procedure TNotificationCenterCocoa.DidFormsLoad(const Sender: TObject; const M: TMessage); begin FApplicationLoaded := True; SendDelayedNotifications; end; procedure TNotificationCenterCocoa.DoReceiveLocalNotification(const Sender: TObject; const M: TMessage); procedure SendNotification(Notification: TNotification); begin TMessageManager.DefaultManager.SendMessage(Self, TMessage<TNotification>.Create(Notification)); // Sending Delayed notifications if FDelayedNotifications.Count > 0 then SendDelayedNotifications; end; var NativeNotification: UILocalNotification; Notification: TNotification; begin if M is TMessage<UILocalNotification> then begin NativeNotification := (M as TMessage<UILocalNotification>).Value; // iOS doesn't provide list of presented notification. So we need to store it // in our list for cancelling in future with using ID Notification := ConvertNativeToDelphiNotification(NativeNotification); try if not FApplicationLoaded then FDelayedNotifications.Add(Notification) else SendNotification(Notification); finally FreeAndNil(Notification); end; end; end; function TNotificationCenterCocoa.ConvertNativeToDelphiNotification( const ANotification: UILocalNotification): TNotification; var UserInfo: NSDictionary; NotificationTmp: TNotification; begin NotificationTmp := nil; if Assigned(ANotification) then begin NotificationTmp := TNotification.Create; UserInfo := ANotification.userInfo; if Assigned(UserInfo) then NotificationTmp.Name := UTF8ToString(TNSString.Wrap(UserInfo.valueForKey(NSSTR('id'))).UTF8String); if Assigned(ANotification.AlertBody) then NotificationTmp.AlertBody := UTF8ToString(ANotification.AlertBody.UTF8String); if Assigned(ANotification.AlertAction) then NotificationTmp.AlertAction := UTF8ToString(ANotification.AlertAction.UTF8String);; NotificationTmp.Number := ANotification.ApplicationIconBadgeNumber; NotificationTmp.FireDate := NSDateToDateTime(ANotification.FireDate); NotificationTmp.EnableSound := Assigned(ANotification.SoundName); NotificationTmp.HasAction := ANotification.HasAction; end; Result := NotificationTmp; end; procedure TNotificationCenterCocoa.PresentNotification(const ANotification: TNotification); var NativeNatification: UILocalNotification; begin CancelNotification(ANotification); NativeNatification := CreateNativeNotification(ANotification); SharedApplication.presentLocalNotificationNow(NativeNatification); end; procedure TNotificationCenterCocoa.ScheduleNotification(const ANotification: TNotification); var NativeNatification: UILocalNotification; begin CancelNotification(ANotification); NativeNatification := CreateNativeNotification(ANotification); SharedApplication.scheduleLocalNotification(NativeNatification); end; procedure TNotificationCenterCocoa.SendDelayedNotifications; var Notification: TNotification; begin for Notification in FDelayedNotifications do TMessageManager.DefaultManager.SendMessage(Self, TMessage<TNotification>.Create(Notification)); ClearDelayedNotifications; end; function TNotificationCenterCocoa.GetIconBadgeNumber: Integer; begin Result := SharedApplication.ApplicationIconBadgeNumber; end; procedure TNotificationCenterCocoa.SetIconBadgeNumber(const ACount: Integer); begin SharedApplication.setApplicationIconBadgeNumber(ACount); end; procedure TNotificationCenterCocoa.ResetIconBadgeNumber; begin SharedApplication.setApplicationIconBadgeNumber(0); end; {$ENDREGION} end.
{$IFDEF FREEPASCAL} {$MODE DELPHI} {$ENDIF} unit dll_user32_win; interface uses atmcmbaseconst, winconst, wintype, wintypeA; const SW_HIDE = 0; SW_NORMAL = 1; SW_SHOWMINIMIZED = 2; SW_MAXIMIZE = 3; SW_SHOWNOACTIVATE = 4; SW_SHOW = 5; SW_MINIMIZE = 6; SW_SHOWMINNOACTIVE= 7; SW_SHOWNA = 8; SW_RESTORE = 9; SW_SHOWDEFAULT = 10; SW_MAX = 10; { Old ShowWindow() Commands } {$EXTERNALSYM HIDE_WINDOW} HIDE_WINDOW = 0; SHOW_OPENWINDOW = 1; SHOW_ICONWINDOW = 2; SHOW_FULLSCREEN = 3; SHOW_OPENNOACTIVATE = 4; { Identifiers for the WM_SHOWWINDOW message } SW_PARENTCLOSING = 1; SW_OTHERZOOM = 2; SW_PARENTOPENING = 3; SW_OTHERUNZOOM = 4; SWP_NOSIZE = 1; SWP_NOMOVE = 2; SWP_NOZORDER = 4; SWP_NOREDRAW = 8; SWP_NOACTIVATE = $10; SWP_FRAMECHANGED = $20; { The frame changed: send WM_NCCALCSIZE } SWP_SHOWWINDOW = $40; SWP_HIDEWINDOW = $80; SWP_NOCOPYBITS = $100; SWP_NOOWNERZORDER = $200; { Don't do owner Z ordering } SWP_NOSENDCHANGING = $400; { Don't send WM_WINDOWPOSCHANGING } SWP_DRAWFRAME = SWP_FRAMECHANGED; SWP_NOREPOSITION = SWP_NOOWNERZORDER; SWP_DEFERERASE = $2000; SWP_ASYNCWINDOWPOS = $4000; { Window Styles } WS_OVERLAPPED = 0; WS_POPUP = DWORD($80000000); // 创建一个子窗口。不能与WS_POPUP风格一起使用 WS_CHILD = $40000000; WS_MINIMIZE = $20000000; WS_VISIBLE = $10000000; WS_DISABLED = $8000000; // 剪裁相关的子窗口,这意味着,当一个特定的子窗口接收到重绘消息时, // WS_CLIPSIBLINGS风格将在子窗口要重画的区域中去掉与其它子窗口重叠的部分。 // (如果没有指定WS_CLIPSIBLINGS风格,并且子窗口有重叠,当你在一个子窗口的客户区绘图时, // 它可能会画在相邻的子窗口的客户区中。)只与WS_CHILD风格一起使用 // http://blog.csdn.net/klarclm/article/details/7493126 // WS_CLIPSIBLINGS实际上还需要和控件的叠放顺序(z order)配合使用,才能看出明显的效果 WS_CLIPSIBLINGS = $4000000; // 裁减兄弟窗口 // 子窗口间相互裁减。也就是说当两个窗口相互重叠时, // 设置了WS_CLIPSIBLINGS样式的子窗口重绘时不能绘制 // 被重叠的部分。反之没有设置WS_CLIPSIBLINGS样式的 // 子窗口重绘时是不考虑重叠不重叠,统统重绘 // 当你在父窗口中绘图时,除去子窗口所占的区域。在创建父窗口的时候使用 //** 这两个属性很重要 不设置容易引起 闪烁 WS_CLIPCHILDREN = $2000000; // 裁减子窗口 // WS_CLIPCHILDREN样式主要是用于父窗口,也就是说当在父窗口绘制的时候, // 父窗口上还有一个子窗口,那么设置了这个样式的话,子窗口区域父窗口就不负责绘制 WS_MAXIMIZE = $1000000; WS_CAPTION = $C00000; { WS_BORDER or WS_DLGFRAME } WS_BORDER = $800000; WS_DLGFRAME = $400000; WS_VSCROLL = $200000; WS_HSCROLL = $100000; WS_SYSMENU = $80000; WS_THICKFRAME = $40000; // WS_TABSTOP&WS_GROUP WS_GROUP = $20000; WS_TABSTOP = $10000; WS_MINIMIZEBOX = $20000; WS_MAXIMIZEBOX = $10000; WS_TILED = WS_OVERLAPPED; WS_ICONIC = WS_MINIMIZE; WS_SIZEBOX = WS_THICKFRAME; { Common Window Styles } WS_OVERLAPPEDWINDOW = (WS_OVERLAPPED or WS_CAPTION or WS_SYSMENU or WS_THICKFRAME or WS_MINIMIZEBOX or WS_MAXIMIZEBOX); WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW; WS_POPUPWINDOW = (WS_POPUP or WS_BORDER or WS_SYSMENU); WS_CHILDWINDOW = (WS_CHILD); { Extended Window Styles } // 创建一个带双边框的窗口,该窗口可以在 // dwStyle 中指定 WS_CAPTION 风格来创建一个标题栏 WS_EX_DLGMODALFRAME = 1; // 指明以这个风格创建的子窗口在被创建和销毁时不向父窗口发送 WM_PARENTNOTIFY 消息 WS_EX_NOPARENTNOTIFY = 4; // 指明以该风格创建的窗口应始终放置在所有非最顶层窗口的上面, // 即使窗口未被激活。可使用 SetWindowPos 函数来设置和移去这个风格 WS_EX_TOPMOST = 8; // 该风格的窗口可以接受一个拖拽文件 WS_EX_ACCEPTFILES = $10; // 指定以这个风格创建的窗口在窗口下的同属窗口已重画时, // 该窗口才可以重画。由于其下的同属富口已被重画,所以该窗口是透明的 WS_EX_TRANSPARENT = $20; // 创建一个 MDI 子窗口 WS_EX_MDICHILD = $40; // 创建一个工具窗口,即窗口是一个浮动的工具条。工具窗口的标题栏比一般窗口的标题栏短, // 并且窗口标题栏以小字体显示。工具窗口不在任务栏里显示,当用户按下 ALT+TAB 键时工具 // 窗口不在对话框里显示。如果工具窗口有一个系统菜单,它的图标也不会显示在标题栏里, // 但是,可以通过点击鼠标右键或使用 ALT+SPACE 键来显示菜单。 WS_EX_TOOLWINDOW = $80; // 指定窗口具有凸起的边框 WS_EX_WINDOWEDGE = $100; // 指定窗口有一个带阴影的边界 WS_EX_CLIENTEDGE = $200; // 在窗口的标题栏包含一个问号标志 // WS_EX_CONTEXTHELP不能与WS_MAXIMIZEBOX和WS_MINIMIZEBOX同时使用 WS_EX_CONTEXTHELP = $400; WS_EX_RIGHT = $1000; WS_EX_LEFT = 0; WS_EX_RTLREADING = $2000; WS_EX_LTRREADING = 0; // 外壳语言是如 Hebrew、Arabic或其他支持 reading order alignment 的语言, // 则标题栏(如果存在)在客户区的左部分。若是其他语言,该风格被忽略 WS_EX_LEFTSCROLLBAR = $4000; WS_EX_RIGHTSCROLLBAR = 0; // 允许用户使用 Tab 键等在窗口的子窗口间搜索 WS_EX_CONTROLPARENT = $10000; WS_EX_STATICEDGE = $20000; WS_EX_APPWINDOW = $40000; // 当窗口可见时,将一个顶层窗口放置到任务栏上 WS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE or WS_EX_CLIENTEDGE); WS_EX_PALETTEWINDOW = (WS_EX_WINDOWEDGE or WS_EX_TOOLWINDOW or WS_EX_TOPMOST); // Windows 2000/XP:创建一个层窗口(layered window),该样式不能应用于子窗口, // 并且不能用于拥有CS_OWNDC 或 CS_CLASSDC 风格的窗口 WS_EX_LAYERED = $00080000; // Windows 2000/XP: 使用该风格创建的窗口不会将窗口布局传递到子窗口 WS_EX_NOINHERITLAYOUT = $00100000; // Disable inheritence of mirroring by children // Windows 2000/XP: 窗口水平坐标原点在窗口右边界,水平坐标从右向左递增 WS_EX_LAYOUTRTL = $00400000; // Right to left mirroring // Windows XP:使用双缓冲区绘制所有子窗口 // 当窗口含有 CS_OWNDC 或 CS_CLASSDC 样式时不能指定该样式 WS_EX_COMPOSITED = $02000000; // Windows 2000/XP:对于使用该样式创建的始终在最顶层的窗口, // 当用户单击它时不会将其设为前台窗口,并且在用户将现有的前台窗口最小化或关闭时, // 也不会将该窗口设为前台窗口。要激活该窗口,可使用 SetActiveWindow 或 SetForegroundWindow 函数。 // 默认情况下窗口不会在任务栏上出现,要使窗口在任务栏上显示,可指定 WS_EX_APPWINDOW 风格 WS_EX_NOACTIVATE = $08000000; type PWindowPlacement = ^TWindowPlacement; TWindowPlacement = packed record length: UINT; flags: UINT; showCmd: UINT; ptMinPosition: TPoint; ptMaxPosition: TPoint; rcNormalPosition: TRect; end; PWindowInfo = ^TWindowInfo; TWindowInfo = packed record cbSize: DWORD; rcWindow: TRect; rcClient: TRect; dwStyle: DWORD; dwExStyle: DWORD; dwOtherStuff: DWORD; cxWindowBorders: UINT; cyWindowBorders: UINT; atomWindowType: TAtom; wCreatorVersion: WORD; end; TWNDPROC = function (AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; const GWL_WNDPROC = -4; GWL_HINSTANCE = -6; GWL_HWNDPARENT = -8; GWL_STYLE = -16; GWL_EXSTYLE = -20; GWL_USERDATA = -21; GWL_ID = -12; function GetWindowInfo(AWnd: HWND; var pwi: TWindowInfo): BOOL; stdcall; external user32 name 'GetWindowInfo'; function SetWindowLongA(AWnd: HWND; nIndex: Integer; dwNewLong: Longint): Longint; stdcall; external user32 name 'SetWindowLongA'; function GetWindowLongA(AWnd: HWND; nIndex: Integer): Longint; stdcall; external user32 name 'GetWindowLongA'; function IsHungAppWindow(Awnd : HWND): boolean; stdcall; external user32 name 'IsHungAppWindow'; procedure NotifyWinEvent(event: DWORD; hwnd: HWND; idObject, idChild: Cardinal); stdcall; external user32 name 'NotifyWinEvent'; function DefWindowProcA(AWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; external user32 name 'DefWindowProcA'; function CallWindowProcA(lpPrevWndFunc: TFNWndProc; AWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; external user32 name 'CallWindowProcA'; { //uCmd 可选值: GW_HWNDFIRST = 0; GW_HWNDLAST = 1; GW_HWNDNEXT = 2; //同级别 Z 序之下 GW_HWNDPREV = 3; //同级别 Z 序之上 GW_OWNER = 4; GW_CHILD = 5; } function GetWindow(AWnd: HWND; uCmd: UINT): HWND; stdcall; external user32 name 'GetWindow'; // 获取指定窗口的子窗口中最顶层的窗口句柄 function GetTopWindow(AWnd: HWND): HWND; stdcall; external user32 name 'GetTopWindow'; function FindWindowA(lpClassName, lpWindowName: PAnsiChar): HWND; stdcall; external user32 name 'FindWindowA'; function FindWindowExA(AParent, AChild: HWND; AClassName, AWindowName: PAnsiChar): HWND; stdcall; external user32 name 'FindWindowExA'; // function GetWindowThreadProcessId(AWnd: HWND; var dwProcessId: DWORD): DWORD; stdcall; overload; external user32 name 'GetWindowThreadProcessId'; function GetWindowThreadProcessId(AWnd: HWND; lpdwProcessId: Pointer): DWORD; stdcall; overload; external user32 name 'GetWindowThreadProcessId'; function ShowWindow(AWnd: HWND; nCmdShow: Integer): BOOL; stdcall; external user32 name 'ShowWindow'; function UpdateWindow(AWnd: HWND): BOOL; stdcall; external user32 name 'UpdateWindow'; function ExitWindowsEx(uFlags: UINT; dwReserved: DWORD): BOOL; stdcall; external user32 name 'ExitWindowsEx'; function CreateWindowExA(dwExStyle: DWORD; lpClassName: PAnsiChar; lpWindowName: PAnsiChar; dwStyle: DWORD; X, Y, nWidth, nHeight: Integer; AWndParent: HWND; AMenu: HMENU; hInstance: HINST; lpParam: Pointer): HWND; stdcall; external user32 name 'CreateWindowExA'; function CreateWindowExW(dwExStyle: DWORD; lpClassName: PWideChar; lpWindowName: PWideChar; dwStyle: DWORD; X, Y, nWidth, nHeight: Integer; AWndParent: HWND; AMenu: HMENU; hInstance: HINST; lpParam: Pointer): HWND; stdcall; external user32 name 'CreateWindowExW'; function GetDesktopWindow: HWND; stdcall; external user32 name 'GetDesktopWindow'; function SetParent(AWndChild, AWndNewParent: HWND): HWND; stdcall; external user32 name 'SetParent'; function SwitchToThisWindow(AWnd: hwnd; fAltTab: boolean): boolean; stdcall; external user32; function IsWindow(AWnd: HWND): BOOL; stdcall; external user32 name 'IsWindow'; function DestroyWindow(AWnd: HWND): BOOL; stdcall; external user32 name 'DestroyWindow'; function SetPropA(AWnd: HWND; lpStr: PAnsiChar; hData: THandle): BOOL; stdcall; external user32 name 'SetPropA'; function SetTimer(AWnd: HWND; nIDEvent, uElapse: UINT; lpTimerFunc: TFNTimerProc): UINT; stdcall; external user32 name 'SetTimer'; function KillTimer(AWnd: HWND; uIDEvent: UINT): BOOL; stdcall; external user32 name 'KillTimer'; function InvalidateRect(AWnd: HWND; lpRect: PRect; bErase: BOOL): BOOL; stdcall; external user32 name 'InvalidateRect'; { Invalidate()是强制系统进行重画,但是不一定就马上进行重画。因为Invalidate()只是通知系统, 此时的窗口已经变为无效。强制系统调用WM_PAINT,而这个消息只是Post就是将该消息放入消息队列。 当执行到WM_PAINT消息时才会对敞口进行重绘。 UpdateWindow只向窗体发送WM_PAINT消息,在发送之前判断GetUpdateRect(hWnd,NULL,TRUE)看有无可绘制的客户区域, 如果没有,则不发送WM_PAINT。 RedrawWindow()则是具有Invalidate()和UpdateWindow()的双特性。声明窗口的状态为无效,并立即更新窗口,立即调用WM_PAINT消息处理。 InvalidateRect(hctrl,null,true) ; UpdateWindow(hctrl); 这两个函数组合起来是什么意思呢? InvalidateRect是会触发WM_PAINT事件,但是不是立即就触发,一般都会等当前操作的过程结束才触发, 如果需要立即触发, 那么配合UpdateWindow()使用就可以了。先执行InvalidateRect,再执行UpdateWindow(). flag   RDW_INVALIDATE or RDW_VALIDATE or RDW_FRAME RDW_ERASENOW RDW_UPDATENOW RDW_ERASE 重画前,先清除重画区域的背景。也必须指定RDW_INVALIDATE RDW_NOERASE 禁止删除重画区域的背景 RDW_NOFRAME 禁止非客户区域重画 } function RedrawWindow(AWnd: HWND; lprcUpdate: PRect; hrgnUpdate: HRGN; flags: UINT): BOOL; stdcall; external user32 name 'RedrawWindow'; function MessageBoxA(AWnd: HWND; lpText, lpCaption: PAnsiChar; uType: UINT): Integer; stdcall; external user32 name 'MessageBoxA'; (* 禁止截屏PrintScreen FormCreate RegisterHotKey(Handle, IDHOT_SNAPDESKTOP, 0, VK_SNAPSHOT); FormClose UnregisterHotKey(Handle, IDHOT_SNAPDESKTOP); FormActivate RegisterHotKey (Handle, IDHOT_SNAPWINDOW, MOD_ALT, VK_SNAPSHOT); FormDeactivate UnregisterHotKey(Handle, IDHOT_SNAPWINDOW); *) const IDHOT_SNAPWINDOW = -1; { SHIFT-PRINTSCRN } IDHOT_SNAPDESKTOP = -2; { PRINTSCRN } function RegisterHotKey(AWnd: HWND; id: Integer; fsModifiers, vk: UINT): BOOL; stdcall; external user32 name 'RegisterHotKey'; function UnregisterHotKey(AWnd: HWND; id: Integer): BOOL; stdcall; external user32 name 'UnregisterHotKey'; function GetCapture: HWND; stdcall; external user32 name 'GetCapture'; { setCapture捕获以下鼠标事件: onmousedown、 onmouseup、 onmousemove、 onclick、 ondblclick、 onmouseover和 onmouseout, SetCapture会引起失去鼠标捕获的窗口接收一个WM_CAPTURECHANGED消息 该函数在属于当前线程的指定窗口里设置鼠标捕获。一旦窗口捕获了鼠标, 所有鼠标输入都针对该窗口,无论光标是否在窗口的边界内。同一时刻只能 有一个窗口捕获鼠标。如果鼠标光标在另一个线程创建的窗口上,只有当鼠 标键按下时系统才将鼠标输入指向指定的窗口 此函数不能被用来捕获另一进程的鼠标输入 TSplitter 需要调用这个函数 Mouseup ReleaseCapture } function SetCapture(AWnd: HWND): HWND; stdcall; external user32 name 'SetCapture'; function ReleaseCapture: BOOL; stdcall; external user32 name 'ReleaseCapture'; function GetClassInfoA(AInstance: HINST; lpClassName: PAnsiChar; var lpWndClass: TWndClassA): BOOL; stdcall; external user32 name 'GetClassInfoA'; function GetClassInfoExA(AInstance: HINST; Classname: PAnsiChar; var WndClass: TWndClassExA): BOOL; stdcall; external user32 name 'GetClassInfoExA'; function GetClassNameA(AWnd: HWND; lpClassName: PAnsiChar; nMaxCount: Integer): Integer; stdcall; external user32 name 'GetClassNameA'; const { Class styles } CS_VREDRAW = DWORD(1); CS_HREDRAW = DWORD(2); CS_KEYCVTWINDOW = 4; CS_DBLCLKS = 8; CS_OWNDC = $20; CS_CLASSDC = $40; CS_PARENTDC = $80; CS_NOKEYCVT = $100; // 则窗口上的关闭按钮和系统菜单上的关闭命令失效 CS_NOCLOSE = $200; // 菜单,对话框,下拉框都拥有CS_SAVEBITS标志。当窗口使用这个标志时, // 系统用位图形式保存一份被窗口遮盖(或灰隐)的屏幕图象 CS_SAVEBITS = $800; CS_BYTEALIGNCLIENT = $1000; CS_BYTEALIGNWINDOW = $2000; // http://blog.csdn.net/nskevin/article/details/2939857 // window系统提供了三种类型的窗口类 // 系统全局类(System global classes) // 应用程序全局类(Application global classes) // CS_GLOBALCLASS // 应用程序全局类只是在进程内部的“全局”而已。这是什么意思呢?一个DLL或.EXE可以注册一个类, // 这个类可以让在相同的进程空间里其他.EXE和DLL使用。如果一个DLL注册了一个非应用程序全局类的窗口类, // 那么,只有该DLL可以使用该类,同样的,.EXE里注册的非应用程序全局类也适用这个规则,即该类只在该.EXE里有效 // 作为这个特性的扩展,win32有一项技术,允许一个第三方窗口控件在DLL里实现,然后把这个DLL载入和初始化到每个 // Win32进程空间里。这项技术的细节是,把DLL的名字写入注册表的指定键值里: // HKEY_LOCAL_MACHINE/Software/Microsoft/Windows NT/CurrentVersion/Windows/APPINIT_DLLS // 这样当任意一个win32应用程序加载的时候,系统也同时将该dll加载到进程空间里(这可能有点过于奢侈, // 因为很多win32程序不一定会使用该控件)。DLL在初始化的时候注册应用程序全局类,这样的窗口类就可以 // 在每个进程空间的.EXE或DLL里使用了。这个技术基于win32系统的这个特性:允许在每个进程空间里自动的 // (也是强制的)加载特定的DLL(事实上,这也是打破进程边界,把你的代码切入到其他进程里的一种办法) // 应用程序局部类(Application local classes) // windows 本身注册了几个系统全局类供全部的应用程序使用,这些类包括了以下的常用标准窗口控件 // Listbox , ComboBox , ScrollBar , Edit , Button , Static // 所有的win32应用程序都可以使用系统全局类,但不能增加或删除一个这样的类 // 应用程序局部类是由应用程序注册的并由它自己专用的窗口类, // 尽管应用程序可以注册任意数目的局部类,但绝大多数应用程序只注册一个, // 这个窗口类支持应用程序主窗口的窗口过程。 // 注册应用程序局部类与注册一个应用程序全局类差不多, // 只是WNDCLASSEX结构的style成员没有设置成CS_GLOBALCLASS风格。 // windows系统销毁一个局部类是在注册它的应用程序关闭时, // 应用程序也可用函数UnregisterClass来删除一个局部类并释放与之相关的内存空间。 CS_GLOBALCLASS = $4000; CS_IME = $10000; CS_DROPSHADOW = $20000; function RegisterClassA(const lpWndClass: TWndClassA): ATOM; stdcall; external user32 name 'RegisterClassA'; function RegisterClassExA(const WndClass: TWndClassExA): ATOM; stdcall; external user32 name 'RegisterClassExA'; function UnregisterClassA(lpClassName: PAnsiChar; hInstance: HINST): BOOL; stdcall; external user32 name 'UnregisterClassA'; function OpenIcon(AWnd: HWND): BOOL; stdcall; external user32 name 'OpenIcon'; function CloseWindow(AWnd: HWND): BOOL; stdcall; external user32 name 'CloseWindow'; function MoveWindow(AWnd: HWND; X, Y, nWidth, nHeight: Integer; bRepaint: BOOL): BOOL; stdcall; external user32 name 'MoveWindow'; { // hWndInsertAfter: HWND_BOTTOM, HWND_NOTOPMOST, HWND_TOP, HWND_TOPMOST // 设置窗体 ZOrder // SWP_NOACTIVATE hWndInsertAfter 在z序中的位于被置位的窗口前的窗口句柄 hWndInsertAfter 置于 hWnd 之前 // SetWindowPos(FHandle, Pos, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE); } function SetWindowPos(AWnd: HWND; hWndInsertAfter: HWND; X, Y, cx, cy: Integer; uFlags: UINT): BOOL; stdcall; external user32 name 'SetWindowPos'; function GetWindowPlacement(AWnd: HWND; WindowPlacement: PWindowPlacement): BOOL; stdcall; external user32 name 'GetWindowPlacement'; function SetWindowPlacement(AWnd: HWND; WindowPlacement: PWindowPlacement): BOOL; stdcall; external user32 name 'SetWindowPlacement'; function GetWindowModuleFileName(Awnd: HWND; pszFileName: PAnsiChar; cchFileNameMax: UINT): UINT; stdcall; external user32 name 'GetWindowModuleFileNameA'; function BringWindowToTop(AWnd: HWND): BOOL; stdcall; external user32 name 'BringWindowToTop'; function IsZoomed(AWnd: HWND): BOOL; stdcall; external user32 name 'IsZoomed'; function GetClientRect(AWnd: HWND; var lpRect: TRect): BOOL; stdcall; external user32 name 'GetClientRect'; function GetWindowRect(AWnd: HWND; var lpRect: TRect): BOOL; stdcall; external user32 name 'GetWindowRect'; function GetUpdateRgn(AWnd: HWND; hRgn: HRGN; bErase: BOOL): Integer; stdcall; external user32 name 'GetUpdateRgn'; function SetWindowRgn(AWnd: HWND; hRgn: HRGN; bRedraw: BOOL): Integer; stdcall; external user32 name 'SetWindowRgn'; function GetWindowRgn(AWnd: HWND; hRgn: HRGN): Integer; stdcall; external user32 name 'GetWindowRgn'; function GetUpdateRect(AWnd: HWND; lpRect: PRect; bErase: BOOL): BOOL; stdcall; external user32 name 'GetUpdateRect'; function ExcludeUpdateRgn(ADC: HDC; hWnd: HWND): Integer; stdcall; external user32 name 'ExcludeUpdateRgn'; function WindowFromPoint(APoint: TPoint): HWND; stdcall; external user32 name 'WindowFromPoint'; function ChildWindowFromPoint(AWndParent: HWND; Point: TPoint): HWND; stdcall; external user32 name 'ChildWindowFromPoint'; (* http://blog.sina.com.cn/s/blog_48f93b530100jonm.html 多层次窗口调整大小 如果窗口包含很多子窗口,当我们调整窗口大小时,可能要同时调整子窗口的位置和大小。 此时若使用 MoveWindow() 或 SetWindowPos() 等函数进行调整,由于这些函数会等窗口 刷新完才返回,因此当有大量子窗口时,这个过程肯定会引起闪烁。 这时我们可以应用 BeginDeferWindowPos(), DeferWindowPos() 和 EndDeferWindowPos() 三个函数解决。首先调用 BeginDeferWindowPos(),设定需要调整的窗口个数;然后用 DeferWindowPos() 移动窗口(并非立即移动窗口);最后调用 EndDeferWindowPos() 一次性完成所有窗口的调整 *) type HDWP = THandle; function BeginDeferWindowPos(nNumWindows: Integer): HDWP; stdcall; external user32 name 'BeginDeferWindowPos'; function DeferWindowPos(AWinPosInfo: HDWP; AWnd: HWND; AWndInsertAfter: HWND; x, y, cx, cy: Integer; uFlags: UINT): HDWP; stdcall; external user32 name 'DeferWindowPos'; function EndDeferWindowPos(AWinPosInfo: HDWP): BOOL; stdcall; external user32 name 'EndDeferWindowPos'; const CWP_ALL = 0; CWP_SKIPINVISIBLE = 1; CWP_SKIPDISABLED = 2; CWP_SKIPTRANSPARENT = 4; function ChildWindowFromPointEx(AWnd: HWND; Point: TPoint; Flags: UINT): HWND; stdcall; external user32 name 'ChildWindowFromPointEx'; function IsWindowVisible(AWnd: HWND): BOOL; stdcall; external user32 name 'IsWindowVisible'; function SetFocus(AWnd: HWND): HWND; stdcall; external user32 name 'SetFocus'; function GetActiveWindow: HWND; stdcall; external user32 name 'GetActiveWindow'; function GetFocus: HWND; stdcall; external user32 name 'GetFocus'; function GetForegroundWindow: HWND; stdcall; external user32 name 'GetForegroundWindow'; function SetForegroundWindow(AWnd: HWND): BOOL; stdcall; external user32 name 'SetForegroundWindow'; type PTrackMouseEvent = ^TTrackMouseEvent; TTrackMouseEvent = record cbSize: DWORD; dwFlags: DWORD; hwndTrack: HWND; dwHoverTime: DWORD; end; const { Key State Masks for Mouse Messages } MK_LBUTTON = 1; MK_RBUTTON = 2; MK_SHIFT = 4; MK_CONTROL = 8; MK_MBUTTON = $10; TME_HOVER = $00000001; TME_LEAVE = $00000002; TME_QUERY = $40000000; TME_CANCEL = DWORD($80000000); HOVER_DEFAULT = DWORD($FFFFFFFF); function TrackMouseEvent(var EventTrack: TTrackMouseEvent): BOOL; stdcall; external user32 name 'TrackMouseEvent'; implementation end.
unit UnitTest; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Controls.Presentation, FMX.Edit; type TForm1 = class(TForm) PaintBox1: TPaintBox; Button1: TButton; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormTouch(Sender: TObject; const Touches: TTouches; const Action: TTouchAction); procedure PaintBox1Paint(Sender: TObject; Canvas: TCanvas); procedure PaintBox1Tap(Sender: TObject; const Point: TPointF); private { Private declarations } FTouches: TTouches; FBitmap: TBitmap; procedure DoPaint; procedure DrawPoint(APoint: TPointF; ASize: Integer = 2); public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} { TForm1 } procedure TForm1.Button1Click(Sender: TObject); begin FBitmap.SetSize(Width, Height); FBitmap.Clear(TAlphaColors.White); PaintBox1.Repaint; end; procedure TForm1.DoPaint; var I: Integer; begin PaintBox1.Canvas.BeginScene; FBitmap.Canvas.Stroke.Color := TAlphaColors.Black; for I := 0 to High(FTouches) do begin DrawPoint(FTouches[I].Location); end; PaintBox1.Canvas.EndScene; end; procedure TForm1.DrawPoint(APoint: TPointF; ASize: Integer); var R: TRectF; locOffset: TPointF; begin if FBitmap <> nil then begin FBitmap.Canvas.BeginScene; try locOffset := TPointF.Create(ASize, ASize); R := TRectF.Create(APoint - locOffset, APoint + locOffset); FBitmap.Canvas.DrawRect(R, 0, 0, [], 1); finally FBitmap.Canvas.EndScene; end; PaintBox1.Repaint; end; end; procedure TForm1.FormActivate(Sender: TObject); begin FBitmap.SetSize(Width, Height); FBitmap.Clear(TAlphaColors.White); end; procedure TForm1.FormCreate(Sender: TObject); begin FBitmap := TBitmap.Create; FBitmap.SetSize(Width, Height); FBitmap.Clear(TAlphaColors.White); end; procedure TForm1.FormTouch(Sender: TObject; const Touches: TTouches; const Action: TTouchAction); begin FTouches := Touches; DoPaint; end; procedure TForm1.PaintBox1Paint(Sender: TObject; Canvas: TCanvas); var R: TRectF; begin R := TRectF.Create(0, 0, FBitmap.Width, FBitmap.Height); PaintBox1.Canvas.DrawBitmap(FBitmap, R, R, 1, True); end; procedure TForm1.PaintBox1Tap(Sender: TObject; const Point: TPointF); begin PaintBox1.Canvas.BeginScene; FBitmap.Canvas.Stroke.Color := TAlphaColors.Red; DrawPoint(Point, 5); PaintBox1.Canvas.EndScene; end; end.
unit CommonObjs; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; const tf_Create_Dir = 1; tf_Include_Radar = 2; tf_Include_Year = 4; tf_Include_Month = 8; tf_Include_Day = $10; // User levels ul_God = 9; ul_Author = 8; ul_Supervisor = 7; ul_Service = 6; ul_Designer = 5; ul_Operator = 4; ul_Guest = 3; ul_NotLogged = 2; ul_NotUser = 1; ul_Failed = 0; type MaxMin = packed record Min: Smallint; Max: Smallint; end; // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Borland types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:string - "http://www.w3.org/2001/XMLSchema" // !:int - "http://www.w3.org/2001/XMLSchema" // !:dateTime - "http://www.w3.org/2001/XMLSchema" // !:boolean - "http://www.w3.org/2001/XMLSchema" // !:unsignedInt - "http://www.w3.org/2001/XMLSchema" // !:double - "http://www.w3.org/2001/XMLSchema" // !:TIntegerDynArray - "http://www.borland.com/namespaces/Types" // !:float - "http://www.w3.org/2001/XMLSchema" // !:TStringDynArray - "http://www.borland.com/namespaces/Types" TxRxInfo = class; { "urn:CommunicationObj" } FormatData = class; { "urn:CommunicationObj" } TTemplateInfo = class; { "urn:CommunicationObj" } { "urn:CommunicationObj" } DesignKindEnum = (dk_PPI, dk_RHI); { "urn:CommunicationObj" } TxPulseEnum = (tx_Pulse_Long, tx_Pulse_Short, tx_Pulse_None); { "urn:CommunicationObj" } TxRxOptionsEnum = (xo_No, xo_Yes, xo_Nevermind); { "urn:CommunicationObj" } TWaveLengthEnum = (wl_3cm, wl_10cm); { "urn:CommunicationObj" } RadarBrandsEnum = (rbUnknown, rbMRL5, rbRC32B, rbMRL5M, rbResearch); { "urn:CommunicationObj" } TSyncSourceEnum = (ss_Internal, ss_External_Digital, ss_Analog_Raising_Edge, ss_Analog_Falling_Edge); // ************************************************************************ // // Namespace : urn:LoginWSIntf // ************************************************************************ // TUserInfo = class(TRemotable) private FName: WideString; FLevel: Integer; published property Name: WideString read FName write FName; property Level: Integer read FLevel write FLevel; end; // ************************************************************************ // // Namespace : urn:CommunicationObj // ************************************************************************ // TAuthHeader = class(TSOAPHeader) private FUserName: WideString; FToken: WideString; FLevel: Integer; published property UserName: WideString read FUserName write FUserName; property Token: WideString read FToken write FToken; property Level: Integer read FLevel write FLevel; end; // ************************************************************************ // // Namespace : urn:CommonObjs // ************************************************************************ // TCyclopAuthHeader = class(TSOAPHeader) private FUserName: WideString; FToken: WideString; published property UserName: WideString read FUserName write FUserName; property Token: WideString read FToken write FToken; end; // ************************************************************************ // // Namespace : urn:CommunicationObj // ************************************************************************ // TxRxInfo = class(TRemotable) private FCRT: TxRxOptionsEnum; FCMG: TxRxOptionsEnum; FCMS: TxRxOptionsEnum; published property CRT: TxRxOptionsEnum read FCRT write FCRT; property CMG: TxRxOptionsEnum read FCMG write FCMG; property CMS: TxRxOptionsEnum read FCMS write FCMS; end; // ************************************************************************ // // Namespace : urn:CommunicationObj // ************************************************************************ // FormatData = class(TRemotable) private FOnda: TWaveLengthEnum; FCeldas: Integer; FLong: Integer; FPotMet: Single; published property Onda: TWaveLengthEnum read FOnda write FOnda; property Celdas: Integer read FCeldas write FCeldas; property Long: Integer read FLong write FLong; property PotMet: Single read FPotMet write FPotMet; end; TFormatArray = array of FormatData; { "urn:CommunicationObj" } // ************************************************************************ // // Namespace : urn:CommunicationObj // ************************************************************************ // TTemplateInfo = class(TRemotable) private FName: WideString; FFlags: Integer; FAddress: WideString; FFTPSettings: WideString; FPeriod: TXSDateTime; FDelay: TXSDateTime; FKind: DesignKindEnum; FStart: Integer; FFinish: Integer; FSpeed: Integer; FAngles: Integer; FFormats: Integer; FAutomatic: Boolean; FSentFTP: Boolean; FLastTime: TXSDateTime; FNextTime: TXSDateTime; FADRate: Cardinal; FSectors: Integer; FPulse: TxPulseEnum; FTR1: TxRxInfo; FTR2: TxRxInfo; FCH10cm_B0: Double; FCH10cm_B1: Double; FCH10cm_B2: Double; FCH10cm_A1: Double; FCH10cm_A2: Double; FCH3cm_B0: Double; FCH3cm_B1: Double; FCH3cm_B2: Double; FCH3cm_A1: Double; FCH3cm_A2: Double; FFilter: Boolean; FSaveFilter: Boolean; FApplyFilter: Boolean; FCH10cm_Threshold: Double; FCH3cm_Threshold: Double; FMaxAngleEchoFilter: Double; FMaxHeightEchoFilter: Integer; FMaxDistanceEchoFilter: Integer; FAngleList: TIntegerDynArray; FFormatList: TFormatArray; private procedure SetAutomatic(const Value: boolean); procedure SetLastTime(const Value: TXSDateTime); procedure SetAngles(const Value: integer); procedure SetFormats(const Value: integer); public constructor Create; override; destructor Destroy; override; published property Name: WideString read FName write FName; property Flags: Integer read FFlags write FFlags; property Address: WideString read FAddress write FAddress; property FTPSettings: WideString read FFTPSettings write FFTPSettings; property Period: TXSDateTime read FPeriod write FPeriod; property Delay: TXSDateTime read FDelay write FDelay; property Kind: DesignKindEnum read FKind write FKind; property Start: Integer read FStart write FStart; property Finish: Integer read FFinish write FFinish; property Speed: Integer read FSpeed write FSpeed; property Angles: Integer read FAngles write SetAngles; property Formats: Integer read FFormats write SetFormats; property Automatic: Boolean read FAutomatic write SetAutomatic; property SentFTP: Boolean read FSentFTP write FSentFTP; property LastTime: TXSDateTime read FLastTime write SetLastTime; property NextTime: TXSDateTime read FNextTime write FNextTime; property ADRate: Cardinal read FADRate write FADRate; property Sectors: Integer read FSectors write FSectors; property Pulse: TxPulseEnum read FPulse write FPulse; property TR1: TxRxInfo read FTR1 write FTR1; property TR2: TxRxInfo read FTR2 write FTR2; property CH10cm_B0: Double read FCH10cm_B0 write FCH10cm_B0; property CH10cm_B1: Double read FCH10cm_B1 write FCH10cm_B1; property CH10cm_B2: Double read FCH10cm_B2 write FCH10cm_B2; property CH10cm_A1: Double read FCH10cm_A1 write FCH10cm_A1; property CH10cm_A2: Double read FCH10cm_A2 write FCH10cm_A2; property CH3cm_B0: Double read FCH3cm_B0 write FCH3cm_B0; property CH3cm_B1: Double read FCH3cm_B1 write FCH3cm_B1; property CH3cm_B2: Double read FCH3cm_B2 write FCH3cm_B2; property CH3cm_A1: Double read FCH3cm_A1 write FCH3cm_A1; property CH3cm_A2: Double read FCH3cm_A2 write FCH3cm_A2; property Filter: Boolean read FFilter write FFilter; property SaveFilter: Boolean read FSaveFilter write FSaveFilter; property ApplyFilter: Boolean read FApplyFilter write FApplyFilter; property CH10cm_Threshold: Double read FCH10cm_Threshold write FCH10cm_Threshold; property CH3cm_Threshold: Double read FCH3cm_Threshold write FCH3cm_Threshold; property MaxAngleEchoFilter: Double read FMaxAngleEchoFilter write FMaxAngleEchoFilter; property MaxHeightEchoFilter: Integer read FMaxHeightEchoFilter write FMaxHeightEchoFilter; property MaxDistanceEchoFilter: Integer read FMaxDistanceEchoFilter write FMaxDistanceEchoFilter; property AngleList: TIntegerDynArray read FAngleList write FAngleList; property FormatList: TFormatArray read FFormatList write FFormatList; end; // ************************************************************************ // // Namespace : urn:CommunicationObj // ************************************************************************ // TChannelsData = class(TRemotable) public FCh1Data: TCardinalDynArray; FCh2Data: TCardinalDynArray; published property Ch1Data: TCardinalDynArray read FCh1Data write FCh1Data; property Ch2Data: TCardinalDynArray read FCh2Data write FCh2Data; end; // ************************************************************************ // // Namespace : urn:CommunicationObj // ************************************************************************ // TLogEntry = class(TRemotable) private FMsgCode: Integer; FDateTime: TXSDateTime; FCategory: Integer; FClient: WideString; FTitle: WideString; FMsg: WideString; FZone: WideString; public destructor Destroy; override; published property MsgCode: Integer read FMsgCode write FMsgCode; property DateTime: TXSDateTime read FDateTime write FDateTime; property Category: Integer read FCategory write FCategory; property Client: WideString read FClient write FClient; property Title: WideString read FTitle write FTitle; property Msg: WideString read FMsg write FMsg; property Zone: WideString read FZone write FZone; end; TCalibrationTable = class(TRemotable) private FData: TWordDynArray; FRange: Integer; FSensibility: Integer; public constructor Init(Range : integer; Sensibility : integer); published property Data: TWordDynArray read FData write FData; property Range: Integer read FRange write FRange; property Sensibility: Integer read FSensibility write FSensibility; end; implementation uses SysUtils; constructor TTemplateInfo.Create; begin inherited Create; fTR1 := TxRxInfo.Create; fTR2 := TxRxInfo.Create; end; destructor TTemplateInfo.Destroy; var I: Integer; begin for I := 0 to Length(FFormatList)-1 do if Assigned(FFormatList[I]) then FFormatList[I].Free; SetLength(FFormatList, 0); if Assigned(FPeriod) then FPeriod.Free; if Assigned(FDelay) then FDelay.Free; if Assigned(FLastTime) then FLastTime.Free; if Assigned(FNextTime) then FNextTime.Free; if Assigned(FTR1) then FTR1.Free; if Assigned(FTR2) then FTR2.Free; inherited Destroy; end; procedure TTemplateInfo.SetAngles(const Value: integer); begin fAngles := Value; SetLength(fAngleList, Value); end; procedure TTemplateInfo.SetAutomatic(const Value: boolean); begin fAutomatic := Value; if(fNextTime = nil) then fNextTime := TXSDateTime.Create; if fAutomatic then fNextTime.AsDateTime := fPeriod.AsDateTime * (trunc(Now/fPeriod.AsDateTime) + 1) + fDelay.AsDateTime else fNextTime.AsDateTime := 0; end; procedure TTemplateInfo.SetFormats(const Value: integer); var i : integer; begin fFormats := Value; SetLength(fFormatList, Value); for i := Low(fFormatList) to High(fFormatList) do if(fFormatList[i] = nil) then fFormatList[i] := FormatData.Create; end; procedure TTemplateInfo.SetLastTime(const Value: TXSDateTime); begin fLastTime := Value; if(fNextTime = nil) then fNextTime := TXSDateTime.Create; fNextTime.AsDateTime := fPeriod.AsDateTime * (trunc(fLastTime.AsDateTime/fPeriod.AsDateTime) + 1) + fDelay.AsDateTime; end; { TLogEntry } destructor TLogEntry.Destroy; begin if Assigned(FDateTime) then FDateTime.Free; inherited; end; { TCalibrationTable } constructor TCalibrationTable.Init(Range, Sensibility: integer); begin inherited Create; fRange := Range; fSensibility := Sensibility; SetLength(fData, fRange); end; initialization RemClassRegistry.RegisterXSInfo(TypeInfo(DesignKindEnum), 'urn:CommunicationObj', 'DesignKindEnum'); RemClassRegistry.RegisterXSInfo(TypeInfo(TxPulseEnum), 'urn:CommunicationObj', 'TxPulseEnum'); RemClassRegistry.RegisterXSInfo(TypeInfo(TxRxOptionsEnum), 'urn:CommunicationObj', 'TxRxOptionsEnum'); RemClassRegistry.RegisterXSInfo(TypeInfo(TWaveLengthEnum), 'urn:CommunicationObj', 'TWaveLengthEnum'); RemClassRegistry.RegisterXSClass(TxRxInfo, 'urn:CommunicationObj', 'TxRxInfo'); RemClassRegistry.RegisterXSClass(FormatData, 'urn:CommunicationObj', 'FormatData'); RemClassRegistry.RegisterXSClass(TChannelsData, 'urn:CommunicationObj', 'TChannelsData'); RemClassRegistry.RegisterXSClass(TCalibrationTable, 'urn:CommunicationObj', 'TCalibrationTable'); RemClassRegistry.RegisterXSInfo(TypeInfo(TFormatArray), 'urn:CommunicationObj', 'TFormatArray'); RemClassRegistry.RegisterXSClass(TTemplateInfo, 'urn:CommunicationObj', 'TTemplateInfo'); RemClassRegistry.RegisterXSClass(TLogEntry, 'urn:CommunicationObj', 'TLogEntry'); RemClassRegistry.RegisterXSInfo(TypeInfo(TSyncSourceEnum), 'urn:CommunicationObj', 'TSyncSourceEnum'); end.
{******************************************************************************} { } { Delphi SwagDoc Library } { Copyright (c) 2018 Marcelo Jaloto } { https://github.com/marcelojaloto/SwagDoc } { } {******************************************************************************} { } { 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 Swag.Doc.SecurityDefinition; interface uses System.JSON, Swag.Common.Types; type /// <summary> /// A declaration of the security schemes available to be used in the specification. /// This does not enforce the security schemes on the operations and only serves to provide the relevant details for each scheme. /// </summary> TSwagSecurityDefinition = class abstract(TObject) protected fSchemaName: TSwagSecuritySchemaName; fDescription: string; function GetTypeSecurity: TSwagSecurityDefinitionType; virtual; abstract; function ReturnTypeSecurityToString: string; virtual; public function GenerateJsonObject: TJSONObject; virtual; abstract; /// <summary> /// A single security scheme definition, mapping a "name" to the scheme it defines. /// </summary> property SchemaName: TSwagSecuritySchemaName read fSchemaName write fSchemaName; /// <summary> /// Required. The type of the security scheme. Valid values are "basic", "apiKey" or "oauth2". /// </summary> property TypeSecurity: TSwagSecurityDefinitionType read GetTypeSecurity; /// <summary> /// A short description for security scheme. /// </summary> property Description: string read fDescription write fDescription; end; implementation uses Swag.Common.Consts; { TSwagSecurityDefinition } function TSwagSecurityDefinition.ReturnTypeSecurityToString: string; begin Result := c_SwagSecurityDefinitionType[GetTypeSecurity]; end; end.
unit AqDrop.Core.Helpers.TObject; {$I '..\Core\AqDrop.Core.Defines.Inc'} interface uses System.Rtti, System.SyncObjs, System.Generics.Collections, {$IF CompilerVersion >= 27} // DXE6+ System.JSON; {$ELSE} Data.DBXJSON; {$ENDIF} type TAqFieldMapping = class strict private FFieldFrom: TRttiField; FFieldTo: TRttiField; public constructor Create(const pFieldFrom, pFieldTo: TRttiField); property FieldFrom: TRttiField read FFieldFrom; property FieldTo: TRttiField read FFieldTo; end; {TODO 3 -oTatu -cMelhoria: tirar class method de clone e colocar em classe especializada} TAqObjectMapping = class strict private FFieldMappings: TObjectList<TAqFieldMapping>; class var FLocker: TCriticalSection; class var FMappings: TObjectDictionary<string, TAqObjectMapping>; class var FFieldsToIgnore: TList<TRttiField>; class procedure AddDefaultFieldsToIgnoreList; private class procedure _Initialize; class procedure _Finalize; public constructor Create(const pFrom, pTo: TClass); destructor Destroy; override; procedure Execute(const pFrom, pTo: TObject); class procedure Clone(const pFrom, pTo: TObject); end; TAqObjectHelper = class helper for TObject public function CloneTo(const pObject: TObject): TObject; overload; function CloneTo<T: class, constructor>: T; overload; end; implementation uses System.SysUtils, Data.DBXJSONReflect, AqDrop.Core.Types, AqDrop.Core.Clonable.Attributes, AqDrop.Core.Clonable.Intf, AqDrop.Core.Exceptions, AqDrop.Core.Helpers.TValue, AqDrop.Core.Helpers.TRttiObject, AqDrop.Core.Helpers.Rtti, AqDrop.Core.Helpers.TRttiType; { TAqObjectHelper } function TAqObjectHelper.CloneTo(const pObject: TObject): TObject; begin TAqObjectMapping.Clone(Self, pObject); Result := pObject; end; function TAqObjectHelper.CloneTo<T>: T; begin if Assigned(Self) then begin Result := T.Create; try Self.CloneTo(Result); except Result.Free; raise; end; end else begin Result := nil; end; end; { TAqObjectMapping } class procedure TAqObjectMapping.AddDefaultFieldsToIgnoreList; procedure AddFieldRefCountToIgnoreList; var lField: TRttiField; begin lField := TAqRtti.&Implementation.GetType(TInterfacedObject).GetField('FRefCount'); if not Assigned(lField) then begin raise EAqInternal.Create('Field FRefCount not found to add to ignored field list to clone.'); end; FFieldsToIgnore.Add(lField); end; begin FFieldsToIgnore := TList<TRttiField>.Create; AddFieldRefCountToIgnoreList; end; class procedure TAqObjectMapping.Clone(const pFrom, pTo: TObject); var lMappingName: string; lMapping: TAqObjectMapping; begin lMappingName := pFrom.QualifiedClassName + '|' + pTo.QualifiedClassName; FLocker.Enter; try if not FMappings.TryGetValue(lMappingName, lMapping) then begin if not Assigned(FFieldsToIgnore) then begin AddDefaultFieldsToIgnoreList; end; lMapping := TAqObjectMapping.Create(pFrom.ClassType, pTo.ClassType); FMappings.Add(lMappingName, lMapping); end; finally FLocker.Leave; end; lMapping.Execute(pFrom, pTo); end; constructor TAqObjectMapping.Create(const pFrom, pTo: TClass); var lFieldFrom: TRttiField; lFieldTo: TRttiField; lSameClass: Boolean; lFrom: TRttiType; lTo: TRttiType; lFieldToFound: Boolean; begin FFieldMappings := TObjectList<TAqFieldMapping>.Create; lFrom := TAqRtti.&Implementation.GetType(pFrom); lSameClass := pFrom = pTo; lTo := nil; if not lSameClass then begin lTo := TAqRtti.&Implementation.GetType(pTo); end; for lFieldFrom in lFrom.GetFields do begin if (FFieldsToIgnore.IndexOf(lFieldFrom) < 0) and not lFieldFrom.HasAttribute<AqCloneOff> then begin if lSameClass then begin lFieldTo := lFieldFrom; lFieldToFound := True; end else begin lFieldTo := lTo.GetField(lFieldFrom.Name); lFieldToFound := Assigned(lFieldTo) and (FFieldsToIgnore.IndexOf(lFieldTo) < 0) and not lFieldTo.HasAttribute<AqCloneOff>; end; if lFieldToFound then begin FFieldMappings.Add(TAqFieldMapping.Create(lFieldFrom, lFieldTo)); end; end; end; end; destructor TAqObjectMapping.Destroy; begin FFieldMappings.Free; end; procedure TAqObjectMapping.Execute(const pFrom, pTo: TObject); var lFieldMapping: TAqFieldMapping; lInterfaceFrom: IInterface; lInterfaceTo: IInterface; lClonableFrom: IAqClonable; lClonableTo: IAqClonable; lValueFrom: TValue; begin for lFieldMapping in FFieldMappings do begin if lFieldMapping.FieldTo.FieldType.GetDataType = TAqDataType.adtClass then begin {TODO 3 -oTatu -cMelhoria: estudar a necessidade de verificar se as object implementa iaqclonable, exemplo: Fdeleteditens de um detalhe} if lFieldMapping.FieldTo.GetValue(pTo).AsObject = nil then begin lFieldMapping.FieldTo.SetValue(pTo, lFieldMapping.FieldFrom.GetValue(pFrom)); end; end else if lFieldMapping.FieldTo.FieldType.GetDataType = TAqDataType.adtInterface then begin lValueFrom := lFieldMapping.FieldFrom.GetValue(pFrom); lInterfaceFrom := lValueFrom.AsInterface; lInterfaceTo := lFieldMapping.FieldTo.GetValue(pTo).AsInterface; if Assigned(lInterfaceFrom) then begin if not Assigned(lInterfaceTo) then begin lFieldMapping.FieldTo.SetValue(pTo, lValueFrom); end else if Supports(lInterfaceFrom, IAqClonable, lClonableFrom) and Supports(lInterfaceTo, IAqClonable, lClonableTo) then begin lClonableFrom.CloneTo(lClonableTo); end; end; end else begin lFieldMapping.FieldTo.SetValue(pTo, lFieldMapping.FieldFrom.GetValue(pFrom).ConvertTo(lFieldMapping.FieldTo.FieldType.Handle)); end; end; end; class procedure TAqObjectMapping._Finalize; begin FFieldsToIgnore.Free; FMappings.Free; FLocker.Free; end; class procedure TAqObjectMapping._Initialize; begin FLocker := TCriticalSection.Create; FMappings := TObjectDictionary<string, TAqObjectMapping>.Create([doOwnsValues]); end; { TAqFieldMapping } constructor TAqFieldMapping.Create(const pFieldFrom, pFieldTo: TRttiField); begin FFieldFrom := pFieldFrom; FFieldTo := pFieldTo; end; initialization TAqObjectMapping._Initialize; finalization TAqObjectMapping._Finalize; end.
unit dbProcedureBoatTest; interface uses TestFramework, ZConnection, ZDataset, dbTest; type TdbProcedureTest = class(TdbTest) published procedure CreateDefault; procedure CreateProtocol; procedure CreateObjectTools; procedure CreareSystem; end; type TdbObjectHistoryProcedureTest = class(TdbTest) published procedure CreateCOMMON; procedure CreatePriceListItem; procedure CreateDiscountPeriodItem; end; type TdbMovementProcedureTest = class(TdbTest) published procedure CreateCOMMON; end; type TdbMovementItemProcedureTest = class(TdbTest) published procedure CreateCOMMON; end; type TdbMovementItemContainerProcedureTest = class(TdbTest) published procedure CreateCOMMON; end; type TdbObjectProcedureTest = class(TdbTest) published procedure CreateCOMMON; end; implementation uses zLibUtil; const CommonProcedurePath = '..\DATABASE\Boat\PROCEDURE\'; MetadataPath = '..\DATABASE\Boat\METADATA\'; ReportsPath = '..\DATABASE\Boat\REPORTS\'; ProcessPath = '..\DATABASE\Boat\Process\'; { TdbProcedureTest } procedure TdbProcedureTest.CreareSystem; begin DirectoryLoad(CommonProcedurePath + 'System\'); end; procedure TdbProcedureTest.CreateDefault; begin DirectoryLoad(CommonProcedurePath + 'Default\'); end; procedure TdbProcedureTest.CreateProtocol; begin DirectoryLoad(CommonProcedurePath + 'Protocol\'); end; procedure TdbProcedureTest.CreateObjectTools; begin DirectoryLoad(CommonProcedurePath + 'ObjectsTools\'); end; { TdbObjectHistoryProcedureTest } procedure TdbObjectHistoryProcedureTest.CreateCOMMON; begin DirectoryLoad(CommonProcedurePath + 'ObjectHistory\_COMMON\'); end; procedure TdbObjectHistoryProcedureTest.CreatePriceListItem; begin DirectoryLoad(CommonProcedurePath + 'ObjectHistory\PriceListItem\'); end; procedure TdbObjectHistoryProcedureTest.CreateDiscountPeriodItem; begin DirectoryLoad(CommonProcedurePath + 'ObjectHistory\DiscountPeriodItem\'); end; { TdbMovementProcedureTest } procedure TdbMovementProcedureTest.CreateCOMMON; begin DirectoryLoad(CommonProcedurePath + 'Movement\_COMMON\'); end; { TdbObjectProcedureTest } procedure TdbObjectProcedureTest.CreateCOMMON; begin DirectoryLoad(CommonProcedurePath + 'OBJECTS\_COMMON\'); end; { TdbMovementItemProcedureTest } procedure TdbMovementItemProcedureTest.CreateCOMMON; begin DirectoryLoad(CommonProcedurePath + 'MovementItem\_COMMON\'); end; { TdbMovementItemContainerProcedureTest } procedure TdbMovementItemContainerProcedureTest.CreateCOMMON; begin DirectoryLoad(CommonProcedurePath + 'MovementItemContainer\_COMMON\'); end; initialization TestFramework.RegisterTest('Процедуры', TdbProcedureTest.Suite); TestFramework.RegisterTest('Процедуры', TdbObjectHistoryProcedureTest.Suite); TestFramework.RegisterTest('Процедуры', TdbMovementProcedureTest.Suite); TestFramework.RegisterTest('Процедуры', TdbMovementItemProcedureTest.Suite); TestFramework.RegisterTest('Процедуры', TdbMovementItemContainerProcedureTest.Suite); TestFramework.RegisterTest('Процедуры', TdbObjectProcedureTest.Suite); end.
unit AqDrop.Core.Helpers.TRttiType; interface uses System.Rtti, AqDrop.Core.Types; type TAqRttiTypeHelper = class helper for TRttiType public function GetDataType: TAqDataType; end; implementation uses System.TypInfo, AqDrop.Core.Exceptions; { TAqRttiTypeHelper } function TAqRttiTypeHelper.GetDataType: TAqDataType; var lQualifiedName: string; begin lQualifiedName := Self.QualifiedName; case Self.TypeKind of tkUnknown: Result := TAqDataType.adtUnknown; tkInteger: Result := TAqDataType.adtInt32; tkChar: Result := TAqDataType.adtAnsiChar; tkEnumeration: begin if lQualifiedName = 'System.Boolean' then begin Result := TAqDataType.adtBoolean; end else begin Result := TAqDataType.adtEnumerated; end; end; tkFloat: begin if lQualifiedName = 'System.TDateTime' then begin Result := TAqDataType.adtDatetime; end else if lQualifiedName = 'System.TDate' then begin Result := TAqDataType.adtDate; end else if lQualifiedName = 'System.TTime' then begin Result := TAqDataType.adtTime; end else if lQualifiedName = 'System.Currency' then begin Result := TAqDataType.adtCurrency; end else begin Result := TAqDataType.adtDouble; end; end; tkSet: Result := TAqDataType.adtSet; tkClass: Result := TAqDataType.adtClass; tkMethod: Result := TAqDataType.adtMethod; tkWChar: Result := TAqDataType.adtChar; tkLString: Result := TAqDataType.adtAnsiString; tkWString: Result := TAqDataType.adtWideString; tkVariant: Result := TAqDataType.adtVariant; tkRecord: Result := TAqDataType.adtRecord; tkInterface: Result := TAqDataType.adtInterface; tkInt64: Result := TAqDataType.adtInt64; tkUString: Result := TAqDataType.adtString; else raise EAqInternal.Create('Tipo inesperado em TAqRttiTypeHelper.GetTipoDado'); end; end; end.