text
stringlengths
14
6.51M
unit dPipeServer; interface uses Pipes, Windows, Generics.Collections, SysUtils, Classes; type TPipeServerExt = class(TPipeServer) private FPrinterName: string; FData: TMemoryStream; public procedure AfterConstruction;override; destructor Destroy; override; property PrinterName: string read FPrinterName write FPrinterName; end; TdmPipeServer = class(TDataModule) private FPipes: TObjectlist<TPipeServerExt>; procedure PipeConnect(Sender: TObject; Pipe: HPIPE); procedure PipeDisconnect(Sender: TObject; Pipe: HPIPE); procedure PipeMessage(Sender: TObject; Pipe: HPIPE; Stream: TStream); procedure PipeSent(Sender: TObject; Pipe: HPIPE; Size: DWORD); procedure PipeError(Sender: TObject; Pipe: HPIPE; PipeContext: TPipeContext; ErrorCode: Integer); procedure PrintData(aPipe: TPipeServerExt); public procedure AfterConstruction;override; destructor Destroy; override; procedure LoadPipes; end; var dmPipeServer: TdmPipeServer; implementation uses Forms, ShellAPI, IniFiles, Printers, fMainform; {$R *.dfm} procedure TdmPipeServer.PipeSent(Sender: TObject; Pipe: HPIPE; Size: DWORD); begin TThread.Queue(nil, procedure begin frmMain.AddLog('Data sent to ' + (Sender as TPipeServerExt).PipeName + ', Size = ' + IntToStr(Size) ); end); end; procedure TdmPipeServer.PrintData(aPipe: TPipeServerExt); var sprintxps, sPrinter, sFile: string; begin //save received data to file sFile := Format('%s\%s_%s.xps', [ExtractFilePath(Application.ExeName), 'Temp_' + aPipe.PipeName, FormatDatetime('hhnnsszzz', now)]); aPipe.FData.SaveToFile(sFile); aPipe.FData.Clear; if FileExists('printxps.exe') then sprintxps := 'printxps.exe' else sprintxps := 'xpswin.exe'; //print xps file to printer sPrinter := aPipe.PrinterName; if not FileExists(sprintxps) then ShellExecute(0, 'print', PChar(Format('"%s"', [sFile])), nil, nil, SW_SHOWNORMAL) else ShellExecute(0, 'open', PChar(sprintxps), PChar(Format('"%s" "%s"', [sPrinter, sFile])), nil, SW_SHOWNORMAL); TThread.Queue(nil, procedure begin frmMain.AddLog('Printing: ' + aPipe.PipeName); frmMain.UpdatePrintCount(aPipe.PipeName); end); end; procedure TdmPipeServer.AfterConstruction; begin inherited; FPipes := TObjectlist<TPipeServerExt>.Create(True); end; destructor TdmPipeServer.Destroy; begin FPipes.Free; inherited; end; procedure TdmPipeServer.LoadPipes; var ini: TMemIniFile; pipes: TStrings; spipe: string; pipe: TPipeServerExt; begin FPipes.Clear; ini := TMemIniFile.Create( ExtractFilePath(Application.ExeName) + 'printerpipes.ini'); try pipes := TStringList.Create; try ini.ReadSections(pipes); for spipe in pipes do begin pipe := TPipeServerExt.Create(nil); pipe.PipeName := ini.ReadString(spipe, 'Pipe', ''); pipe.PrinterName := ini.ReadString(spipe, 'Printer', ''); pipe.OnPipeSent := Self.PipeSent; pipe.OnPipeConnect := Self.PipeConnect; pipe.OnPipeDisconnect := Self.PipeDisconnect; pipe.OnPipeMessage := Self.PipeMessage; pipe.OnPipeError := Self.PipeError; //printer exists? then make active pipe.Active := Printer.Printers.IndexOf(pipe.PrinterName) >= 0; end; finally pipes.Free; end; finally ini.Free; end; end; procedure TdmPipeServer.PipeConnect(Sender: TObject; Pipe: HPIPE); begin TThread.Queue(nil, procedure begin frmMain.AddLog('Connected: ' + (Sender as TPipeServerExt).PipeName); end); (Sender as TPipeServerExt).FData.Clear; end; procedure TdmPipeServer.PipeDisconnect(Sender: TObject; Pipe: HPIPE); begin TThread.Queue(nil, procedure begin frmMain.AddLog('Dicconnected: ' + (Sender as TPipeServerExt).PipeName); end); PrintData( (Sender as TPipeServerExt) ); end; procedure TdmPipeServer.PipeError(Sender: TObject; Pipe: HPIPE; PipeContext: TPipeContext; ErrorCode: Integer); begin TThread.Queue(nil, procedure begin frmMain.AddLog('Error at ' + (Sender as TPipeServerExt).PipeName + ', errorcode = ' + IntToStr(ErrorCode) ); end); end; procedure TdmPipeServer.PipeMessage(Sender: TObject; Pipe: HPIPE; Stream: TStream); begin TThread.Queue(nil, procedure begin frmMain.AddLog('Stream received at ' + (Sender as TPipeServerExt).PipeName + ', Size = ' + IntToStr(Stream.Size) ); end); Stream.Position := 0; with (Sender as TPipeServerExt) do begin FData.Position := FData.Size; FData.CopyFrom(stream, Stream.Size); end; end; { TPipeServerExt } procedure TPipeServerExt.AfterConstruction; begin inherited; FData := TMemoryStream.Create; end; destructor TPipeServerExt.Destroy; begin FData.Free; inherited; end; end.
unit NodeAttributeForma; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OkCancel_frame, DB, FIBDataSet, pFIBDataSet, DBGridEh, StdCtrls, DBCtrls, Mask, DBCtrlsEh, DBLookupEh, CnErrorProvider, FIBQuery, PrjConst, System.UITypes; type TNodeAttributForm = class(TForm) OkCancelFrame1: TOkCancelFrame; srcAttributes: TDataSource; dsAttributes: TpFIBDataSet; dbluAttribute: TDBLookupComboboxEh; memNotice: TDBMemoEh; Label1: TLabel; lblAttribute: TLabel; Label2: TLabel; edtNA_VALUE: TDBEditEh; CnErrors: TCnErrorProvider; dsNodeAttribute: TpFIBDataSet; srcNodeAttribute: TDataSource; cbbList: TDBComboBoxEh; procedure OkCancelFrame1bbOkClick(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dbluAttributeChange(Sender: TObject); private FCID: Integer; public end; function EditAttribute(const NODE_ID: Integer; const Attribute: string; const NA_ID: Integer = -1): Boolean; implementation uses DM, NodesForma, RegularExpressions, pFIBQuery; {$R *.dfm} function EditAttribute(const NODE_ID: Integer; const Attribute: string; const NA_ID: Integer = -1): Boolean; var ForSelected: Boolean; AID: Integer; NOTICE: string; VALUE: string; bm: TBookmark; Save_Cursor: TCursor; i: Integer; begin with TNodeAttributForm.Create(Application) do try if Attribute = '' then begin dsAttributes.ParamByName('IS_OLD').AsInteger := 0; end else begin dsAttributes.ParamByName('IS_OLD').AsInteger := 1; dbluAttribute.Enabled := false; end; FCID := NODE_ID; dsAttributes.ParamByName('CID').AsInt64 := FCID; dsAttributes.Open; dsNodeAttribute.ParamByName('NA_ID').AsInteger := NA_ID; dsNodeAttribute.Open; if NA_ID = -1 then dsNodeAttribute.Insert else dsNodeAttribute.Edit; if ShowModal = mrOk then begin ForSelected := false; if Assigned(NodesForm) then begin if (NodesForm.dbgNodes.SelectedRows.Count > 0) then ForSelected := (MessageDlg(rsProcessAllSelectedRows, mtConfirmation, [mbYes, mbNo], 0) = mrYes); end; if ForSelected and (dsAttributes['O_UNIQ'] <> 1) then begin Save_Cursor := Screen.Cursor; Screen.Cursor := crHourGlass; AID := dbluAttribute.VALUE; NOTICE := memNotice.Lines.Text; VALUE := edtNA_VALUE.Text; dsNodeAttribute.Cancel; dsNodeAttribute.DisableControls; bm := NodesForm.dbgNodes.DataSource.DataSet.GetBookmark; NodesForm.dbgNodes.DataSource.DataSet.DisableControls; for i := 0 to NodesForm.dbgNodes.SelectedRows.Count - 1 do begin NodesForm.dbgNodes.DataSource.DataSet.Bookmark := NodesForm.dbgNodes.SelectedRows[i]; try FCID := NodesForm.dbgNodes.DataSource.DataSet['NODE_ID']; dsNodeAttribute.Insert; dsNodeAttribute.FieldByName('O_ID').AsInteger := AID; dsNodeAttribute.FieldByName('NA_VALUE').AsString := VALUE; dsNodeAttribute.FieldByName('NOTICE').AsString := NOTICE; dsNodeAttribute.FieldByName('NODE_ID').AsInteger := FCID; dsNodeAttribute.Post; except // end; end; dsNodeAttribute.EnableControls; NodesForm.dbgNodes.DataSource.DataSet.GotoBookmark(bm); NodesForm.dbgNodes.DataSource.DataSet.EnableControls; Screen.Cursor := Save_Cursor; end else begin dsNodeAttribute.FieldByName('NODE_ID').AsInteger := NODE_ID; dsNodeAttribute.Post; end; result := true; end else begin dsNodeAttribute.Cancel; result := false; end; if dsAttributes.Active then dsAttributes.Close; finally free end; end; procedure TNodeAttributForm.dbluAttributeChange(Sender: TObject); begin cbbList.Items.Clear; cbbList.KeyItems.Clear; cbbList.Items.Text := dsAttributes['VLIST']; cbbList.KeyItems.Text := dsAttributes['VLIST']; cbbList.Visible := (dsAttributes['VLIST'] <> ''); edtNA_VALUE.Visible := not cbbList.Visible; end; procedure TNodeAttributForm.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then OkCancelFrame1bbOkClick(Sender); end; procedure TNodeAttributForm.OkCancelFrame1bbOkClick(Sender: TObject); var errors: Boolean; s: string; reg: string; fq: TpFIBQuery; begin errors := false; if (dbluAttribute.Text = '') then begin errors := true; CnErrors.SetError(dbluAttribute, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink); end else CnErrors.Dispose(dbluAttribute); if ((dbluAttribute.Text <> '')) then begin if dsAttributes['REGEXP'] <> '' then begin s := edtNA_VALUE.Text; reg := '^' + dsAttributes['REGEXP'] + '$'; errors := not TRegEx.IsMatch(s, reg); if errors then CnErrors.SetError(edtNA_VALUE, rsInputIncorrect, iaMiddleLeft, bsNeverBlink) else CnErrors.Dispose(edtNA_VALUE); end end; if (dsAttributes['O_UNIQ'] = 1) then begin fq := TpFIBQuery.Create(Self); try fq.Database := dmMain.dbTV; fq.Transaction := dmMain.trReadQ; with fq.sql do begin Clear; add('select first 1 c.Name as who'); add('from Nodes_Attributes a inner join Nodes c on (a.Node_Id = c.Node_Id)'); add('where a.O_Id = :aid and a.Node_Id <> :cid and upper(a.Na_Value) = upper(:val)'); end; fq.ParamByName('cid').AsInteger := FCID; fq.ParamByName('aid').AsInteger := dbluAttribute.VALUE; if cbbList.Visible then fq.ParamByName('val').AsString := cbbList.Text else fq.ParamByName('val').AsString := edtNA_VALUE.Text; fq.Transaction.StartTransaction; fq.ExecQuery; s := ''; if not fq.FieldByName('who').IsNull then s := fq.FieldByName('who').AsString; fq.Transaction.Commit; fq.Close; finally fq.free; end; if s <> '' then begin errors := true; s := format(rsERROR_UNIQUE, [s]); if cbbList.Visible then CnErrors.SetError(cbbList, s, iaMiddleLeft, bsNeverBlink) else CnErrors.SetError(edtNA_VALUE, s, iaMiddleLeft, bsNeverBlink); end; end; if not errors then ModalResult := mrOk else ModalResult := mrNone; end; end.
unit MP3Player; interface uses Windows, Messages, DirectSound, DSoundOut, MP3Reader; type TMP3PlayerState = (mpsStopped, mpsPlaying, mpsPaused); TMP3Player = class; TOnStateChange = procedure(Sender : TMP3Player; PrevState, NewState : TMP3PlayerState) of object; TMP3Player = class public constructor Create; destructor Destroy; override; public procedure Play; procedure Stop; procedure Pause; private fFileName : string; fLoop : boolean; fState : TMP3PlayerState; fOnStateChange : TOnStateChange; function GetVolume : integer; procedure SetVolume(aVolume : integer); function GetDirectSound : IDirectSound; procedure SetDirectSound(const aDirectSound : IDirectSound); procedure SetState(aState : TMP3PlayerState); public property DirectSound : IDirectSound read GetDirectSound write SetDirectSound; property FileName : string read fFileName write fFileName; property Loop : boolean read fLoop write fLoop; property Volume : integer read GetVolume write SetVolume; property State : TMP3PlayerState read fState; public property OnStateChange : TOnStateChange read fOnStateChange write fOnStateChange; private fPlayer : TDsoundOut; fReader : TMP3Reader; fLastChunk : integer; fAutoStop : boolean; fSyncWnd : hWnd; procedure OpenStream; function PlayerData(var Data; Size : integer) : integer; procedure WndProc(var Msg : TMessage); end; implementation uses Forms, SysUtils; const BufferMs = 1000; CM_STOP = WM_USER + 10; constructor TMP3Player.Create; begin inherited Create; fPlayer := TDsoundOut.Create; fPlayer.OnData := PlayerData; fPlayer.BufferSize := BufferMs; fSyncWnd := AllocatehWnd(WndProc); end; destructor TMP3Player.Destroy; begin fOnStateChange := nil; Stop; fPlayer.Free; fReader.Free; DeallocatehWnd(fSyncWnd); inherited; end; procedure TMP3Player.Play; begin case State of mpsStopped : begin OpenStream; fPlayer.Play; SetState(mpsPlaying); end; mpsPaused : begin fPlayer.Resume; SetState(mpsPlaying); end; end; end; procedure TMP3Player.Stop; begin fPlayer.Stop; SetState(mpsStopped); end; procedure TMP3Player.Pause; begin case State of mpsPlaying : begin fPlayer.Pause; SetState(mpsPaused); end; end; end; function TMP3Player.GetVolume : integer; begin Result := fPlayer.Volume; end; procedure TMP3Player.SetVolume(aVolume : integer); begin fPlayer.Volume := aVolume; end; function TMP3Player.GetDirectSound : IDirectSound; begin Result := fPlayer.DirectSound; end; procedure TMP3Player.SetDirectSound(const aDirectSound : IDirectSound); begin fPlayer.DirectSound := aDirectSound; end; procedure TMP3Player.SetState(aState : TMP3PlayerState); begin if aState <> fState then begin if assigned(fOnStateChange) then fOnStateChange(Self, fState, aState); fState := aState; end; end; procedure TMP3Player.OpenStream; begin Stop; //FreeAndNil(fReader); fReader.Free; fReader := nil; fReader := TMP3Reader.Create(fFileName, fLoop); fPlayer.SamplingRate := fReader.Format.nSamplesPerSec; fPlayer.Channels := fReader.Format.nChannels; fPlayer.BitsPerSample := fReader.Format.wBitsPerSample; end; function TMP3Player.PlayerData(var Data; Size : integer) : integer; var Read : integer; begin Read := fReader.Read(Data, Size); if Read < Size then begin fillchar(TByteArray(Data)[Read], Size - Read, 0); inc(fLastChunk, Size - Read); if (fLastChunk >= MulDiv(fPlayer.BufferSize, fReader.Format.nAvgBytesPerSec, 1000)) and not fAutoStop then begin PostMessage(fSyncWnd, CM_STOP, 0, 0); fAutoStop := true; end; end else begin fLastChunk := 0; fAutoStop := false; end; Result := Size; end; procedure TMP3Player.WndProc(var Msg : TMessage); begin with Msg do if Msg = CM_STOP then Stop else Result := DefWindowProc(fSyncWnd, Msg, wParam, lParam); end; end.
// islip - IneQuation's Simple LOLCODE Interpreter in Pascal // Written by Leszek "IneQuation" Godlewski <leszgod081@student.polsl.pl> // Parsing helper unit unit parser; {$IFDEF fpc} {$MODE objfpc} {$ENDIF} interface uses typedefs; const TOKEN_HISTORY_SIZE = 5; // how many previous tokens the parser is // supposed to remember; must be >= 1 type // helper types pstring = ^string; // retrieves characters from file, keeping track of the cursor position islip_reader = class public constructor create(var input : cfile); //destructor destroy; override; // retrieves a single character from input file and advances // counters and stuff function get_char(var c : char) : boolean; // retrieves cursor position in input file (for error reporting) procedure get_pos(var row : size_t; var col : size_t); private m_row : size_t; m_col : size_t; m_input : pcfile; end; islip_parser_token_type = ( TT_WS, // whitespace TT_EXPR, // expression TT_STRING // string constant ); // assembles read characters into proper tokens islip_parser = class public constructor create(var input : cfile); //destructor destroy; override; // retrieves a single token // puts token into s; empty string on eof // returns false on parsing errors function get_token(var s : string; var t : islip_parser_token_type) : boolean; // returns to previous token for reinterpretation // NOTE: can only roll TOKEN_HISTORY_SIZE tokens back procedure unget_token; // retrieves current token starting position in input file (for // error reporting) procedure get_pos(var row : size_t; var col : size_t); private m_reader : islip_reader; m_row : size_t; m_col : size_t; m_undepth : size_t; m_tokens : array[0..TOKEN_HISTORY_SIZE] of string; m_types : array[0..TOKEN_HISTORY_SIZE] of islip_parser_token_type; function comment : boolean; end; implementation // ======================================================== // islip_reader implementation // ======================================================== constructor islip_reader.create(var input : cfile); begin m_input := @input; m_row := 0; m_col := 0; end; function islip_reader.get_char(var c : char) : boolean; begin get_char := true; // check if there's anything left to read if eof(m_input^) then begin get_char := false; exit; end; read(m_input^, c); if ord(c) = 10 then begin inc(m_row); m_col := 0; end else inc(m_col); end; procedure islip_reader.get_pos(var row : size_t; var col : size_t); begin row := m_row; col := m_col - 1; end; // ======================================================== // islip_parser implementation // ======================================================== constructor islip_parser.create(var input : cfile); var i : size_t; begin m_reader := islip_reader.create(input); m_undepth := 0; for i := 0 to TOKEN_HISTORY_SIZE do begin m_tokens[i] := ''; m_types[i] := TT_WS; end; end; function islip_parser.comment : boolean; var c : char; begin comment := false; if m_tokens[0] = 'BTW' then begin // skip characters until we read a newline and // start a new token while m_reader.get_char(c) do if c in [chr(10), chr(13)] then begin m_tokens[0] := ''; break; end; end else if m_tokens[0] = 'OBTW' then begin // skip characters until we read a "TLDR" while m_reader.get_char(c) do begin if c = 'T' then begin if not m_reader.get_char(c) then exit; if c = 'L' then begin if not m_reader.get_char(c) then exit; if c = 'D' then begin if not m_reader.get_char(c) then exit; if c = 'R' then begin if not m_reader.get_char(c) then exit; m_tokens[0] := ''; break; end; end; end; end; end; end; comment := true; end; function islip_parser.get_token(var s : string; var t : islip_parser_token_type) : boolean; var c : char; esc : boolean; i : size_t; begin get_token := true; esc := false; if m_undepth > 0 then begin s := m_tokens[m_undepth]; t := m_types[m_undepth]; dec(m_undepth); exit; // if we still have something to throw, do it end else if length(m_tokens[0]) > 0 then begin s := m_tokens[0]; t := m_types[0]; for i := TOKEN_HISTORY_SIZE downto 1 do begin m_tokens[i] := m_tokens[i - 1]; m_types[i] := m_types[i - 1]; end; m_tokens[0] := chr(0); // HACK HACK HACK! somehow necessary for the m_tokens[0] := ''; // string to be zeroed in FPC m_types[0] := TT_WS; exit; end; // initial state m_types[0] := TT_WS; while m_reader.get_char(c) do begin case m_types[0] of TT_WS: begin if c = '"' then begin m_types[0] := TT_STRING; // keep track of where we started the token m_reader.get_pos(m_row, m_col); end else if c in [chr(10), chr(13), ','] then begin if c = ',' then c := chr(10); m_tokens[0] := c; s := m_tokens[0]; t := m_types[0]; for i := TOKEN_HISTORY_SIZE downto 1 do begin m_tokens[i] := m_tokens[i - 1]; m_types[i] := m_types[i - 1]; end; m_tokens[0] := chr(0); // HACK HACK HACK! somehow m_tokens[0] := ''; // necessary for the string to m_types[0] := TT_WS; // be zeroed in FPC exit; end else if ord(c) > 32 then begin m_tokens[0] := m_tokens[0] + c; m_types[0] := TT_EXPR; // keep track of where we started the token m_reader.get_pos(m_row, m_col); end; end; TT_EXPR: begin if c in [chr(10), chr(13), ','] then begin // handle comments if comment then begin if m_tokens[0] = '' then continue; end else begin writeln('ERROR: Unterminated multi-line comment'); get_token := false; exit; end; // throw what we've got so far and keep that newline in // mind s := m_tokens[0]; t := m_types[0]; for i := TOKEN_HISTORY_SIZE downto 1 do begin m_tokens[i] := m_tokens[i - 1]; m_types[i] := m_types[i - 1]; end; if c = ',' then c := chr(10); m_tokens[0] := c; exit; end else if ord(c) > 32 then m_tokens[0] := m_tokens[0] + c else begin // handle comments if comment then begin if m_tokens[0] = '' then continue; end else begin writeln('ERROR: Unterminated multi-line comment'); get_token := false; exit; end; s := m_tokens[0]; t := m_types[0]; for i := TOKEN_HISTORY_SIZE downto 1 do begin m_tokens[i] := m_tokens[i - 1]; m_types[i] := m_types[i - 1]; end; m_tokens[0] := chr(0); // HACK HACK HACK! somehow m_tokens[0] := ''; // necessary for the string to m_types[0] := TT_WS; // be zeroed in FPC exit; end; end; TT_STRING: begin if c = ':' then begin if esc then begin m_tokens[0] := m_tokens[0] + c; esc := false; end else esc := true; end else if esc then begin if c = ')' then m_tokens[0] := m_tokens[0] + chr(10) else if c = '>' then m_tokens[0] := m_tokens[0] + chr(9) else if c = 'o' then m_tokens[0] := m_tokens[0] + chr(7) else if c = '"' then m_tokens[0] := m_tokens[0] + c // FIXME: hex, var, unicode name else // invalid escape sequence, handle the error break; esc := false; end else if c <> '"' then m_tokens[0] := m_tokens[0] + c else begin s := m_tokens[0]; t := m_types[0]; for i := TOKEN_HISTORY_SIZE downto 1 do begin m_tokens[i] := m_tokens[i - 1]; m_types[i] := m_types[i - 1]; end; m_tokens[0] := chr(0); // HACK HACK HACK! somehow m_tokens[0] := ''; // necessary for the string to m_types[0] := TT_WS; // be zeroed in FPC exit; end; end; end; end; // the only proper (i.e. non-eof) way out of this function is by manual exit if esc then begin m_reader.get_pos(m_row, m_col); writeln('ERROR: Unknown escape sequence ":', c, '" at line ', m_row, ', column ', m_col); get_token := false; // make sure token is nonempty s := '!'; end else if (t = TT_STRING) then begin writeln('ERROR: Unterminated string starting at line ', m_row, ', column ', m_col); get_token := false; // make sure token is nonempty s := '!'; end else begin // return the last token on eof s := m_tokens[0]; for i := TOKEN_HISTORY_SIZE downto 1 do begin m_tokens[i] := m_tokens[i - 1]; m_types[i] := m_types[i - 1]; end; m_tokens[0] := chr(0); // HACK HACK HACK! somehow m_tokens[0] := ''; // necessary for the string to m_types[0] := TT_WS; // be zeroed in FPC end; end; procedure islip_parser.unget_token; var i : size_t; begin if m_undepth < TOKEN_HISTORY_SIZE then inc(m_undepth) else writeln('WARNING: Attempted to unget tokens beyond token history size'); end; procedure islip_parser.get_pos(var row : size_t; var col : size_t); begin row := m_row + 1; col := m_col - 1; end; end.
unit Glib; {$R-,Q-} interface uses Windows, Graphics, Types, PNGImage, SysUtils; function CreateBitmap(Width, Height: Integer): TBitmap; function LoadBitmap(FN: string): TBitmap; procedure SaveAsPNG(B: TBitmap; FN: string); function GetPixel(B: TBitmap; X, Y: Integer) : TColor ; inline; // 32-BPP only procedure PutPixel(B: TBitmap; X, Y: Integer; C: TColor); inline; // 32-BPP only function Crop(B: TBitmap; X1, Y1, X2, Y2: Integer): TBitmap; function LoadPNG(FN: string): TPNGObject; procedure SavePNG(P: TPNGObject; FN: string); function CropPNG(P: TPNGObject; X1, Y1, X2, Y2: Integer): TPNGObject; // slow function ToBitmap(P: TPNGObject): TBitmap; function VConcatPNG(P1, P2: TPNGObject): TPNGObject; // XOR function Difference(P0, P1: TPNGObject): TPNGObject; // Create alpha PNG of an object taken with a black (P0) and white (P1) backgrounds. function MakeAlpha(P0, P1: TPNGObject): TPNGObject; // Create alpha PNG of an object using a picture without (P0) and with (P1) the object, assuming the object has only grayscale colors. //function MakeAlphaGrayscale(P0, P1: TPNGObject): TPNGObject; // Averages NxN blocks function Downscale(Bitmap: TBitmap; N: Integer): TBitmap; // Render text to a new bitmap function RenderText(Font: TFont; BackgroundColor: TColor; Text: String): TBitmap; implementation function CreateBitmap(Width, Height: Integer): TBitmap; begin Result := TBitmap.Create; Result.PixelFormat := pf32bit; Result.Width := Width; Result.Height := Height; end; function LoadBitmap(FN: string): TBitmap; begin if LowerCase(ExtractFileExt(FN))='.png' then Result := ToBitmap(LoadPNG(FN)) else begin Result := TBitmap.Create; Result.LoadFromFile(FN); Result.PixelFormat := pf32bit; end; end; procedure SaveAsPNG(B: TBitmap; FN: string); var P: TPNGObject; begin P := TPNGObject.Create; P.Assign(B); SavePNG(P, FN); P.Free; end; function GetPixel(B: TBitmap; X, Y: Integer): TColor; inline; begin Result := PIntegerArray(B.Scanline[Y])[X]; end; procedure PutPixel(B: TBitmap; X, Y: Integer; C: TColor); inline; begin PIntegerArray(B.Scanline[Y])[X] := C; end; function Crop(B: TBitmap; X1, Y1, X2, Y2: Integer): TBitmap; begin Result := TBitmap.Create; Result.Assign(B); Result.Width := X2-X1; Result.Height := Y2-Y1; Result.Canvas.CopyRect(Rect(0, 0, Result.Width, Result.Height), B.Canvas, Rect(X1, Y1, X2, Y2)); end; // ******************************************************** function LoadPNG(FN: string): TPNGObject; begin Result := TPNGObject.Create; Result.LoadFromFile(FN); end; procedure SavePNG(P: TPNGObject; FN: string); begin P.CompressionLevel:=9; P.Filters:=[pfNone, pfSub, pfUp, pfAverage, pfPaeth]; P.SaveToFile(FN); end; function CropPNG(P: TPNGObject; X1, Y1, X2, Y2: Integer): TPNGObject; var X, Y: Integer; begin if (X2>P.Width) then raise Exception.Create('CropPNG: X2 > Width'); if (Y2>P.Height) then raise Exception.Create('CropPNG: Y2 > Height'); Result := TPNGObject.CreateBlank(P.Header.ColorType, P.Header.BitDepth, X2-X1, Y2-Y1); Result.Palette := P.Palette; //Result := TPNGObject.Create; //Result.Assign(P); for Y := 0 to Y2-Y1-1 do for X := 0 to X2-X1-1 do Result.Pixels[X, Y] := P.Pixels[X1+X, Y1+Y]; end; function VConcatPNG(P1, P2: TPNGObject): TPNGObject; var X, Y: Integer; begin if P1.Height<>P2.Height then raise Exception.Create('Mismatching height in VConcatPNG'); Result := TPNGObject.CreateBlank(P1.Header.ColorType, P1.Header.BitDepth, P1.Width+P2.Width, P1.Height); for Y := 0 to P1.Height-1 do for X := 0 to P1.Width-1 do Result.Pixels[X, Y] := P1.Pixels[X, Y]; for Y := 0 to P2.Height-1 do for X := 0 to P2.Width-1 do Result.Pixels[X+P1.Width, Y] := P2.Pixels[X, Y]; end; function ToBitmap(P: TPNGObject): TBitmap; begin Result := TBitmap.Create; Result.Assign(P); Result.PixelFormat := pf32bit; end; // ******************************************************** function Difference(P0, P1: TPNGObject): TPNGObject; var X, Y: Integer; begin Result := TPNGObject.CreateBlank(P0.Header.ColorType, P0.Header.BitDepth, P0.Width, P0.Height); for Y:=0 to P0.Height-1 do for X:=0 to P0.Width-1 do Result.Pixels[X, Y] := P0.Pixels[X,Y] xor P1.Pixels[X,Y]; end; procedure CalcAlpha(X, Y: Byte; var C, A: Byte); inline; begin A := 255+X-Y; if A=0 then C := 0 else C := 255*X div A; end; function MakeAlpha(P0, P1: TPNGObject): TPNGObject; var X, Y: Integer; C0, C1: TColor; R, G, B, A1, A2, A3: Byte; begin Result := TPNGObject.CreateBlank(COLOR_RGBALPHA, 8, P0.Width, P0.Height); for Y:=0 to P0.Height-1 do for X:=0 to P0.Width-1 do begin C0 := P0.Pixels[X,Y]; C1 := P1.Pixels[X,Y]; CalcAlpha(GetRValue(C0), GetRValue(C1), R, A1); CalcAlpha(GetGValue(C0), GetGValue(C1), G, A2); CalcAlpha(GetBValue(C0), GetBValue(C1), B, A3); //PIntegerArray(Result. Scanline[Y])[X] := RGB(R, G, B); Result.Pixels[X, Y] := RGB(R, G, B); PByteArray (Result.AlphaScanline[Y])[X] := (A1 + A2 + A3) div 3; end; end; {function MakeAlphaGrayscale(P0, P1: TPNGObject): TPNGObject; var X, Y: Integer; C0, C1: TColor; R0, G0, B0, R1, G1, B1, RD, GD, BD: Integer; begin Result := TPNGObject.CreateBlank(COLOR_RGBALPHA, 8, P0.Width, P0.Height); for Y:=0 to P0.Height-1 do for X:=0 to P0.Width-1 do begin C0 := P0.Pixels[X,Y]; C1 := P1.Pixels[X,Y]; R0 := GetRValue(C0); G0 := GetGValue(C0); B0 := GetBValue(C0); R1 := GetRValue(C1); G1 := GetGValue(C1); B1 := GetBValue(C1); // P1 = (ResultColor * ResultAlpha) + (P0 * (1-ResultAlpha)) CalcAlpha(GetRValue(C0), GetRValue(C1), R, A1); CalcAlpha(GetGValue(C0), GetGValue(C1), G, A2); CalcAlpha(GetBValue(C0), GetBValue(C1), B, A3); //PIntegerArray(Result. Scanline[Y])[X] := RGB(R, G, B); Result.Pixels[X, Y] := RGB(R, G, B); PByteArray (Result.AlphaScanline[Y])[X] := (A1 + A2 + A3) div 3; end; end;} function Downscale(Bitmap: TBitmap; N: Integer): TBitmap; var X, Y, I, J: Integer; R, G, B: Integer; C: TColor; begin Result := TBitmap.Create; Result.Width := Bitmap.Width div N; Result.Height := Bitmap.Height div N; for Y:=0 to Bitmap.Height div N - 1 do for X:=0 to Bitmap.Width div N - 1 do begin R := 0; G := 0; B := 0; for J:=0 to N-1 do for I:=0 to N-1 do begin C := Bitmap.Canvas.Pixels[X*N+I, Y*N+J]; Inc(R, GetRValue(C)); Inc(G, GetGValue(C)); Inc(B, GetBValue(C)); end; Result.Canvas.Pixels[X, Y] := RGB(R div (N*N), G div (N*N), B div (N*N)); end; end; function RenderText(Font: TFont; BackgroundColor: TColor; Text: String): TBitmap; begin Result := TBitmap.Create; Result.Canvas.Font := Font; Result.Canvas.Brush.Color := BackgroundColor; Result.Width := Result.Canvas.TextWidth(Text); Result.Height := Result.Canvas.TextHeight(Text); Result.Canvas.TextOut(0, 0, Text); end; end.
unit DrawnControl; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs; type IDrawnControl = interface end; TDrawing = class; { TElement } TElement = class(TComponent) private FBrush: TBrush; FPen: TPen; FControl: TGraphicControl; FDrawing: TDrawing; procedure Draw; virtual; function GetBrush: TBrush; function GetControl: TGraphicControl; function GetPen: TPen; procedure InitDraw; virtual; procedure Resize; virtual; procedure SetControl(AValue: TGraphicControl); virtual; procedure SetDrawing(AValue: TDrawing); property Drawing: TDrawing read FDrawing write SetDrawing; protected class function GetVectorDirection(V: TPoint): Extended; class function GetVectorLength(V: TPoint): Integer; class procedure SetVectorDirection(var V: TPoint; Angle: Extended); class procedure SetVectorLength(var V: TPoint; Length: Extended); class procedure VectorRotate(var Vec: TPoint; Angle: Extended); class procedure VectorZoom(var Vec: TPoint; Factor: Extended); procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Shift(V: TPoint); virtual; abstract; procedure Rotate(CP: TPoint; Angle: Extended); virtual; abstract; procedure Zoom(CP: TPoint; Factor: Extended); virtual; abstract; public destructor Destroy; override; property Brush: TBrush read GetBrush; property Pen: TPen read GetPen; property Control: TGraphicControl read GetControl write SetControl; end; { TLine } TLine = class(TElement) private FEP: TPoint; FSP: TPoint; function GetAngle: Extended; function GetLength: Integer; function GetDiffVec: TPoint; procedure SetAngle(AValue: Extended); procedure SetLength(AValue: Integer); protected procedure Shift(V: TPoint); override; procedure Rotate(CP: TPoint; Angle: Extended); override; procedure Zoom(CP: TPoint; Factor: Extended); override; procedure Draw; override; public property Angle: Extended read GetAngle write SetAngle; property Length: Integer read GetLength write SetLength; property SP: TPoint read FSP write FSP; property EP: TPoint read FEP write FEP; end; { TRotativePointer } TRotativePointer = class(TElement) private FAngle, FOffset: Extended; FCenter: TPoint; FRadius: Integer; procedure Draw; override; protected procedure Rotate(CP: TPoint; Angle: Extended); override; procedure Shift(V: TPoint); override; procedure Zoom(CP: TPoint; Factor: Extended); override; public property Center: TPoint read FCenter write FCenter; published property Angle: Extended read FAngle write FAngle; property Offset: Extended read FOffset write FOffset; property Radius: Integer read FRadius write FRadius; end; { TWSRectangle } TWSRectangle = class(TElement) private FR: TRect; function GetHeight: Integer; function GetLeft: Integer; function GetTop: Integer; function GetWidth: Integer; procedure SetHeight(AValue: Integer); procedure SetLeft(AValue: Integer); procedure SetTop(AValue: Integer); procedure SetWidth(AValue: Integer); protected procedure Draw; override; procedure Rotate(CP: TPoint; Angle: Extended); override; procedure Shift(V: TPoint); override; procedure Zoom(CP: TPoint; Factor: Extended); override; published property Height: Integer read GetHeight write SetHeight; property Left: Integer read GetLeft write SetLeft; property Top: Integer read GetTop write SetTop; property Width: Integer read GetWidth write SetWidth; end; { TCircle } TCircle = class(TElement) private function GetDiameter: Integer; procedure SetDiameter(AValue: Integer); private FCenter: TPoint; FRadius: Integer; procedure Draw; override; public property Center: TPoint read FCenter write FCenter; property Diameter: Integer read GetDiameter write SetDiameter; published property Radius: Integer read FRadius write FRadius; end; { TDrawing } TDrawing = class(TElement) private FElementList: TFpList; function GetElementCount: Integer; function GetElementList: TFpList; function GetElements(Index: Integer): TElement; procedure SetControl(AValue: TGraphicControl); override; private protected function AddElement(AElement: TElement): Integer; procedure Draw; override; procedure Shift(V: TPoint); override; procedure Rotate(CP: TPoint; Angle: Extended); override; procedure Resize; override; procedure Zoom(CP: TPoint; Factor: Extended); override; property ElementCount: Integer read GetElementCount; property ElementList: TFpList read GetElementList; property Elements[Index: Integer]: TElement read GetElements; public destructor Destroy; override; end; TDrawingClass = class of TDrawing; { TDrawnControl } TDrawnControl = class(TGraphicControl) private FDrawing: TDrawing; procedure Draw; protected function GetDrawing: TDrawing; class function GetDrawingClass: TDrawingClass; virtual; procedure Paint; override; procedure Resize; override; procedure SetParent(NewParent: TWinControl); override; public property Drawing: TDrawing read GetDrawing; published end; procedure Register; implementation procedure Register; begin RegisterComponents('HMI',[]); end; { TWSRectangle } procedure TWSRectangle.SetHeight(AValue: Integer); begin FR.Height := AValue; end; function TWSRectangle.GetHeight: Integer; begin Result := FR.Height; end; function TWSRectangle.GetLeft: Integer; begin Result := FR.Left; end; function TWSRectangle.GetTop: Integer; begin Result := FR.Top; end; function TWSRectangle.GetWidth: Integer; begin Result := FR.Width; end; procedure TWSRectangle.SetLeft(AValue: Integer); begin FR.Left := AValue; end; procedure TWSRectangle.SetTop(AValue: Integer); begin FR.Top := AValue; end; procedure TWSRectangle.SetWidth(AValue: Integer); begin FR.Width := AValue; end; procedure TWSRectangle.Draw; begin inherited Draw; Control.Canvas.Rectangle(FR); end; procedure TWSRectangle.Rotate(CP: TPoint; Angle: Extended); var V1, V2: TPoint; begin V1 := FR.TopLeft - CP; V2 := FR.BottomRight - CP; VectorRotate(V1, Angle); VectorRotate(V2, Angle); FR.TopLeft := CP + V1; FR.BottomRight := CP + V2; end; procedure TWSRectangle.Shift(V: TPoint); begin FR.Offset(V) end; procedure TWSRectangle.Zoom(CP: TPoint; Factor: Extended); var V: TPoint; begin V := FR.TopLeft - CP; VectorZoom(V, Factor); FR.TopLeft := CP + V; V := FR.BottomRight - CP; VectorZoom(V, Factor); FR.BottomRight := CP + V end; { TDrawnControl } procedure TDrawnControl.Draw; begin Drawing.Draw end; function TDrawnControl.GetDrawing: TDrawing; begin if not Assigned(FDrawing) then begin FDrawing := GetDrawingClass.Create(Self); FDrawing.Control := Self; end; Result := FDrawing; end; class function TDrawnControl.GetDrawingClass: TDrawingClass; begin Result := TDrawing; end; procedure TDrawnControl.Paint; begin inherited Paint; Canvas.Brush.Color := Color; Canvas.FillRect(ClientRect); Draw end; procedure TDrawnControl.Resize; begin inherited Resize; Drawing.Resize; end; procedure TDrawnControl.SetParent(NewParent: TWinControl); begin inherited SetParent(NewParent); if NewParent <> nil then Repaint; end; { TElement } procedure TElement.Draw; begin InitDraw end; function TElement.GetBrush: TBrush; begin if not Assigned(FBrush) then begin FBrush := TBrush.Create; FBrush.Color := clWhite end; Result := FBrush; end; function TElement.GetControl: TGraphicControl; begin Result := FControl end; function TElement.GetPen: TPen; begin if not Assigned(FPen) then begin FPen := TPen.Create; FPen.Color := clBlack; end; Result := FPen end; procedure TElement.InitDraw; begin if Assigned(Control) then begin Control.Canvas.Pen := Pen; Control.Canvas.Brush := Brush end; end; procedure TElement.Resize; begin end; procedure TElement.SetControl(AValue: TGraphicControl); begin if FControl = AValue then Exit; if Assigned(FControl) then FControl.RemoveFreeNotification(Self); FControl := AValue; if Assigned(FControl) then FControl.FreeNotification(Self); end; procedure TElement.SetDrawing(AValue: TDrawing); begin if AValue = FDrawing then Exit; if FDrawing <> nil then FDrawing.RemoveFreeNotification(Self); FDrawing := AValue; if FDrawing <> nil then FDrawing.FreeNotification(Self); end; class function TElement.GetVectorDirection(V: TPoint): Extended; begin if V.X = 0 then if V.Y >= 0 then Result := Pi / 2 else Result := -Pi / 2 else begin Result := ArcTan(V.Y / V.X); if V.X < 0 then begin Result := Result + Pi; if Result > Pi then Result := Result - 2 * Pi else if Result < -Pi then Result := Result + 2 * Pi end; end; end; class function TElement.GetVectorLength(V: TPoint): Integer; begin Result := Round(Sqrt(Sqr(V.X) + Sqr(V.Y))) end; class procedure TElement.SetVectorDirection(var V: TPoint; Angle: Extended); var L: Integer; begin L := GetVectorLength(V); V.X := Round(L * Cos(Angle)); V.Y := Round(L * Sin(Angle)) end; class procedure TElement.SetVectorLength(var V: TPoint; Length: Extended); var A: Extended; begin A := GetVectorDirection(V); V.X := Round(Length * Cos(A)); V.Y := Round(Length * Sin(A)) end; class procedure TElement.VectorRotate(var Vec: TPoint; Angle: Extended); begin SetVectorDirection(Vec, GetVectorDirection(Vec) + Angle) end; class procedure TElement.VectorZoom(var Vec: TPoint; Factor: Extended); begin SetVectorLength(Vec, GetVectorLength(Vec) * Factor) end; procedure TElement.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if AComponent = FControl then case Operation of opRemove: Control := nil end; end; destructor TElement.Destroy; begin FBrush.Free; FPen.Free; inherited Destroy; end; { TDrawing } function TDrawing.GetElementCount: Integer; begin if Assigned(FElementList) then Result := FElementList.Count else Result := 0 end; function TDrawing.GetElementList: TFpList; begin if not Assigned(FElementList) then FElementList := TFpList.Create; Result := FElementList end; function TDrawing.GetElements(Index: Integer): TElement; begin Pointer(Result) := ElementList[Index] end; procedure TDrawing.SetControl(AValue: TGraphicControl); var i: Integer; begin inherited SetControl(AValue); for i := 0 to ElementCount - 1 do Elements[i].Control := AValue end; function TDrawing.AddElement(AElement: TElement): Integer; begin if Assigned(AElement) then if ElementList.IndexOf(AElement) < 0 then begin AElement.Control := Control; AElement.Drawing := Drawing; Result := ElementList.Add(AElement) end end; procedure TDrawing.Draw; var i: Integer; begin inherited Draw; for i := 0 to ElementCount - 1 do Elements[i].Draw end; procedure TDrawing.Shift(V: TPoint); var i: Integer; begin for i := 0 to ElementCount - 1 do begin Elements[i].Shift(V); end; end; procedure TDrawing.Rotate(CP: TPoint; Angle: Extended); var i: Integer; begin for i := 0 to ElementCount - 1 do Elements[i].Rotate(CP, Angle) end; procedure TDrawing.Resize; var i: Integer; begin for i := 0 to ElementCount - 1 do Elements[i].Resize; end; procedure TDrawing.Zoom(CP: TPoint; Factor: Extended); var i: Integer; begin for i := 0 to ElementCount - 1 do Elements[i].Zoom(CP, Factor); end; destructor TDrawing.Destroy; begin FElementList.Free; inherited Destroy; end; { TLine } function TLine.GetAngle: Extended; var V: TPoint; begin V := EP - SP; if V.X = 0 then if V.Y = 0 then Result := 0 else if V.Y > 0 then Result := Pi / 2 else Result := -Pi / 2 else begin Result := ArcTan(V.Y / V.X); if V.X < 0 then if V.Y = 0 then Result := Pi else begin Result := Result + Pi; if Result > Pi then Result := Result - 2 * Pi else if Result <= -Pi then Result := Result + 2 * Pi end; end; end; function TLine.GetLength: Integer; begin Result := Round(SP.Distance(EP)); end; function TLine.GetDiffVec: TPoint; begin Result := EP - SP end; procedure TLine.SetAngle(AValue: Extended); var V: TPoint; begin V.X := Round(Length * Cos(AValue)); V.Y := Round(Length * Sin(AValue)); EP := SP + V end; procedure TLine.SetLength(AValue: Integer); var V: TPoint; begin V.X := Round(AValue * Cos(Angle)); V.Y := Round(AValue * Sin(Angle)); EP := SP + V end; procedure TLine.Shift(V: TPoint); begin SP := SP + V; EP := EP + V end; procedure TLine.Rotate(CP: TPoint; Angle: Extended); var V: TPoint; begin V := EP - CP; VectorRotate(V, Angle); EP := CP + V; V := SP - CP; VectorRotate(V, Angle); SP := CP + V end; procedure TLine.Zoom(CP: TPoint; Factor: Extended); var V: TPoint; begin V := SP - CP; VectorZoom(V, Factor); SP := CP + V; V := EP - CP; VectorZoom(V, Factor); EP := CP + V end; procedure TLine.Draw; begin inherited Draw; Control.Canvas.Line(SP, EP); end; { TCircle } function TCircle.GetDiameter: Integer; begin Result := 2 * Radius; end; procedure TCircle.SetDiameter(AValue: Integer); begin Radius := AValue div 2; end; procedure TCircle.Draw; var R: TRect; begin inherited Draw; if Assigned(Control) then begin R := Rect(Center.x - Radius, Center.y - Radius, Center.x + Radius, Center.y + Radius); Control.Canvas.Ellipse(R); end end; { TRotativePointer } procedure TRotativePointer.Draw; var Tip: TPoint; begin inherited Draw; Tip := Center + Point(Round(Radius * cos(Angle + Offset)), Round(Radius * sin(Angle + Offset))); Control.Canvas.Line(Center, Tip); end; procedure TRotativePointer.Rotate(CP: TPoint; Angle: Extended); var V: TPoint; begin V := Center - CP; VectorRotate(V, Angle); Center := CP + V; Offset := Offset + Angle end; procedure TRotativePointer.Shift(V: TPoint); begin Center := Center + V end; procedure TRotativePointer.Zoom(CP: TPoint; Factor: Extended); var V: TPoint; begin V := Center - CP; SetVectorLength(V, GetVectorLength(V) * Factor); Center := CP + V; Radius := Round(Radius * Factor) end; end.
unit dsEditions; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Business" // Автор: Тучнин Д.А. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Business/Document/dsEditions.pas" // Начат: 2005/09/23 17:08:24 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ViewAreaControllerImp::Class>> F1 Core::Common::Business::Document::TdsEditions // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses DocumentAndListInterfaces {$If not defined(NoVCM)} , vcmExternalInterfaces {$IfEnd} //not NoVCM {$If not defined(NoVCM)} , vcmInterfaces {$IfEnd} //not NoVCM {$If not defined(NoVCM)} , vcmLocalInterfaces {$IfEnd} //not NoVCM , l3ProtoObjectWithCOMQI, l3Interfaces, l3NotifyPtrList, l3TreeInterfaces ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type _FormDataSourceType_ = IdsEditions; _UseCaseControllerType_ = IsdsPrimDocument; {$Include w:\common\components\gui\Garant\VCM\implementation\vcmFormDataSourcePrimWithFlexUseCaseControllerType.imp.pas} TdsEditions = {final vac} class(_vcmFormDataSourcePrimWithFlexUseCaseControllerType_, IdsEditions) protected // realized methods function GetEditionsRoot: Il3SimpleRootNode; {* получение списка редакций документа } protected // overridden protected methods {$If not defined(NoVCM)} function GetIsSame(const aValue: _FormDataSourceType_): Boolean; override; {$IfEnd} //not NoVCM end;//TdsEditions {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses nsEditionNodes, SysUtils, l3InterfacesMisc, l3Base ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type _Instance_R_ = TdsEditions; {$Include w:\common\components\gui\Garant\VCM\implementation\vcmFormDataSourcePrimWithFlexUseCaseControllerType.imp.pas} // start class TdsEditions function TdsEditions.GetEditionsRoot: Il3SimpleRootNode; //#UC START# *49217DB001A7_4921809902CF_var* //#UC END# *49217DB001A7_4921809902CF_var* begin //#UC START# *49217DB001A7_4921809902CF_impl* Result := TnsEditionsRoot.MakeAsSimpleRoot(UseCaseController.DocInfo.Doc); //#UC END# *49217DB001A7_4921809902CF_impl* end;//TdsEditions.GetEditionsRoot {$If not defined(NoVCM)} function TdsEditions.GetIsSame(const aValue: _FormDataSourceType_): Boolean; //#UC START# *49147FB4028C_4921809902CF_var* var l_SDS1 : IsdsPrimDocument; //#UC END# *49147FB4028C_4921809902CF_var* begin //#UC START# *49147FB4028C_4921809902CF_impl* Result := inherited GetIsSame(aValue); if not Result and Assigned(aValue) then if aValue.CastUCC(IsdsPrimDocument, l_SDS1) then //if Supports(aValue.UseCaseController, IsdsPrimDocument, l_SDS1) then try Result := UseCaseController.DocInfo.IsSame(l_SDS1.DocInfo, False); finally l_SDS1 := nil; end;//try..finally //#UC END# *49147FB4028C_4921809902CF_impl* end;//TdsEditions.GetIsSame {$IfEnd} //not NoVCM {$IfEnd} //not Admin AND not Monitorings end.
/// Dynamic arrays based on JavaScript Array functionality. /// author: Tomasz Tyrakowski (t.tyrakowski@sol-system.pl) /// license: public domain unit DynArr; interface uses SysUtils, System.Generics.Collections, System.Generics.Defaults; type /// Raw array of values of type T. TRawArr<T> = array of T; /// Dynamic JS-like array of values of type T. TDynArr<T> = record private _items: TRawArr<T>; // property accessors function getLength(): Integer; procedure setLength(newLength: Integer); function getItem(itemNo: Integer): T; procedure setItem(itemNo: Integer; const newValue: T); public /// Create an array with the initial length as specified. constructor create(const initialLength: Integer); /// Creates an array from a raw array constructor from(const a: TRawArr<T>; startIndex: Integer = -1; endIndex: Integer = -1); overload; /// Creates an array from another TDynArr constructor from(const a: TDynArr<T>); overload; /// The length of the array. property length: Integer read getLength write setLength; /// Access individual items of the array. property items[itemNo: Integer]: T read getItem write setItem; default; /// Get a raw array of values. property raw: TRawArr<T> read _items write _items; /// Array manipulation routines. /// Joins two or more arrays, and returns a copy of the joined arrays. function concat(const a: TDynArr<T>): TDynArr<T>; /// Checks if every element in an array pass a test. function every(test: TFunc<T, Integer, Boolean>): Boolean; overload; function every(test: TFunc<T, Boolean>): Boolean; overload; /// Fill the elements in an array with a static value. procedure fill(const val: T); /// Creates a new array with every element in an array that pass a test. function filter(test: TFunc<T, Boolean>): TDynArr<T>; /// Returns the value of the first element in an array that pass a test. /// Raises an exception if there are no items passing the test. function find(test: TFunc<T, Boolean>): T; /// Returns the index of the first element in an array that pass a test. function findIndex(test: TFunc<T, Boolean>): Integer; /// Calls a function for each array element. procedure forEach(process: TProc<T>); /// Check if an array contains the specified element. function includes(const val: T): Boolean; /// Search the array for an element and returns its position. function indexOf(const val: T): Integer; /// Joins all elements of an array into a string. function join(mapper: TFunc<T, string>; const separator: string = ''): string; /// Search the array for an element, starting at the end, and returns its position. function lastIndexOf(const val: T): Integer; /// Creates a new array with the result of calling a function for each array element. function map<S>(mapper: TFunc<T, S>): TDynArr<S>; /// Removes the last element of an array, and returns that element. function pop(): T; /// Adds new elements to the end of an array, and returns the new length. function push(const val: T): Integer; /// Reduce the values of an array to a single value (going left-to-right). function reduce<S>(reducer: TFunc<S, T, Integer, S>; const initialValue: S): S; overload; function reduce<S>(reducer: TFunc<S, T, S>; const initialValue: S): S; overload; /// Reduce the values of an array to a single value (going right-to-left). function reduceRight<S>(reducer: TFunc<S, T, Integer, S>; const initialValue: S): S; overload; function reduceRight<S>(reducer: TFunc<S, T, S>; const initialValue: S): S; overload; /// Reverses the order of the elements in an array. procedure reverse(); function reversed(): TDynArr<T>; /// Removes the first element of an array, and returns that element. function shift(): T; /// Selects a part of an array, and returns the new array. function slice(const startIndex, endIndex: Integer): TDynArr<T>; /// Checks if any of the elements in an array pass a test. function some(test: TFunc<T, Integer, Boolean>): Boolean; overload; function some(test: TFunc<T, Boolean>): Boolean; overload; /// Sorts the elements of an array. procedure sort(compare: TComparison<T>); function sorted(compare: TComparison<T>): TDynArr<T>; /// Adds/removes items to/from an array, and returns the removed item(s). function splice(const startIndex, howMany: Integer; const newItems: TDynArr<T>): TDynArr<T>; overload; function splice(const startIndex, howMany: Integer): TDynArr<T>; overload; /// Converts an array to a string, and returns the result. function toString(mapper: TFunc<T, string>): string; /// Adds new elements to the beginning of an array, and returns the new length. function unshift(const toAdd: TDynArr<T>): Integer; /// Operators /// Implicit cast, e.g. const a: TDynArr<Integer> := [1, 2, 3]; class operator Implicit(a: TRawArr<T>): TDynArr<T>; /// Explicit cast, e.g. a := TDynArr<Integer>([1, 2, 3]); class operator Explicit(a: TRawArr<T>): TDynArr<T>; /// Addition (concatenation), e.g. c := a + b; class operator Add(const a1, a2: TDynArr<T>): TDynArr<T>; /// Multiply an array by an integer, creating an array with /// n copies of a. class operator Multiply(const a: TDynArr<T>; const n: Integer): TDynArr<T>; /// Check arrays for equality. class operator Equal(const a1, a2: TDynArr<T>): Boolean; /// BitwiseAnd - return an array consisting of items common /// to a1 and a2 class operator BitwiseAnd(const a1, a2: TDynArr<T>): TDynArr<T>; /// Checks whether two items of type T are equal (uses CompareMem). class function itemsEqual(const i1, i2: T): Boolean; static; /// Swaps the values of two items of type T. class procedure swap(var i1, i2: T); static; /// Returns an empty DynArray<T>. class function empty(): TDynArr<T>; static; end; implementation class operator TDynArr<T>.Add(const a1, a2: TDynArr<T>): TDynArr<T>; begin Result := a1.concat(a2); end; class operator TDynArr<T>.BitwiseAnd(const a1, a2: TDynArr<T>): TDynArr<T>; begin Result := a1.filter( function(it: T): Boolean begin Result := a2.includes(it); end ); end; function TDynArr<T>.concat(const a: TDynArr<T>): TDynArr<T>; var i: Integer; begin Result := TDynArr<T>.create(self.length + a.length); for i := 0 to self.length - 1 do Result[i] := self._items[i]; for i := 0 to a.length - 1 do Result[i + self.length] := a[i]; end; constructor TDynArr<T>.create(const initialLength: Integer); begin System.SetLength(self._items, initialLength); end; class function TDynArr<T>.empty: TDynArr<T>; begin Result := TDynArr<T>.create(0); end; class operator TDynArr<T>.Equal(const a1, a2: TDynArr<T>): Boolean; var i: Integer; begin if a1.length = a2.length then Result := a1.every( function(it: T; idx: Integer): Boolean begin Result := TDynArr<T>.itemsEqual(it, a2[idx]); end ) else Result := false; end; function TDynArr<T>.every(test: TFunc<T, Integer, Boolean>): Boolean; var i: Integer; begin Result := false; for i := 0 to self.length - 1 do if not test(self._items[i], i) then Exit; Result := true; end; function TDynArr<T>.every(test: TFunc<T, Boolean>): Boolean; begin Result := self.every( function(val: T; idx: Integer): Boolean begin Result := test(val); end ); end; class operator TDynArr<T>.Explicit(a: TRawArr<T>): TDynArr<T>; begin Result := TDynArr<T>.from(a); end; procedure TDynArr<T>.fill(const val: T); var i: Integer; begin for i := 0 to self.length - 1 do self._items[i] := val; end; function TDynArr<T>.filter(test: TFunc<T, Boolean>): TDynArr<T>; var i, ii: Integer; begin Result := TDynArr<T>.create(self.length); ii := 0; for i := 0 to self.length - 1 do if test(self._items[i]) then begin Result[ii] := self._items[i]; ii := ii + 1; end; Result.length := ii; end; function TDynArr<T>.find(test: TFunc<T, Boolean>): T; var ii: Integer; begin ii := self.findIndex(test); if ii >= 0 then Result := self._items[ii] else raise Exception.Create('The value is not present in the TDynArr.'); end; function TDynArr<T>.findIndex(test: TFunc<T, Boolean>): Integer; var i: Integer; begin for i := 0 to self.length - 1 do if test(self._items[i]) then begin Result := i; Exit; end; Result := -1; end; procedure TDynArr<T>.forEach(process: TProc<T>); var i: Integer; begin for i := 0 to self.length - 1 do process(self._items[i]); end; constructor TDynArr<T>.from(const a: TDynArr<T>); var i: Integer; begin System.SetLength(self._items, a.length); for i := 0 to a.length - 1 do self._items[i] := a[i]; end; constructor TDynArr<T>.from(const a: TRawArr<T>; startIndex: Integer = -1; endIndex: Integer = -1); var i: Integer; begin if startIndex < 0 then startIndex := 0; if endIndex < 0 then endIndex := System.Length(a); System.SetLength(self._items, endIndex - startIndex); for i := startIndex to endIndex - 1 do self._items[i - startIndex] := a[i]; end; function TDynArr<T>.getItem(itemNo: Integer): T; begin if itemNo < self.length then Result := self._items[itemNo] else raise ERangeError.CreateFmt('DynArr item index out of range: %d (max allowed: %d)', [itemNo, self.length]); end; function TDynArr<T>.getLength: Integer; begin Result := System.Length(self._items); end; class operator TDynArr<T>.Implicit(a: TRawArr<T>): TDynArr<T>; begin Result := TDynArr<T>.from(a); end; function TDynArr<T>.includes(const val: T): Boolean; begin Result := self.indexOf(val) >= 0; end; function TDynArr<T>.indexOf(const val: T): Integer; var i: Integer; begin for i := 0 to self.length - 1 do if TDynArr<T>.itemsEqual(self._items[i], val) then begin Result := i; Exit; end; Result := -1; end; class function TDynArr<T>.itemsEqual(const i1, i2: T): Boolean; begin Result := CompareMem(@i1, @i2, SizeOf(T)); end; function TDynArr<T>.join(mapper: TFunc<T, string>; const separator: string = ''): string; var i: Integer; begin Result := ''; for i := 0 to self.length - 1 do begin if Result <> '' then Result := Result + separator + mapper(self._items[i]) else Result := Result + mapper(self._items[i]); end; end; function TDynArr<T>.lastIndexOf(const val: T): Integer; var i: Integer; begin for i := self.length - 1 downto 0 do if TDynArr<T>.itemsEqual(self._items[i], val) then begin Result := i; Exit; end; Result := -1; end; function TDynArr<T>.map<S>(mapper: TFunc<T, S>): TDynArr<S>; var i: Integer; begin Result := TDynArr<S>.Create(self.length); for i := Low(_items) to High(_items) do Result[i] := mapper(_items[i]); end; class operator TDynArr<T>.Multiply(const a: TDynArr<T>; const n: Integer): TDynArr<T>; var i, j: Integer; begin Result := TDynArr<T>.Create(n * a.length); for i := 0 to a.length - 1 do for j := 0 to n - 1 do Result[j * a.length + i] := a[i]; end; function TDynArr<T>.pop: T; begin if self.length > 0 then begin Result := self._items[self.length - 1]; Delete(self._items, self.length - 1, 1); end else raise Exception.Create('Cannot pop an item from and empty TDynArr.'); end; function TDynArr<T>.push(const val: T): Integer; begin self.length := self.length + 1; self._items[self.length - 1] := val; end; function TDynArr<T>.reduce<S>(reducer: TFunc<S, T, S>; const initialValue: S): S; begin Result := self.reduce<S>( function(accumulated: S; it: T; index: Integer): S begin Result := reducer(accumulated, it); end, initialValue ); end; function TDynArr<T>.reduce<S>(reducer: TFunc<S, T, Integer, S>; const initialValue: S): S; var i: Integer; begin Result := initialValue; for i := 0 to self.length - 1 do Result := reducer(Result, self._items[i], i); end; function TDynArr<T>.reduceRight<S>(reducer: TFunc<S, T, S>; const initialValue: S): S; begin Result := self.reduceRight<S>( function(accumulated: S; it: T; index: Integer): S begin Result := reducer(accumulated, it); end, initialValue ); end; function TDynArr<T>.reduceRight<S>(reducer: TFunc<S, T, Integer, S>; const initialValue: S): S; var i: Integer; begin Result := initialValue; for i := self.length - 1 downto 0 do Result := reducer(Result, self._items[i], i); end; procedure TDynArr<T>.reverse; var i: Integer; tmp: T; begin for i := 0 to self.length div 2 do TDynArr<T>.swap(self._items[i], self._items[self.length - i - 1]); end; function TDynArr<T>.reversed: TDynArr<T>; begin Result := TDynArr<T>.from(self); Result.reverse(); end; procedure TDynArr<T>.setItem(itemNo: Integer; const newValue: T); begin if itemNo < self.length then self._items[itemNo] := newValue else raise ERangeError.CreateFmt('DynArr item index out of range: %d (max allowed: %d)', [itemNo, self.length]); end; procedure TDynArr<T>.setLength(newLength: Integer); begin if newLength <> self.length then System.SetLength(_items, newLength); end; function TDynArr<T>.shift: T; begin if self.length > 0 then begin Result := self._items[0]; Delete(self._items, 0, 1); end else raise Exception.Create('Cannot shift an empty TDynArr'); end; function TDynArr<T>.slice(const startIndex, endIndex: Integer): TDynArr<T>; begin Result := TDynArr<T>.from(self._items, startIndex, endIndex); end; function TDynArr<T>.some(test: TFunc<T, Boolean>): Boolean; begin Result := self.some( function(val: T; idx: Integer): Boolean begin Result := test(val); end ); end; function TDynArr<T>.some(test: TFunc<T, Integer, Boolean>): Boolean; var i: Integer; begin Result := true; for i := 0 to self.length - 1 do if test(self._items[i], i) then Exit; Result := false; end; procedure TDynArr<T>.sort(compare: TComparison<T>); var cmp: IComparer<T>; begin if self.length > 1 then begin cmp := TDelegatedComparer<T>.Create(compare); TArray.Sort<T>(_items, cmp); end; end; function TDynArr<T>.sorted(compare: TComparison<T>): TDynArr<T>; begin Result := TDynArr<T>.from(self); Result.sort(compare); end; function TDynArr<T>.splice(const startIndex, howMany: Integer; const newItems: TDynArr<T>): TDynArr<T>; begin Result := self.slice(startIndex, startIndex + howMany); Delete(self._items, startIndex, howMany); if newItems.length > 0 then Insert(newItems.raw, self._items, startIndex); end; function TDynArr<T>.splice(const startIndex, howMany: Integer): TDynArr<T>; begin Result := self.splice(startIndex, howMany, TDynArr<T>.empty); end; class procedure TDynArr<T>.swap(var i1, i2: T); var tmp: T; begin tmp := i1; i1 := i2; i2 := tmp; end; function TDynArr<T>.toString(mapper: TFunc<T, string>): string; begin Result := self.join(mapper, ', '); end; function TDynArr<T>.unshift(const toAdd: TDynArr<T>): Integer; begin Insert(toAdd.raw, self._items, 0); Result := self.length; end; end.
unit UNetW; interface uses Classes; const MyAddr = 1; MaxPacketDataSize = 1000; // Обработка пакета, полученного по соединению Conn function NetW_receive(Conn:Pointer; const Data; DataSize:Integer):Boolean; // Получение пакета для передачи по соединению Conn function NetW_transmit(Conn:Pointer; var Buf; BufSize:Integer):Integer; // Принудительное ассоциирование соединения с адресом/адресами procedure NetW_assocConn(Conn:Pointer; Addr:Byte); // Освобождение ресурсов, ассоциированных с соединением Conn procedure NetW_remConn(Conn:Pointer); type TService = class(TObject) public ID:Byte; function HaveDataToTransmit:Boolean;virtual; procedure getDataToTransmit(var Data:String; MaxSize:Integer);virtual; procedure receiveData(const Data:String);virtual;abstract; end; FProcessIO = procedure of object; procedure NetW_addProcessIO(IO:FProcessIO); procedure NetW_remProcessIO(IO:FProcessIO); procedure NetW_ProcessIO; procedure NetW_addService(Addr:Byte; Svc:TService); procedure NetW_remService(Addr:Byte; Svc:TService); function CreateSortedStringList:TStringList; implementation uses SysUtils, Contnrs, UCRC; var // для каждого сетевого адреса [0..255] список сервисов (TService) SvcList: array[0..255] of TStringList; // справочник соответствия [соединение -> сетевой адрес] // ключ: адрес объекта "соединение" // значение: сетевой адрес удалённого устройства ConnList: TStringList; // перечень методов-обработчиков ввода-вывода FProcessIO // ключ: хеш-код метода // значение: метод ListIO: TStringList; function PtrToHex(Ptr:Pointer):String; begin Result:=IntToHex(Integer(Ptr),8); end; function MethodToHex(pMethod:Pointer):String; type PI64 = ^Int64; begin Result:=IntToHex(PI64(pMethod)^,SizeOf(TMethod)*2); end; function CreateSortedStringList:TStringList; begin Result:=TStringList.Create; Result.Duplicates:=dupAccept; // to enable duplicated Objects??? Result.Sorted:=True; end; type PFProcessIO = ^FProcessIO; procedure NetW_addProcessIO(IO:FProcessIO); var P:PFProcessIO; M:TMethod absolute IO; begin GetMem(P,SizeOf(FProcessIO)); P^:=IO; ListIO.AddObject(MethodToHex(@M),Pointer(P)); end; procedure NetW_remProcessIO(IO:FProcessIO); var S:String; i:Integer; P:PFProcessIO; M:TMethod absolute IO; begin S:=MethodToHex(@M); if not ListIO.Find(S,i) then exit; P:=Pointer(ListIO.Objects[i]); FreeMem(P); ListIO.Delete(i); end; procedure NetW_ProcessIO; var i:Integer; begin i:=ListIO.Count-1; while i>=0 do begin PFProcessIO(ListIO.Objects[i])^(); Dec(i); end; end; procedure NetW_addService(Addr:Byte; Svc:TService); var L:TStringList; begin L:=TStringList(SvcList[Addr]); if L=nil then begin L:=CreateSortedStringList; SvcList[Addr]:=L; end; L.AddObject(Chr(Svc.ID),Svc); end; procedure NetW_remService(Addr:Byte; Svc:TService); var L:TStringList; i:Integer; begin L:=TStringList(SvcList[Addr]); if (L<>nil) and L.Find(Chr(Svc.ID),i) then L.Delete(i); end; function NetW_getService(Addr,SvcID:Byte):TService; var L:TStringList; i:Integer; begin L:=TStringList(SvcList[Addr]); if (L<>nil) and L.Find(Chr(SvcID),i) then Result:=TService(L.Objects[i]) else Result:=nil; end; procedure NetW_remConn(Conn:Pointer); var i:Integer; S:String; begin S:=PtrToHex(Conn); if not ConnList.Find(S,i) then exit; TList(ConnList.Objects[i]).Free; ConnList.Delete(i); end; procedure NetW_assocConn(Conn:Pointer; Addr:Byte); var i:Integer; S:String; addrs:TList; begin S:=PtrToHex(Conn); if not ConnList.Find(S,i) then begin addrs:=TList.Create(); i:=ConnList.AddObject(S,addrs); end; addrs:=TList(ConnList.Objects[i]); if addrs.IndexOf(Pointer(Addr))<0 then addrs.Add(Pointer(Addr)); end; function SetConnAssoc(Conn:Pointer; Addr, SvcID:Byte):TService; begin NetW_assocConn(Conn,Addr); Result:=NetW_getService(Addr,SvcID); end; function GetConnSvcToTx(Conn:Pointer; var Addr, SvcID:Byte):TService; var iConn,iSvc,iAddr,tmpAddr:Integer; L:TStringList; addrs:TList; NoSvc:Boolean; begin Result:=nil; if not ConnList.Find(PtrToHex(Conn),iConn) then exit; addrs:=TList(ConnList.Objects[iConn]); for iSvc:=0 to 255 do begin NoSvc:=true; for iAddr:=addrs.Count-1 downto 0 do begin tmpAddr:=Byte(addrs[iAddr]); L:=TStringList(SvcList[tmpAddr]); if iSvc>=L.Count then continue; NoSvc:=false; if TService(L.Objects[iSvc]).HaveDataToTransmit() then begin Result:=TService(L.Objects[iSvc]); Addr:=tmpAddr; SvcID:=Result.ID; addrs.Move(iAddr,0); exit; end; end; if NoSvc then break; end; end; { TService } procedure TService.getDataToTransmit(var Data: String; MaxSize: Integer); begin // do nothing end; function TService.HaveDataToTransmit: Boolean; begin Result:=False; end; //***************** type TPacketHeader = packed record ToAddr,FromAddr,ServiceID:Byte; end; TPacket=record Hdr:TPacketHeader; Data:packed array[0..MaxPacketDataSize-1] of Byte; end; PPacket = ^TPacket; function NetW_receive(Conn:Pointer; const Data; DataSize:Integer):Boolean; var p:PPacket; s:String; Svc:TService; begin if(DataSize<=0) then begin Result:=False; exit; end; if FCS_is_OK(Data,DataSize) then begin Result:=True; p := PPacket(@Data); if (p.Hdr.ToAddr = MyAddr) or (p.Hdr.ToAddr = 0) then begin Svc:=SetConnAssoc(Conn,p.Hdr.FromAddr,p.Hdr.ServiceID); if Assigned(Svc) then begin Dec(DataSize,(SizeOf(TPacketHeader)+2)); SetLength(s,DataSize); if(DataSize>0) then Move(P.Data,s[1],DataSize); Svc.receiveData(S); end; end; end else Result:=False; //dododo end; function NetW_transmit(Conn:Pointer; var Buf; BufSize:Integer):Integer; type PWord = ^Word; var Svc:TService; S:String; P:PPacket; begin Result:=0; P:=@Buf; Svc:=GetConnSvcToTx(Conn,P.Hdr.ToAddr,P.Hdr.ServiceID); if Assigned(Svc) then begin Svc.getDataToTransmit(S,BufSize-(SizeOf(TPacketHeader)+2)); Result:=SizeOf(TPacketHeader)+Length(S); P:=@Buf; P.Hdr.FromAddr:=MyAddr; if Length(S)>0 then Move(S[1],P.Data,Length(S)); PWord(Integer(@Buf)+Result)^ := PPP_FCS16(Buf,Result); Inc(Result,2); end; end; initialization ConnList:=CreateSortedStringList; ListIO:=CreateSortedStringList; finalization ListIO.Free; ConnList.Free; end.
unit k2InPlaceGenerator; { Библиотека "K-2" } { Автор: Люлин А.В. © } { Модуль: k2InPlaceGenerator - } { Начат: 24.06.2005 21:52 } { $Id: k2InPlaceGenerator.pas,v 1.3 2007/08/10 18:27:17 lulin Exp $ } // $Log: k2InPlaceGenerator.pas,v $ // Revision 1.3 2007/08/10 18:27:17 lulin // - избавляемся от излишнего использования интерфейсов, т.к. переносимость может быть достигнута другими методами. // // Revision 1.2 2005/06/25 12:17:45 lulin // - сделана возможнось использовать генератор для моногоразовой генерации. // // Revision 1.1 2005/06/24 18:12:26 lulin // - добавлен генератор, который может генерировать внутрь существующего тега. // {$Include k2Define.inc } interface uses l3Types, k2Interfaces, k2Base, k2DocumentGenerator ; type Tk2InPlaceGenerator = class(Tk2DocumentGenerator) private // internal fields f_Root : Ik2Tag; f_Type : Tk2Type; protected // internal methods procedure StartChild(TypeID: Long); override; {-} procedure Cleanup; override; {-} public // public methods constructor Make(const aType : Tk2Type; const aRoot : Ik2Tag); reintroduce; {-} public // public properties property Root: Ik2Tag read f_Root write f_Root; {-} property TagType: Tk2Type read f_Type write f_Type; {-} end;//Tk2InPlaceGenerator implementation // start class Tk2InPlaceGenerator constructor Tk2InPlaceGenerator.Make(const aType : Tk2Type; const aRoot : Ik2Tag); //reintroduce; {-} begin inherited Create; f_Root := aRoot; f_Type := aType; end; procedure Tk2InPlaceGenerator.Cleanup; //override; {-} begin f_Type := nil; f_Root := nil; inherited; end; procedure Tk2InPlaceGenerator.StartChild(TypeID: Long); //override; {-} begin inherited; if (f_Root <> nil) then begin f_Tags.Drop; f_Tags.Push(f_Type, f_Root, true, -1); f_Type := nil; f_Root := nil; end;//f_Root <> nil end; end.
unit capture; {$mode objfpc}{$H+} interface uses Classes, forms, SysUtils, Graphics, lclintf, lcltype, clipbrd, math, mouse ,icon, debug, extctrls; type tScreenCapture = class public MousePosition: TPoint; procedure CaptureAreaFromClipboard(area: tRect; showMouse: boolean = false); procedure CaptureScreenFromClipboard(showMouse: boolean = false); procedure CaptureScreen(showMouse: boolean = false); procedure CaptureArea(area: tRect; showMouse: boolean = false); procedure SaveCapture(); protected image: TBitmap; //jpg: TJpegImage; targetRect: tRect; sourceRect: tRect; fileName: ansistring; MouseShow: Boolean; procedure AreaCapInit(area: tRect); procedure ScreenCapInit(); procedure CreateFileName(); Procedure TakeCapture(); procedure SaveToClipboard; //procedure ImageChangeEvent(Sender: TObject); end; implementation { procedure tScreenCapture.ImageChangeEvent(Sender: TObject); begin // SaveToClipboard; // saveCapture; end; } //AREA MODE///////////////////////////////////////////////////////////////////////////// procedure tScreenCapture.areaCapInit(area: tREct); begin self.image:=tBitmap.Create; self.sourceRect.Left:= math.Max(area.Left, screen.Desktoprect.Left); self.SourceRect.Top:= math.Max(area.Top , screen.DesktopRect.top); self.SourceRect.Right:= math.Min(area.Right , screen.DesktopRect.right); self.SourceRect.Bottom:= math.Min(area.Bottom , screen.DesktopRect.Bottom); self.image.Width:= (SourceRect.Right - SourceRect.left ); self.image.Height:= (SourceRect.Bottom - SourceRect.Top); self.targetRect:= Rect(0,0,self.image.Width, self.image.Height); self.CreateFileName(); end; procedure tScreenCapture.CaptureAreaFromClipboard(area: tRect; showMouse: boolean = false) ; var tempImage: tBitmap; begin self.AreaCapInit(area); tempImage:= tBitmap.Create; tempImage.LoadFromClipboardFormat(PredefinedClipboardFormat(pcfBitmap)); Image.Canvas.CopyRect(self.targetRect, tempImage.Canvas, self.sourceRect);; if showMouse then begin icon.DrawCursor3(self.image.Canvas, self.mouseposition); end; freeandnil(tempImage); end; procedure tScreenCapture.CaptureArea(area: tRect; showMouse: boolean = false ); begin self.AreaCapInit(area); self.TakeCapture(); if showMouse then begin icon.DrawCursor3(self.image.Canvas, self.mouseposition); end; end; //SCREEN MODE/////////////////////////////////////////////////////////////////// procedure tScreenCapture.ScreenCapInit(); begin //Bitmap copy self.sourceRect:=screen.DesktopRect; self.image:=tBitmap.Create; self.image.Width:= (screen.DesktopRect.Right - screen.DesktopRect.Left); self.image.Height:= (screen.DesktopRect.Bottom - screen.DesktopRect.Top); self.targetRect:= Rect(0,0,self.image.Width, self.image.Height); self.sourceRect:= screen.DesktopRect; end; procedure tScreenCapture.CaptureScreenFromClipboard(showMouse: boolean = false); begin self.ScreenCapInit(); //self.image.LoadFromClipboardFormat(PredefinedClipboardFormat(pcfPixmap)); self.image.LoadFromClipboardFormat(PredefinedClipboardFormat(pcfBitmap)); // if Clipboard.FindPictureFormatID = PredefinedClipboardFormat(pcfDelphiBitmap) then // begin // self.image.LoadFromClipboardFormat(PredefinedClipboardFormat(pcfDelphiBitmap)); //end; if showMouse then begin icon.DrawCursor3(self.image.Canvas, self.MousePosition ); end; end; procedure tScreenCapture.CaptureScreen(showMouse: boolean = false); begin self.ScreenCapInit(); self.TakeCapture(); if showMouse then begin icon.DrawCursor3(self.image.Canvas, self.MousePosition ); end; end; //////////////////////////////////////////////////////////////////////////////////// procedure tScreenCapture.TakeCapture(); var c: TCanvas; begin c:= TCanvas.Create; c.Handle := GetDC(0); self.image.Canvas.CopyRect(self.targetRect, c, self.sourceRect); //BITMAP ReleaseDC(0, c.Handle); freeandnil(c); end; Procedure tScreenCapture.CreateFileName(); var aFilePath: String; aFileName: String; aFileRevision: byte; aFullFilePathName: String; begin try begin aFilePath:=debug.GetCurrentFolderPath(); aFileRevision:=0; aFileName:= FormatDateTime('\hh.mm.ss',Now) ; aFullFilePathName:=aFilePath + aFileName + '.jpg'; while fileExists(aFullFilePathName) do begin aFileRevision:=(aFileRevision + 1); aFullFilePathName:=aFilePath + aFileName + '(' + IntToStr(aFileRevision) + ')' + '.jpg'; end; end; finally end; self.fileName:=aFullFilePathName; aFileName:=''; aFullFilePathName:=''; end; procedure tScreenCapture.SaveCapture(); Var aJPG: TJpegImage; Begin self.CreateFileName(); aJPG:=TJpegImage.Create; aJPG.Assign(self.image); aJPG.SaveToFile(self.fileName); self.SaveToClipboard; self.image.FreeImage; self.image.Free; self.image:=nil; freeandnil(aJPG); end; procedure tScreenCapture.SaveToClipboard(); begin Clipboard.Assign(self.Image); end; end.
unit CreateFilterKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы CreateFilter } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Filters\Forms\CreateFilterKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "CreateFilterKeywordsPack" MUID: (4CB6DBE6009F_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , CreateFilter_Form , tfwPropertyLike , vtLabel , tfwScriptingInterfaces , TypInfo , tfwTypeInfo {$If Defined(Nemesis)} , nscComboBox {$IfEnd} // Defined(Nemesis) , tfwControlString , kwBynameControlPush , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4CB6DBE6009F_Packimpl_uses* //#UC END# *4CB6DBE6009F_Packimpl_uses* ; type TkwCreateFilterFormNameLabel = {final} class(TtfwPropertyLike) {* Слово скрипта .TCreateFilterForm.NameLabel } private function NameLabel(const aCtx: TtfwContext; aCreateFilterForm: TCreateFilterForm): TvtLabel; {* Реализация слова скрипта .TCreateFilterForm.NameLabel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwCreateFilterFormNameLabel TkwCreateFilterFormFilterName = {final} class(TtfwPropertyLike) {* Слово скрипта .TCreateFilterForm.FilterName } private function FilterName(const aCtx: TtfwContext; aCreateFilterForm: TCreateFilterForm): TnscEdit; {* Реализация слова скрипта .TCreateFilterForm.FilterName } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwCreateFilterFormFilterName Tkw_Form_CreateFilter = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы CreateFilter ---- *Пример использования*: [code]форма::CreateFilter TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_CreateFilter Tkw_CreateFilter_Control_NameLabel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола NameLabel ---- *Пример использования*: [code]контрол::NameLabel TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_CreateFilter_Control_NameLabel Tkw_CreateFilter_Control_NameLabel_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола NameLabel ---- *Пример использования*: [code]контрол::NameLabel:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_CreateFilter_Control_NameLabel_Push Tkw_CreateFilter_Control_FilterName = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола FilterName ---- *Пример использования*: [code]контрол::FilterName TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_CreateFilter_Control_FilterName Tkw_CreateFilter_Control_FilterName_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола FilterName ---- *Пример использования*: [code]контрол::FilterName:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_CreateFilter_Control_FilterName_Push function TkwCreateFilterFormNameLabel.NameLabel(const aCtx: TtfwContext; aCreateFilterForm: TCreateFilterForm): TvtLabel; {* Реализация слова скрипта .TCreateFilterForm.NameLabel } begin Result := aCreateFilterForm.NameLabel; end;//TkwCreateFilterFormNameLabel.NameLabel class function TkwCreateFilterFormNameLabel.GetWordNameForRegister: AnsiString; begin Result := '.TCreateFilterForm.NameLabel'; end;//TkwCreateFilterFormNameLabel.GetWordNameForRegister function TkwCreateFilterFormNameLabel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtLabel); end;//TkwCreateFilterFormNameLabel.GetResultTypeInfo function TkwCreateFilterFormNameLabel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwCreateFilterFormNameLabel.GetAllParamsCount function TkwCreateFilterFormNameLabel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TCreateFilterForm)]); end;//TkwCreateFilterFormNameLabel.ParamsTypes procedure TkwCreateFilterFormNameLabel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству NameLabel', aCtx); end;//TkwCreateFilterFormNameLabel.SetValuePrim procedure TkwCreateFilterFormNameLabel.DoDoIt(const aCtx: TtfwContext); var l_aCreateFilterForm: TCreateFilterForm; begin try l_aCreateFilterForm := TCreateFilterForm(aCtx.rEngine.PopObjAs(TCreateFilterForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aCreateFilterForm: TCreateFilterForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(NameLabel(aCtx, l_aCreateFilterForm)); end;//TkwCreateFilterFormNameLabel.DoDoIt function TkwCreateFilterFormFilterName.FilterName(const aCtx: TtfwContext; aCreateFilterForm: TCreateFilterForm): TnscEdit; {* Реализация слова скрипта .TCreateFilterForm.FilterName } begin Result := aCreateFilterForm.FilterName; end;//TkwCreateFilterFormFilterName.FilterName class function TkwCreateFilterFormFilterName.GetWordNameForRegister: AnsiString; begin Result := '.TCreateFilterForm.FilterName'; end;//TkwCreateFilterFormFilterName.GetWordNameForRegister function TkwCreateFilterFormFilterName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscEdit); end;//TkwCreateFilterFormFilterName.GetResultTypeInfo function TkwCreateFilterFormFilterName.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwCreateFilterFormFilterName.GetAllParamsCount function TkwCreateFilterFormFilterName.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TCreateFilterForm)]); end;//TkwCreateFilterFormFilterName.ParamsTypes procedure TkwCreateFilterFormFilterName.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству FilterName', aCtx); end;//TkwCreateFilterFormFilterName.SetValuePrim procedure TkwCreateFilterFormFilterName.DoDoIt(const aCtx: TtfwContext); var l_aCreateFilterForm: TCreateFilterForm; begin try l_aCreateFilterForm := TCreateFilterForm(aCtx.rEngine.PopObjAs(TCreateFilterForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aCreateFilterForm: TCreateFilterForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(FilterName(aCtx, l_aCreateFilterForm)); end;//TkwCreateFilterFormFilterName.DoDoIt function Tkw_Form_CreateFilter.GetString: AnsiString; begin Result := 'CreateFilterForm'; end;//Tkw_Form_CreateFilter.GetString class procedure Tkw_Form_CreateFilter.RegisterInEngine; begin inherited; TtfwClassRef.Register(TCreateFilterForm); end;//Tkw_Form_CreateFilter.RegisterInEngine class function Tkw_Form_CreateFilter.GetWordNameForRegister: AnsiString; begin Result := 'форма::CreateFilter'; end;//Tkw_Form_CreateFilter.GetWordNameForRegister function Tkw_CreateFilter_Control_NameLabel.GetString: AnsiString; begin Result := 'NameLabel'; end;//Tkw_CreateFilter_Control_NameLabel.GetString class procedure Tkw_CreateFilter_Control_NameLabel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtLabel); end;//Tkw_CreateFilter_Control_NameLabel.RegisterInEngine class function Tkw_CreateFilter_Control_NameLabel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::NameLabel'; end;//Tkw_CreateFilter_Control_NameLabel.GetWordNameForRegister procedure Tkw_CreateFilter_Control_NameLabel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('NameLabel'); inherited; end;//Tkw_CreateFilter_Control_NameLabel_Push.DoDoIt class function Tkw_CreateFilter_Control_NameLabel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::NameLabel:push'; end;//Tkw_CreateFilter_Control_NameLabel_Push.GetWordNameForRegister function Tkw_CreateFilter_Control_FilterName.GetString: AnsiString; begin Result := 'FilterName'; end;//Tkw_CreateFilter_Control_FilterName.GetString class procedure Tkw_CreateFilter_Control_FilterName.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscEdit); end;//Tkw_CreateFilter_Control_FilterName.RegisterInEngine class function Tkw_CreateFilter_Control_FilterName.GetWordNameForRegister: AnsiString; begin Result := 'контрол::FilterName'; end;//Tkw_CreateFilter_Control_FilterName.GetWordNameForRegister procedure Tkw_CreateFilter_Control_FilterName_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('FilterName'); inherited; end;//Tkw_CreateFilter_Control_FilterName_Push.DoDoIt class function Tkw_CreateFilter_Control_FilterName_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::FilterName:push'; end;//Tkw_CreateFilter_Control_FilterName_Push.GetWordNameForRegister initialization TkwCreateFilterFormNameLabel.RegisterInEngine; {* Регистрация CreateFilterForm_NameLabel } TkwCreateFilterFormFilterName.RegisterInEngine; {* Регистрация CreateFilterForm_FilterName } Tkw_Form_CreateFilter.RegisterInEngine; {* Регистрация Tkw_Form_CreateFilter } Tkw_CreateFilter_Control_NameLabel.RegisterInEngine; {* Регистрация Tkw_CreateFilter_Control_NameLabel } Tkw_CreateFilter_Control_NameLabel_Push.RegisterInEngine; {* Регистрация Tkw_CreateFilter_Control_NameLabel_Push } Tkw_CreateFilter_Control_FilterName.RegisterInEngine; {* Регистрация Tkw_CreateFilter_Control_FilterName } Tkw_CreateFilter_Control_FilterName_Push.RegisterInEngine; {* Регистрация Tkw_CreateFilter_Control_FilterName_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(TCreateFilterForm)); {* Регистрация типа TCreateFilterForm } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtLabel)); {* Регистрация типа TvtLabel } {$If Defined(Nemesis)} TtfwTypeRegistrator.RegisterType(TypeInfo(TnscEdit)); {* Регистрация типа TnscEdit } {$IfEnd} // Defined(Nemesis) {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
UNIT Pseudo_ver1; INTERFACE TYPE SignsPlace = SET OF 1 .. 25; SignsLine = SET OF 1 .. 250; FUNCTION FindLetterNumberEn(VAR F: TEXT): INTEGER; { Sets to each letter in F-file equal number in EN_alphabet } FUNCTION GetPseudoLetterEn(VAR Number: INTEGER): SignsPlace; { Getting from alph-file letter in pseudo graphic} {Number = 1/2/3/4... => Letter = A/B/C/D... } PROCEDURE CreatingPseudoLines(VAR F: TEXT); { Makes 5 lines of letters from F-file in pseudo_graphic style } PROCEDURE WritingPseudoLines; { Use it after CreatingPseudoLines proc, to write out letters in pseudo_graphic style } PROCEDURE WritePseudo(VAR PseudoLetter: SignsPlace); { Writes ONE! letter in pseudo graphics } IMPLEMENTATION CONST Rows = 5; Columns = 5; VAR AlphEn: FILE OF SignsPlace; AlphRu: FILE OF SignsPlace; Line1, Line2, Line3, Line4, Line5: SignsLine; I: INTEGER; FUNCTION FindLetterNumberEn(VAR F: TEXT): INTEGER; VAR Letter: CHAR; Number: INTEGER; BEGIN {FindLetterNumberEn} Number := -1; IF NOT EOLN(F) THEN BEGIN READ(F, Letter); IF (Letter = ' ') THEN Number := 0 ELSE IF (Letter = 'A') OR (Letter = 'a') THEN Number := 1 ELSE IF (Letter = 'B') OR (Letter = 'b') THEN Number := 2 ELSE IF (Letter = 'C') OR (Letter = 'c') THEN Number := 3 ELSE IF (Letter = 'D') OR (Letter = 'd') THEN Number := 4 ELSE IF (Letter = 'E') OR (Letter = 'e') THEN Number := 5 ELSE IF (Letter = 'F') OR (Letter = 'f') THEN Number := 6 ELSE IF (Letter = 'G') OR (Letter = 'g') THEN Number := 7 ELSE IF (Letter = 'H') OR (Letter = 'h') THEN Number := 8 ELSE IF (Letter = 'I') OR (Letter = 'i') THEN Number := 9 ELSE IF (Letter = 'J') OR (Letter = 'j') THEN Number := 10 ELSE IF (Letter = 'K') OR (Letter = 'k') THEN Number := 11 ELSE IF (Letter = 'L') OR (Letter = 'l') THEN Number := 12 ELSE IF (Letter = 'M') OR (Letter = 'm') THEN Number := 13 ELSE IF (Letter = 'N') OR (Letter = 'n') THEN Number := 14 ELSE IF (Letter = 'O') OR (Letter = 'o') THEN Number := 15 ELSE IF (Letter = 'P') OR (Letter = 'p') THEN Number := 16 ELSE IF (Letter = 'Q') OR (Letter = 'q') THEN Number := 17 ELSE IF (Letter = 'R') OR (Letter = 'r') THEN Number := 18 ELSE IF (Letter = 'S') OR (Letter = 's') THEN Number := 19 ELSE IF (Letter = 'T') OR (Letter = 't') THEN Number := 20 ELSE IF (Letter = 'U') OR (Letter = 'u') THEN Number := 21 ELSE IF (Letter = 'V') OR (Letter = 'v') THEN Number := 22 ELSE IF (Letter = 'W') OR (Letter = 'w') THEN Number := 23 ELSE IF (Letter = 'X') OR (Letter = 'x') THEN Number := 24 ELSE IF (Letter = 'Y') OR (Letter = 'y') THEN Number := 25 ELSE IF (Letter = 'Z') OR (Letter = 'z') THEN Number := 26 ELSE IF (Letter = '.') THEN Number := 27 ELSE IF (Letter = ',') THEN Number := 28 ELSE IF (Letter = '!') THEN Number := 29 ELSE IF (Letter = '?') THEN Number := 30 ELSE IF (Letter = '''') THEN Number := 31 ELSE IF (Letter = '-') THEN Number := 32 ELSE IF (Letter = '"') THEN Number := 33 ELSE IF (Letter = ':') THEN Number := 34 ELSE IF (Letter = ';') THEN Number := 35 ELSE IF (Letter = '<') THEN Number := 36 ELSE IF (Letter = '>') THEN Number := 37 ELSE IF (Letter = '~') THEN Number := 38 ELSE IF (Letter = '`') THEN Number := 39 ELSE IF (Letter = '@') THEN Number := 40 ELSE IF (Letter = '#') THEN Number := 41 ELSE IF (Letter = '$') THEN Number := 42 ELSE IF (Letter = '%') THEN Number := 43 ELSE IF (Letter = '^') THEN Number := 44 ELSE IF (Letter = '&') THEN Number := 45 ELSE IF (Letter = '*') THEN Number := 46 ELSE IF (Letter = '(') THEN Number := 47 ELSE IF (Letter = ')') THEN Number := 48 ELSE IF (Letter = '_') THEN Number := 49 ELSE IF (Letter = '+') THEN Number := 50 ELSE IF (Letter = '=') THEN Number := 51 ELSE IF (Letter = '[') THEN Number := 52 ELSE IF (Letter = ']') THEN Number := 53 ELSE IF (Letter = '{') THEN Number := 54 ELSE IF (Letter = '}') THEN Number := 55 ELSE IF (Letter = '|') THEN Number := 56 ELSE IF (Letter = '/') THEN Number := 57 ELSE IF (Letter = '\') THEN Number := 58 ELSE IF (Letter = '1') THEN Number := 59 ELSE IF (Letter = '2') THEN Number := 60 ELSE IF (Letter = '3') THEN Number := 61 ELSE IF (Letter = '4') THEN Number := 62 ELSE IF (Letter = '5') THEN Number := 63 ELSE IF (Letter = '6') THEN Number := 64 ELSE IF (Letter = '7') THEN Number := 65 ELSE IF (Letter = '8') THEN Number := 66 ELSE IF (Letter = '9') THEN Number := 67 ELSE IF (Letter = '0') THEN Number := 68 ELSE Number := -1 END ELSE WRITELN('Err, file is empty...'); FindLetterNumberEn := Number END; {FindLetterNumberEn} FUNCTION GetPseudoLetterEn(VAR Number: INTEGER): SignsPlace; VAR PseudoLetter: SignsPlace; BEGIN {GetPseudoLetterEn} RESET(AlphEn); IF Number = -1 THEN PseudoLetter := []; WHILE NOT EOF(AlphEn) AND (Number <> -1) DO BEGIN Number := Number - 1; READ(AlphEn, PseudoLetter) END; GetPseudoLetterEn := PseudoLetter END; {GetPseudoLetterEn} PROCEDURE CreatingPseudoLines(VAR F: TEXT); VAR Number, Sign, LetterAmount: INTEGER; PseudoLetter: SignsPlace; BEGIN {CreatingPseudoLines} Line1 := []; Line2 := []; Line3 := []; Line4 := []; Line5 := []; {Prepare Lines} LetterAmount := 0; WHILE NOT EOLN(F) DO BEGIN Number := FindLetterNumberEn(F); {Get char's number} PseudoLetter := GetPseudoLetterEn(Number); {Get set of pseudoletter for equal number} FOR Sign := 1 TO 5 DO IF Sign IN PseudoLetter THEN Line1 := Line1 + [Sign + LetterAmount * 5]; FOR Sign := 6 TO 10 DO IF Sign IN PseudoLetter THEN Line2 := Line2 + [Sign + LetterAmount * 5]; FOR Sign := 11 TO 15 DO IF Sign IN PseudoLetter THEN Line3 := Line3 + [Sign + LetterAmount * 5]; FOR Sign := 16 TO 20 DO IF Sign IN PseudoLetter THEN Line4 := Line4 + [Sign + LetterAmount * 5]; FOR Sign := 21 TO 25 DO IF Sign IN PseudoLetter THEN Line5 := Line5 + [Sign + LetterAmount * 5]; LetterAmount := LetterAmount + 1 END END; {CreatingPseudoLines} PROCEDURE WritingPseudoLines; VAR Sign: INTEGER; BEGIN {WritingPseudoLines} FOR Sign := 1 TO 124 DO BEGIN IF Sign IN Line1 THEN WRITE('#') ELSE WRITE(' '); IF Sign MOD 5 = 0 THEN WRITE(' ') END; WRITELN; FOR Sign := 6 TO 129 DO BEGIN IF Sign IN Line2 THEN WRITE('#') ELSE WRITE(' '); IF Sign MOD 5 = 0 THEN WRITE(' ') END; WRITELN; FOR Sign := 11 TO 134 DO BEGIN IF Sign IN Line3 THEN WRITE('#') ELSE WRITE(' '); IF Sign MOD 5 = 0 THEN WRITE(' ') END; WRITELN; FOR Sign := 16 TO 139 DO BEGIN IF Sign IN Line4 THEN WRITE('#') ELSE WRITE(' '); IF Sign MOD 5 = 0 THEN WRITE(' ') END; WRITELN; FOR Sign := 21 TO 144 DO BEGIN IF Sign IN Line5 THEN WRITE('#') ELSE WRITE(' '); IF Sign MOD 5 = 0 THEN WRITE(' ') END END; {WritingPseudoLines} PROCEDURE WritePseudo(VAR PseudoLetter: SignsPlace); VAR PositionInRow: INTEGER; BEGIN {WritePseudo} FOR PositionInRow := 1 TO (Rows * Columns) DO BEGIN IF PositionInRow IN PseudoLetter THEN WRITE('#') ELSE WRITE(' '); IF (PositionInRow MOD 5) = 0 THEN WRITELN END; WRITELN END; {WritePseudo} BEGIN {Pseudo} ASSIGN(AlphEn, 'Letters_EN_Bin.txt'); ASSIGN(AlphRu, 'Letters_RU_Bin.txt') END. {Pseudo}
namespace Sugar.Xml; interface uses {$IF COOPER} org.w3c.dom, {$ELSEIF ECHOES} System.Xml.Linq, System.Linq, {$ELSEIF TOFFEE} Foundation, {$ENDIF} Sugar; type XmlElement = public class (XmlNode) private {$IF NOT TOFFEE} property Element: {$IF COOPER}Element{$ELSEIF ECHOES}XElement{$ENDIF} read Node as{$IF COOPER}Element{$ELSEIF ECHOES}XElement{$ENDIF}; {$ENDIF} {$IF TOFFEE} method CopyNS(aNode: XmlAttribute); {$ENDIF} public {$IF ECHOES} property Name: String read Element.Name.ToString; override; property LocalName: String read Element.Name.LocalName; override; property Value: String read Element.Value write Element.Value; override; {$ENDIF} property NodeType: XmlNodeType read XmlNodeType.Element; override; { Children } method AddChild(aNode: XmlNode); method RemoveChild(aNode: XmlNode); method ReplaceChild(aNode: XmlNode; WithNode: XmlNode); { Attributes } method GetAttribute(aName: String): String; method GetAttribute(aLocalName, NamespaceUri: String): String; method GetAttributeNode(aName: String): XmlAttribute; method GetAttributeNode(aLocalName, NamespaceUri: String): XmlAttribute; method SetAttribute(aName, aValue: String); method SetAttribute(aLocalName, NamespaceUri, aValue: String); method SetAttributeNode(Node: XmlAttribute); method RemoveAttribute(aName: String); method RemoveAttribute(aLocalName, NamespaceUri: String); method RemoveAttributeNode(Node: XmlAttribute); method HasAttribute(aName: String): Boolean; method HasAttribute(aLocalName, NamespaceUri: String): Boolean; property Attributes[aName: String]: XmlAttribute read GetAttributeNode(aName); method GetAttributes: array of XmlAttribute; { Elements } //method GetElements(): array of XmlElement; method GetElementsByTagName(aName: String): array of XmlElement; method GetElementsByTagName(aLocalName, NamespaceUri: String): array of XmlElement; method GetFirstElementWithName(aName: String): XmlElement; end; implementation method XmlElement.GetAttributes: array of XmlAttribute; begin {$IF COOPER} var ItemsCount: Integer := Element.Attributes.Length; var lItems: array of XmlAttribute := new XmlAttribute[ItemsCount]; for i: Integer := 0 to ItemsCount-1 do lItems[i] := new XmlAttribute(Element.Attributes.Item(i)); exit lItems; {$ELSEIF ECHOES} var items := Element.Attributes:ToArray; if items = nil then exit new XmlAttribute[0]; result := new XmlAttribute[items.Length]; for i: Integer := 0 to items.Length-1 do result[i] := new XmlAttribute(items[i]); {$ELSEIF TOFFEE} var List := new Sugar.Collections.List<XmlAttribute>; var ChildPtr := Node^.properties; while ChildPtr <> nil do begin List.Add(new XmlAttribute(^libxml.__struct__xmlNode(ChildPtr), OwnerDocument)); ChildPtr := ^libxml.__struct__xmlAttr(ChildPtr^.next); end; result := List.ToArray; {$ENDIF} end; method XmlElement.AddChild(aNode: XmlNode); begin SugarArgumentNullException.RaiseIfNil(aNode, "Node"); if aNode.OwnerDocument <> nil then if not aNode.OwnerDocument.Equals(self.OwnerDocument) then raise new SugarInvalidOperationException("Unable to insert node that is owned by other document"); {$IF COOPER} if aNode.NodeType = XmlNodeType.Attribute then SetAttributeNode(XmlAttribute(aNode)) else Element.appendChild(aNode.Node); {$ELSEIF ECHOES} if aNode.Node.Parent <> nil then RemoveChild(aNode); Element.Add(aNode.Node); {$ELSEIF TOFFEE} if aNode.Node^.parent <> nil then libxml.xmlUnlinkNode(libxml.xmlNodePtr(aNode.Node)); var NewNode := libxml.xmlAddChild(libxml.xmlNodePtr(Node), libxml.xmlNodePtr(aNode.Node)); aNode.Node := ^libxml.__struct__xmlNode(NewNode); {$ENDIF} end; method XmlElement.RemoveChild(aNode: XmlNode); begin {$IF COOPER} Element.removeChild(aNode.Node); {$ELSEIF ECHOES} (aNode.Node as XNode):&Remove; {$ELSEIF TOFFEE} libxml.xmlUnlinkNode(libxml.xmlNodePtr(aNode.Node)); //libxml.xmlFreeNode(libxml.xmlNodePtr(aNode.Node)); {$ENDIF} end; method XmlElement.ReplaceChild(aNode: XmlNode; WithNode: XmlNode); begin if aNode.Parent = nil then raise new SugarInvalidOperationException("Unable to replace element without parent"); {$IF COOPER} Element.replaceChild(WithNode.Node, aNode.Node); {$ELSEIF ECHOES} if WithNode.Node.Parent <> nil then RemoveChild(WithNode); (aNode.Node as XNode):ReplaceWith(WithNode.Node); {$ELSEIF TOFFEE} libxml.xmlReplaceNode(libxml.xmlNodePtr(aNode.Node), libxml.xmlNodePtr(WithNode.Node)); {$ENDIF} end; method XmlElement.GetAttribute(aName: String): String; begin exit GetAttributeNode(aName):Value; end; method XmlElement.GetAttribute(aLocalName: String; NamespaceUri: String): String; begin exit GetAttributeNode(aLocalName, NamespaceUri):Value; end; method XmlElement.GetAttributeNode(aName: String): XmlAttribute; begin if aName = nil then exit nil; var Attr := {$IF COOPER}Element.GetAttributeNode(aName){$ELSEIF ECHOES}Element.Attribute(System.String(aName)) {$ELSEIF TOFFEE}libxml.xmlHasProp(libxml.xmlNodePtr(Node), XmlChar.FromString(aName)){$ENDIF}; if Attr = nil then exit nil; exit new XmlAttribute({$IF TOFFEE}^libxml.__struct__xmlNode(Attr), OwnerDocument{$ELSE}Attr{$ENDIF}); end; method XmlElement.GetAttributeNode(aLocalName: String; NamespaceUri: String): XmlAttribute; begin SugarArgumentNullException.RaiseIfNil(aLocalName, "LocalName"); SugarArgumentNullException.RaiseIfNil(NamespaceUri, "NamespaceUri"); var Attr := {$IF COOPER} Element.getAttributeNodeNS(NamespaceUri, aLocalName) {$ELSEIF ECHOES}Element.Attribute(XNamespace(NamespaceUri) + aLocalName) {$ELSEIF TOFFEE}libxml.xmlHasNsProp(libxml.xmlNodePtr(Node), XmlChar.FromString(aLocalName), XmlChar.FromString(NamespaceUri)){$ENDIF}; if Attr = nil then exit nil; exit new XmlAttribute({$IF TOFFEE}^libxml.__struct__xmlNode(Attr), OwnerDocument{$ELSE}Attr{$ENDIF}); end; method XmlElement.SetAttribute(aName: String; aValue: String); begin SugarArgumentNullException.RaiseIfNil(aName, "Name"); if aValue = nil then begin RemoveAttribute(aName); exit; end; {$IF COOPER} Element.SetAttribute(aName, aValue); {$ELSEIF ECHOES} Element.SetAttributeValue(aName, aValue); {$ELSEIF TOFFEE} libxml.xmlSetProp(libxml.xmlNodePtr(Node), XmlChar.FromString(aName), XmlChar.FromString(aValue)); {$ENDIF} end; method XmlElement.SetAttribute(aLocalName: String; NamespaceUri: String; aValue: String); begin SugarArgumentNullException.RaiseIfNil(aLocalName, "LocalName"); SugarArgumentNullException.RaiseIfNil(NamespaceUri, "NamespaceUri"); if aValue = nil then begin RemoveAttribute(aLocalName, NamespaceUri); exit; end; {$IF COOPER} Element.setAttributeNS(NamespaceUri, aLocalName, aValue); {$ELSEIF ECHOES} Element.SetAttributeValue(XNamespace(NamespaceUri) + aLocalName, aValue); {$ELSEIF TOFFEE} var ns := libxml.xmlSearchNsByHref(libxml.xmlDocPtr(Node^.doc), libxml.xmlNodePtr(Node), XmlChar.FromString(NamespaceUri)); //no namespace with specified uri if ns = nil then raise new SugarException("Namespace with specified URI not found"); libxml.xmlSetNsProp(libxml.xmlNodePtr(Node), ns, XmlChar.FromString(aLocalName), XmlChar.FromString(aValue)); {$ENDIF} end; method XmlElement.SetAttributeNode(Node: XmlAttribute); begin if Node.Parent <> nil then raise new SugarInvalidOperationException("Unable to insert attribute that is already owned by other element"); {$IF COOPER} Element.setAttributeNode(Node.Node as Attr); {$ELSEIF ECHOES} var Existing := Element.Attribute(XAttribute(Node.Node).Name); if Existing <> nil then Existing.Remove; Element.Add(Node.Node); {$ELSEIF TOFFEE} AddChild(Node); CopyNS(Node); {$ENDIF} end; method XmlElement.RemoveAttribute(aName: String); begin if aName = nil then exit; {$IF COOPER} Element.RemoveAttribute(aName); {$ELSEIF ECHOES} Element.SetAttributeValue(aName, nil); {$ELSEIF TOFFEE} libxml.xmlUnsetProp(libxml.xmlNodePtr(Node), XmlChar.FromString(aName)); {$ENDIF} end; method XmlElement.RemoveAttribute(aLocalName: String; NamespaceUri: String); begin SugarArgumentNullException.RaiseIfNil(aLocalName, "LocalName"); SugarArgumentNullException.RaiseIfNil(NamespaceUri, "NamespaceUri"); {$IF COOPER} Element.removeAttributeNS(NamespaceUri, aLocalName); {$ELSEIF ECHOES} Element.SetAttributeValue(XNamespace(NamespaceUri) + aLocalName, nil); {$ELSEIF TOFFEE} var Attr := libxml.xmlHasNsProp(libxml.xmlNodePtr(Node), XmlChar.FromString(aLocalName), XmlChar.FromString(NamespaceUri)); if Attr = nil then exit; libxml.xmlRemoveProp(Attr); {$ENDIF} end; method XmlElement.RemoveAttributeNode(Node: XmlAttribute); begin SugarArgumentNullException.RaiseIfNil(Node, "Node"); if Node.OwnerElement = nil then raise new SugarInvalidOperationException("Unable to remove attribute that has no parent element"); if not Node.OwnerElement.Equals(self) then raise new SugarInvalidOperationException("Unable to remove attribute that does not belong to this element"); {$IF COOPER} Element.removeAttributeNode(Node.Node as Attr); {$ELSEIF ECHOES} XAttribute(Node.Node).Remove; {$ELSEIF TOFFEE} libxml.xmlRemoveProp(libxml.xmlAttrPtr(Node.Node)); {$ENDIF} end; method XmlElement.HasAttribute(aName: String): Boolean; begin if aName = nil then exit false; exit GetAttributeNode(aName) <> nil; end; method XmlElement.HasAttribute(aLocalName: String; NamespaceUri: String): Boolean; begin exit GetAttributeNode(aLocalName, NamespaceUri) <> nil; end; method XmlElement.GetElementsByTagName(aLocalName: String; NamespaceUri: String): array of XmlElement; begin {$IF COOPER} var items := Element.GetElementsByTagNameNS(NamespaceUri, aLocalName); if items = nil then exit []; result := new XmlElement[items.length]; for i: Integer := 0 to items.length-1 do result[i] := new XmlElement(items.Item(i)); {$ELSEIF ECHOES} var ns: XNamespace := System.String(NamespaceUri); var items := Element.DescendantsAndSelf(ns + aLocalName).ToArray; result := new XmlElement[items.Length]; for I: Integer := 0 to items.Length - 1 do result[I] := new XmlElement(items[I]); {$ELSEIF TOFFEE} exit new XmlNodeList(self).ElementsByName(aLocalName, NamespaceUri); {$ENDIF} end; method XmlElement.GetElementsByTagName(aName: String): array of XmlElement; begin {$IF COOPER} var items := Element.GetElementsByTagName(aName); if items = nil then exit []; result := new XmlElement[items.length]; for i: Integer := 0 to items.length-1 do result[i] := new XmlElement(items.Item(i)); {$ELSEIF ECHOES} var items := Element.DescendantsAndSelf(System.String(aName)).ToArray; result := new XmlElement[items.Length]; for I: Integer := 0 to items.Length - 1 do result[I] := new XmlElement(items[I]); {$ELSEIF TOFFEE} exit new XmlNodeList(self).ElementsByName(aName); {$ENDIF} end; {$IF TOFFEE} method XmlElement.CopyNS(aNode: XmlAttribute); begin //nothing to copy if aNode.Node^.ns = nil then exit; //if nodes ns list is empty if Node^.nsDef = nil then begin Node^.nsDef := aNode.Node^.ns; //this ns will be our first element exit; end; var curr := ^libxml.__struct__xmlNs(aNode.Node^.ns); var prev := ^libxml.__struct__xmlNs(Node^.nsDef); while prev <> nil do begin //check if same ns already exists if ((prev^.prefix = nil) and (curr^.prefix = nil)) or (libxml.xmlStrEqual(prev^.prefix, curr^.prefix) = 1) then begin //if its a same ns if libxml.xmlStrEqual(prev^.href, curr^.href) = 1 then aNode.Node^.ns := libxml.xmlNsPtr(prev) //use existing else aNode.Node^.ns := nil; //else this ns is wrong //maybe should be exception here //we must release this ns libxml.xmlFreeNs(libxml.xmlNsPtr(curr)); exit; end; prev := ^libxml.__struct__xmlNs(prev^.next); end; //set new ns as a last element in the list prev^.next := curr; end; {$ENDIF} method XmlElement.GetFirstElementWithName(aName: String): XmlElement; begin for item in ChildNodes do if (item is XmlElement) and item.Name.EqualsIgnoringCaseInvariant(aName) then exit XmlElement(item); exit nil; end; end.
{ *************************************************************************** Copyright (c) 2016-2020 Kike Pérez Unit : Quick.Data.InfluxDB Description : InfluxDB data provider Author : Kike Pérez Version : 1.0 Created : 05/04/2019 Modified : 21/04/2020 This file is part of QuickLogger: https://github.com/exilon/QuickLogger *************************************************************************** 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.Data.InfluxDB; {$i QuickLib.inc} interface uses Classes, SysUtils, DateUtils, Quick.Collections, Quick.HttpClient, Quick.Commons, Quick.Value, Quick.Arrays, Quick.Data.Custom; type TInfluxDBData = class(TDataProvider) private fHTTPClient : TJsonHTTPClient; fURL : string; fFullURL : string; fDataBase : string; fUserName : string; fPassword : string; fUserAgent : string; fTags : TPairArray; fCreateDataBaseIfNotExists : Boolean; procedure CreateDataBase; function GenerateWriteQuery(const aMeasurement : string; aTagPairs : IList<TPair>; aFieldPairs : IList<TFlexPair>; aTime : TDateTime): string; procedure EscapeData(var aTags : string); procedure SetWriteURL; procedure SetPassword(const Value: string); procedure SetUserName(const Value: string); procedure Write(const aLine: string); overload; public constructor Create; override; destructor Destroy; override; property URL : string read fURL write fURL; property DataBase : string read fDataBase write fDataBase; property UserName : string read fUserName write SetUserName; property Password : string read fPassword write SetPassword; property CreateDataBaseIfNotExists : Boolean read fCreateDataBaseIfNotExists write fCreateDataBaseIfNotExists; property UserAgent : string read fUserAgent write fUserAgent; property Tags : TPairArray read fTags write fTags; procedure Init; override; procedure Restart; override; procedure Stop; override; procedure Write(const aMeasurement : string; aFieldPairs : IList<TFlexPair>; aTime : TDateTime = 0); overload; procedure Write(const aMeasurement: string; aTagPairs : IList<TPair>; aFieldPairs: IList<TFlexPair>; aTime: TDateTime); overload; procedure Write(const aMeasurement: string; const aFieldKey : string; aFieldValue : TFlexValue; aTime: TDateTime); overload; end; EInfluxDBData = class(Exception); implementation constructor TInfluxDBData.Create; begin inherited; fURL := 'http://localhost:8086'; fDataBase := 'db'; fUserName := ''; fPassword := ''; fCreateDataBaseIfNotExists := True; OutputOptions.UseUTCTime := True; fUserAgent := DEF_USER_AGENT; end; destructor TInfluxDBData.Destroy; begin if Assigned(fHTTPClient) then fHTTPClient.Free; inherited; end; procedure TInfluxDBData.Init; begin if fInitiated then Stop; SetWriteURL; fHTTPClient := TJsonHTTPClient.Create; fHTTPClient.ContentType := 'application/json'; fHTTPClient.UserAgent := fUserAgent; fHTTPClient.HandleRedirects := True; if fCreateDataBaseIfNotExists then CreateDataBase; inherited; end; procedure TInfluxDBData.Restart; begin Stop; if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient); Init; end; procedure TInfluxDBData.SetPassword(const Value: string); begin if fPassword <> Value then begin fPassword := Value; SetWriteURL; end; end; procedure TInfluxDBData.SetWriteURL; begin if fUserName+fPassword <> '' then fFullURL := Format('%s/write?db=%s&u=%s&p=%s&precision=ms',[fURL,fDataBase,fUserName,fPassword]) else fFullURL := Format('%s/write?db=%s&precision=ms',[fURL,fDataBase]); end; procedure TInfluxDBData.Stop; begin inherited; if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient); end; procedure TInfluxDBData.Write(const aMeasurement: string; const aFieldKey : string; aFieldValue : TFlexValue; aTime: TDateTime); var fields : IList<TFlexPair>; begin fields := TxList<TFlexPair>.Create; fields.Add(TFlexPair.Create(aFieldKey,aFieldValue)); if atime <> 0 then Write(GenerateWriteQuery(aMeasurement,nil,fields,aTime)) else Write(GenerateWriteQuery(aMeasurement,nil,fields,Now())); end; procedure TInfluxDBData.Write(const aMeasurement: string; aTagPairs : IList<TPair>; aFieldPairs: IList<TFlexPair>; aTime: TDateTime); begin if atime <> 0 then Write(GenerateWriteQuery(aMeasurement,aTagPairs,aFieldPairs,aTime)) else Write(GenerateWriteQuery(aMeasurement,aTagPairs,aFieldPairs,Now())); end; procedure TInfluxDBData.Write(const aMeasurement: string; aFieldPairs: IList<TFlexPair>; aTime: TDateTime); begin if atime <> 0 then Write(GenerateWriteQuery(aMeasurement,nil,aFieldPairs,aTime)) else Write(GenerateWriteQuery(aMeasurement,nil,aFieldPairs,Now())); end; procedure TInfluxDBData.SetUserName(const Value: string); begin if fUserName <> Value then begin fUserName := Value; SetWriteURL; end; end; procedure TInfluxDBData.CreateDataBase; var resp : IHttpRequestResponse; begin try resp := fHTTPClient.Post(Format('%s/query?q=CREATE DATABASE %s',[fURL,fDatabase]),''); except on E : Exception do raise EInfluxDBData.CreateFmt('[TInfluxDBData] Creating DB: %s',[e.Message]); end; if not (resp.StatusCode in [200,204]) then raise EInfluxDBData.Create(Format('[TInfluxDBData] : Response %d : %s trying to create database',[resp.StatusCode,resp.StatusText])); end; procedure TInfluxDBData.EscapeData(var aTags : string); begin aTags := StringReplace(aTags,' ','\ ',[rfReplaceAll]); end; function TInfluxDBData.GenerateWriteQuery(const aMeasurement : string; aTagPairs : IList<TPair>; aFieldPairs : IList<TFlexPair>; aTime : TDateTime): string; var incinfo : TStringList; tags : string; fields : string; tagpair : TPair; flexpair : TFlexPair; begin incinfo := TStringList.Create; try //add global tags for tagpair in fTags do begin if not tagpair.Value.IsEmpty then incinfo.Add(Format('%s=%s',[tagpair.Name,tagpair.Value])); end; //add current query tags if aTagPairs <> nil then begin for tagpair in aTagPairs do begin if not tagpair.Value.IsEmpty then incinfo.Add(Format('%s=%s',[tagpair.Name,tagpair.Value])); end; end; tags := CommaText(incinfo); EscapeData(tags); incinfo.Clear; for flexpair in aFieldPairs do begin if flexpair.Value.IsInteger then incinfo.Add(Format('%s=%d',[flexpair.Name,flexpair.Value.AsInt64])) else if flexpair.Value.IsFloating then incinfo.Add(Format('%s=%f',[flexpair.Name,flexpair.Value.AsExtended])) else incinfo.Add(Format('%s="%s"',[flexpair.Name,flexpair.Value.AsString])); end; fields := CommaText(incinfo); Result := Format('%s,%s %s %d',[aMeasurement,tags,fields,DateTimeToUnix(LocalTimeToUTC(aTime){$IFNDEF FPC},True{$ENDIF})*1000]); finally incinfo.Free; end; end; procedure TInfluxDBData.Write(const aLine : string); var resp : IHttpRequestResponse; stream : TStringStream; begin if not fInitiated then Init; stream := TStringStream.Create(aLine,TEncoding.UTF8); var a := aline; try try resp := fHTTPClient.Post(fFullURL,stream); except on E : Exception do raise EInfluxDBData.CreateFmt('[TInfluxDBData] Write Error: %s',[e.Message]); end; finally stream.Free; end; if not (resp.StatusCode in [200,204]) then raise EInfluxDBData.Create(Format('[TInfluxDBData] : Response %d : %s trying to post event',[resp.StatusCode,resp.StatusText])); end; end.
unit dmdCadPosicao; interface uses SysUtils, Classes, DmdDatabase, FMTBcd, DB, SqlExpr, DBClient, Provider, arTypes; type TdmCadPosicao = class(TDataModule) sdsPosicao: TSQLDataSet; dspPosicao: TDataSetProvider; cdsPosicao: TClientDataSet; dsPosicao: TDataSource; sdsPosicaoCODIGO: TIntegerField; sdsPosicaoNOME: TStringField; sdsPosicaoIMPAMOSTRA: TStringField; cdsPosicaoCODIGO: TIntegerField; cdsPosicaoNOME: TStringField; cdsPosicaoIMPAMOSTRA: TStringField; sdsPosicaoCABEDAL: TStringField; cdsPosicaoCABEDAL: TStringField; procedure DataModuleCreate(Sender: TObject); private sCommandText: string; FEstado: TarCadState; procedure AtualizaConsulta; public procedure AutoEditar(Ativar: Boolean); procedure IncluirRegistro; procedure GravarRegistro; procedure EditarRegistro; procedure ExcluirRegistro; procedure CancelarRegistro; function LocalizarRegistro(bLocalizar: Boolean; Codigo: Integer = 0): Boolean; procedure ExecutaConsulta(SQL: string); property Estado: TarCadState read FEstado write FEstado; end; implementation {$R *.dfm} { TdmCadPosicao } procedure TdmCadPosicao.AtualizaConsulta; begin if cdsPosicao.Active then begin if not cdsPosicao.Eof then LocalizarRegistro(True) else LocalizarRegistro(False); end else LocalizarRegistro(False); end; procedure TdmCadPosicao.AutoEditar(Ativar: Boolean); begin end; procedure TdmCadPosicao.CancelarRegistro; var iCodigo: integer; begin iCodigo := 0; if Estado = csEdit then iCodigo := cdsPosicaoCODIGO.AsInteger; if cdsPosicao.Active then cdsPosicao.CancelUpdates; AutoEditar(False); if (Estado = csEdit) and (cdsPosicaoCODIGO.AsInteger <> iCodigo) then cdsPosicao.Locate('CODIGO', iCodigo, []); AtualizaConsulta; end; procedure TdmCadPosicao.DataModuleCreate(Sender: TObject); begin sCommandText := sdsPosicao.CommandText; AutoEditar(False); end; procedure TdmCadPosicao.EditarRegistro; begin cdsPosicao.Edit; AutoEditar(True); end; procedure TdmCadPosicao.ExcluirRegistro; var sBookmark: string; begin sBookmark := cdsPosicao.Bookmark; try cdsPosicao.DisableControls; try cdsPosicao.Delete; if (cdsPosicao.ChangeCount > 0) and (cdsPosicao.ApplyUpdates(0) > 0) then Abort; except CancelarRegistro; cdsPosicao.Bookmark := sBookmark; raise; end; finally AtualizaConsulta; cdsPosicao.EnableControls; end; end; procedure TdmCadPosicao.ExecutaConsulta(SQL: string); begin cdsPosicao.Close; sdsPosicao.CommandText := SQL; cdsPosicao.Open; end; procedure TdmCadPosicao.GravarRegistro; begin if cdsPosicao.State in [dsEdit, dsInsert] then cdsPosicao.Post; if cdsPosicao.ApplyUpdates(0) > 0 then Abort; AutoEditar(False); end; procedure TdmCadPosicao.IncluirRegistro; begin if not cdsPosicao.Active then LocalizarRegistro(False); cdsPosicao.Insert; AutoEditar(True); end; function TdmCadPosicao.LocalizarRegistro(bLocalizar: Boolean; Codigo: Integer): Boolean; begin if not bLocalizar and not cdsPosicao.Active then begin ExecutaConsulta(sCommandText + ' WHERE CODIGO = ' + IntToStr(Codigo)); Result := not cdsPosicao.IsEmpty; end else if (not cdsPosicao.IsEmpty) and (Codigo > 0) then begin cdsPosicao.First; Result := cdsPosicao.Locate('CODIGO', Codigo, []); end else Result := not cdsPosicao.IsEmpty; end; end.
unit Events; interface uses Classes, Persistent, BackupInterfaces, Languages; type TEventKind = integer; type TEvent = class( TPersistent ) private fKind : TEventKind; fDateTick : integer; fDate : TDateTime; fTTL : integer; fPriority : integer; fText : TMultiString; fSender : string; fURL : string; public property Kind : TEventKind read fKind; property DateTick : integer read fDateTick; property Date : TDateTime read fDate; property TTL : integer read fTTL; property Priority : integer read fPriority; property Text : TMultiString read fText; property Sender : string read fSender; property URL : string read fURL; public constructor Create( aKind : TEventKind; aDateTick : integer; aDate : TDateTime; aTTL, aPriority : integer; aText : TMultiString; aSender, aURL : string ); destructor Destroy; override; public function CanAssimilate( Event : TEvent ) : boolean; virtual; procedure Assimilate( Event : TEvent ); virtual; function GetPrecedence : integer; virtual; function Render : string; virtual; function Clone : TEvent; virtual; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; procedure RegisterBackup; implementation uses SysUtils, Protocol, Logs; // TEvent constructor TEvent.Create( aKind : TEventKind; aDateTick : integer; aDate : TDateTime; aTTL, aPriority : integer; aText : TMultiString; aSender, aURL : string ); begin inherited Create; fKind := aKind; fDateTick := aDateTick; fDate := aDate; fTTL := aTTL; fPriority := aPriority; fText := aText; fSender := aSender; fURL := aURL; end; destructor TEvent.Destroy; begin { try Logs.Log( 'Demolition', TimeToStr(Now) + ' - ' + ClassName ); except end; } fText.Free; inherited; end; function TEvent.CanAssimilate( Event : TEvent ) : boolean; begin result := false; end; procedure TEvent.Assimilate( Event : TEvent ); begin end; function TEvent.GetPrecedence : integer; begin result := Priority - TTL; end; function TEvent.Render : string; var list : TStringList; i : integer; begin list := TStringList.Create; try list.Values[tidEventField_Date] := DateToStr(Date); list.Values[tidEventField_Kind] := IntToStr(Kind); list.Values[tidEventField_URL] := URL; for i := 0 to pred(Text.Count) do list.Values[tidEventField_Text + IntToStr(i)] := Text.Values[IntToStr(i)]; result := list.Text; finally list.Free; end; end; function TEvent.Clone : TEvent; begin result := TEvent.Create( Kind, DateTick, Date, TTL, Priority, CloneMultiString( Text ), Sender, URL ); end; procedure TEvent.LoadFromBackup( Reader : IBackupReader ); begin inherited; fKind := Reader.ReadInteger( 'Kind', 0 ); fDateTick := Reader.ReadInteger( 'DateTick', 0 ); fDate := StrToDate(Reader.ReadString( 'Date', '0/0/0' )); fTTL := Reader.ReadInteger( 'TTL', 0 ); fPriority := Reader.ReadInteger( 'Priority', 0 ); Reader.ReadObject( 'Text_MLS', fText, nil ); if fText = nil then fText := TMultiString.Create; fSender := Reader.ReadString( 'Sender', '' ); end; procedure TEvent.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteInteger( 'Kind', fKind ); Writer.WriteInteger( 'DateTick', fDateTick ); Writer.WriteString( 'Date', DateToStr(fDate) ); Writer.WriteInteger( 'TTL', fTTL ); Writer.WriteInteger( 'Priority', fPriority ); Writer.WriteLooseObject( 'Text_MLS', fText ); Writer.WriteString( 'Sender', fSender ); end; // RegisterBackup; procedure RegisterBackup; begin RegisterClass( TEvent ); end; end.
unit ChatHandler; interface uses Classes, VoyagerInterfaces, VoyagerServerInterfaces, Controls, ChatHandlerViewer, Protocol; const tidChatCMD_Move = '/go'; type IPrivacyHandler = interface procedure IgnoreUser( username : string ); procedure ClearIgnoredUser( username : string ); function UserIsIgnored( username : string ) : boolean; procedure GetDefaultChannelData( out name, password : string ); procedure SetDefaultChannelData( name, password : string ); end; const evnAnswerPrivacyHandler = 5700; type TMetaChatHandler = class( TInterfacedObject, IMetaURLHandler ) // IMetaURLHandler private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; end; TChatHandler = class( TInterfacedObject, IURLHandler ) private constructor Create; destructor Destroy; override; private fControl : TChatHandlerView; fClientView : IClientView; fMasterURLHandler : IMasterURLHandler; fPrivacyHandler : IPrivacyHandler; fChatOverMap : boolean; private procedure OnMessageComposed( Msg : string ); procedure OnMessageCompositionChanged( State : TMsgCompositionState ); procedure OnCreateChannel( Name, Password, aSessionApp, aSessionAppId : string; anUserLimit : integer ); procedure OnJoinChannel( Name, Password : string ); private procedure threadedCreateChannel( const parms : array of const ); procedure syncCreateChannel( const parms : array of const ); procedure threadedJoinChannel( const parms : array of const ); procedure syncJoinChannel( const parms : array of const ); procedure threadedUpdateChannelList( const parms : array of const ); procedure syncUpdateChannelList( const parms : array of const ); // IURLHandler private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler( URLHandler : IMasterURLHandler ); end; const tidHandlerName_Chat = 'ChatHandler'; function ExecChatCmdURL(URLHandler : IMasterURLHandler; text : string) : boolean; implementation uses SysUtils, Threads, ServerCnxHandler, VoyagerUIEvents, Events, ChatListHandler, ServerCnxEvents, Forms, Windows, MessageBox, Literals, CompStringsParser; function ExecChatCmdURL(URLHandler : IMasterURLHandler; text : string) : boolean; var UpMsg : string; p : integer; x, y : string; begin UpMsg := UpperCase(text); p := pos(UpperCase(tidChatCMD_Move), UpMsg); if p <> 0 then begin inc(p, length(tidChatCMD_Move)); if CompStringsParser.SkipChars(UpMsg, p, Spaces) then begin x := trim(CompStringsParser.GetNextStringUpTo(UpMsg, p, ',')); inc(p); y := trim(CompStringsParser.GetNextStringUpTo(UpMsg, p, ',')); URLHandler.HandleURL('?frame_Id=MapIsoView&frame_Action=MoveTo&x=' + x + '&y=' + y); result := true; end else result := false; end else result := false; end; // TMetaChatHandler function TMetaChatHandler.getName : string; begin result := tidHandlerName_Chat; end; function TMetaChatHandler.getOptions : TURLHandlerOptions; begin result := [hopCacheable, hopEnabledWhenCached]; end; function TMetaChatHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TMetaChatHandler.Instantiate : IURLHandler; begin result := TChatHandler.Create; end; // TChatHandler constructor TChatHandler.Create; begin inherited Create; fControl := TChatHandlerView.Create( nil ); fControl.OnMessageComposed := OnMessageComposed; fControl.OnMessageCompositionChanged := OnMessageCompositionChanged; fControl.OnCreateChannel := OnCreateChannel; fControl.OnJoinChannel := OnJoinChannel; end; destructor TChatHandler.Destroy; begin fControl.Free; inherited; end; procedure TChatHandler.OnMessageComposed( Msg : string ); var ErrorCode : TErrorCode; begin if (fClientView <> nil) and not ExecChatCmdURL(fMasterURLHandler, Msg) then fClientView.SayThis( '', Msg, ErrorCode ); end; procedure TChatHandler.OnMessageCompositionChanged( State : TMsgCompositionState ); var ErrorCode : TErrorCode; begin if fClientView <> nil then fClientView.MsgCompositionChanged( State, ErrorCode ) end; procedure TChatHandler.OnCreateChannel( Name, Password, aSessionApp, aSessionAppId : string; anUserLimit : integer ); begin Fork( threadedCreateChannel, priNormal, [Name, Password, aSessionApp, aSessionAppId, anUserLimit] ); end; procedure TChatHandler.OnJoinChannel( Name, Password : string ); begin Fork( threadedJoinChannel, priNormal, [Name, Password] ); end; procedure TChatHandler.threadedCreateChannel( const parms : array of const ); var Name : string; Password : string; SessionApp : string; SessionAppId : string; UserLimit : integer; ErrorCode : TErrorCode; begin Name := parms[0].vPchar; Password := parms[1].vPchar; SessionApp := parms[2].vPchar; SessionAppId := parms[3].vPchar; UserLimit := parms[4].vInteger; fClientView.CreateChannel( Name, Password, SessionApp, SessionAppId, UserLimit, ErrorCode ); Join( syncCreateChannel, [ErrorCode] ); end; procedure TChatHandler.syncCreateChannel( const parms : array of const ); begin end; procedure TChatHandler.threadedJoinChannel( const parms : array of const ); var Name : string; Password : string; ErrorCode : TErrorCode; begin Name := parms[0].vPchar; Password := parms[1].vPchar; fClientView.JoinChannel( Name, Password, ErrorCode ); Join( syncJoinChannel, [ErrorCode] ); end; procedure TChatHandler.syncJoinChannel( const parms : array of const ); var ErrorCode : TErrorCode absolute parms[0].vInteger; begin case ErrorCode of NOERROR :; ERROR_NotEnoughRoom : ShowMsgBox( GetLiteral('Literal199'), GetLiteral('Literal200'), 0, true, false ); ERROR_InvalidPassword : ShowMsgBox( GetLiteral('Literal201'), GetLiteral('Literal202'), 0, true, false ); end; end; procedure TChatHandler.threadedUpdateChannelList( const parms : array of const ); var ChannelList : TStringList; ErrorCode : TErrorCode; begin ChannelList := fClientView.GetChannelList( ErrorCode ); if ChannelList <> nil then Join( syncUpdateChannelList, [ChannelList] ); end; procedure TChatHandler.syncUpdateChannelList( const parms : array of const ); var ChannelList : TStringList absolute parms[0].vPointer; i : integer; begin if ChannelList.Count > 0 then begin fControl.NoChannels.Visible := false; fControl.ChannelList.Visible := true; fControl.ChannelList.Items.BeginUpdate; try fControl.ChannelList.Items.Clear; for i := 0 to pred(ChannelList.Count div 2) do fControl.AddChannel( ChannelList[2*i], ChannelList[2*i + 1] ); finally fControl.ChannelList.Items.EndUpdate; end; ChannelList.Free; end else begin fControl.NoChannels.Visible := true; fControl.ChannelList.Visible := false; end; end; function TChatHandler.HandleURL( URL : TURL ) : TURLHandlingResult; begin result := urlNotHandled; end; function TChatHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; var ChannelListChangeInfo : TChannelListChangeInfo absolute info; ChannelName : string absolute info; ChatMsgInfo : TChatMsgInfo absolute info; ScrollInfo : TEvnScrollInfo absolute info; begin result := evnNotHandled; case EventId of evnChatMsg : if not fPrivacyHandler.UserIsIgnored( ChatMsgInfo.From ) then fControl.DisplayMsg( ChatMsgInfo.From, ChatMsgInfo.Msg ); evnHandlerExposed : begin fControl.TextInput.SetFocus; fControl.TextInput.Text := GetLiteral('Literal203'); fControl.TextInput.SelectAll; Fork( threadedUpdateChannelList, priNormal, [self] ); end; evnHandlerUnexposed : if not fChatOverMap then fMasterURLHandler.HandleURL( '?' + 'frame_Id=' + tidHandlerName_ChatList + '&frame_Close=yes' ); evnChatOverMap : fChatOverMap := boolean(info); evnChannelListChanged : if ChannelListChangeInfo.Change = uchInclusion then fControl.AddChannel( ChannelListChangeInfo.ChannelName, ChannelListChangeInfo.Password ) else fControl.DelChannel( ChannelListChangeInfo.ChannelName ); evnChannelChanged : fControl.SetChannel( ChannelName ); evnLogonStarted: fMasterURLHandler.HandleURL( '?' + 'frame_Id=' + tidHandlerName_Chat + '&frame_Close=yes' ); { evnScroll : if (ScrollInfo.DirInfo[scrVertical] <> sbsNone) and (ScrollInfo.MousePos.x >= fControl.Left) and (ScrollInfo.MousePos.x <= fControl.Left + fControl.Width) then case ScrollInfo.DirInfo[scrVertical] of sbsPositive : fControl.Scroll( -10 ); sbsNegative : fControl.Scroll( 10 ); end; } else exit; end; result := evnHandled; end; function TChatHandler.getControl : TControl; begin result := fControl; end; procedure TChatHandler.setMasterURLHandler( URLHandler : IMasterURLHandler ); begin URLHandler.HandleEvent( evnAnswerClientView, fClientView ); URLHandler.HandleEvent( evnAnswerPrivacyHandler, fPrivacyHandler ); fMasterURLHandler := URLHandler; fControl.ClientView := fClientView; end; end.
unit CH375DLL; interface // 2003.09.08, 2003.12.28, 2004.10.15, 2004.12.05, 2004.12.10, 2005.01.20, 2005.02.23, 2005.07.15 //**************************************** //** Copyright (C) W.ch 1999-2005 ** //** Web: http://www.winchiphead.com ** //**************************************** //** DLL for USB interface chip CH375 ** //** C, VC5.0 ** //**************************************** // // USB总线接口芯片CH375的应用层接口库 V2.1 // 南京沁恒电子有限公司 作者: W.ch 2005.07 // CH375-DLL V2.1 , Support: Ctrl/Bulk/Int // 运行环境: Windows 98/ME, Windows 2000/XP // support USB chip: CH372/CH375 // uses main,SysUtils,unit1; Const mCH375_PACKET_LENGTH = 64; // CH375支持的数据包的长度 mCH375_MAX_NUMBER = 16; // 最多同时连接的CH375数 mMAX_BUFFER_LENGTH = $1000; // 数据缓冲区最大长度 mDEFAULT_BUFFER_LEN = $400; // 数据缓冲区默认长度1024 // CH375端点地址 mCH375_ENDP_INTER_UP = $81; // CH375的中断数据上传端点的地址 mCH375_ENDP_INTER_DOWN = $1; // CH375的中断数据下传端点的地址 mCH375_ENDP_DATA_UP = $82; // CH375的数据块上传端点的地址 mCH375_ENDP_DATA_DOWN = $2; //CH375的数据块下传端点的地址 // 设备层接口提供的管道操作命令 mPipeDeviceCtrl = $4; // CH375的综合控制管道; mPipeInterUp = $5; //CH375的中断数据上传管道; mPipeDataUp = $6; //CH375的数据块上传管道 mPipeDataDown = $7; //CH375的数据块下传管道 mPipeAuxDown =$8; // CH375的辅助数据下传管道 // 应用层接口的功能代码 mFuncNoOperation = $H0; // 无操作 mFuncGetVersion = $1; // 获取驱动程序版本号 mFuncGetConfig = $2; // 获取USB设备配置描述符 mFuncSetExclusive = $b; // 设置独占使用 mFuncResetDevice = $C; // 复位USB设备 mFuncResetPipe = $D; // 复位USB管道 mFuncAbortPipe = $E; // 取消USB管道的数据请求 mFuncSetTimeout = $0f; // 设置USB通讯超时 mFuncBufferMode = $10; // 设定缓冲上传模式及查询缓冲区中的数据长度 // USB设备标准请求代码 mUSB_CLR_FEATURE = $1; mUSB_SET_FEATURE = $3; mUSB_GET_STATUS = $0 ; mUSB_SET_ADDRESS = $5; mUSB_GET_DESCR = $6; mUSB_SET_DESCR = $7; mUSB_GET_CONFIG = $8; mUSB_SET_CONFIG = $9; mUSB_GET_INTERF = $A; mUSB_SET_INTERF = $B; mUSB_SYNC_FRAME = $C; // CH375控制传输的厂商专用请求类型 mCH375_VENDOR_READ = $C0; //通过控制传输实现的CH375供应商专用读操作 mCH375_VENDOR_WRITE = $40; //通过控制传输实现的CH375供应商专用写操作 // CH375控制传输的供应商专用请求代码 mCH375_SET_CONTROL = $51; // 输出控制信号 mCH375_GET_STATUS = $52; // 输入状态信号 // 寄存器的位定义 mBitInputRxd = $2; // 只读,RXD#引脚输入状态,1:高电平,0:低电平 mBitInputReq = $4; // 只读,REQ#引脚输入状态,1:高电平,0:低电平 // 直接输入的状态信号的位定义 mStateRXD = $200; // RXD#引脚输入状态,1:高电平,0:低电平 mStateREQ = $400; // REQ#引脚输入状态,1:高电平,0:低电平 type PVOID =Pointer; plong=pcardinal; TiIntRoutine=procedure(mbuffer:pbytearray);stdcall; Type mUspValue=record mUspValueLow : Byte; mUspValueHigh : Byte; End; Type mUspIndex=record mUspIndexLow : Byte; mUspIndexHigh : Byte; End ; Type USB_SETUP_PKT=record mUspReqType : Byte; mUspRequest : Byte; mUspValue : mUspValue; mUspIndex : mUspIndex; mLength : Integer; End ; Type WIN32_COMMAND=record //定义WIN32命令接口结构 mFunction : cardinal; //输入时指定功能代码或者管道号 //输出时返回操作状态 mLength : cardinal; //存取长度,返回后续数据的长度 mBuffer:array[0..(mCH375_PACKET_LENGTH-1)] of Byte; //数据缓冲区,长度为0至255B '数据缓冲区,长度为0至255B End ; var mUSB_SETUP_PKT :USB_SETUP_PKT; mWIN32_COMMAND : WIN32_COMMAND; mm:procedure(mbuffer:pbytearray);stdcall; Function CH375OpenDevice(iIndex :cardinal):cardinal ;Stdcall; external 'CH375DLL.DLL' ; //打开CH375设备,返回句柄,出错则无效. 指定CH375设备序号,0对应第一个设备 procedure CH375CloseDevice(iIndex :cardinal) ;Stdcall; external 'CH375DLL.DLL'; //关闭CH375设备,指定CH375设备序号 Function CH375GetVersion():cardinal ;Stdcall; external 'CH375DLL.DLL'; //获得DLL版本号,返回版本号 Function CH375DriverCommand ( // 直接传递命令给驱动程序,出错则返回0,否则返回数据长度 iIndex:cardinal; // 指定CH375设备序号,V1.6以上DLL也可以是设备打开后的句柄 ioCommand:WIN32_COMMAND // 命令结构的指针 ):cardinal;Stdcall;external 'CH375DLL.DLL'; // 该程序在调用后返回数据长度,并且仍然返回命令结构,如果是读操作,则数据返回在命令结构中, // 返回的数据长度在操作失败时为0,操作成功时为整个命令结构的长度,例如读一个字节,则返回mWIN32_COMMAND_HEAD+1, // 命令结构在调用前,分别提供:管道号或者命令功能代码,存取数据的长度(可选),数据(可选) // 命令结构在调用后,分别返回:操作状态代码,后续数据的长度(可选), // 操作状态代码是由WINDOWS定义的代码,可以参考NTSTATUS.H, // 后续数据的长度是指读操作返回的数据长度,数据存放在随后的缓冲区中,对于写操作一般为0 Function CH375GetDrvVersion:cardinal;Stdcall; external'CH375DLL.DLL'; //获得驱动程序版本号,返回版本号,出错则返回0 Function CH375ResetDevice(iIndex:cardinal) : Boolean ;Stdcall; external 'CH375DLL.DLL'; //复位USB设备, iIndex 指定CH375设备序号 Function CH375GetDeviceDescr (iIndex :cardinal;oBuffer:pvoid;ioLength:plong) : Boolean ;Stdcall; external'CH375DLL.DLL'; //读取设备描述符 //iIndex指定CH375设备序号 //oBuffer指向一个足够大的缓冲区,用于保存描述符 //ioLength指向长度单元,输入时为准备读取的长度,返回后为实际读取的长度 Function CH375GetConfigDescr(iIndex :cardinal; oBuffer :pvoid; ioLength:plong) : Boolean ;Stdcall; external 'CH375DLL.DLL' ; //读取配置描述符 //iIndex指定CH375设备序号 //oBuffer指向一个足够大的缓冲区,用于保存描述符 //ioLength 指向长度单元,输入时为准备读取的长度,返回后为实际读取的长度 Function CH375SetIntRoutine (iIndex:cardinal;iIntRoutine :TiIntRoutine) :boolean ;Stdcall; external 'CH375DLL.DLL'; //设定中断服务程序 //iIndex指定CH375设备序号 //iIntRoutine指定中断服务程序,为NULL则取消中断服务,否则在中断时调用该程序 //"TiIntRoutine"过程传递参数要用非默认的'Register'方式传递. Function CH375ReadInter(iIndex:cardinal;oBuffer:pvoid;ioLength :plong) :Boolean ; Stdcall;external 'CH375DLL.DLL'; //读取中断数据 //iIndex指定CH375设备序号 //oBuffer指向一个足够大的缓冲区,用于保存描述符 //ioLength指向长度单元,输入时为准备读取的长度,返回后为实际读取的长度 Function CH375AbortInter (iIndex :cardinal) :Boolean ;Stdcall; external 'CH375DLL.DLL'; //放弃中断数据读操作 //iIndex 指定CH375设备序号 Function CH375ReadData (iIndex :cardinal;oBuffer :pvoid;ioLength :plong):Boolean ;Stdcall; external 'CH375DLL.DLL'; //读取数据块 //iIndex指定CH375设备序号,oBuffer指向一个足够大的缓冲区,用于保存描述符,ioLength指向长度单元,输入时为准备读取的长度,返回后为实际读取的长度 function CH375AbortRead(iIndex:cardinal):boolean ;Stdcall; external 'CH375DLL.DLL' ; //放弃数据块读操作 //iIndex 指定CH375设备序号 Function CH375WriteData(iIndex :cardinal;iBuffer :pvoid;ioLength :plong):longbool ;Stdcall; external 'CH375DLL.DLL'; //先写出标准的数据块(命令,长度不超过8字节),再读取标准的数据块(应答,长度不超过8字节) //iIndex指定CH375设备序号,oBuffer指向一个足够大的缓冲区,用于保存描述符,ioLength指向长度单元,输入时为准备读取的长度,返回后为实际读取的长度 Function CH375AbortWrite (iIndex:cardinal):boolean ;Stdcall; external 'CH375DLL.DLL'; //放弃数据块写操作 //iIndex 指定CH375设备序号 Function CH375WriteRead (iIndex:cardinal;iBuffer:byte;oBuffer :pvoid;ioLength:plong):Boolean ;Stdcall; external 'CH375DLL.DLL'; //写出数据块 //iIndex指定CH375设备序号,iBuffer指向一个缓冲区,放置准备写出的数据,长度不大于mCH375_PACKET_LENGTH,oBuffer指向一个足够大的缓冲区,用于保存描述符,ioLength指向长度单元,输入时为准备读取的长度,返回后为实际读取的长度 Function CH375GetStatus(iIndex:cardinal;var iStatus:plong):boolean ;Stdcall; external 'CH375DLL.DLL'; //通过CH375直接输入数据和状态 //iIndex 指定CH375设备序号 //iStatus 指向一个双字单元,用于保存状态数据 //位7-位0对应CH375的D7-D0引脚,位9对应CH375的RXD#引脚,位10对应CH375的REQ#引脚 Function CH375SetTimeout( // 设置USB数据读写的超时 iIndex:cardinal; // 指定CH375设备序号 iWriteTimeout:cardinal; // 指定USB写出数据块的超时时间,以毫秒mS为单位,0xFFFFFFFF指定不超时(默认值) iReadTimeout:cardinal // 指定USB读取数据块的超时时间,以毫秒mS为单位,0xFFFFFFFF指定不超时(默认值) ):boolean;Stdcall; external 'CH375DLL.DLL'; Function CH375WriteAuxData( // 写出辅助数据 iIndex:cardinal; // 指定CH375设备序号 iBuffer:pvoid; // 指向一个缓冲区,放置准备写出的数据 ioLength:plong // 指向长度单元,输入时为准备写出的长度,返回后为实际写出的长度 ):boolean;Stdcall; external 'CH375DLL.DLL'; Function CH375SetExclusive( // 设置独占使用当前CH375设备 iIndex:cardinal; // 指定CH375设备序号 iExclusive:cardinal // 为0则设备可以共享使用,非0则独占使用 ):boolean;Stdcall; external 'CH375DLL.DLL'; Function CH375GetUsbID( // 获取USB设备ID,返回数据中,低16位为厂商ID,高16位为产品ID,错误时返回全0(无效ID) iIndex:cardinal // 指定CH375设备序号 ):cardinal;Stdcall; external 'CH375DLL.DLL'; Function CH375GetDeviceName( // 返回指向CH375设备名称的缓冲区,出错则返回NULL iIndex:cardinal // 指定CH375设备序号,0对应第一个设备 ):pvoid;Stdcall; external 'CH375DLL.DLL'; Function CH375SetBufUpload( // 设定内部缓冲上传模式 iIndex:cardinal; // 指定CH375设备序号,0对应第一个设备 iEnableOrClear:cardinal ):longbool;Stdcall; external 'CH375DLL.DLL'; // 为0则禁止内部缓冲上传模式,使用直接上传,非0则启用内部缓冲上传模式并清除缓冲区中的已有数据 // 如果启用内部缓冲上传模式,那么CH375驱动程序创建线程自动接收USB上传数据到内部缓冲区,同时清除缓冲区中的已有数据,当应用程序调用CH375ReadData后将立即返回缓冲区中的已有数据 Function CH375QueryBufUpload( // 查询内部上传缓冲区中的已有数据包个数,成功返回数据包个数,出错返回-1 iIndex:cardinal ):integer;Stdcall; external 'CH375DLL.DLL'; // 指定CH375设备序号,0对应第一个设备 Function CH375SetBufDownload( // 设定内部缓冲下传模式 iIndex:cardinal; // 指定CH375设备序号,0对应第一个设备 iEnableOrClear:cardinal ):longbool;Stdcall; external 'CH375DLL.DLL'; // 为0则禁止内部缓冲下传模式,使用直接下传,非0则启用内部缓冲下传模式并清除缓冲区中的已有数据 // 如果启用内部缓冲下传模式,那么当应用程序调用CH375WriteData后将仅仅是将USB下传数据放到内部缓冲区并立即返回,而由CH375驱动程序创建的线程自动发送直到完毕 Function CH375QueryBufDownload( // 查询内部下传缓冲区中的剩余数据包个数(尚未发送),成功返回数据包个数,出错返回-1 iIndex:cardinal ):integer;Stdcall; external 'CH375DLL.DLL'; // 指定CH375设备序号,0对应第一个设备 Function CH375ResetInter( // 复位中断数据读操作 iIndex:cardinal ):longbool;Stdcall; external 'CH375DLL.DLL'; // 指定CH375设备序号 Function CH375ResetAux( // 复位辅助数据写操作 iIndex:cardinal ):longbool;Stdcall; external 'CH375DLL.DLL'; // 指定CH375设备序号 Function CH375ResetRead( // 复位数据块读操作 iIndex:cardinal ):longbool;Stdcall; external 'CH375DLL.DLL'; // 指定CH375设备序号 Function CH375ResetWrite( // 复位数据块写操作 iIndex:cardinal ):longbool;Stdcall; external 'CH375DLL.DLL'; // 指定CH375设备序号 type mPCH375_NOTIFY_ROUTINE=Procedure (iEventStatus:cardinal );stdcall; // 设备事件通知回调程序 // 设备事件和当前状态(在下行定义): 0=设备拔出事件, 3=设备插入事件 const CH375_DEVICE_ARRIVAL= 3; // 设备插入事件,已经插入 CH375_DEVICE_REMOVE_PEND=1; // 设备将要拔出 CH375_DEVICE_REMOVE=0; // 设备拔出事件,已经拔出 Function CH375SetDeviceNotify( // 设定设备事件通知程序 iIndex:cardinal; // 指定CH375设备序号,0对应第一个设备 iDeviceID:PCHAR; // 可选参数,指向字符串,指定被监控的设备的ID,字符串以\0终止 iNotifyRoutine:mPCH375_NOTIFY_ROUTINE ):longbool;Stdcall; external 'CH375DLL.DLL'; // 指定设备事件回调程序,为NULL则取消事件通知,否则在检测到事件时调用该程序 implementation end.
{*****************************************************************} { } { Delphi XML Data Binding } { } { Generated on: 5-5-2002 15:54:53 } { Generated from: D:\Delphi6\NLDelphiTracker\Settings.xml } { Settings stored in: D:\Delphi6\NLDelphiTracker\Settings.xdb } { } {*****************************************************************} unit DeXSettingsU; interface uses xmldom, XMLDoc, XMLIntf; type { Forward Decls } IXMLSettingsType = interface; IXMLPopupType = interface; IXMLIgnoreSelfType = interface; IXMLNotifySoundType = interface; IXMLUserType = interface; IXMLSortType = interface; { IXMLSettingsType } IXMLSettingsType = interface(IXMLNode) ['{D61D3C42-E930-4718-8481-797814C984E9}'] { Property Accessors } function Get_Version: WideString; function Get_Popup: IXMLPopupType; function Get_IgnoreSelf: IXMLIgnoreSelfType; function Get_AutoSave: Boolean; function Get_Interval: Integer; function Get_NotifySound: IXMLNotifySoundType; function Get_User: IXMLUserType; function Get_Sort: IXMLSortType; function Get_SiteURL: WideString; procedure Set_Version(Value: WideString); procedure Set_AutoSave(Value: Boolean); procedure Set_Interval(Value: Integer); procedure Set_SiteURL(Value: WideString); { Methods & Properties } property Version: WideString read Get_Version write Set_Version; property Popup: IXMLPopupType read Get_Popup; property IgnoreSelf: IXMLIgnoreSelfType read Get_IgnoreSelf; property AutoSave: Boolean read Get_AutoSave write Set_AutoSave; property Interval: Integer read Get_Interval write Set_Interval; property NotifySound: IXMLNotifySoundType read Get_NotifySound; property User: IXMLUserType read Get_User; property Sort: IXMLSortType read Get_Sort; property SiteURL: WideString read Get_SiteURL write Set_SiteURL; end; { IXMLPopupType } IXMLPopupType = interface(IXMLNode) ['{199AEEDB-A4C0-44C3-BC50-7DC0C6FECB10}'] { Property Accessors } function Get_Color: WideString; function Get_Time: Integer; function Get_Enabled: Boolean; function Get_DeleteOnClick: Boolean; function Get_TextColor: WideString; function Get_LinkColor: WideString; procedure Set_Color(Value: WideString); procedure Set_Time(Value: Integer); procedure Set_Enabled(Value: Boolean); procedure Set_DeleteOnClick(Value: Boolean); procedure Set_TextColor(Value: WideString); procedure Set_LinkColor(Value: WideString); { Methods & Properties } property Color: WideString read Get_Color write Set_Color; property Time: Integer read Get_Time write Set_Time; property Enabled: Boolean read Get_Enabled write Set_Enabled; property DeleteOnClick: Boolean read Get_DeleteOnClick write Set_DeleteOnClick; property TextColor: WideString read Get_TextColor write Set_TextColor; property LinkColor: WideString read Get_LinkColor write Set_LinkColor; end; { IXMLIgnoreSelfType } IXMLIgnoreSelfType = interface(IXMLNode) ['{F68945D0-EDAD-4739-A07E-22F24BD9A01A}'] { Property Accessors } function Get_Enabled: Boolean; function Get_Username: WideString; procedure Set_Enabled(Value: Boolean); procedure Set_Username(Value: WideString); { Methods & Properties } property Enabled: Boolean read Get_Enabled write Set_Enabled; property Username: WideString read Get_Username write Set_Username; end; { IXMLNotifySoundType } IXMLNotifySoundType = interface(IXMLNode) ['{6C1B23B0-FDB5-438A-92B4-DBD96CCFA9A0}'] { Property Accessors } function Get_Enabled: Boolean; function Get_FileName: WideString; procedure Set_Enabled(Value: Boolean); procedure Set_FileName(Value: WideString); { Methods & Properties } property Enabled: Boolean read Get_Enabled write Set_Enabled; property FileName: WideString read Get_FileName write Set_FileName; end; { IXMLUserType } IXMLUserType = interface(IXMLNode) ['{41E85AA4-BDF7-4E02-AF06-6BD064FDE50C}'] { Property Accessors } function Get_Name: WideString; function Get_Password: WideString; function Get_Location: WideString; procedure Set_Name(Value: WideString); procedure Set_Password(Value: WideString); procedure Set_Location(Value: WideString); { Methods & Properties } property Name: WideString read Get_Name write Set_Name; property Password: WideString read Get_Password write Set_Password; property Location: WideString read Get_Location write Set_Location; end; { IXMLSortType } IXMLSortType = interface(IXMLNode) ['{955D5C4A-77EC-432A-8508-8DDD6DB17847}'] { Property Accessors } function Get_Direction: Integer; function Get_SortType: Integer; procedure Set_Direction(Value: Integer); procedure Set_SortType(Value: Integer); { Methods & Properties } property Direction: Integer read Get_Direction write Set_Direction; property SortType: Integer read Get_SortType write Set_SortType; end; { Forward Decls } TXMLSettingsType = class; TXMLPopupType = class; TXMLIgnoreSelfType = class; TXMLNotifySoundType = class; TXMLUserType = class; TXMLSortType = class; { TXMLSettingsType } TXMLSettingsType = class(TXMLNode, IXMLSettingsType) protected { IXMLSettingsType } function Get_Version: WideString; function Get_Popup: IXMLPopupType; function Get_IgnoreSelf: IXMLIgnoreSelfType; function Get_AutoSave: Boolean; function Get_Interval: Integer; function Get_NotifySound: IXMLNotifySoundType; function Get_User: IXMLUserType; function Get_Sort: IXMLSortType; function Get_SiteURL: WideString; procedure Set_Version(Value: WideString); procedure Set_AutoSave(Value: Boolean); procedure Set_Interval(Value: Integer); procedure Set_SiteURL(Value: WideString); public procedure AfterConstruction; override; end; { TXMLPopupType } TXMLPopupType = class(TXMLNode, IXMLPopupType) protected { IXMLPopupType } function Get_Color: WideString; function Get_Time: Integer; function Get_Enabled: Boolean; function Get_DeleteOnClick: Boolean; function Get_TextColor: WideString; function Get_LinkColor: WideString; procedure Set_Color(Value: WideString); procedure Set_Time(Value: Integer); procedure Set_Enabled(Value: Boolean); procedure Set_DeleteOnClick(Value: Boolean); procedure Set_TextColor(Value: WideString); procedure Set_LinkColor(Value: WideString); end; { TXMLIgnoreSelfType } TXMLIgnoreSelfType = class(TXMLNode, IXMLIgnoreSelfType) protected { IXMLIgnoreSelfType } function Get_Enabled: Boolean; function Get_Username: WideString; procedure Set_Enabled(Value: Boolean); procedure Set_Username(Value: WideString); end; { TXMLNotifySoundType } TXMLNotifySoundType = class(TXMLNode, IXMLNotifySoundType) protected { IXMLNotifySoundType } function Get_Enabled: Boolean; function Get_FileName: WideString; procedure Set_Enabled(Value: Boolean); procedure Set_FileName(Value: WideString); end; { TXMLUserType } TXMLUserType = class(TXMLNode, IXMLUserType) protected { IXMLUserType } function Get_Name: WideString; function Get_Password: WideString; function Get_Location: WideString; procedure Set_Name(Value: WideString); procedure Set_Password(Value: WideString); procedure Set_Location(Value: WideString); end; { TXMLSortType } TXMLSortType = class(TXMLNode, IXMLSortType) protected { IXMLSortType } function Get_Direction: Integer; function Get_SortType: Integer; procedure Set_Direction(Value: Integer); procedure Set_SortType(Value: Integer); end; { Global Functions } function GetSettings(Doc: IXMLDocument): IXMLSettingsType; function LoadSettings(const FileName: WideString): IXMLSettingsType; function NewSettings: IXMLSettingsType; const TargetNamespace = ''; implementation { Global Functions } function GetSettings(Doc: IXMLDocument): IXMLSettingsType; begin Result := Doc.GetDocBinding('Settings', TXMLSettingsType, TargetNamespace) as IXMLSettingsType; end; function LoadSettings(const FileName: WideString): IXMLSettingsType; begin Result := LoadXMLDocument(FileName).GetDocBinding('Settings', TXMLSettingsType, TargetNamespace) as IXMLSettingsType; end; function NewSettings: IXMLSettingsType; begin Result := NewXMLDocument.GetDocBinding('Settings', TXMLSettingsType, TargetNamespace) as IXMLSettingsType; end; { TXMLSettingsType } procedure TXMLSettingsType.AfterConstruction; begin RegisterChildNode('Popup', TXMLPopupType); RegisterChildNode('IgnoreSelf', TXMLIgnoreSelfType); RegisterChildNode('NotifySound', TXMLNotifySoundType); RegisterChildNode('User', TXMLUserType); RegisterChildNode('Sort', TXMLSortType); inherited; end; function TXMLSettingsType.Get_Version: WideString; begin Result := ChildNodes['Version'].Text; end; procedure TXMLSettingsType.Set_Version(Value: WideString); begin ChildNodes['Version'].NodeValue := Value; end; function TXMLSettingsType.Get_Popup: IXMLPopupType; begin Result := ChildNodes['Popup'] as IXMLPopupType; end; function TXMLSettingsType.Get_IgnoreSelf: IXMLIgnoreSelfType; begin Result := ChildNodes['IgnoreSelf'] as IXMLIgnoreSelfType; end; function TXMLSettingsType.Get_AutoSave: Boolean; begin Result := ChildNodes['AutoSave'].NodeValue; end; procedure TXMLSettingsType.Set_AutoSave(Value: Boolean); begin ChildNodes['AutoSave'].NodeValue := Value; end; function TXMLSettingsType.Get_Interval: Integer; begin Result := ChildNodes['Interval'].NodeValue; end; procedure TXMLSettingsType.Set_Interval(Value: Integer); begin ChildNodes['Interval'].NodeValue := Value; end; function TXMLSettingsType.Get_NotifySound: IXMLNotifySoundType; begin Result := ChildNodes['NotifySound'] as IXMLNotifySoundType; end; function TXMLSettingsType.Get_User: IXMLUserType; begin Result := ChildNodes['User'] as IXMLUserType; end; function TXMLSettingsType.Get_Sort: IXMLSortType; begin Result := ChildNodes['Sort'] as IXMLSortType; end; function TXMLSettingsType.Get_SiteURL: WideString; begin Result := ChildNodes['SiteURL'].Text; end; procedure TXMLSettingsType.Set_SiteURL(Value: WideString); begin ChildNodes['SiteURL'].NodeValue := Value; end; { TXMLPopupType } function TXMLPopupType.Get_Color: WideString; begin Result := ChildNodes['Color'].Text; end; procedure TXMLPopupType.Set_Color(Value: WideString); begin ChildNodes['Color'].NodeValue := Value; end; function TXMLPopupType.Get_Time: Integer; begin Result := ChildNodes['Time'].NodeValue; end; procedure TXMLPopupType.Set_Time(Value: Integer); begin ChildNodes['Time'].NodeValue := Value; end; function TXMLPopupType.Get_Enabled: Boolean; begin Result := ChildNodes['Enabled'].NodeValue; end; procedure TXMLPopupType.Set_Enabled(Value: Boolean); begin ChildNodes['Enabled'].NodeValue := Value; end; function TXMLPopupType.Get_DeleteOnClick: Boolean; begin Result := ChildNodes['DeleteOnClick'].NodeValue; end; procedure TXMLPopupType.Set_DeleteOnClick(Value: Boolean); begin ChildNodes['DeleteOnClick'].NodeValue := Value; end; function TXMLPopupType.Get_TextColor: WideString; begin Result := ChildNodes['TextColor'].Text; end; procedure TXMLPopupType.Set_TextColor(Value: WideString); begin ChildNodes['TextColor'].NodeValue := Value; end; function TXMLPopupType.Get_LinkColor: WideString; begin Result := ChildNodes['LinkColor'].Text; end; procedure TXMLPopupType.Set_LinkColor(Value: WideString); begin ChildNodes['LinkColor'].NodeValue := Value; end; { TXMLIgnoreSelfType } function TXMLIgnoreSelfType.Get_Enabled: Boolean; begin Result := ChildNodes['Enabled'].NodeValue; end; procedure TXMLIgnoreSelfType.Set_Enabled(Value: Boolean); begin ChildNodes['Enabled'].NodeValue := Value; end; function TXMLIgnoreSelfType.Get_Username: WideString; begin Result := ChildNodes['Username'].Text; end; procedure TXMLIgnoreSelfType.Set_Username(Value: WideString); begin ChildNodes['Username'].NodeValue := Value; end; { TXMLNotifySoundType } function TXMLNotifySoundType.Get_Enabled: Boolean; begin Result := ChildNodes['Enabled'].NodeValue; end; procedure TXMLNotifySoundType.Set_Enabled(Value: Boolean); begin ChildNodes['Enabled'].NodeValue := Value; end; function TXMLNotifySoundType.Get_FileName: WideString; begin Result := ChildNodes['FileName'].Text; end; procedure TXMLNotifySoundType.Set_FileName(Value: WideString); begin ChildNodes['FileName'].NodeValue := Value; end; { TXMLUserType } function TXMLUserType.Get_Name: WideString; begin Result := ChildNodes['Name'].Text; end; procedure TXMLUserType.Set_Name(Value: WideString); begin ChildNodes['Name'].NodeValue := Value; end; function TXMLUserType.Get_Password: WideString; begin Result := ChildNodes['Password'].Text; end; procedure TXMLUserType.Set_Password(Value: WideString); begin ChildNodes['Password'].NodeValue := Value; end; function TXMLUserType.Get_Location: WideString; begin Result := ChildNodes['Location'].Text; end; procedure TXMLUserType.Set_Location(Value: WideString); begin ChildNodes['Location'].NodeValue := Value; end; { TXMLSortType } function TXMLSortType.Get_Direction: Integer; begin Result := ChildNodes['Direction'].NodeValue; end; procedure TXMLSortType.Set_Direction(Value: Integer); begin ChildNodes['Direction'].NodeValue := Value; end; function TXMLSortType.Get_SortType: Integer; begin Result := ChildNodes['SortType'].NodeValue; end; procedure TXMLSortType.Set_SortType(Value: Integer); begin ChildNodes['SortType'].NodeValue := Value; end; end.
unit Ragna.Criteria.Intf; {$IF DEFINED(FPC)} {$MODE DELPHI}{$H+} {$ENDIF} interface type ICriteria = interface ['{BC7603D3-DB7D-4A61-AA73-E1152A933E07}'] procedure Where(const AField: string); procedure &Or(const AField: string); procedure &And(const AField: string); procedure Like(const AValue: string); procedure &Equals(const AValue: Int64); overload; procedure &Equals(const AValue: Boolean); overload; procedure &Equals(const AValue: string); overload; procedure Order(const AField: string); end; implementation end.
unit udmOrdsAbastecimento; interface uses Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS; type TdmOrdsAbastecimento = class(TdmPadrao) qryManutencaoFIL_ORIGEM: TStringField; qryManutencaoNRO_ABASTECIMENTO: TFloatField; qryManutencaoPTO_ABASTECIMENTO: TStringField; qryManutencaoEMISSAO: TDateTimeField; qryManutencaoBAIXA: TDateTimeField; qryManutencaoVEICULO: TStringField; qryManutencaoMOTORISTA: TStringField; qryManutencaoCOMBUSTIVEL: TStringField; qryManutencaoKM_INICIAL: TFloatField; qryManutencaoKM_FINAL: TFloatField; qryManutencaoBMB_INICIAL: TFloatField; qryManutencaoBMB_FINAL: TFloatField; qryManutencaoLITRAGEM: TFloatField; qryManutencaoVLR_UNITARIO: TFloatField; qryManutencaoVLR_TOTAL: TFloatField; qryManutencaoLIBERADO_POR: TStringField; qryManutencaoFRENTISTA: TStringField; qryManutencaoIMPRESSA: TStringField; qryManutencaoN_FISCAL: TIntegerField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; qryManutencaoPLC_VEICULO: TStringField; qryManutencaoMRC_VEICULO: TStringField; qryManutencaoMOD_VEICULO: TStringField; qryManutencaoSITUACAO: TStringField; qryManutencaoDESC_VEICULO: TStringField; qryManutencaoNM_MOTORISTA: TStringField; qryManutencaoRG_MOTORISTA: TStringField; qryManutencaoNM_PTOABASTECIMENTO: TStringField; qryLocalizacaoFIL_ORIGEM: TStringField; qryLocalizacaoNRO_ABASTECIMENTO: TFloatField; qryLocalizacaoPTO_ABASTECIMENTO: TStringField; qryLocalizacaoEMISSAO: TDateTimeField; qryLocalizacaoBAIXA: TDateTimeField; qryLocalizacaoVEICULO: TStringField; qryLocalizacaoMOTORISTA: TStringField; qryLocalizacaoCOMBUSTIVEL: TStringField; qryLocalizacaoKM_INICIAL: TFloatField; qryLocalizacaoKM_FINAL: TFloatField; qryLocalizacaoBMB_INICIAL: TFloatField; qryLocalizacaoBMB_FINAL: TFloatField; qryLocalizacaoLITRAGEM: TFloatField; qryLocalizacaoVLR_UNITARIO: TFloatField; qryLocalizacaoVLR_TOTAL: TFloatField; qryLocalizacaoLIBERADO_POR: TStringField; qryLocalizacaoFRENTISTA: TStringField; qryLocalizacaoIMPRESSA: TStringField; qryLocalizacaoN_FISCAL: TIntegerField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoPLC_VEICULO: TStringField; qryLocalizacaoMRC_VEICULO: TStringField; qryLocalizacaoMOD_VEICULO: TStringField; qryLocalizacaoSITUACAO: TStringField; qryLocalizacaoDESC_VEICULO: TStringField; qryLocalizacaoNM_MOTORISTA: TStringField; qryLocalizacaoRG_MOTORISTA: TStringField; qryLocalizacaoNM_PTOABASTECIMENTO: TStringField; protected procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; private FNumero: Real; FEmissora: string; FPtoAbastecimento: string; FNotaAbastecimento: integer; FVeiculo: string; FDtaFinal: TDateTime; FDtaInicial: TDateTime; function GetSQLDefault: string; { Private declarations } public property Emissora: string read FEmissora write FEmissora; property Nro_Abastecimento: Real read FNumero write FNumero; property Veiculo: string read FVeiculo write FVeiculo; property Pto_Abastecimento: string read FPtoAbastecimento write FPtoAbastecimento; property Dta_Inicial: TDateTime read FDtaInicial write FDtaInicial; property Dta_Final: TDateTime read FDtaFinal write FDtaFinal; property Nota_Abastecimento: integer read FNotaAbastecimento write FNotaAbastecimento; property SQLDefault: string read GetSQLDefault; function LocalizarBaixadasPorPeriodo(DataSet: TDataSet = nil): Boolean; function LocalizarEmAbertoPorPeriodo(DataSet: TDataSet = nil): Boolean; function LocalizarPorPontoAbastecimento(DataSet: TDataSet = nil): Boolean; function LocalizarKmFinalNaUltimaOrdem(DataSet: TDataSet = nil): Real; function ExisteNro_Ordem(): Boolean; end; const SQL_DEFAULT = ' SELECT ORD.FIL_ORIGEM,' + ' ORD.NRO_ABASTECIMENTO,' + ' ORD.PTO_ABASTECIMENTO,' + ' ORD.EMISSAO,' + ' ORD.BAIXA,' + ' ORD.VEICULO,' + ' ORD.MOTORISTA,' + ' ORD.COMBUSTIVEL,' + ' ORD.KM_INICIAL,' + ' ORD.KM_FINAL,' + ' ORD.BMB_INICIAL,' + ' ORD.BMB_FINAL,' + ' ORD.LITRAGEM,' + ' ORD.VLR_UNITARIO,' + ' ORD.VLR_TOTAL,' + ' ORD.LIBERADO_POR,' + ' ORD.FRENTISTA,' + ' ORD.IMPRESSA,' + ' ORD.N_FISCAL,' + ' ORD.DT_ALTERACAO,' + ' ORD.OPERADOR,' + ' VEI.PLACA PLC_VEICULO,' + ' VEI.MARCA MRC_VEICULO,' + ' VEI.MODELO MOD_VEICULO,' + ' IIF(VAR.CGC = VEI.CGC_PRO, ''PRP'',''TRC'') SITUACAO,' + ' TPV.DESCRICAO DESC_VEICULO,' + ' MOT.NOME NM_MOTORISTA,' + ' MOT.RG RG_MOTORISTA,' + ' PTO.NOME NM_PTOABASTECIMENTO' + ' FROM STWABSTORD ORD' + ' LEFT JOIN STWOPETVEI VEI ON VEI.FROTA = ORD.VEICULO' + ' LEFT JOIN STWOPETVAR VAR ON VAR.CGC = VEI.CGC_PRO AND VAR.FILIAL = ORD.FIL_ORIGEM' + ' LEFT JOIN STWOPETTPVE TPV ON TPV.CODIGO = VEI.TIPO' + ' LEFT JOIN STWOPETMOT MOT ON MOT.CPF = ORD.MOTORISTA' + ' LEFT JOIN STWABSTPTO PTO ON PTO.CODIGO = ORD.PTO_ABASTECIMENTO'; var dmOrdsAbastecimento: TdmOrdsAbastecimento; implementation {$R *.dfm} { TdmOrdsAbastecimento } function TdmOrdsAbastecimento.GetSQLDefault: string; begin Result := SQL_DEFAULT; end; function TdmOrdsAbastecimento.LocalizarBaixadasPorPeriodo( DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add(' WHERE ( ORD.BAIXA IS NOT NULL ) AND ( ORD.LITRAGEM > 0 ) AND ( ORD.EMISSAO BETWEEN :DT_INICIO AND :DT_FINAL )'); if Length(FVeiculo) > 0 then SQL.Add(' AND ( ORD.VEICULO = ' + QuotedStr(FVeiculo)+ ')'); if Length(FPtoAbastecimento) > 0 then SQL.Add(' AND ( ORD.PTO_ABASTECIMENTO = ' + QuotedStr(FPtoAbastecimento) + ')'); SQL.Add('ORDER BY ORD.VEICULO, ORD.FIL_ORIGEM, ORD.NRO_ABASTECIMENTO'); Params[0].AsDate := FDtaFinal; Params[1].AsDate := FDtaFinal; Open; Result := not IsEmpty; end; end; function TdmOrdsAbastecimento.LocalizarEmAbertoPorPeriodo( DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add(' WHERE ( ORD.BAIXA IS NULL ) AND ( ORD.EMISSAO BETWEEN :DT_INICIO AND :DT_FINAL )'); if Length(FVeiculo) > 0 then SQL.Add(' AND ( ORD.VEICULO = ' + QuotedStr(FVeiculo) + ')'); if Length(FPtoAbastecimento) > 0 then SQL.Add(' AND ( ORD.PTO_ABASTECIMENTO = ' + QuotedStr(FPtoAbastecimento) + ')'); SQL.Add('ORDER BY ORD.VEICULO, ORD.FIL_ORIGEM, ORD.NRO_ABASTECIMENTO'); Params[0].AsDate := FDtaInicial; Params[1].AsDate := FDtaFinal; Open; Result := not IsEmpty; end; end; {Essa função retorna o KM final de uma ordem já baixada} function TdmOrdsAbastecimento.LocalizarKmFinalNaUltimaOrdem(DataSet: TDataSet): Real; begin if DataSet = nil then DataSet := qryManipulacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add('SELECT FIRST 1 ORD.KM_FINAL'); SQL.Add(' FROM STWABSTORD ORD'); SQL.Add(' LEFT JOIN STWOPETVEI VEI ON VEI.FROTA = ORD.VEICULO'); SQL.Add(' WHERE VEI.PLACA = :PLACAORD'); SQL.Add( 'AND ORD.BAIXA IS NOT NULL'); SQL.Add(' ORDER BY ORD.NRO_ABASTECIMENTO DESC'); Params[0].AsString := FVeiculo; Open; result := dmOrdsAbastecimento.qryManipulacao.FieldByName('KM_FINAL').AsFloat; end; end; procedure TdmOrdsAbastecimento.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add(' WHERE ( ORD.FIL_ORIGEM = :FIL_ORIGEM ) AND ( ORD.NRO_ABASTECIMENTO = :NRO_ABASTECIMENTO )'); SQL.Add(' ORDER BY ORD.FIL_ORIGEM, ORD.NRO_ABASTECIMENTO'); Params[0].AsString := FEmissora; Params[1].AsFloat := FNumero; end; end; Function TdmOrdsAbastecimento.LocalizarPorPontoAbastecimento(DataSet: TDataSet) : Boolean; begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add(' WHERE ( ORD.PTO_ABASTECIMENTO = :PTO_ABASTECIMENTO )'); SQL.Add(' AND (ORD.N_FISCAL = :N_ABASTECIMENTO)'); Params[0].AsString := FPtoAbastecimento; Params[1].AsInteger := FNotaAbastecimento; Open; Result := not IsEmpty; end; end; procedure TdmOrdsAbastecimento.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add(' ORDER BY ORD.FIL_ORIGEM, ORD.NRO_ABASTECIMENTO'); end; end; function TdmOrdsAbastecimento.ExisteNro_Ordem(): Boolean; begin with (qryManipulacao) do begin Close; SQL.Clear; SQL.Add('SELECT ORD.NRO_ABASTECIMENTO NRO_ABST'); SQL.Add(' FROM STWABSTORD ORD'); SQL.Add(' WHERE ORD.FIL_ORIGEM = :FIL_ORIGEM'); SQL.Add(' AND ORD.NRO_ABASTECIMENTO = :NROABST'); Params[0].AsString := FEmissora; Params[1].AsFloat := FNumero ; Open; Result := not IsEmpty; //result := dmOrdsAbastecimento.qryManipulacao.FieldByName('NRO_ABST').AsFloat; end; end; end.
unit vtDateEditRes; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "VT" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/VT/vtDateEditRes.pas" // Начат: 03.03.2010 14:43 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi::VT::DateEdit::vtDateEditRes // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\VT\vtDefine.inc} interface uses l3StringIDEx ; type TvtMonths = 1..12; {* Месяцы } var { Локализуемые строки TvtDateEditHints } str_vtStrPrevYear : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtStrPrevYear'; rValue : 'Предыдущий год'); { 'Предыдущий год' } str_vtStrPrevMonth : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtStrPrevMonth'; rValue : 'Предыдущий месяц'); { 'Предыдущий месяц' } str_vtStrNextMonth : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtStrNextMonth'; rValue : 'Следующий месяц'); { 'Следующий месяц' } str_vtStrNextYear : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtStrNextYear'; rValue : 'Следующий год'); { 'Следующий год' } var { Локализуемые строки TvtMiscMessages } str_vtTodayLongLabel : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtTodayLongLabel'; rValue : 'Сегодня %s'); { 'Сегодня %s' } str_vtTodayHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtTodayHint'; rValue : 'Нажмите для установки сегодняшней даты'); { 'Нажмите для установки сегодняшней даты' } str_vtCancel : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtCancel'; rValue : 'Отмена'); { 'Отмена' } str_vtTodayShortLabel : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtTodayShortLabel'; rValue : 'Сегодня'); { 'Сегодня' } str_vtChoose : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtChoose'; rValue : 'Выбрать'); { 'Выбрать' } var { Локализуемые строки Months } str_vtJanuary : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtJanuary'; rValue : 'Январь'); { 'Январь' } str_vtFebruary : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtFebruary'; rValue : 'Февраль'); { 'Февраль' } str_vtMarch : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMarch'; rValue : 'Март'); { 'Март' } str_vtApril : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtApril'; rValue : 'Апрель'); { 'Апрель' } str_vtMay : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMay'; rValue : 'Май'); { 'Май' } str_vtJune : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtJune'; rValue : 'Июнь'); { 'Июнь' } str_vtJuly : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtJuly'; rValue : 'Июль'); { 'Июль' } str_vtAugust : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtAugust'; rValue : 'Август'); { 'Август' } str_vtSeptember : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtSeptember'; rValue : 'Сентябрь'); { 'Сентябрь' } str_vtOctober : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtOctober'; rValue : 'Октябрь'); { 'Октябрь' } str_vtNovember : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtNovember'; rValue : 'Ноябрь'); { 'Ноябрь' } str_vtDecember : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtDecember'; rValue : 'Декабрь'); { 'Декабрь' } var { Локализуемые строки TStDayType } str_vtSunday : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtSunday'; rValue : 'Вс'); { 'Вс' } str_vtMonday : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMonday'; rValue : 'Пн'); { 'Пн' } str_vtTuesday : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtTuesday'; rValue : 'Вт'); { 'Вт' } str_vtWednesday : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtWednesday'; rValue : 'Ср'); { 'Ср' } str_vtThursday : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtThursday'; rValue : 'Чт'); { 'Чт' } str_vtFriday : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtFriday'; rValue : 'Пт'); { 'Пт' } str_vtSaturday : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtSaturday'; rValue : 'Сб'); { 'Сб' } implementation uses l3MessageID ; initialization // Инициализация str_vtStrPrevYear str_vtStrPrevYear.Init; // Инициализация str_vtStrPrevMonth str_vtStrPrevMonth.Init; // Инициализация str_vtStrNextMonth str_vtStrNextMonth.Init; // Инициализация str_vtStrNextYear str_vtStrNextYear.Init; // Инициализация str_vtTodayLongLabel str_vtTodayLongLabel.Init; // Инициализация str_vtTodayHint str_vtTodayHint.Init; // Инициализация str_vtCancel str_vtCancel.Init; // Инициализация str_vtTodayShortLabel str_vtTodayShortLabel.Init; // Инициализация str_vtChoose str_vtChoose.Init; // Инициализация str_vtJanuary str_vtJanuary.Init; // Инициализация str_vtFebruary str_vtFebruary.Init; // Инициализация str_vtMarch str_vtMarch.Init; // Инициализация str_vtApril str_vtApril.Init; // Инициализация str_vtMay str_vtMay.Init; // Инициализация str_vtJune str_vtJune.Init; // Инициализация str_vtJuly str_vtJuly.Init; // Инициализация str_vtAugust str_vtAugust.Init; // Инициализация str_vtSeptember str_vtSeptember.Init; // Инициализация str_vtOctober str_vtOctober.Init; // Инициализация str_vtNovember str_vtNovember.Init; // Инициализация str_vtDecember str_vtDecember.Init; // Инициализация str_vtSunday str_vtSunday.Init; // Инициализация str_vtMonday str_vtMonday.Init; // Инициализация str_vtTuesday str_vtTuesday.Init; // Инициализация str_vtWednesday str_vtWednesday.Init; // Инициализация str_vtThursday str_vtThursday.Init; // Инициализация str_vtFriday str_vtFriday.Init; // Инициализация str_vtSaturday str_vtSaturday.Init; end.
unit AutoMapper.ConfigurationProvider; interface uses AutoMapper.CfgMapper , AutoMapper.MappingExpression ; type /// <summary>Mapper Configuration Provider.</summary> TConfigurationProvider = class private FCfgMapper: TCfgMapper; public /// <summary>Set Mapper settings.</summary> /// <param name="Value">Setting Flags.</param> function Settings(const Value: TMapperSettings): TConfigurationProvider; /// <summary>Create a map for the source-destination pair by specifying the expression.</summary> /// <typeparam name="TSource">Source type to use, regardless of the runtime type.</typeparam> /// <typeparam name="TDestination">Destination type to create.</typeparam> /// <param name="MappingExpression">Expression for mapping.</param> function CreateMap<TSource; TDestination>(const MappingExpression: TMapExpression<TSource, TDestination>): TConfigurationProvider; overload; /// <summary>Create a map for the source-destination pair using default expressions.</summary> /// <typeparam name="TSource">Source type to use, regardless of the runtime type.</typeparam> /// <typeparam name="TDestination">Destination type to create.</typeparam> function CreateMap<TSource; TDestination>(): TConfigurationProvider; overload; /// <summary>Not implemented</summary> procedure Validate; constructor Create(const CfgMapper: TCfgMapper); virtual; destructor Destroy; override; end; implementation { TConfigurationProvider } constructor TConfigurationProvider.Create(const CfgMapper: TCfgMapper); begin FCfgMapper := CfgMapper; end; function TConfigurationProvider.CreateMap<TSource, TDestination>( const MappingExpression: TMapExpression<TSource, TDestination>): TConfigurationProvider; begin FCfgMapper.CreateMap<TSource, TDestination>(MappingExpression); result := Self; end; function TConfigurationProvider.CreateMap<TSource, TDestination>: TConfigurationProvider; begin FCfgMapper.CreateMap<TSource, TDestination>; Result := Self; end; destructor TConfigurationProvider.Destroy; begin FCfgMapper := nil; inherited; end; function TConfigurationProvider.Settings( const Value: TMapperSettings): TConfigurationProvider; begin FCfgMapper.Settings := Value; result := self; end; procedure TConfigurationProvider.Validate; begin end; end.
unit m_floatspinedit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Spin; type { TMariaeFloatSpinEdit } TMariaeFloatSpinEdit = class(TFloatSpinEdit) private FChanged: Boolean; procedure SetChanged(AValue: Boolean); protected public procedure OnChange; procedure ResetChanged; published property Changed: Boolean read FChanged write SetChanged; end; procedure Register; implementation procedure Register; begin {$I m_floatspinedit_icon.lrs} RegisterComponents('Mariae Controls',[TMariaeFloatSpinEdit]); end; { TMariaeFloatSpinEdit } procedure TMariaeFloatSpinEdit.SetChanged(AValue: Boolean); begin if FChanged = AValue then Exit; FChanged := AValue; end; procedure TMariaeFloatSpinEdit.OnChange; begin Self.SetChanged(True); end; procedure TMariaeFloatSpinEdit.ResetChanged; begin Self.SetChanged(False); end; end.
unit Providers.Mascaras.Intf; interface uses System.UITypes; type IMascaras = interface ['{0F1050E9-3029-4D22-AC14-D8B5AE187D80}'] function ExecMask(Value: string): string; end; implementation end.
{***************************************************************************} { } { Records Helper } { } { Copyright (C) Amarildo Lacerda } { } { https://github.com/amarildolacerda } { } { } {***************************************************************************} { } { 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 System.SysUtils.Helper; interface uses System.SysUtils, System.Types, System.DateUtils; type TDoubleHelper = record helper for double public function Add( n:double) : double; function ToString:String;overload; function ToString(AFormat:string):string;overload; function ToInteger:Integer; function ToDateTime:TDateTime; function ToISODatetime :string; procedure FromISODatetime( DateTimeAsString:string ); function ToTime:TTime; function ToISOTime:String; procedure FromISOTime(ATime:String); procedure FromString( AString:String;ADef:double);overload; procedure FromString( AString:String);overload; end; TStringHelper = record helper for string public function ToFloat:Double; function ToDateTime:TDatetime; function ToInteger:Integer; procedure FromFloat( Value:Double );overload; procedure FromFloat(AFormat:string;Value:Double);overload; end; implementation function ISOTimeToString(ATime: TTime): string; var fs: TFormatSettings; begin fs.TimeSeparator := ':'; Result := FormatDateTime('hh:nn:ss', ATime, fs); end; function ISODateToString(ADate: TDateTime): string; begin Result := FormatDateTime('YYYY-MM-DD', ADate); end; function ISODateTimeToString(ADateTime: TDateTime): string; var fs: TFormatSettings; begin fs.TimeSeparator := ':'; Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', ADateTime, fs); end; function ISOStrToDateTime(DateTimeAsString: string): TDateTime; begin Result := EncodeDateTime(StrToInt(Copy(DateTimeAsString, 1, 4)), StrToInt(Copy(DateTimeAsString, 6, 2)), StrToInt(Copy(DateTimeAsString, 9, 2)), StrToInt(Copy(DateTimeAsString, 12, 2)), StrToInt(Copy(DateTimeAsString, 15, 2)), StrToInt(Copy(DateTimeAsString, 18, 2)), 0); end; function ISOStrToTime(TimeAsString: string): TTime; begin Result := EncodeTime(StrToInt(Copy(TimeAsString, 1, 2)), StrToInt(Copy(TimeAsString, 4, 2)), StrToInt(Copy(TimeAsString, 7, 2)), 0); end; function ISOStrToDate(DateAsString: string): TDate; begin Result := EncodeDate(StrToInt(Copy(DateAsString, 1, 4)), StrToInt(Copy(DateAsString, 6, 2)), StrToInt(Copy(DateAsString, 9, 2))); end; { TDoubleHelper } function TDoubleHelper.Add(n: double): double; begin self := self + n; result := self; end; procedure TDoubleHelper.fromISODatetime(DateTimeAsString: string); begin self := ISOStrToDateTime(DateTimeAsString); end; procedure TDoubleHelper.FromISOTime(ATime: String); begin self := ISOStrToTime(ATime); end; procedure TDoubleHelper.FromString(AString: String); begin self := StrToFloat(AString); end; procedure TDoubleHelper.FromString(AString: String; ADef:double); begin self := StrToFloatDef(AString,ADef); end; function TDoubleHelper.ToDateTime: TDateTime; begin result := self; end; function TDoubleHelper.ToInteger: Integer; begin result := Round(self); end; function TDoubleHelper.toISODatetime: string; begin result := ISODateTimeToString(self) end; function TDoubleHelper.ToISOTime: String; begin result := ISOTimeToString( TTime(self) ); end; function TDoubleHelper.ToString(AFormat: string): string; begin result := System.SysUtils.FormatFloat(AFormat,self); end; function TDoubleHelper.ToString: String; begin result := FloatToStr(self); end; function TDoubleHelper.ToTime: TTime; begin result := TTime(self); end; { TStringHelper } procedure TStringHelper.FromFloat(Value: Double); begin self := FloatToStr(Value); end; procedure TStringHelper.FromFloat(AFormat: string; Value: Double); begin self := FormatFloat(AFormat,Value) end; function TStringHelper.toDateTime: TDatetime; begin result := StrToDateTime(self); end; function TStringHelper.ToFloat: Double; begin result := StrToFloat(self); end; function TStringHelper.ToInteger: Integer; begin result := StrToInt(self); end; end.
{ COPYRIGHT: (C) Copyright IBM Corporation 1987-1990. All rights reserved. } {| Version: 1.00 | Original translation: Peter Singer (PSi) } Unit Error; Interface CONST NO_ERROR = 0; ERROR_INVALID_FUNCTION = 1; ERROR_FILE_NOT_FOUND = 2; ERROR_PATH_NOT_FOUND = 3; ERROR_TOO_MANY_OPEN_FILES = 4; ERROR_ACCESS_DENIED = 5; ERROR_INVALID_HANDLE = 6; ERROR_ARENA_TRASHED = 7; ERROR_NOT_ENOUGH_MEMORY = 8; ERROR_INVALID_BLOCK = 9; ERROR_BAD_ENVIRONMENT = 10; ERROR_BAD_FORMAT = 11; ERROR_INVALID_ACCESS = 12; ERROR_INVALID_DATA = 13; ERROR_INVALID_DRIVE = 15; ERROR_CURRENT_DIRECTORY = 16; ERROR_NOT_SAME_DEVICE = 17; ERROR_NO_MORE_FILES = 18; ERROR_WRITE_PROTECT = 19; ERROR_BAD_UNIT = 20; ERROR_NOT_READY = 21; ERROR_BAD_COMMAND = 22; ERROR_CRC = 23; ERROR_BAD_LENGTH = 24; ERROR_SEEK = 25; ERROR_NOT_DOS_DISK = 26; ERROR_SECTOR_NOT_FOUND = 27; ERROR_OUT_OF_PAPER = 28; ERROR_WRITE_FAULT = 29; ERROR_READ_FAULT = 30; ERROR_GEN_FAILURE = 31; ERROR_SHARING_VIOLATION = 32; ERROR_LOCK_VIOLATION = 33; ERROR_WRONG_DISK = 34; ERROR_FCB_UNAVAILABLE = 35; ERROR_SHARING_BUFFER_EXCEEDED = 36; ERROR_NOT_SUPPORTED = 50; ERROR_NETWORK_ACCESS_DENIED = 65; ERROR_FILE_EXISTS = 80; ERROR_DUP_FCB = 81; ERROR_CANNOT_MAKE = 82; ERROR_FAIL_I24 = 83; ERROR_OUT_OF_STRUCTURES = 84; ERROR_ALREADY_ASSIGNED = 85; ERROR_INVALID_PASSWORD = 86; ERROR_INVALID_PARAMETER = 87; ERROR_NET_WRITE_FAULT = 88; ERROR_NO_PROC_SLOTS = 89; ERROR_NOT_FROZEN = 90; ERR_TSTOVFL = 91; ERR_TSTDUP = 92; ERROR_NO_ITEMS = 93; ERROR_INTERRUPT = 95; ERROR_TOO_MANY_SEMAPHORES = 100; ERROR_EXCL_SEM_ALREADY_OWNED = 101; ERROR_SEM_IS_SET = 102; ERROR_TOO_MANY_SEM_REQUESTS = 103; ERROR_INVALID_AT_INTERRUPT_TIME = 104; ERROR_SEM_OWNER_DIED = 105; ERROR_SEM_USER_LIMIT = 106; ERROR_DISK_CHANGE = 107; ERROR_DRIVE_LOCKED = 108; ERROR_BROKEN_PIPE = 109; ERROR_OPEN_FAILED = 110; ERROR_BUFFER_OVERFLOW = 111; ERROR_DISK_FULL = 112; ERROR_NO_MORE_SEARCH_HANDLES = 113; ERROR_INVALID_TARGET_HANDLE = 114; ERROR_PROTECTION_VIOLATION = 115; ERROR_VIOKBD_REQUEST = 116; ERROR_INVALID_CATEGORY = 117; ERROR_INVALID_VERIFY_SWITCH = 118; ERROR_BAD_DRIVER_LEVEL = 119; ERROR_CALL_NOT_IMPLEMENTED = 120; ERROR_SEM_TIMEOUT = 121; ERROR_INSUFFICIENT_BUFFER = 122; ERROR_INVALID_NAME = 123; ERROR_INVALID_LEVEL = 124; ERROR_NO_VOLUME_LABEL = 125; ERROR_MOD_NOT_FOUND = 126; ERROR_PROC_NOT_FOUND = 127; ERROR_WAIT_NO_CHILDREN = 128; ERROR_CHILD_NOT_COMPLETE = 129; ERROR_DIRECT_ACCESS_HANDLE = 130; ERROR_NEGATIVE_SEEK = 131; ERROR_SEEK_ON_DEVICE = 132; ERROR_IS_JOIN_TARGET = 133; ERROR_IS_JOINED = 134; ERROR_IS_SUBSTED = 135; ERROR_NOT_JOINED = 136; ERROR_NOT_SUBSTED = 137; ERROR_JOIN_TO_JOIN = 138; ERROR_SUBST_TO_SUBST = 139; ERROR_JOIN_TO_SUBST = 140; ERROR_SUBST_TO_JOIN = 141; ERROR_BUSY_DRIVE = 142; ERROR_SAME_DRIVE = 143; ERROR_DIR_NOT_ROOT = 144; ERROR_DIR_NOT_EMPTY = 145; ERROR_IS_SUBST_PATH = 146; ERROR_IS_JOIN_PATH = 147; ERROR_PATH_BUSY = 148; ERROR_IS_SUBST_TARGET = 149; ERROR_SYSTEM_TRACE = 150; ERROR_INVALID_EVENT_COUNT = 151; ERROR_TOO_MANY_MUXWAITERS = 152; ERROR_INVALID_LIST_FORMAT = 153; ERROR_LABEL_TOO_LONG = 154; ERROR_TOO_MANY_TCBS = 155; ERROR_SIGNAL_REFUSED = 156; ERROR_DISCARDED = 157; ERROR_NOT_LOCKED = 158; ERROR_BAD_THREADID_ADDR = 159; ERROR_BAD_ARGUMENTS = 160; ERROR_BAD_PATHNAME = 161; ERROR_SIGNAL_PENDING = 162; ERROR_UNCERTAIN_MEDIA = 163; ERROR_MAX_THRDS_REACHED = 164; ERROR_MONITORS_NOT_SUPPORTED = 165; ERROR_INVALID_SEGMENT_NUMBER = 180; ERROR_INVALID_CALLGATE = 181; ERROR_INVALID_ORDINAL = 182; ERROR_ALREADY_EXISTS = 183; ERROR_NO_CHILD_PROCESS = 184; ERROR_CHILD_ALIVE_NOWAIT = 185; ERROR_INVALID_FLAG_NUMBER = 186; ERROR_SEM_NOT_FOUND = 187; ERROR_INVALID_STARTING_CODESEG = 188; ERROR_INVALID_STACKSEG = 189; ERROR_INVALID_MODULETYPE = 190; ERROR_INVALID_EXE_SIGNATURE = 191; ERROR_EXE_MARKED_INVALID = 192; ERROR_BAD_EXE_FORMAT = 193; ERROR_ITERATED_DATA_EXCEEDS_64k = 194; ERROR_INVALID_MINALLOCSIZE = 195; ERROR_DYNLINK_FROM_INVALID_RING = 196; ERROR_IOPL_NOT_ENABLED = 197; ERROR_INVALID_SEGDPL = 198; ERROR_AUTODATASEG_EXCEEDS_64k = 199; ERROR_RING2SEG_MUST_BE_MOVABLE = 200; ERROR_RELOC_CHAIN_XEEDS_SEGLIM = 201; ERROR_INFLOOP_IN_RELOC_CHAIN = 202; ERROR_ENVVAR_NOT_FOUND = 203; ERROR_NOT_CURRENT_CTRY = 204; ERROR_NO_SIGNAL_SENT = 205; ERROR_FILENAME_EXCED_RANGE = 206; ERROR_RING2_STACK_IN_USE = 207; ERROR_META_EXPANSION_TOO_LONG = 208; ERROR_INVALID_SIGNAL_NUMBER = 209; ERROR_THREAD_1_INACTIVE = 210; ERROR_INFO_NOT_AVAIL = 211; ERROR_LOCKED = 212; ERROR_BAD_DYNALINK = 213; ERROR_TOO_MANY_MODULES = 214; ERROR_NESTING_NOT_ALLOWED = 215; ERROR_SMG_NO_TARGET_WINDOW = 224; ERROR_USER_DEFINED_BASE = $F000; ERROR_I24_WRITE_PROTECT = 0; ERROR_I24_BAD_UNIT = 1; ERROR_I24_NOT_READY = 2; ERROR_I24_BAD_COMMAND = 3; ERROR_I24_CRC = 4; ERROR_I24_BAD_LENGTH = 5; ERROR_I24_SEEK = 6; ERROR_I24_NOT_DOS_DISK = 7; ERROR_I24_SECTOR_NOT_FOUND = 8; ERROR_I24_OUT_OF_PAPER = 9; ERROR_I24_WRITE_FAULT = $0A; ERROR_I24_READ_FAULT = $0B; ERROR_I24_GEN_FAILURE = $0C; ERROR_I24_DISK_CHANGE = $0D; ERROR_I24_WRONG_DISK = $0F; ERROR_I24_UNCERTAIN_MEDIA = $10; ERROR_I24_CHAR_CALL_INTERRUPTED = $11; ERROR_I24_NO_MONITOR_SUPPORT = $12; ERROR_I24_INVALID_PARAMETER = $13; ALLOWED_FAIL = $0001; ALLOWED_ABORT = $0002; ALLOWED_RETRY = $0004; ALLOWED_IGNORE = $0008; I24_OPERATION = $1; I24_AREA = $6; I24_CLASS = $80; ERRCLASS_OUTRES = 1; ERRCLASS_TEMPSIT = 2; ERRCLASS_AUTH = 3; ERRCLASS_INTRN = 4; ERRCLASS_HRDFAIL = 5; ERRCLASS_SYSFAIL = 6; ERRCLASS_APPERR = 7; ERRCLASS_NOTFND = 8; ERRCLASS_BADFMT = 9; ERRCLASS_LOCKED = 10; ERRCLASS_MEDIA = 11; ERRCLASS_ALREADY = 12; ERRCLASS_UNK = 13; ERRCLASS_CANT = 14; ERRCLASS_TIME = 15; ERRACT_RETRY = 1; ERRACT_DLYRET = 2; ERRACT_USER = 3; ERRACT_ABORT = 4; ERRACT_PANIC = 5; ERRACT_IGNORE = 6; ERRACT_INTRET = 7; ERRLOC_UNK = 1; ERRLOC_DISK = 2; ERRLOC_NET = 3; ERRLOC_SERDEV = 4; ERRLOC_MEM = 5; TC_NORMAL = 0; TC_HARDERR = 1; TC_GP_TRAP = 2; TC_SIGNAL = 3; implementation end.
//Exercicio 54: Fulano tem 1,50 m e cresce 2 cm por ano, enquanto Beltrano tem 1,10 m e cresce 3 cm por ano. //Elabore um algoritmo que calcule e exiba quantos anos serão necessários para que Beltrano seja mais alto que Fulano. { Solução em Portugol Algoritmo Exercicio 54; Const crescimento_fulano = 2; // Vou fazer o exercício em cm. crescimento_beltrano = 3; altura_fulano = 150; altura_beltrano = 110; Var fulano,beltrano,anos: inteiro; Inicio exiba("Programa que calcula quantos anos levarão para que Beltrano seja maior que Fulano."); anos <- 0; fulano <- 150; beltrano <- 110; enquanto(fulano >= beltrano)faça anos := anos + 1; fulano <- altura_fulano + crescimento_fulano * anos; beltrano <- altura_beltrano + crescimento_beltrano * anos; fimenquanto; exiba("Serão necessários ",anos," anos para que Beltrano fique maior que Fulano."); Fim. } // Solução em Pascal Program Exercicio54; uses crt; Const crescimento_fulano = 2; crescimento_beltrano = 3; altura_fulano = 150; altura_beltrano = 110; var fulano,beltrano,anos: integer; begin clrscr; writeln('Programa que calcula quantos anos levarão para que Beltrano seja maior que Fulano.'); anos := 0; fulano := 150; beltrano := 110; while(fulano >= beltrano)do Begin anos := anos + 1; fulano := altura_fulano + crescimento_fulano * anos; beltrano := altura_beltrano + crescimento_beltrano * anos; End; writeln('Serão necessários ',anos,' anos para que Beltrano fique maior que Fulano.'); repeat until keypressed; end.
unit tmsUBreakList; {$INCLUDE ..\FLXCOMPILER.INC} interface uses Classes, SysUtils, tmsXlsMessages, tmsUXlsBaseRecords; type TBreakList=class(TList) private CurrentPos: integer; ZeroPos: integer; protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; public constructor Create(const aZeroPos: integer); function CurrentId: integer; function CurrentSize: integer; function AcumSize: integer; procedure IncCurrent; procedure Add(const aId, aSize: integer); procedure AddToZeroPos(const Delta: integer); end; implementation type TRBreakList=record Id, Size, AcumSize: integer; end; PRBreakList= ^TRBreakList; { TBreakList } function TBreakList.AcumSize: integer; begin if (CurrentPos>= Count)or (CurrentPos<0) then Raise Exception.Create(ErrInternal); Result:= PRBreakList(Items[CurrentPos]).AcumSize + ZeroPos + SizeOf(TRecordHeader)*(CurrentPos); end; procedure TBreakList.Add(const aId, aSize: integer); var RBreakList: PRBreakList; begin New( RBreakList); RBreakList.Id:=aId; RBreakList.Size:=aSize; RBreakList.AcumSize:=aSize; if Count>0 then inc(RBreakList.AcumSize, PRBreakList(Items[Count-1]).AcumSize); inherited Add(RBreakList); end; procedure TBreakList.AddToZeroPos(const Delta: integer); begin inc(ZeroPos, Delta); end; constructor TBreakList.Create(const aZeroPos: integer); begin inherited Create; ZeroPos:= aZeroPos; end; function TBreakList.CurrentId: integer; begin if (CurrentPos>= Count)or (CurrentPos<0) then Raise Exception.Create(ErrInternal); Result:= PRBreakList(Items[CurrentPos]).Id; end; function TBreakList.CurrentSize: integer; begin if (CurrentPos+1>= Count)or (CurrentPos+1<0) then Raise Exception.Create(ErrInternal); Result:= PRBreakList(Items[CurrentPos+1]).Size; end; procedure TBreakList.IncCurrent; begin inc(CurrentPos); end; procedure TBreakList.Notify(Ptr: Pointer; Action: TListNotification); begin inherited; if Action = lnDeleted then Dispose(PRBreakList(Ptr)); inherited Notify(Ptr, Action); end; end.
unit BaseFloatWindow; interface uses Windows, BaseApp, UIBaseWin, win.thread, uiwin.memdc, ui.color; type PRT_BaseFloatWindow = ^TRT_BaseFloatWindow; TRT_BaseFloatWindow = record BaseApp : TBaseApp; BaseWindow : TUIBaseWnd; DataThread : TSysWinThread; Font : HFONT; MemDC : TWinMemDC; OnPaint : procedure(ADC: HDC; ABaseFloatWindow: PRT_BaseFloatWindow); end; procedure SaveLayout(ABaseFloatWindow: PRT_BaseFloatWindow); procedure Paint_FloatWindow_Layered(ABaseFloatWindow: PRT_BaseFloatWindow); function WMPaint_FloatWindowWndProcA(ABaseFloatWindow: PRT_BaseFloatWindow; AWnd: HWND): LRESULT; implementation uses IniFiles, SysUtils; function WMPaint_FloatWindowWndProcA(ABaseFloatWindow: PRT_BaseFloatWindow; AWnd: HWND): LRESULT; var tmpPS: TPaintStruct; tmpDC: HDC; begin Result := 0; tmpDC := BeginPaint(AWnd, tmpPS); try if Assigned(ABaseFloatWindow.OnPaint) then begin ABaseFloatWindow.OnPaint(tmpDC, ABaseFloatWindow); end; finally end; EndPaint(AWnd, tmpPS); end; procedure SaveLayout(ABaseFloatWindow: PRT_BaseFloatWindow); var tmpIni: TIniFile; begin tmpIni := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')); try tmpIni.WriteInteger('win', 'left', ABaseFloatWindow.BaseWindow.WindowRect.Left); tmpIni.WriteInteger('win', 'top', ABaseFloatWindow.BaseWindow.WindowRect.Top); finally tmpIni.Free; end; end; procedure Paint_FloatWindow_Layered(ABaseFloatWindow: PRT_BaseFloatWindow); var tmpBlend: TBLENDFUNCTION; i, j: Integer; tmpColor: PColor32Array; begin if 0 = ABaseFloatWindow.MemDC.DCHandle then begin UpdateMemDC(@ABaseFloatWindow.MemDC, ABaseFloatWindow.BaseWindow.ClientRect.Right, ABaseFloatWindow.BaseWindow.ClientRect.Bottom); end; tmpColor := ABaseFloatWindow.MemDC.MemBitmap.BitsData; if tmpColor <> nil then begin for i := 0 to ABaseFloatWindow.MemDC.Height - 1 do begin for j := 0 to ABaseFloatWindow.MemDC.Width - 1 do begin PColor32Entry(tmpColor).A := 255; PColor32Entry(tmpColor).A := 1; //PColor32Entry(tmpColor).B := 255; Inc(tmpColor); end; end; end; if Assigned(ABaseFloatWindow.OnPaint) then begin ABaseFloatWindow.OnPaint(ABaseFloatWindow.MemDC.DCHandle, ABaseFloatWindow); end; tmpColor := ABaseFloatWindow.MemDC.MemBitmap.BitsData; if tmpColor <> nil then begin for i := 0 to ABaseFloatWindow.MemDC.Height - 1 do begin for j := 0 to ABaseFloatWindow.MemDC.Width - 1 do begin if 1 <> PColor32Entry(tmpColor).A then begin PColor32Entry(tmpColor).A := 255; end; //PColor32Entry(tmpColor).B := 255; Inc(tmpColor); end; end; end; tmpBlend.BlendOp := AC_SRC_OVER; tmpBlend.BlendFlags := 0; tmpBlend.SourceConstantAlpha := 255; //$FF; tmpBlend.AlphaFormat := AC_SRC_ALPHA;// $FF; UpdateLayeredWindow( ABaseFloatWindow.BaseWindow.UIWndHandle, 0, @ABaseFloatWindow.BaseWindow.WindowRect.TopLeft, @ABaseFloatWindow.BaseWindow.ClientRect.BottomRight, ABaseFloatWindow.MemDC.DCHandle, @ABaseFloatWindow.BaseWindow.ClientRect.TopLeft, 0, // crKey: COLORREF @tmpBlend,// pblend: PBLENDFUNCTION; ULW_ALPHA // dwFlags: DWORD ); end; end.
unit Libcod; interface uses LibGeral, Dialogs, SysUtils, Wwtable, Wwdatsrc, Classes; function Referencia(sCodigo :String; aLojm003 :TStringList): String; function TamPosition(sCodigo :String; aLojm003 :TStringList) :String; function CorPosition(sCodigo :String; aLojm003 :TStringList) :String; function TamOk(sCodigo :String; Var sDescTam :String; TPrd, TGrt :TwwTable; aLojm003 :TStringList) :Boolean; function CorOk(sCodigo :String; Var sCodCor :String; Var sDescCor :String; TPrd, TGrc, TCor :TwwTable; aLojm003 :TStringList) :Boolean; function ValidaCod(Var aDadosPrd :Array of String; TEan, TPrd, TGrc, TGrt, TCor :TwwTable; aLojm003 :TStrings; lExibeMens :Boolean) :Boolean; implementation { *--------------------------------------------------------------------------* * FUNCTION REFERENCIA - Rotina que retorna qual a referencia do codigo * * segundo o padrao de codigo utilizado pelo sistema * * * * Parametros * * ---------- * * Codigo String Codigo interno do produto * * * * aLOJM003 TStringList Vetor com os parametros do aLOJM003.CFG * *--------------------------------------------------------------------------* } function Referencia(sCodigo :String; aLojm003 :TStringList): String; begin if aLojm003[17] = '0' then Result := Copy(sCodigo, 1, 8) else Result := Copy(sCodigo, 1, 6); end; { *--------------------------------------------------------------------------* * FUNCTION TAMANHO - Rotina que retorna qual o tamanho do codigo referido * * segundo o padrao de codigo utilizado pelo sistema. * * Atente que o que é retornado, não é a descriçao do * * tamanho, mas sim a sua posição na grade ou indicação * * de que o tamanho é único * * * * Parametros * * ---------- * * Codigo String Codigo interno do produto * * * * aLOJM003 Array of String Vetor com os parametros do aLOJM003.CFG * *--------------------------------------------------------------------------* } function TamPosition(sCodigo :String; aLojm003 :TStringList ) :String; Begin If aLojm003[17] = '0' Then Result := Copy(sCodigo, 9, 2) Else Result := Copy(sCodigo,11, 2); End; { *--------------------------------------------------------------------------* * FUNCTION CorPosition - Rotina que retorna qual a cor do codigo segundo o padrao * * de codigo utilizado pelo sistema. * * Atente que o que é retornado, não é a descriçao da cor* * mas sim a sua posição na grade (quando VerUp) ou o có-* * digo da cor (quando Linx) * * * * Parametros * * ---------- * * Codigo String Codigo interno do produto * * * * aLOJM003 Array of String Vetor com os parametros do aLOJM003.CFG * *--------------------------------------------------------------------------* } function CorPosition(sCodigo :String; aLojm003 :TStringList) :String; Begin If aLojm003[17] = '0' Then Result := Copy(sCodigo,11, 2) Else Result := Copy(sCodigo, 7, 4); End; { *--------------------------------------------------------------------------* * FUNCTION TAMOK - Rotina que passado um codigo, retorna se o tamanho está * * de acordo com o definido no cadastro de produtos e conse* * quentemente se a grade a ele relacionado existe e ainda * * se o há um tamanho na posição especificada. * * * * Importante * * ---------- * * . É OBRIGATORIO que o ponteiro do arquivo de produtos já esteja posi-* * cionado no codigo referente. * * * * Parametros * * ---------- * * sCodigo String Codigo do Produto * * aPrd TTable Alias do cadastro de Produtos * * aGrt TTable Alias do cadastro de Grade de Tamanhos * * aLOJM003 Array of String Vetor com os parametros do aLOJM003.CFG* * sDescTam String Descriçao do Tamanho * *--------------------------------------------------------------------------* } function TamOk(sCodigo :String; Var sDescTam :String; TPrd, TGrt :TwwTable; aLojm003 :TStringList) :Boolean; var sTamanho : String[ 2]; sCampoGrt : String[15]; begin sDescTam := ''; Result := False; sTamanho := TamPosition(sCodigo,aLojm003); {Tamanho Unico } If (sTamanho = '99') And (TPrd.FieldByName('TAMUNICO').AsString = 'S') Then begin sDescTam := 'UN'; Result := True; end; {Tamanho Variavel} if (sTamanho <> '99') and (sTamanho >= '01') and (sTamanho <= '12') and (TPrd.FieldByName('TAMUNICO').AsString = 'N') Then begin Result := TPrd.FieldByName('TAMUNICO').AsString = 'N'; if Result And TGrt.FindKey([TPrd.FieldByName('GRADETAM').AsString]) then begin If Copy(sTamanho, 1, 1) = '0' Then sTamanho := Copy(sTamanho, 2, 1); sCampoGrt := 'TAM_GRAT'+sTamanho; sDescTam := TGrt.FieldByName(sCampoGrt).AsString; Result := Copy(sDescTam,1,1) <> ' '; end else Result := False; end; end; { *--------------------------------------------------------------------------* * FUNCTION COROK - Rotina que passado um codigo, retorna se a cor está * * de acordo com o definido no cadastro de produtos e conse* * quentemente se a grade a ela relacionada existe e ainda * * se o há uma cor na posição especificada. * * * * Importante * * ---------- * * . É OBRIGATORIO que o ponteiro do arquivo de produtos já esteja posi-* * cionado no codigo referente. * * * * Parametros * * ---------- * * sCodigo String Codigo do Produto * * sCodCor String Código da Cor * * sDescCor String Descriçao da Cor * * TPrd TTable Name do cadastro de Produtos * * TGrc TTable Name do cadastro de Grade de Cor * * TCor TTable Name do cadastro de Cores * * aLojm003 Array of String Vetor com os parametros do aLOJM003.CFG* *--------------------------------------------------------------------------* } function CorOk(sCodigo :String; Var sCodCor :String; Var sDescCor :String; TPrd, TGrc, TCor :TwwTable; aLojm003 :TStringList) :Boolean; Var sCor : String[ 4]; sCampoCor : String[15]; Begin Result := False ; sCodCor := '' ; sDescCor := '' ; sCor := CorPosition(sCodigo,aLojm003); {Cor Unica - Prevendo padrao de codigo VerUp ou Linx } If ((sCor = '99') Or (sCor = '9999')) And (TPrd.FieldByName('CORUNICA').AsString = 'S') Then begin sCodCor := 'UN '; sDescCor := 'Única' ; Result := True; end; {Cor Variavel - Prevendo padrao de codigo VerUp ou Linx } If ((sCor <> '99') Or (sCor <> '9999')) And (TPrd.FieldByName('CORUNICA').AsString = 'N') Then begin if aLojm003[17] = '0' then begin Result := (sCor >= '01') And (sCor <= '20') ; If Result And TGrc.FindKey([Referencia(sCodigo, aLojm003)]) then begin if Copy(sCor, 1, 1) = '0' then sCor := Copy(sCor, 2, 1); sCampoCor := 'GRAC' + sCor; sCodCor := TGrc.FieldByName(sCampoCor).AsString; If (Copy(sCodCor, 1, 1) <> ' ') and TCor.FindKey([sCodCor]) then sDescCor := TCor.FieldByName('DESC_COR').AsString else Result := False; end else Result := False ; end else Result := True ; end; end; { *--------------------------------------------------------------------------* * FUNCTION VALIDACOD - Rotina de validacao de um codigo, seja ele auxiliar * * ou interno. * * * * Importante * * ---------- * * Os arquivos já devem estar abertos. * * * * * * Parametros * * ---------- * * aDadosPrd Array of String Vetor com os dados do Produto * * => Formato * * 0. Codigo * * 1. Descricao * * 2. Narrativa * * 3. Tamanho * * 4. Código da Cor * * 5. Descrição da Cor * * 6. Unidade do Produto * * TEan TTable Name do cadastro de Códigos Auxilares * * TPrd TTable Name do cadastro de Produtos * * TGrc TTable Name do cadastro de Grade de Cor * * TCor TTable Name do cadastro de Cores * * aLojm003 Array of String Vetor com os parametros do aLOJM003.CFG* * lExibeMens Boolean Indica se mensagem de produto não cadas* * trado deve ou não ser exibida * *--------------------------------------------------------------------------* } function ValidaCod(Var aDadosPrd :Array of String; TEan, TPrd, TGrc, TGrt, TCor :TwwTable; aLojm003 :TStrings; lExibeMens :Boolean) :Boolean; var lEan : Boolean; lInterno : Boolean; lTamOk : Boolean; lCorOk : Boolean; sCodigo : String[13]; sCodAuxiliar : String[13]; iContador : Integer; begin sCodigo := aDadosPrd[ 0]; lEan := False; lInterno := False; for iContador := 1 to 6 do aDadosPrd[iContador] := ''; If aLojm003[22] = '0' then begin TEan.IndexName := ''; sCodAuxiliar := PadR(sCodigo, 13); lEan := TEan.FindKey([sCodAuxiliar]); if lEan then sCodigo := TEan.FieldByName('CODIGO').AsString; end; aDadosPrd[ 0] := sCodigo; if TPrd.FindKey([Referencia(sCodigo, aLojm003)]) then begin aDadosPrd[ 1] := TPrd.FieldByName('DESCRICAO').AsString; aDadosPrd[ 6] := TPrd.FieldByName('UNIDADE').AsString; lTamOk := TamOk(sCodigo, aDadosPrd[ 3], TPrd, TGrt, aLojm003); lCorOk := CorOk(sCodigo, aDadosPrd[ 4], aDadosPrd[ 5], TPrd, TGrc, TCor, aLojm003); lInterno := (lTamOk and lCorOk); end; Result := (lInterno and lEan) or (lInterno); if Not Result and lExibeMens then MessageDlg('Produto Não Cadastrado !', mtError, [mbOk], 0); end; end.
unit BasicPolitics; interface uses Kernel, Politics, Population, BackupInterfaces, CacheAgent, Languages; const tidRating_CampaignAccuracy = 'CampaignAccuracy'; tidRating_PopGrowth = 'PopGrowth'; tidRating_CityProfit = 'CityProfit'; tidRating_Unemployment = 'Unemployment'; tidRating_Services = 'Services'; tidRating_Wealth = 'Wealth'; tidRating_Taxes = 'Taxes'; const tidProjectKind_Percent = 'Percent'; const tidProject_Unemployment = 'Unemployment'; tidProject_Services = 'Services'; tidProject_Wealth = 'Wealth'; tidProject_SalaryTaxes = 'SalaryTaxes'; tidProject_IncomeTaxes = 'IncomeTaxes'; const plidPopGrowth = 10; plidPublicParm = 11; plidUnemployment = 12; plidGQOS = 14; plidWealth = 15; type TMetaCampaignAccuracyRating = class( TMetaRating ) end; TCampaignAccuracyRating = class( TRating ) protected procedure ComputeIFELRating; override; end; TMetaPopGrowthRating = class( TMetaRating ) end; TPopGrowthRating = class( TRating ) protected procedure ComputeIFELRating; override; end; TMetaPublicParmRating = class( TMetaRating ) public constructor Create( anId, aName : string; aMetaPublicFacId : string; aWeight : integer; aRatingClass : CRating ); private fMetaPublicFac : TMetaPublicFacilityInfo; end; TPublicParmRating = class( TRating ) protected procedure ComputeIFELRating; override; end; TMetaUnemploymentRating = class( TMetaRating ) end; TUnemploymentRating = class( TRating ) protected procedure ComputeIFELRating; override; end; TMetaServicesRating = class( TMetaRating ) end; TServicesRating = class( TRating ) protected procedure ComputeIFELRating; override; end; TMetaWealthRating = class( TMetaRating ) end; TWealthRating = class( TRating ) protected procedure ComputeIFELRating; override; end; TMetaTaxesRating = class( TMetaRating ) end; TTaxesRating = class( TRating ) protected procedure ComputeIFELRating; override; end; TComparisonMode = (cmdLessThan, cmdGreaterThan); TMetaPercentProject = class( TMetaProject ) public constructor Create( anId, aName : string; aWeight : integer; aComparisonMode : TComparisonMode; aProjectClass : CProject ); private fComparisonMode : TComparisonMode; public property ComparisonMode : TComparisonMode read fComparisonMode; end; TPercentProject = class( TProject ) private fValue : TPercent; fLessTan : boolean; public property Value : TPercent read fValue; property LessTan : boolean read fLessTan; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; public procedure ParseData( Data : string ); override; procedure SetDefaultValue; override; public procedure StoreToCache( Cache : TObjectCache ); override; protected function ComputeCloseness ( Sample : TPercent ) : TPercent; function ComputeAcceptance( Sample : TPercent ) : TPercent; end; TMetaPublicParmProject = class( TMetaPercentProject ) public constructor Create( anId, aName : string; aMetaPublicFacId : string; aWeight : integer; aComparisonMode : TComparisonMode; aProjectClass : CProject ); private fMetaPublicFac : TMetaPublicFacilityInfo; end; TPublicParmProject = class( TPercentProject ) protected function GetRating : TPercent; override; function GetAccuracy : TPercent; override; end; TMetaGrowthProject = class( TMetaPercentProject ) end; TGrowthProject = class( TPercentProject ) protected function GetRating : TPercent; override; function GetAccuracy : TPercent; override; end; TMetaServicesProject = class( TMetaPercentProject ) end; TServicesProject = class( TPercentProject ) protected function GetRating : TPercent; override; function GetAccuracy : TPercent; override; end; TMetaWealthProject = class( TMetaPercentProject ) end; TWealthProject = class( TPercentProject ) protected function GetRating : TPercent; override; function GetAccuracy : TPercent; override; end; TMetaUnemploymentProject = class( TMetaPercentProject ) end; TUnemploymentProject = class( TPercentProject ) protected function GetRating : TPercent; override; function GetAccuracy : TPercent; override; end; // Registration procedure RegisterPolitics; procedure RegisterBackup; implementation uses ClassStorage, MathUtils, SysUtils; // TCampaignAccuracyRating procedure TCampaignAccuracyRating.ComputeIFELRating; var Campaign : TCampaign; begin Campaign := System.PoliticalEntity.getWinningCampaign; if Campaign <> nil then fIFELRating := Campaign.Accuracy else fIFELRating := 100; end; // TPopGrowthRating procedure TPopGrowthRating.ComputeIFELRating; var PopGrowth : integer; begin PopGrowth := round(System.PoliticalEntity.getParm( plidPopGrowth, self )); fIFELRating := min(100, 3*PopGrowth ); end; // TMetaPublicParmRating constructor TMetaPublicParmRating.Create( anId, aName : string; aMetaPublicFacId : string; aWeight : integer; aRatingClass : CRating ); begin inherited Create( anId, aName, aWeight, aRatingClass ); fMetaPublicFac := TMetaPublicFacilityInfo(TheClassStorage.ClassById[tidClassFamily_PublicFacilities, aMetaPublicFacId]); end; // TPublicParmRating procedure TPublicParmRating.ComputeIFELRating; begin fIFELRating := round(System.PoliticalEntity.getParm( plidPublicParm, TMetaPublicParmRating(MetaRating).fMetaPublicFac )); end; // TUnemploymentRating procedure TUnemploymentRating.ComputeIFELRating; begin fIFELRating := round(System.PoliticalEntity.getParm( plidUnemployment, self )); end; // TServicesRating procedure TServicesRating.ComputeIFELRating; begin fIFELRating := round(System.PoliticalEntity.getParm( plidGQOS, self )); end; // TWealthRating procedure TWealthRating.ComputeIFELRating; begin fIFELRating := round(System.PoliticalEntity.getParm( plidWealth, self )); end; // TTaxesRating procedure TTaxesRating.ComputeIFELRating; begin fIFELRating := 80 + random(20); end; // TMetaPercentProject constructor TMetaPercentProject.Create( anId, aName : string; aWeight : integer; aComparisonMode : TComparisonMode; aProjectClass : CProject ); begin inherited Create( anId, aName, tidProjectKind_Percent, aWeight, aProjectClass ); fComparisonMode := aComparisonMode; end; // TPercentProject procedure TPercentProject.LoadFromBackup( Reader : IBackupReader ); begin inherited; fValue := Reader.ReadByte( 'Value', 0 ); end; procedure TPercentProject.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteByte( 'Value', fValue ); end; procedure TPercentProject.ParseData( Data : string ); begin fValue := StrToInt(Data); end; procedure TPercentProject.SetDefaultValue; begin case TMetaPercentProject(MetaProject).ComparisonMode of cmdLessThan : fValue := 10; cmdGreaterThan : fValue := 80; end; end; procedure TPercentProject.StoreToCache( Cache : TObjectCache ); begin inherited; Cache.WriteInteger( 'Value', fValue ); Cache.WriteInteger( 'Mode', integer(TMetaPercentProject(MetaProject).ComparisonMode) ); end; function TPercentProject.ComputeCloseness( Sample : TPercent ) : TPercent; var actValue : TPercent; actSample : TPercent; begin if TMetaPublicParmProject(MetaProject).ComparisonMode = cmdGreaterThan then begin actValue := Value; actSample := Sample; end else begin actValue := 100 - Value; actSample := 100 - Sample; end; if actSample >= actValue then result := 100 else result := 100 - (actValue - actSample) end; function TPercentProject.ComputeAcceptance( Sample : TPercent ) : TPercent; var actValue : TPercent; actSample : TPercent; begin if TMetaPublicParmProject(MetaProject).ComparisonMode = cmdGreaterThan then begin actValue := Value; actSample := Sample; end else begin actValue := 100 - Value; actSample := 100 - Sample; end; if actValue div 10 >= actSample div 10 then result := actValue else result := 0; end; // TMetaPublicParmProject constructor TMetaPublicParmProject.Create( anId, aName : string; aMetaPublicFacId : string; aWeight : integer; aComparisonMode : TComparisonMode; aProjectClass : CProject ); begin inherited Create( anId, aName, aWeight, aComparisonMode, aProjectClass ); fMetaPublicFac := TMetaPublicFacilityInfo(TheClassStorage.ClassById[tidClassFamily_PublicFacilities, aMetaPublicFacId]); end; // TPublicParmProject function TPublicParmProject.GetRating : TPercent; var Coverage : single; begin Coverage := Campaign.System.PoliticalEntity.getParm( plidPublicParm, TMetaPublicParmProject(MetaProject).fMetaPublicFac ); result := ComputeAcceptance( round(Coverage) ); end; function TPublicParmProject.GetAccuracy : TPercent; var Coverage : single; begin Coverage := Campaign.System.PoliticalEntity.getParm( plidPublicParm, TMetaPublicParmProject(MetaProject).fMetaPublicFac ); result := ComputeCloseness( round(Coverage) ); end; // TGrowthProject function TGrowthProject.GetRating : TPercent; var PopGrowth : integer; begin PopGrowth := round(Campaign.System.PoliticalEntity.getParm( plidPopGrowth, self )); result := ComputeAcceptance( min(100, PopGrowth) ); end; function TGrowthProject.GetAccuracy : TPercent; var PopGrowth : integer; begin PopGrowth := round(Campaign.System.PoliticalEntity.getParm( plidPopGrowth, self )); result := ComputeCloseness( min(100, PopGrowth) ); end; // TServicesProject function TServicesProject.GetRating : TPercent; begin result := ComputeAcceptance( min(100, round(100*Campaign.System.PoliticalEntity.getParm( plidGQOS, self ))) ); end; function TServicesProject.GetAccuracy : TPercent; begin result := ComputeCloseness( min(100, round(100*Campaign.System.PoliticalEntity.getParm( plidGQOS, self ))) ); end; // TWealthProject function TWealthProject.GetRating : TPercent; begin result := ComputeAcceptance( min(100, round(100*Campaign.System.PoliticalEntity.getParm( plidWealth, self ))) ); end; function TWealthProject.GetAccuracy : TPercent; begin result := ComputeCloseness( min(100, round(100*Campaign.System.PoliticalEntity.getParm( plidWealth, self ))) ); end; // TUnemploymentProject function TUnemploymentProject.GetRating : TPercent; begin result := ComputeAcceptance( round(Campaign.System.PoliticalEntity.getParm( plidUnemployment, self )) ); end; function TUnemploymentProject.GetAccuracy : TPercent; begin result := ComputeCloseness( round(Campaign.System.PoliticalEntity.getParm( plidUnemployment, self )) ); end; // Registration procedure RegisterPolitics; procedure RegisterPublicParmRatings; var count, i : integer; MPFI : TMetaPublicFacilityInfo; begin count := TheClassStorage.ClassCount[tidClassFamily_PublicFacilities]; for i := 0 to pred(count) do begin MPFI := TMetaPublicFacilityInfo(TheClassStorage.ClassByIdx[tidClassFamily_PublicFacilities, i]); TMetaPublicParmRating.Create( MPFI.Id, MPFI.Name, MPFI.Id, MPFI.Importance, TPublicParmRating ).Register( tidClassFamily_Ratings ); end; end; procedure RegisterPublicParmProjects; var count, i : integer; MPFI : TMetaPublicFacilityInfo; begin count := TheClassStorage.ClassCount[tidClassFamily_PublicFacilities]; for i := 0 to pred(count) do begin MPFI := TMetaPublicFacilityInfo(TheClassStorage.ClassByIdx[tidClassFamily_PublicFacilities, i]); TMetaPublicParmProject.Create( MPFI.Id, MPFI.Name, MPFI.Id, MPFI.Importance, cmdGreaterThan, TPublicParmProject ).Register( tidClassFamily_Projects ); end; end; begin // Ratings TMetaCampaignAccuracyRating.Create( tidRating_CampaignAccuracy, 'Campaign Acomplishment', 200, TCampaignAccuracyRating ).Register( tidClassFamily_Ratings ); RegisterPublicParmRatings; TMetaPopGrowthRating.Create( tidRating_PopGrowth, 'City Growth', 70, TPopGrowthRating ).Register( tidClassFamily_Ratings ); TMetaUnemploymentRating.Create( tidRating_Unemployment, 'Employment', 100, TUnemploymentRating ).Register( tidClassFamily_Ratings ); TMetaServicesRating.Create( tidRating_Services, 'Services and Amusement', 70, TServicesRating ).Register( tidClassFamily_Ratings ); TMetaWealthRating.Create( tidRating_Wealth, 'Economic Wealth', 80, TWealthRating ).Register( tidClassFamily_Ratings ); TMetaTaxesRating.Create( tidRating_Taxes, 'Taxes', 60, TTaxesRating ).Register( tidClassFamily_Ratings ); // Projects RegisterPublicParmProjects; TMetaServicesProject.Create( tidProject_Services, 'Services and Amusement', 100, cmdGreaterThan, TServicesProject ).Register( tidClassFamily_Projects ); TMetaWealthProject.Create( tidProject_Wealth, 'Economic Wealth', 100, cmdGreaterThan, TWealthProject ).Register( tidClassFamily_Projects ); TMetaUnemploymentProject.Create( tidProject_Unemployment, 'Unemployment', 200, cmdLessThan, TUnemploymentProject ).Register( tidClassFamily_Projects ); end; procedure RegisterBackup; begin RegisterClass( TCampaignAccuracyRating ); RegisterClass( TPopGrowthRating ); RegisterClass( TPublicParmRating ); RegisterClass( TUnemploymentRating ); RegisterClass( TServicesRating ); RegisterClass( TWealthRating ); RegisterClass( TTaxesRating ); RegisterClass( TPublicParmProject ); RegisterClass( TGrowthProject ); RegisterClass( TServicesProject ); RegisterClass( TWealthProject ); RegisterClass( TUnemploymentProject ); end; end.
unit input_method_unstable_v1_protocol; {$mode objfpc} {$H+} {$interfaces corba} interface uses Classes, Sysutils, ctypes, wayland_util, wayland_client_core, wayland_protocol; type Pzwp_input_method_context_v1 = Pointer; Pzwp_input_method_v1 = Pointer; Pzwp_input_panel_v1 = Pointer; Pzwp_input_panel_surface_v1 = Pointer; Pzwp_input_method_context_v1_listener = ^Tzwp_input_method_context_v1_listener; Tzwp_input_method_context_v1_listener = record surrounding_text : procedure(data: Pointer; AZwpInputMethodContextV1: Pzwp_input_method_context_v1; AText: Pchar; ACursor: DWord; AAnchor: DWord); cdecl; reset : procedure(data: Pointer; AZwpInputMethodContextV1: Pzwp_input_method_context_v1); cdecl; content_type : procedure(data: Pointer; AZwpInputMethodContextV1: Pzwp_input_method_context_v1; AHint: DWord; APurpose: DWord); cdecl; invoke_action : procedure(data: Pointer; AZwpInputMethodContextV1: Pzwp_input_method_context_v1; AButton: DWord; AIndex: DWord); cdecl; commit_state : procedure(data: Pointer; AZwpInputMethodContextV1: Pzwp_input_method_context_v1; ASerial: DWord); cdecl; preferred_language : procedure(data: Pointer; AZwpInputMethodContextV1: Pzwp_input_method_context_v1; ALanguage: Pchar); cdecl; end; Pzwp_input_method_v1_listener = ^Tzwp_input_method_v1_listener; Tzwp_input_method_v1_listener = record activate : procedure(data: Pointer; AZwpInputMethodV1: Pzwp_input_method_v1; AId: Pzwp_input_method_context_v1); cdecl; deactivate : procedure(data: Pointer; AZwpInputMethodV1: Pzwp_input_method_v1; AContext: Pzwp_input_method_context_v1); cdecl; end; Pzwp_input_panel_v1_listener = ^Tzwp_input_panel_v1_listener; Tzwp_input_panel_v1_listener = record end; const ZWP_INPUT_PANEL_SURFACE_V1_POSITION_CENTER_BOTTOM = 0; // type Pzwp_input_panel_surface_v1_listener = ^Tzwp_input_panel_surface_v1_listener; Tzwp_input_panel_surface_v1_listener = record end; TZwpInputMethodContextV1 = class; TZwpInputMethodV1 = class; TZwpInputPanelV1 = class; TZwpInputPanelSurfaceV1 = class; IZwpInputMethodContextV1Listener = interface ['IZwpInputMethodContextV1Listener'] procedure zwp_input_method_context_v1_surrounding_text(AZwpInputMethodContextV1: TZwpInputMethodContextV1; AText: String; ACursor: DWord; AAnchor: DWord); procedure zwp_input_method_context_v1_reset(AZwpInputMethodContextV1: TZwpInputMethodContextV1); procedure zwp_input_method_context_v1_content_type(AZwpInputMethodContextV1: TZwpInputMethodContextV1; AHint: DWord; APurpose: DWord); procedure zwp_input_method_context_v1_invoke_action(AZwpInputMethodContextV1: TZwpInputMethodContextV1; AButton: DWord; AIndex: DWord); procedure zwp_input_method_context_v1_commit_state(AZwpInputMethodContextV1: TZwpInputMethodContextV1; ASerial: DWord); procedure zwp_input_method_context_v1_preferred_language(AZwpInputMethodContextV1: TZwpInputMethodContextV1; ALanguage: String); end; IZwpInputMethodV1Listener = interface ['IZwpInputMethodV1Listener'] procedure zwp_input_method_v1_activate(AZwpInputMethodV1: TZwpInputMethodV1; AId: TZwpInputMethodContextV1); procedure zwp_input_method_v1_deactivate(AZwpInputMethodV1: TZwpInputMethodV1; AContext: TZwpInputMethodContextV1); end; IZwpInputPanelV1Listener = interface ['IZwpInputPanelV1Listener'] end; IZwpInputPanelSurfaceV1Listener = interface ['IZwpInputPanelSurfaceV1Listener'] end; TZwpInputMethodContextV1 = class(TWLProxyObject) private const _DESTROY = 0; const _COMMIT_STRING = 1; const _PREEDIT_STRING = 2; const _PREEDIT_STYLING = 3; const _PREEDIT_CURSOR = 4; const _DELETE_SURROUNDING_TEXT = 5; const _CURSOR_POSITION = 6; const _MODIFIERS_MAP = 7; const _KEYSYM = 8; const _GRAB_KEYBOARD = 9; const _KEY = 10; const _MODIFIERS = 11; const _LANGUAGE = 12; const _TEXT_DIRECTION = 13; public destructor Destroy; override; procedure CommitString(ASerial: DWord; AText: String); procedure PreeditString(ASerial: DWord; AText: String; ACommit: String); procedure PreeditStyling(AIndex: DWord; ALength: DWord; AStyle: DWord); procedure PreeditCursor(AIndex: LongInt); procedure DeleteSurroundingText(AIndex: LongInt; ALength: DWord); procedure CursorPosition(AIndex: LongInt; AAnchor: LongInt); procedure ModifiersMap(AMap: Pwl_array); procedure Keysym(ASerial: DWord; ATime: DWord; ASym: DWord; AState: DWord; AModifiers: DWord); function GrabKeyboard(AProxyClass: TWLProxyObjectClass = nil {TWlKeyboard}): TWlKeyboard; procedure Key(ASerial: DWord; ATime: DWord; AKey: DWord; AState: DWord); procedure Modifiers(ASerial: DWord; AModsDepressed: DWord; AModsLatched: DWord; AModsLocked: DWord; AGroup: DWord); procedure Language(ASerial: DWord; ALanguage: String); procedure TextDirection(ASerial: DWord; ADirection: DWord); function AddListener(AIntf: IZwpInputMethodContextV1Listener): LongInt; end; TZwpInputMethodV1 = class(TWLProxyObject) function AddListener(AIntf: IZwpInputMethodV1Listener): LongInt; end; TZwpInputPanelV1 = class(TWLProxyObject) private const _GET_INPUT_PANEL_SURFACE = 0; public function GetInputPanelSurface(ASurface: TWlSurface; AProxyClass: TWLProxyObjectClass = nil {TZwpInputPanelSurfaceV1}): TZwpInputPanelSurfaceV1; function AddListener(AIntf: IZwpInputPanelV1Listener): LongInt; end; TZwpInputPanelSurfaceV1 = class(TWLProxyObject) private const _SET_TOPLEVEL = 0; const _SET_OVERLAY_PANEL = 1; public procedure SetToplevel(AOutput: TWlOutput; APosition: DWord); procedure SetOverlayPanel; function AddListener(AIntf: IZwpInputPanelSurfaceV1Listener): LongInt; end; var zwp_input_method_context_v1_interface: Twl_interface; zwp_input_method_v1_interface: Twl_interface; zwp_input_panel_v1_interface: Twl_interface; zwp_input_panel_surface_v1_interface: Twl_interface; implementation var vIntf_zwp_input_method_context_v1_Listener: Tzwp_input_method_context_v1_listener; vIntf_zwp_input_method_v1_Listener: Tzwp_input_method_v1_listener; vIntf_zwp_input_panel_v1_Listener: Tzwp_input_panel_v1_listener; vIntf_zwp_input_panel_surface_v1_Listener: Tzwp_input_panel_surface_v1_listener; destructor TZwpInputMethodContextV1.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; procedure TZwpInputMethodContextV1.CommitString(ASerial: DWord; AText: String); begin wl_proxy_marshal(FProxy, _COMMIT_STRING, ASerial, PChar(AText)); end; procedure TZwpInputMethodContextV1.PreeditString(ASerial: DWord; AText: String; ACommit: String); begin wl_proxy_marshal(FProxy, _PREEDIT_STRING, ASerial, PChar(AText), PChar(ACommit)); end; procedure TZwpInputMethodContextV1.PreeditStyling(AIndex: DWord; ALength: DWord; AStyle: DWord); begin wl_proxy_marshal(FProxy, _PREEDIT_STYLING, AIndex, ALength, AStyle); end; procedure TZwpInputMethodContextV1.PreeditCursor(AIndex: LongInt); begin wl_proxy_marshal(FProxy, _PREEDIT_CURSOR, AIndex); end; procedure TZwpInputMethodContextV1.DeleteSurroundingText(AIndex: LongInt; ALength: DWord); begin wl_proxy_marshal(FProxy, _DELETE_SURROUNDING_TEXT, AIndex, ALength); end; procedure TZwpInputMethodContextV1.CursorPosition(AIndex: LongInt; AAnchor: LongInt); begin wl_proxy_marshal(FProxy, _CURSOR_POSITION, AIndex, AAnchor); end; procedure TZwpInputMethodContextV1.ModifiersMap(AMap: Pwl_array); begin wl_proxy_marshal(FProxy, _MODIFIERS_MAP, AMap); end; procedure TZwpInputMethodContextV1.Keysym(ASerial: DWord; ATime: DWord; ASym: DWord; AState: DWord; AModifiers: DWord); begin wl_proxy_marshal(FProxy, _KEYSYM, ASerial, ATime, ASym, AState, AModifiers); end; function TZwpInputMethodContextV1.GrabKeyboard(AProxyClass: TWLProxyObjectClass = nil {TWlKeyboard}): TWlKeyboard; var keyboard: Pwl_proxy; begin keyboard := wl_proxy_marshal_constructor(FProxy, _GRAB_KEYBOARD, @wl_keyboard_interface, nil); if AProxyClass = nil then AProxyClass := TWlKeyboard; Result := TWlKeyboard(AProxyClass.Create(keyboard)); if not AProxyClass.InheritsFrom(TWlKeyboard) then Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TWlKeyboard]); end; procedure TZwpInputMethodContextV1.Key(ASerial: DWord; ATime: DWord; AKey: DWord; AState: DWord); begin wl_proxy_marshal(FProxy, _KEY, ASerial, ATime, AKey, AState); end; procedure TZwpInputMethodContextV1.Modifiers(ASerial: DWord; AModsDepressed: DWord; AModsLatched: DWord; AModsLocked: DWord; AGroup: DWord); begin wl_proxy_marshal(FProxy, _MODIFIERS, ASerial, AModsDepressed, AModsLatched, AModsLocked, AGroup); end; procedure TZwpInputMethodContextV1.Language(ASerial: DWord; ALanguage: String); begin wl_proxy_marshal(FProxy, _LANGUAGE, ASerial, PChar(ALanguage)); end; procedure TZwpInputMethodContextV1.TextDirection(ASerial: DWord; ADirection: DWord); begin wl_proxy_marshal(FProxy, _TEXT_DIRECTION, ASerial, ADirection); end; function TZwpInputMethodContextV1.AddListener(AIntf: IZwpInputMethodContextV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zwp_input_method_context_v1_Listener, @FUserDataRec); end; function TZwpInputMethodV1.AddListener(AIntf: IZwpInputMethodV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zwp_input_method_v1_Listener, @FUserDataRec); end; function TZwpInputPanelV1.GetInputPanelSurface(ASurface: TWlSurface; AProxyClass: TWLProxyObjectClass = nil {TZwpInputPanelSurfaceV1}): TZwpInputPanelSurfaceV1; var id: Pwl_proxy; begin id := wl_proxy_marshal_constructor(FProxy, _GET_INPUT_PANEL_SURFACE, @zwp_input_panel_surface_v1_interface, nil, ASurface.Proxy); if AProxyClass = nil then AProxyClass := TZwpInputPanelSurfaceV1; Result := TZwpInputPanelSurfaceV1(AProxyClass.Create(id)); if not AProxyClass.InheritsFrom(TZwpInputPanelSurfaceV1) then Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TZwpInputPanelSurfaceV1]); end; function TZwpInputPanelV1.AddListener(AIntf: IZwpInputPanelV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zwp_input_panel_v1_Listener, @FUserDataRec); end; procedure TZwpInputPanelSurfaceV1.SetToplevel(AOutput: TWlOutput; APosition: DWord); begin wl_proxy_marshal(FProxy, _SET_TOPLEVEL, AOutput.Proxy, APosition); end; procedure TZwpInputPanelSurfaceV1.SetOverlayPanel; begin wl_proxy_marshal(FProxy, _SET_OVERLAY_PANEL); end; function TZwpInputPanelSurfaceV1.AddListener(AIntf: IZwpInputPanelSurfaceV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zwp_input_panel_surface_v1_Listener, @FUserDataRec); end; procedure zwp_input_method_context_v1_surrounding_text_Intf(AData: PWLUserData; Azwp_input_method_context_v1: Pzwp_input_method_context_v1; AText: Pchar; ACursor: DWord; AAnchor: DWord); cdecl; var AIntf: IZwpInputMethodContextV1Listener; begin if AData = nil then Exit; AIntf := IZwpInputMethodContextV1Listener(AData^.ListenerUserData); AIntf.zwp_input_method_context_v1_surrounding_text(TZwpInputMethodContextV1(AData^.PascalObject), AText, ACursor, AAnchor); end; procedure zwp_input_method_context_v1_reset_Intf(AData: PWLUserData; Azwp_input_method_context_v1: Pzwp_input_method_context_v1); cdecl; var AIntf: IZwpInputMethodContextV1Listener; begin if AData = nil then Exit; AIntf := IZwpInputMethodContextV1Listener(AData^.ListenerUserData); AIntf.zwp_input_method_context_v1_reset(TZwpInputMethodContextV1(AData^.PascalObject)); end; procedure zwp_input_method_context_v1_content_type_Intf(AData: PWLUserData; Azwp_input_method_context_v1: Pzwp_input_method_context_v1; AHint: DWord; APurpose: DWord); cdecl; var AIntf: IZwpInputMethodContextV1Listener; begin if AData = nil then Exit; AIntf := IZwpInputMethodContextV1Listener(AData^.ListenerUserData); AIntf.zwp_input_method_context_v1_content_type(TZwpInputMethodContextV1(AData^.PascalObject), AHint, APurpose); end; procedure zwp_input_method_context_v1_invoke_action_Intf(AData: PWLUserData; Azwp_input_method_context_v1: Pzwp_input_method_context_v1; AButton: DWord; AIndex: DWord); cdecl; var AIntf: IZwpInputMethodContextV1Listener; begin if AData = nil then Exit; AIntf := IZwpInputMethodContextV1Listener(AData^.ListenerUserData); AIntf.zwp_input_method_context_v1_invoke_action(TZwpInputMethodContextV1(AData^.PascalObject), AButton, AIndex); end; procedure zwp_input_method_context_v1_commit_state_Intf(AData: PWLUserData; Azwp_input_method_context_v1: Pzwp_input_method_context_v1; ASerial: DWord); cdecl; var AIntf: IZwpInputMethodContextV1Listener; begin if AData = nil then Exit; AIntf := IZwpInputMethodContextV1Listener(AData^.ListenerUserData); AIntf.zwp_input_method_context_v1_commit_state(TZwpInputMethodContextV1(AData^.PascalObject), ASerial); end; procedure zwp_input_method_context_v1_preferred_language_Intf(AData: PWLUserData; Azwp_input_method_context_v1: Pzwp_input_method_context_v1; ALanguage: Pchar); cdecl; var AIntf: IZwpInputMethodContextV1Listener; begin if AData = nil then Exit; AIntf := IZwpInputMethodContextV1Listener(AData^.ListenerUserData); AIntf.zwp_input_method_context_v1_preferred_language(TZwpInputMethodContextV1(AData^.PascalObject), ALanguage); end; procedure zwp_input_method_v1_activate_Intf(AData: PWLUserData; Azwp_input_method_v1: Pzwp_input_method_v1; AId: Pzwp_input_method_context_v1); cdecl; var AIntf: IZwpInputMethodV1Listener; begin if AData = nil then Exit; AIntf := IZwpInputMethodV1Listener(AData^.ListenerUserData); AIntf.zwp_input_method_v1_activate(TZwpInputMethodV1(AData^.PascalObject), TZwpInputMethodContextV1.Create(AId)); end; procedure zwp_input_method_v1_deactivate_Intf(AData: PWLUserData; Azwp_input_method_v1: Pzwp_input_method_v1; AContext: Pzwp_input_method_context_v1); cdecl; var AIntf: IZwpInputMethodV1Listener; begin if AData = nil then Exit; AIntf := IZwpInputMethodV1Listener(AData^.ListenerUserData); AIntf.zwp_input_method_v1_deactivate(TZwpInputMethodV1(AData^.PascalObject), TZwpInputMethodContextV1(TWLProxyObject.WLToObj(AContext))); end; const pInterfaces: array[0..13] of Pwl_interface = ( (nil), (nil), (nil), (nil), (nil), (nil), (nil), (nil), (@wl_keyboard_interface), (@zwp_input_method_context_v1_interface), (@zwp_input_panel_surface_v1_interface), (@wl_surface_interface), (@wl_output_interface), (nil) ); zwp_input_method_context_v1_requests: array[0..13] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'commit_string'; signature: 'us'; types: @pInterfaces[0]), (name: 'preedit_string'; signature: 'uss'; types: @pInterfaces[0]), (name: 'preedit_styling'; signature: 'uuu'; types: @pInterfaces[0]), (name: 'preedit_cursor'; signature: 'i'; types: @pInterfaces[0]), (name: 'delete_surrounding_text'; signature: 'iu'; types: @pInterfaces[0]), (name: 'cursor_position'; signature: 'ii'; types: @pInterfaces[0]), (name: 'modifiers_map'; signature: 'a'; types: @pInterfaces[0]), (name: 'keysym'; signature: 'uuuuu'; types: @pInterfaces[0]), (name: 'grab_keyboard'; signature: 'n'; types: @pInterfaces[8]), (name: 'key'; signature: 'uuuu'; types: @pInterfaces[0]), (name: 'modifiers'; signature: 'uuuuu'; types: @pInterfaces[0]), (name: 'language'; signature: 'us'; types: @pInterfaces[0]), (name: 'text_direction'; signature: 'uu'; types: @pInterfaces[0]) ); zwp_input_method_context_v1_events: array[0..5] of Twl_message = ( (name: 'surrounding_text'; signature: 'suu'; types: @pInterfaces[0]), (name: 'reset'; signature: ''; types: @pInterfaces[0]), (name: 'content_type'; signature: 'uu'; types: @pInterfaces[0]), (name: 'invoke_action'; signature: 'uu'; types: @pInterfaces[0]), (name: 'commit_state'; signature: 'u'; types: @pInterfaces[0]), (name: 'preferred_language'; signature: 's'; types: @pInterfaces[0]) ); zwp_input_method_v1_events: array[0..1] of Twl_message = ( (name: 'activate'; signature: 'n'; types: @pInterfaces[0]), (name: 'deactivate'; signature: 'o'; types: @pInterfaces[9]) ); zwp_input_panel_v1_requests: array[0..0] of Twl_message = ( (name: 'get_input_panel_surface'; signature: 'no'; types: @pInterfaces[10]) ); zwp_input_panel_surface_v1_requests: array[0..1] of Twl_message = ( (name: 'set_toplevel'; signature: 'ou'; types: @pInterfaces[12]), (name: 'set_overlay_panel'; signature: ''; types: @pInterfaces[0]) ); initialization Pointer(vIntf_zwp_input_method_context_v1_Listener.surrounding_text) := @zwp_input_method_context_v1_surrounding_text_Intf; Pointer(vIntf_zwp_input_method_context_v1_Listener.reset) := @zwp_input_method_context_v1_reset_Intf; Pointer(vIntf_zwp_input_method_context_v1_Listener.content_type) := @zwp_input_method_context_v1_content_type_Intf; Pointer(vIntf_zwp_input_method_context_v1_Listener.invoke_action) := @zwp_input_method_context_v1_invoke_action_Intf; Pointer(vIntf_zwp_input_method_context_v1_Listener.commit_state) := @zwp_input_method_context_v1_commit_state_Intf; Pointer(vIntf_zwp_input_method_context_v1_Listener.preferred_language) := @zwp_input_method_context_v1_preferred_language_Intf; Pointer(vIntf_zwp_input_method_v1_Listener.activate) := @zwp_input_method_v1_activate_Intf; Pointer(vIntf_zwp_input_method_v1_Listener.deactivate) := @zwp_input_method_v1_deactivate_Intf; zwp_input_method_context_v1_interface.name := 'zwp_input_method_context_v1'; zwp_input_method_context_v1_interface.version := 1; zwp_input_method_context_v1_interface.method_count := 14; zwp_input_method_context_v1_interface.methods := @zwp_input_method_context_v1_requests; zwp_input_method_context_v1_interface.event_count := 6; zwp_input_method_context_v1_interface.events := @zwp_input_method_context_v1_events; zwp_input_method_v1_interface.name := 'zwp_input_method_v1'; zwp_input_method_v1_interface.version := 1; zwp_input_method_v1_interface.method_count := 0; zwp_input_method_v1_interface.methods := nil; zwp_input_method_v1_interface.event_count := 2; zwp_input_method_v1_interface.events := @zwp_input_method_v1_events; zwp_input_panel_v1_interface.name := 'zwp_input_panel_v1'; zwp_input_panel_v1_interface.version := 1; zwp_input_panel_v1_interface.method_count := 1; zwp_input_panel_v1_interface.methods := @zwp_input_panel_v1_requests; zwp_input_panel_v1_interface.event_count := 0; zwp_input_panel_v1_interface.events := nil; zwp_input_panel_surface_v1_interface.name := 'zwp_input_panel_surface_v1'; zwp_input_panel_surface_v1_interface.version := 1; zwp_input_panel_surface_v1_interface.method_count := 2; zwp_input_panel_surface_v1_interface.methods := @zwp_input_panel_surface_v1_requests; zwp_input_panel_surface_v1_interface.event_count := 0; zwp_input_panel_surface_v1_interface.events := nil; end.
unit uCadMaster; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uMaster, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, Data.DB, Vcl.Mask, Vcl.DBCtrls, Datasnap.DBClient, SimpleDS, Data.SqlExpr, FireDAC.Comp.Client, dmPrincipal, Data.DBXFirebird, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, Vcl.Grids, Vcl.DBGrids, Vcl.ImgList, System.ImageList; type TChaveTabela = array of string; TfrmCadMaster = class(TfrmMaster) pnlBotoes: TPanel; bbIncluir: TBitBtn; bbAlterar: TBitBtn; bbCancelar: TBitBtn; bbGravar: TBitBtn; bbPesquisar: TBitBtn; bbImprimir: TBitBtn; bbFechar: TBitBtn; bbExcluir: TBitBtn; pnlGeral: TPanel; dsPadrao: TDataSource; FDTablePadrao: TFDTable; ImgList: TImageList; procedure FormCreate(Sender: TObject); overload; procedure bbIncluirClick(Sender: TObject); procedure bbGravarClick(Sender: TObject); procedure bbAlterarClick(Sender: TObject); procedure bbExcluirClick(Sender: TObject); procedure bbCancelarClick(Sender: TObject); procedure bbFecharClick(Sender: TObject); procedure bbPesquisarClick(Sender: TObject); private { Private declarations } FSQLConsultaPesquisa: string; FConexao: TFDConnection; FChaves: TChaveTabela; FSQLPesquisa: string; procedure setChavesTabela(chaves: TChaveTabela); function getChavesTabela(): TChaveTabela; procedure setConexao(conexao: TFDConnection); function getConexao(): TFDConnection; function getSQLConsultaPesquisa(): string; procedure setSQLConsultaPesquisa(sql: string); procedure HabilitaControles; procedure HabilitaControlesVisuais(Status: Boolean); procedure somenteMetadados(); procedure abrirPesquisa(); procedure ChangeEnter(Sender: TObject); procedure ChangeExit(Sender: TObject); function getSQLPesquisa: string; public { Public declarations } constructor Create(AOwner: TComponent); overload; published constructor Create(AOwner: TComponent; conexao: TFDConnection; tabela: string; camposChave: array of string); overload; procedure setDataField(componente: TWinControl; field: string; display: string); procedure filtrarDados(filtro: string); procedure setProximoCodigo(tabela, campoChave: string; condicao: string = ''); procedure prepararPesquisa(conexao: TFDConnection; consulta: string; chaves: TChaveTabela); procedure setSQLPesquisa(sql: string); end; var frmCadMaster: TfrmCadMaster; irParaUltimoRegistro: Boolean; implementation uses uConsulta, uConstantes, uPesquisa; {$R *.dfm} procedure TfrmCadMaster.abrirPesquisa(); var pesquisa: TfrmPesquisar; chaves: TChaveTabela; i: integer; filtro: string; begin // Cria a pesquisa passando os parametros adicionais pesquisa := TfrmPesquisar.Create(Application, getConexao(), getSQLConsultaPesquisa()); try // Abre em modal para o usuario escolher o registro desejado if not pesquisa.pesquisar() then Exit; // Filtra para o registro que o usuario escolheu chaves := getChavesTabela(); for i := Low(chaves) to High(chaves) do if filtro = '' then filtro := filtro + chaves[i] + ' = ' + pesquisa.getValorCampoAsString (chaves[i]) else filtro := filtro + ' AND ' + chaves[i] + ' = ' + pesquisa.getValorCampoAsString(chaves[i]); filtrarDados(filtro); finally FreeAndNil(pesquisa); end; end; procedure TfrmCadMaster.bbAlterarClick(Sender: TObject); begin inherited; dsPadrao.DataSet.Edit; HabilitaControles(); HabilitaControlesVisuais(True); irParaUltimoRegistro := False; end; procedure TfrmCadMaster.bbCancelarClick(Sender: TObject); begin inherited; with dsPadrao.DataSet do begin Cancel; Filtered := False; end; HabilitaControles(); HabilitaControlesVisuais(False); end; procedure TfrmCadMaster.bbExcluirClick(Sender: TObject); begin inherited; if MessageDlg('Deseja Excluir o Registro', mtconfirmation, [mbYes, mbNo], 0) = mrYes then begin dsPadrao.DataSet.Delete; HabilitaControles(); HabilitaControlesVisuais(False); end; end; procedure TfrmCadMaster.bbFecharClick(Sender: TObject); begin inherited; Close; end; procedure TfrmCadMaster.bbGravarClick(Sender: TObject); begin inherited; dsPadrao.DataSet.Post; dsPadrao.DataSet.Filtered := False; HabilitaControles(); HabilitaControlesVisuais(False); if irParaUltimoRegistro then dsPadrao.DataSet.Last; end; procedure TfrmCadMaster.bbIncluirClick(Sender: TObject); begin inherited; dsPadrao.DataSet.Insert; HabilitaControles(); irParaUltimoRegistro := True; // Comentado pois as telas deverão usar o auto incremento // setProximoCodigo(FDTablePadrao.TableName, FDTablePadrao.IndexFieldNames); // Como não irá precisar de buscar os ultimos codigos entao coloque como nao requerido a chave primaria, pois será criada pelo generator FDTablePadrao.FieldByName(FDTablePadrao.IndexFieldNames).Required := False; pnlGeral.SetFocus; end; procedure TfrmCadMaster.setSQLPesquisa(sql: string); begin FSQLPesquisa := sql; end; function TfrmCadMaster.getSQLPesquisa(): string; begin Result := FSQLPesquisa; end; procedure TfrmCadMaster.bbPesquisarClick(Sender: TObject); var sqlPesquisa: string; begin sqlPesquisa := getSQLPesquisa(); if sqlPesquisa = '' then sqlPesquisa := 'SELECT * FROM ' + FDTablePadrao.TableName; prepararPesquisa(conexaoSistema, sqlPesquisa, [FDTablePadrao.IndexFieldNames]); inherited; abrirPesquisa(); HabilitaControles(); HabilitaControlesVisuais(False); setSQLPesquisa(''); end; constructor TfrmCadMaster.Create(AOwner: TComponent); begin inherited; FormCreate(TObject(AOwner)); end; procedure TfrmCadMaster.filtrarDados(filtro: string); begin FDTablePadrao.Filter := filtro; FDTablePadrao.Filtered := FDTablePadrao.Filter <> ''; end; procedure TfrmCadMaster.somenteMetadados; begin filtrarDados(FDTablePadrao.IndexFieldNames + ' IS NULL'); end; constructor TfrmCadMaster.Create(AOwner: TComponent; conexao: TFDConnection; tabela: string; camposChave: array of string); begin Create(AOwner); FDTablePadrao.Connection := conexao; FDTablePadrao.TableName := tabela; FDTablePadrao.Active := True; somenteMetadados(); end; procedure TfrmCadMaster.ChangeEnter(Sender: TObject); begin if Sender is TDBEdit then TDBEdit(Sender).Color := $00E6FED8 else if Sender is TDBLookupComboBox then TDBLookupComboBox(Sender).Color := $00E6FED8 else if Sender is TDBComboBox then TDBComboBox(Sender).Color := $00E6FED8 else if Sender is TDBMemo then TDBMemo(Sender).Color := $00E6FED8; end; procedure TfrmCadMaster.ChangeExit(Sender: TObject); begin if Sender is TDBEdit then TDBEdit(Sender).Color := clWindow else if Sender is TDBLookupComboBox then TDBLookupComboBox(Sender).Color := clWindow else if Sender is TDBComboBox then TDBComboBox(Sender).Color := clWindow else if Sender is TDBMemo then TDBMemo(Sender).Color := clWindow; end; procedure TfrmCadMaster.FormCreate(Sender: TObject); var i: integer; begin for i := 0 to ComponentCount - 1 do begin if Components[i] is TDBEdit then begin TDBEdit(Components[i]).OnEnter := ChangeEnter; TDBEdit(Components[i]).OnExit := ChangeExit; end else if Components[i] is TDBLookupComboBox then begin TDBLookupComboBox(Components[i]).OnEnter := ChangeEnter; TDBLookupComboBox(Components[i]).OnExit := ChangeExit; end else if Components[i] is TDBComboBox then begin TDBComboBox(Components[i]).OnEnter := ChangeEnter; TDBComboBox(Components[i]).OnExit := ChangeExit; end else if Components[i] is TDBMemo then begin TDBMemo(Components[i]).OnEnter := ChangeEnter; TDBMemo(Components[i]).OnExit := ChangeExit; end end; try HabilitaControles; HabilitaControlesVisuais(False); except on e: Exception do ShowMessage('Erro ao conectar base de dados' + #13 + 'Erro : ' + e.Message + #13 + 'Classe : ' + e.ClassName); end; end; function TfrmCadMaster.getChavesTabela: TChaveTabela; begin Result := FChaves; end; function TfrmCadMaster.getConexao: TFDConnection; begin Result := FConexao end; function TfrmCadMaster.getSQLConsultaPesquisa: string; begin Result := FSQLConsultaPesquisa end; procedure TfrmCadMaster.HabilitaControles; begin bbIncluir.Enabled := not(dsPadrao.DataSet.State in [dsInsert, dsEdit]); bbGravar.Enabled := (dsPadrao.DataSet.State in [dsInsert, dsEdit]); bbAlterar.Enabled := (dsPadrao.DataSet.State in [dsBrowse]) and not(dsPadrao.DataSet.IsEmpty); bbExcluir.Enabled := (dsPadrao.DataSet.State in [dsBrowse]) and not(dsPadrao.DataSet.IsEmpty); bbCancelar.Enabled := (dsPadrao.DataSet.State in [dsInsert, dsEdit]); bbPesquisar.Enabled := not(dsPadrao.DataSet.State in [dsInsert, dsEdit]); HabilitaControlesVisuais(True); end; procedure TfrmCadMaster.HabilitaControlesVisuais(Status: Boolean); var i: integer; begin for i := 0 to ComponentCount - 1 do begin if Components[i] is TDBEdit then TDBEdit(Components[i]).Enabled := Status else if Components[i] is TDBLookupComboBox then TDBLookupComboBox(Components[i]).Enabled := Status else if Components[i] is TDBComboBox then TDBComboBox(Components[i]).Enabled := Status else if Components[i] is TDBMemo then TDBMemo(Components[i]).Enabled := Status else if Components[i] is TButtonedEdit then begin TButtonedEdit(Components[i]).Images := ImgList; TButtonedEdit(Components[i]).RightButton.Visible := True; TButtonedEdit(Components[i]).RightButton.Enabled := True; TButtonedEdit(Components[i]).RightButton.ImageIndex := 0; TButtonedEdit(Components[i]).Color := clBtnFace; TButtonedEdit(Components[i]).ReadOnly := True; TButtonedEdit(Components[i]).TabStop := False; end; end; end; procedure TfrmCadMaster.prepararPesquisa(conexao: TFDConnection; consulta: string; chaves: TChaveTabela); begin setConexao(conexao); setSQLConsultaPesquisa(consulta); setChavesTabela(chaves); end; procedure TfrmCadMaster.setChavesTabela(chaves: TChaveTabela); begin FChaves := chaves end; procedure TfrmCadMaster.setConexao(conexao: TFDConnection); begin FConexao := conexao end; procedure TfrmCadMaster.setDataField(componente: TWinControl; field: string; display: string); begin if componente is TDBEdit then TDBEdit(componente).DataField := field else if componente is TDBMemo then TDBMemo(componente).DataField := field else if componente is TDBCheckBox then TDBCheckBox(componente).DataField := field; FDTablePadrao.FieldByName(field).DisplayLabel := AnsiUpperCase(Trim(display)); end; procedure TfrmCadMaster.setProximoCodigo(tabela, campoChave: string; condicao: string = ''); begin FDTablePadrao.FieldByName(campoChave).AsInteger := StrToInt(ultimoCodigo(conexaoSistema, tabela, campoChave, condicao)) + 1; end; procedure TfrmCadMaster.setSQLConsultaPesquisa(sql: string); begin FSQLConsultaPesquisa := sql end; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Collections, RemObjects.Elements.EUnit; type StackTest = public class (Test) private Data: Stack<String>; public method Setup; override; method Count; method Contains; method Clear; method Peek; method Pop; method Push; method ToArray; end; implementation method StackTest.Setup; begin Data := new Stack<String>; Data.Push("One"); Data.Push("Two"); Data.Push("Three"); end; method StackTest.Count; begin Assert.AreEqual(Data.Count, 3); Data.Pop; Assert.AreEqual(Data.Count, 2); Assert.AreEqual(new Stack<Integer>().Count, 0); end; method StackTest.Contains; begin Assert.IsTrue(Data.Contains("One")); Assert.IsTrue(Data.Contains("Two")); Assert.IsTrue(Data.Contains("Three")); Assert.IsFalse(Data.Contains("one")); //case sensetive Assert.IsFalse(Data.Contains("xxx")); Assert.IsFalse(Data.Contains(nil)); end; method StackTest.Clear; begin Assert.AreEqual(Data.Count, 3); Data.Clear; Assert.AreEqual(Data.Count, 0); end; method StackTest.Peek; begin Assert.AreEqual(Data.Peek, "Three"); Assert.AreEqual(Data.Peek, "Three"); //peek shouldn't remove item from stack Data.Push("Four"); Assert.AreEqual(Data.Peek, "Four"); Data.Clear; Assert.Throws(->Data.Peek); //empty stack end; method StackTest.Pop; begin //pop removes item from stack Assert.AreEqual(Data.Pop, "Three"); Assert.AreEqual(Data.Pop, "Two"); Assert.AreEqual(Data.Pop, "One"); Assert.AreEqual(Data.Count, 0); Assert.Throws(->Data.Pop); end; method StackTest.Push; begin Data.Push("Four"); Assert.AreEqual(Data.Count, 4); Assert.AreEqual(Data.Peek, "Four"); Data.Push(nil); Assert.AreEqual(Data.Count, 5); Assert.IsNil(Data.Peek); //duplicates allowed Assert.AreEqual(Data.Count, 5); Data.Push("x"); Data.Push("x"); Assert.AreEqual(Data.Count, 7); end; method StackTest.ToArray; begin var Expected: array of String := ["Three", "Two", "One"]; var Values: array of String := Data.ToArray; Assert.AreEqual(Values, Expected); end; end.
unit WinMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls; type TFormMain = class(TForm) LabelDir: TLabel; EditDir: TEdit; ButtonDir: TButton; TViewList: TTreeView; LabelList: TLabel; OpenDialogDir: TOpenDialog; LViewSong: TListView; LabelSong: TLabel; ButtonList: TButton; procedure ButtonDirClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.dfm} procedure TFormMain.FormCreate(Sender: TObject); begin ClientHeight:=601; ClientWidth:=857; end; procedure TFormMain.ButtonDirClick(Sender: TObject); begin if (OpenDialogDir.Execute) then begin EditDir.Text:=OpenDialogDir.InitialDir; end; end; end.
unit udmCore; interface uses Windows, Classes, SysUtils, DB, DBClient, Forms, Ora, uSupportLib, Variants; const CrLf = #13#10; resourcestring stCheckDel = 'Confermi l''eliminazione del record?'; stDeadlock = 'Il record corrente è attualmente in uso oppure bloccato'; stReqDErr = 'Inserire il valore'; stDuplicateRec = 'Il codice inserito è già utilizzato!'; stMaxCod = 'Codice maggiore dell''ultimo inserito!'; stDsError = 'Errore in fase di apertura del DataSet: '; stRecNotFound = 'Codice non presente!'; type TdmState = (hdmInsert, hdmEdit, hdmView, hdmDelete); TdmType = (hdmRead, hdmWrite); TdmTipAttNum = (hPrgAut, hPrgMan, hPrgAutAaa); TdmCore = class; TdmCore = class(TDataModule) private { Private declarations } FhDataSet: TDataSet; FhdmType: TdmType; FhKeyValues: TStringList; FhKeyFields: TStringList; FhdmState: TdmState; FhTipAttNum: TdmTipAttNum; procedure SetDataSetsMethods; procedure SethKeyFields(const Value: TStringList); procedure SethKeyValues(const Value: TStringList); protected procedure dmAfterInsert(DataSet: TDataSet); virtual; procedure dmAfterOpen(DataSet: TDataSet); virtual; procedure dmAfterPost(DataSet: TDataSet); virtual; procedure dmBeforeInsert(DataSet: TDataSet); virtual; procedure dmBeforeOpen(DataSet: TDataSet); virtual; procedure dmBeforePost(DataSet: TDataSet); virtual; function dmCheckValidateData: boolean; virtual; public { Public declarations } constructor Create(Owner: TComponent); override; destructor Destroy; override; function dmDsApplyUpdates(DataSet: TClientDataSet): boolean; virtual; procedure dmDsCancel(DataSet: TDataSet); virtual; procedure dmDsClose(DataSet: TDataSet); virtual; function dmDsDelete(DataSet: TDataSet): boolean; virtual; function dmDsEdit(DataSet: TDataSet): boolean; virtual; function dmDsInsert(DataSet: TDataSet): boolean; virtual; function dmDsOpen(DataSet: TDataSet): boolean; virtual; function dmDsPost(DataSet: TDataSet): boolean; virtual; procedure dmDsRefresh(DataSet: TDataSet); virtual; function dmExecStoredProc(ASp: TOraStoredProc): boolean; virtual; procedure dmOpenAll; virtual; function dmPostAll: boolean; virtual; procedure dmCloseAll; virtual; function getCodValKey: String; procedure SetKeyValues; procedure SetMasterParams; property hdmState : TdmState read FhdmState write FhdmState; published property hDataSet : TDataSet read FhDataSet write FhDataSet; property hdmType : TdmType read FhdmType write FhdmType default hdmRead; property hKeyFields : TStringList read FhKeyFields write SethKeyFields; property hKeyValues : TStringList read FhKeyValues write SethKeyValues; property hTipAttNum : TdmTipAttNum read FhTipAttNum write FhTipAttNum default hPrgAut; end; var dmCore: TdmCore; implementation uses Dialogs; constructor TdmCore.Create(Owner: TComponent); begin FhKeyFields := TStringList.Create; FhKeyValues := TStringList.Create; FhdmState := hdmView; inherited Create(Owner); SetDataSetsMethods; end; destructor TdmCore.Destroy; begin FhKeyValues.Free; FhKeyFields.Free; inherited Destroy; end; procedure TdmCore.dmAfterInsert(DataSet: TDataSet); begin // do nothing end; procedure TdmCore.dmAfterOpen(DataSet: TDataSet); begin // do nothing end; procedure TdmCore.dmAfterPost(DataSet: TDataSet); begin // do nothing end; procedure TdmCore.dmBeforeInsert(DataSet: TDataSet); begin // do nothing end; procedure TdmCore.dmBeforeOpen(DataSet: TDataSet); begin // do nothing end; procedure TdmCore.dmBeforePost(DataSet: TDataSet); begin if Assigned(DataSet.FindField('Des_Pdl')) then DataSet.FieldByName('Des_Pdl').AsString := GetMachineName; if Assigned(DataSet.FindField('Dat_Agg_Rec')) then DataSet.FieldByName('Dat_Agg_Rec').AsDateTime := Now; end; function TdmCore.dmDsApplyUpdates(DataSet: TClientDataSet): boolean; begin try try DataSet.ApplyUpdates(-1); except Result := False; end; finally Result := True; end; end; procedure TdmCore.dmDsCancel(DataSet: TDataSet); begin try DataSet.Cancel; except end; end; procedure TdmCore.dmDsClose(DataSet: TDataSet); begin try DataSet.Close; except end; end; function TdmCore.dmDsDelete(DataSet: TDataSet): boolean; begin try try DataSet.Delete; except on E : Exception do begin MessageDlg(E.Message, mtWarning, [mbOK], 0); Result := False; end; end; finally Result := True; end; end; function TdmCore.dmDsEdit(DataSet: TDataSet): boolean; begin try try DataSet.Edit; except Result := False; end; finally Result := True; end; end; function TdmCore.dmDsInsert(DataSet: TDataSet): boolean; begin try try DataSet.Insert; except Result := False; end; finally Result := True; end; end; function TdmCore.dmDsOpen(DataSet: TDataSet): boolean; begin try try DataSet.Open; except on E:Exception do begin MessageDlg(E.Message, mtInformation, [mbOK], 0); Result := False; end; end; finally Result := True; end; end; function TdmCore.dmDsPost(DataSet: TDataSet): boolean; begin try try DataSet.Post; except Result := False; end; finally Result := True; end; end; procedure TdmCore.dmDsRefresh(DataSet: TDataSet); begin try try dmDsClose(DataSet); finally dmDsOpen(DataSet); end; except end; end; function TdmCore.dmExecStoredProc(ASp: TOraStoredProc): boolean; begin Result := False; if ASp.StoredProcName <> '' then begin if Assigned(ASp.FindParam('iDes_Pdl')) then ASp.ParamByName('iDes_Pdl').AsString := GetMachineName; if Assigned(ASp.FindParam('iDat_Agg_Rec')) then ASp.ParamByName('iDat_Agg_Rec').AsDateTime := Now; try ASp.Execute; finally Result := True; end; end; end; function TdmCore.dmCheckValidateData: boolean; begin Result := True; end; procedure TdmCore.dmCloseAll; var i : integer; begin for i := 0 to ComponentCount - 1 do if Components[i] is TClientDataSet then dmDsClose(TClientDataSet(Components[i])); end; procedure TdmCore.dmOpenAll; var i : integer; begin if Assigned(hDataSet) then if dmDsOpen(hDataSet) then begin for i := 0 to ComponentCount - 1 do begin if (Components[i] is TClientDataSet) and (Components[i] <> hDataSet) then if not dmDsOpen(TClientDataSet(Components[i])) then begin MessageDlg(stDsError+TClientDataSet(Components[i]).Name, mtError, [mbOK], 0); Break; end; end; end; if Assigned(hDataSet) then hDataSet.First; end; function TdmCore.dmPostAll: boolean; var i : integer; begin if dmDsPost(hDataSet) then begin if dmDsApplyUpdates(TClientDataSet(hDataSet)) then begin Result := True; for i := 0 to ComponentCount - 1 do if (Components[i] is TClientDataSet) and (Components[i] <> hDataSet) then begin Result := dmDsApplyUpdates(TClientDataSet(Components[i])); if not Result then Break; end; end else Result := False; end else Result := False; end; procedure TdmCore.SetDataSetsMethods; var i : integer; begin for i := 0 to ComponentCount - 1 do if Components[i] is TDataSet then begin TDataSet(Components[i]).AfterInsert := dmAfterInsert; TDataSet(Components[i]).AfterOpen := dmAfterOpen; TDataSet(Components[i]).AfterPost := dmAfterPost; TDataSet(Components[i]).BeforeInsert := dmBeforeInsert; TDataSet(Components[i]).BeforeOpen := dmBeforeOpen; TDataSet(Components[i]).BeforePost := dmBeforePost; TDataSet(Components[i]).FilterOptions := [foCaseInsensitive]; end; end; procedure TdmCore.SethKeyFields(const Value: TStringList); begin if Assigned(Value) then FhKeyFields.Assign(Value); end; procedure TdmCore.SethKeyValues(const Value: TStringList); begin if Assigned(Value) then FhKeyValues.Assign(Value); end; procedure TdmCore.SetKeyValues; var i : integer; begin Self.hKeyValues.Clear; for i := 0 to Self.hKeyFields.Count - 1 do if not Self.hDataSet.FieldByName(Self.hKeyFields[i]).IsNull then Self.hKeyValues.Append(VarToStr(Self.hDataSet.FieldByName(Self.hKeyFields[i]).Value)) else Self.hKeyValues.Append(''); end; function TdmCore.getCodValKey: String; var i : integer; AppKey: String; begin AppKey := ''; for i := 0 to hKeyValues.Count - 1 do AppKey := AppKey + hKeyValues[i]; Result := AppKey; end; procedure TdmCore.SetMasterParams; var i : integer; OraQuery : TOraQuery; begin if Assigned(hDataSet) then begin if hDataSet is TClientDataSet then OraQuery := TOraQuery(GetDataSetFromClientDataSet(TClientDataSet(hDataSet))) else OraQuery := TOraQuery(hDataSet); for i := 0 to hKeyValues.Count - 1 do if Assigned(OraQuery.FindParam(hKeyFields[i])) then OraQuery.ParamByName(hKeyFields[i]).Value := hKeyValues[i]; end; end; end.
{ rxtbrsetup unit Copyright (C) 2005-2010 Lagunov Aleksey alexs@yandex.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit rxtbrsetup; {$I rx.inc} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Buttons, rxtoolbar, StdCtrls, ComCtrls, ExtCtrls, ButtonPanel; type { TToolPanelSetupForm } TToolPanelSetupForm = class(TForm) BitBtn3: TBitBtn; BitBtn4: TBitBtn; BitBtn5: TBitBtn; BitBtn6: TBitBtn; ButtonPanel1: TButtonPanel; cbShowHint: TCheckBox; cbTransp: TCheckBox; cbFlatBtn: TCheckBox; cbShowCaption: TCheckBox; Label1: TLabel; Label2: TLabel; ListBtnAvaliable: TListBox; ListBtnVisible: TListBox; PageControl1: TPageControl; Panel1: TPanel; Panel2: TPanel; RadioGroup1: TRadioGroup; RadioGroup2: TRadioGroup; TabSheet1: TTabSheet; TabSheet2: TTabSheet; procedure BitBtn3Click(Sender: TObject); procedure BitBtn4Click(Sender: TObject); procedure BitBtn5Click(Sender: TObject); procedure BitBtn6Click(Sender: TObject); procedure CheckBox1Change(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormResize(Sender: TObject); procedure ListBox1DrawItem(Control: TWinControl; Index: Integer; ARect: TRect; State: TOwnerDrawState); procedure ListBtnAvaliableClick(Sender: TObject); procedure cbShowCaptionChange(Sender: TObject); private procedure FillItems(List:TStrings; AVisible:boolean); procedure UpdateStates; procedure Localize; public FToolPanel:TToolPanel; constructor CreateSetupForm(AToolPanel:TToolPanel); end; var ToolPanelSetupForm: TToolPanelSetupForm; implementation uses vclutils, ActnList, boxprocs, rxconst; {$R *.lfm} type THackToolPanel = class(TToolPanel); { TToolPanelSetupForm } procedure TToolPanelSetupForm.FormDestroy(Sender: TObject); begin if Assigned(FToolPanel) then begin THackToolPanel(FToolPanel).SetCustomizing(false); THackToolPanel(FToolPanel).FCustomizer:=nil; end; end; procedure TToolPanelSetupForm.FormResize(Sender: TObject); begin ListBtnVisible.Width:=BitBtn6.Left - 4 - ListBtnVisible.Left; ListBtnAvaliable.Left:=BitBtn6.Left + BitBtn6.Width + 4; ListBtnAvaliable.Width:=Width - ListBtnAvaliable.Left - 4; Label1.Left:=ListBtnAvaliable.Left; end; procedure TToolPanelSetupForm.ListBox1DrawItem(Control: TWinControl; Index: Integer; ARect: TRect; State: TOwnerDrawState); var Offset:integer; P:TToolbarItem; BtnRect:TRect; Cnv:TCanvas; C: TColor; begin Cnv:=(Control as TListBox).Canvas; C:=Cnv.Brush.Color; Cnv.FillRect(ARect); { clear the rectangle } P:=TToolbarItem((Control as TListBox).Items.Objects[Index]); if Assigned(P) then begin if Assigned(FToolPanel.ImageList) and Assigned(P.Action) then begin if (P.Action is TCustomAction) and (TCustomAction(P.Action).ImageIndex>-1) and (TCustomAction(P.Action).ImageIndex < FToolPanel.ImageList.Count) then begin Offset := 2; BtnRect.Top:=ARect.Top + 2; BtnRect.Left:=ARect.Left + Offset; BtnRect.Right:=BtnRect.Left + FToolPanel.BtnWidth; BtnRect.Bottom:=BtnRect.Top + FToolPanel.BtnHeight; Cnv.Brush.Color := clBtnFace; Cnv.FillRect(BtnRect); DrawButtonFrame(Cnv, BtnRect, false, false); FToolPanel.ImageList.Draw(Cnv, BtnRect.Left + (FToolPanel.BtnWidth - FToolPanel.ImageList.Width) div 2, BtnRect.Top + (FToolPanel.BtnHeight - FToolPanel.ImageList.Height) div 2, TCustomAction(P.Action).ImageIndex, True); Offset:=BtnRect.Right; end; Offset := Offset + 6; Cnv.Brush.Color:=C; Cnv.TextOut(ARect.Left + Offset, (ARect.Top + ARect.Bottom - Cnv.TextHeight('W')) div 2, TCustomAction(P.Action).Caption); { display the text } end; end; end; procedure TToolPanelSetupForm.ListBtnAvaliableClick(Sender: TObject); begin with (Sender as TListBox) do begin if (ItemIndex>-1) and (ItemIndex<Items.Count) then begin Panel1.Caption:=TCustomAction(TToolbarItem(Items.Objects[ItemIndex]).Action).Hint; if Sender = ListBtnVisible then cbShowCaption.Checked:=TToolbarItem(Items.Objects[ItemIndex]).ShowCaption; end; end; end; procedure TToolPanelSetupForm.cbShowCaptionChange(Sender: TObject); begin if (ListBtnVisible.ItemIndex>-1) and (ListBtnVisible.ItemIndex<ListBtnVisible.Items.Count) then TToolbarItem(ListBtnVisible.Items.Objects[ListBtnVisible.ItemIndex]).ShowCaption:=cbShowCaption.Checked; end; procedure TToolPanelSetupForm.FillItems(List: TStrings; AVisible: boolean); var i, p:integer; begin List.Clear; for i:=0 to FToolPanel.Items.Count - 1 do begin if (FToolPanel.Items[i].Visible = AVisible) and Assigned(FToolPanel.Items[i].Action) then begin P:=List.Add(FToolPanel.Items[i].Action.Name); List.Objects[P]:=FToolPanel.Items[i]; end; end; end; procedure TToolPanelSetupForm.UpdateStates; var i:integer; begin for I:=0 to ListBtnVisible.Items.Count - 1 do TToolbarItem(ListBtnVisible.Items.Objects[i]).Visible:=true; for I:=0 to ListBtnAvaliable.Items.Count - 1 do TToolbarItem(ListBtnAvaliable.Items.Objects[i]).Visible:=false; BitBtn6.Enabled:=ListBtnVisible.Items.Count>0; BitBtn5.Enabled:=ListBtnVisible.Items.Count>0; cbShowCaption.Enabled:=ListBtnVisible.Items.Count>0; BitBtn4.Enabled:=ListBtnAvaliable.Items.Count>0; BitBtn3.Enabled:=ListBtnAvaliable.Items.Count>0; cbFlatBtn.Checked:=tpTransparentBtns in FToolPanel.Options; end; procedure TToolPanelSetupForm.Localize; begin Caption:=sToolPanelSetup; TabSheet1.Caption:=sVisibleButtons; TabSheet2.Caption:=sOptions; Label2.Caption:=sVisibleButtons; Label2.Caption:=sVisibleButtons; Label1.Caption:=sAvaliableButtons; cbShowCaption.Caption:=sShowCaption; RadioGroup2.Caption:=sToolBarStyle; RadioGroup2.Items.Clear; RadioGroup2.Items.Add(sToolBarStyle1); RadioGroup2.Items.Add(sToolBarStyle2); RadioGroup2.Items.Add(sToolBarStyle3); cbFlatBtn.Caption:=sFlatButtons; cbTransp.Caption:=sTransparent; cbShowHint.Caption:=sShowHint; RadioGroup1.Caption:=sButtonAlign; RadioGroup1.Items.Clear; RadioGroup1.Items.Add(sButtonAlign1); RadioGroup1.Items.Add(sButtonAlign2); RadioGroup1.Items.Add(sButtonAlign3); end; procedure TToolPanelSetupForm.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin CloseAction:=caFree; end; procedure TToolPanelSetupForm.CheckBox1Change(Sender: TObject); var tpo:TToolPanelOptions; begin tpo:=FToolPanel.Options; if cbTransp.Checked then tpo:=tpo + [tpTransparentBtns] else tpo:=tpo - [tpTransparentBtns]; FToolPanel.ToolBarStyle:=TToolBarStyle(RadioGroup2.ItemIndex); if cbFlatBtn.Checked then tpo:=tpo + [tpFlatBtns] else tpo:=tpo - [tpFlatBtns]; FToolPanel.ShowHint:=cbShowHint.Checked; FToolPanel.Options:=tpo; FToolPanel.ButtonAllign:=TToolButtonAllign(RadioGroup1.ItemIndex); cbFlatBtn.Checked:=tpFlatBtns in FToolPanel.Options; end; procedure TToolPanelSetupForm.BitBtn4Click(Sender: TObject); begin BoxMoveSelectedItems(ListBtnAvaliable, ListBtnVisible); UpdateStates; end; procedure TToolPanelSetupForm.BitBtn3Click(Sender: TObject); begin BoxMoveAllItems(ListBtnAvaliable, ListBtnVisible); UpdateStates; end; procedure TToolPanelSetupForm.BitBtn5Click(Sender: TObject); begin BoxMoveSelectedItems(ListBtnVisible, ListBtnAvaliable); UpdateStates; end; procedure TToolPanelSetupForm.BitBtn6Click(Sender: TObject); begin BoxMoveAllItems(ListBtnVisible, ListBtnAvaliable); UpdateStates; end; constructor TToolPanelSetupForm.CreateSetupForm(AToolPanel: TToolPanel); begin inherited Create(AToolPanel); Localize; PageControl1.ActivePageIndex:=0; FormResize(nil); FToolPanel:=AToolPanel; cbFlatBtn.Checked:=tpFlatBtns in FToolPanel.Options; cbTransp.Checked:=tpTransparentBtns in FToolPanel.Options; cbShowHint.Checked:=FToolPanel.ShowHint; ListBtnAvaliable.ItemHeight:=FToolPanel.BtnHeight + 4; ListBtnVisible.ItemHeight:=FToolPanel.BtnHeight + 4; FillItems(ListBtnVisible.Items, true); FillItems(ListBtnAvaliable.Items, false); RadioGroup1.ItemIndex:=Ord(FToolPanel.ButtonAllign); RadioGroup2.ItemIndex:=Ord(FToolPanel.ToolBarStyle); UpdateStates; cbFlatBtn.OnChange:=@CheckBox1Change; cbTransp.OnChange:=@CheckBox1Change; cbShowHint.OnChange:=@CheckBox1Change; RadioGroup1.OnClick:=@CheckBox1Change; RadioGroup2.OnClick:=@CheckBox1Change; end; end.
unit uFormaPagtoVO; interface uses System.Generics.Collections, uFormaPagtoItemVO, System.SysUtils; type TFormaPagtoVO = class private FItens: TObjectList<TFormaPagtoItemVO>; FAtivo: Boolean; FCodigo: Integer; FId: Integer; FNome: string; procedure SetAtivo(const Value: Boolean); procedure SetCodigo(const Value: Integer); procedure SetId(const Value: Integer); procedure SetItens(const Value: TObjectList<TFormaPagtoItemVO>); procedure SetNome(const Value: string); public property Id: Integer read FId write SetId; property Codigo: Integer read FCodigo write SetCodigo; property Nome: string read FNome write SetNome; property Ativo: Boolean read FAtivo write SetAtivo; property Itens: TObjectList<TFormaPagtoItemVO> read FItens write SetItens; constructor create; destructor destroy; override; end; implementation { TFormaPagtoVO } constructor TFormaPagtoVO.create; begin inherited create; FItens := TObjectList<TFormaPagtoItemVO>.Create(); end; destructor TFormaPagtoVO.destroy; begin FreeAndNil(FItens); inherited; end; procedure TFormaPagtoVO.SetAtivo(const Value: Boolean); begin FAtivo := Value; end; procedure TFormaPagtoVO.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TFormaPagtoVO.SetId(const Value: Integer); begin FId := Value; end; procedure TFormaPagtoVO.SetItens(const Value: TObjectList<TFormaPagtoItemVO>); begin FItens := Value; end; procedure TFormaPagtoVO.SetNome(const Value: string); begin FNome := Value; end; end.
unit UnitOfConstantVariables; interface const Const_TheStartOfComments = '/*'; Const_TheEndOfComments = '*/'; Const_TheEndOfOperator = ';'; Const_TheEndOfLine = '#13#10'; Const_TheLineOfComments = '//'; Const_TheSpace = ' '; Const_TheNullString = ''; Const_TheQuote = ''''; Const_TheDoubleQuote = '"'; Const_TheEndOfMasOfKeyWordsForVariables = 9; implementation end.
unit facturaExpo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, xmldom, XMLIntf, msxmldom, XMLDoc, wsaa, OpenSSLUtils_neo, wsdl_service, XSBuiltIns, InvokeRegistry, Rio, SOAPHTTPClient, JvExStdCtrls, JvEdit, JvValidateEdit, JvCombobox; resourcestring msgNoImplementado = 'Funcion no implementada para factura de exportacion'; const ctPuntoDeVenta = 1; ctEspaniol = 1; ctFactura = 19; ctDebito = 20; ctCredito = 21; ctCUIT = '30708026332'; type aDatosFac = record TipoCte: integer; Puntoventa: Integer; Id: Int64; NumCte: Integer; fecha: TDateTime; Pais: integer; Cliente: string; CUIT_Pais: string; Domicilio: string; Id_impositivo: string; Moneda: string; Cotizacion: Double; ObsComercial: string; Total: Double; Observa: string; Forma_pago: string; Incoterms: string; Incoterms_Ds: string; Idioma_cbte: integer; ImpNeto: Double; ImpNoGra: Double; ImpExcento: double; ImpIVA: double; ImpTrib: Double; TasaIVA: Integer; end; iItem = record Pro_codigo: string; Pro_ds: string; Pro_qty: double; Pro_umed: integer; Pro_precio_uni: double; Pro_total_item: double; end; TFFacturaExpo = class(TForm) bTicket: TButton; xmlDoc: TXMLDocument; MLog: TMemo; bAutorizarTicket: TButton; bConsCte: TButton; bPaises: TButton; bMonedas: TButton; bTiposExpo: TButton; bFactura: TButton; bTiposCte: TButton; bPtosVta: TButton; bCUIT: TButton; bIncoterms: TButton; bCotizacion: TButton; Afip: THTTPRIO; Label1: TLabel; Label2: TLabel; Label6: TLabel; Label7: TLabel; jvTotal: TJvValidateEdit; JVcuit: TJvValidateEdit; cbTipoCte: TJvComboBox; Label8: TLabel; edMoneda: TEdit; bPermisos: TButton; bIdiomas: TButton; Label9: TLabel; edPermiso: TEdit; Label5: TLabel; pais: TEdit; edCte: TEdit; Label10: TLabel; bUltimo: TButton; bID: TButton; bUmed: TButton; Label3: TLabel; edCliente: TEdit; Label4: TLabel; edDom: TEdit; Label11: TLabel; edImpositivo: TEdit; jvCotiza: TJvValidateEdit; Label12: TLabel; Label13: TLabel; lblID: TLabel; procedure bTicketClick(Sender: TObject); procedure bAutorizarTicketClick(Sender: TObject); procedure bConsCteClick(Sender: TObject); procedure bPaisesClick(Sender: TObject); procedure bMonedasClick(Sender: TObject); procedure bTiposCteClick(Sender: TObject); procedure bPtosVtaClick(Sender: TObject); procedure bIncotermsClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure bTiposExpoClick(Sender: TObject); procedure bCUITClick(Sender: TObject); procedure bCotizacionClick(Sender: TObject); procedure bPermisosClick(Sender: TObject); procedure bIdiomasClick(Sender: TObject); procedure bUltimoClick(Sender: TObject); procedure bIDClick(Sender: TObject); procedure bUmedClick(Sender: TObject); procedure bFacturaClick(Sender: TObject); private { Private declarations } ILogin: LoginCMS; IFactura: ServiceSOAP; FCae, FToken, FSign, FCuit: widestring; FNumeroCte: integer; bLoguear: Boolean; FLoguear: Boolean; FErrores: string; FFExpo: boolean; FId: Integer; procedure setTicketRequest( XDoc: TXMLDocument ); function getVersion: string; function getUltimoNumero: Integer; function getID: Integer; procedure Log( const cadena: string ); function getfileContent(const archivo: string): string; function extractMimeHeader(msg: Widestring): Widestring; procedure setLoginResponse( const cadena: string ); function getNodo(XDoc: TXMlDocument; const seccion, Nombre: string): string; procedure autorizarComprobante; procedure consultarPuntosVenta; procedure consultarComprobante( tipo: Integer = 1 ); procedure consultarDoctos; procedure consultarTipoCompte; procedure setAutorizacion( Auth: ClsFEXAuthRequest ); procedure consultarMonedas; procedure getTiposUni; procedure dummy; function FacturaE: boolean; procedure crearTicket; procedure autorizarTicket; procedure setFactura; procedure getdatosAutorizacion; procedure setFecha( fecha: TDateTime; var fecdes: TXSDate ); procedure verErroresFactura( const I: FEXResponseAuthorize ); procedure SetCUIT(const Value: widestring); procedure setLoguear(const Value: Boolean); procedure consultarTiposComprobante; procedure SetFExpo(const Value: boolean); public { Public declarations } constructor create( AOwner: TComponent; log: boolean = True ); overload; function emitirCompte( const tipo: string; const DatosFac : aDatosFac ): string; function getErrores: string; property CUIT: widestring read FCUIT write SetCUIT; property Loguear: Boolean read FLoguear write setLoguear; end; var FFacturaExpo: TFFacturaExpo; implementation uses ConfigFE, DMCons; {$R *.dfm} procedure TFFacturaExpo.autorizarComprobante; begin end; procedure TFFacturaExpo.autorizarTicket; var signer: TMessageSigner; cadena: WideString; arch : string; // FLogin: LoginCMS; begin signer := TMessageSigner.Create; signer.LoadPrivateKey(getClave, ''); signer.LoadCertificate(getCertif); signer.PlainMessage := getFileContent( ExtractFilePath(application.ExeName)+'fe\loginTicketRequest.xml'); signer.FirmarWSAA; cadena := extractMimeHeader( signer.SignedMessage ); ILogin := GetLoginCMS( True ); try cadena := ILogin.loginCms(cadena); Log('Se obtiene respuesta de AFIP: ' ); Log(cadena); arch := ExtractFilePath(application.ExeName)+'fe\loginTicketResponse.xml'; xmlDoc.FileName := arch; setLoginResponse( cadena ); FToken := getNodo( xmlDoc, 'credentials', 'token' ); FSign := getNodo( xmlDoc, 'credentials', 'sign' ); FCuit := DCons.getCUIT; FCuit := '30708026332'; except on e:exception do ShowMessage( e.Message ); end; end; procedure TFFacturaExpo.bAutorizarTicketClick(Sender: TObject); begin autorizarTicket; end; procedure TFFacturaExpo.bConsCteClick(Sender: TObject); begin consultarComprobante; end; procedure TFFacturaExpo.bCUITClick(Sender: TObject); var Auth: ClsFEXAuthRequest; IRespuesta: FEXResponse_DST_cuit; i: Integer; begin try Auth := ClsFEXAuthRequest.Create; setFactura; autorizarTicket; getDatosAutorizacion; setAutorizacion(Auth); // ShowMessage( IntToStr(Auth.Cuit )); IRespuesta := IFactura.FEXGetPARAM_DST_CUIT(Auth); for i:=0 to High(IRespuesta.FEXResultGet) do begin Log(IntToStr(IRespuesta.FEXResultGet[i].DST_CUIT) + '-' + IRespuesta.FEXResultGet[i].DST_Ds ); end; Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); finally Auth.Free; end; end; procedure TFFacturaExpo.bFacturaClick(Sender: TObject); var Auth: ClsFEXAuthRequest; Cmp: ClsFEXRequest; IRespuesta: FEXResponseAuthorize; i: Integer; Fac: aDatosFac; aItem: arrayofItem; FItem: Item; begin try Auth := ClsFEXAuthRequest.Create; Cmp := ClsFEXRequest.Create; setFactura; autorizarTicket; getDatosAutorizacion; setAutorizacion(Auth); Cmp.Tipo_cbte := cbTipoCte.ItemIndex + ctFactura; Cmp.Punto_vta := ctPuntoDeVenta; FNumeroCte := StrToInt(edCte.text); Cmp.Cbte_nro := FNumeroCte; Cmp.Fecha_cbte := FormatDateTime('yyyymmdd', date ); Cmp.Dst_cmp := StrToInt(pais.Text); Cmp.Cliente := edCliente.Text; Cmp.Cuit_pais_cliente := JVcuit.Value; Cmp.Domicilio_cliente := edDom.Text; Cmp.Id_impositivo := edImpositivo.Text; Cmp.Moneda_Id := edMoneda.Text; Cmp.Moneda_ctz := jvCotiza.value; Cmp.Obs_comerciales := 'ORIGEN REP. ARGENTINA'; Cmp.Obs := 'demo factura exportacion'; Cmp.Imp_total := jvTotal.value; Cmp.Forma_pago := 'CONTADO'; Cmp.Incoterms := 'FOB'; Cmp.Incoterms_Ds := 'Freight on Board'; Cmp.Idioma_cbte := 1; Cmp.Tipo_expo := 1; cmp.Permiso_existente := 'N'; FId := FId + 1; Cmp.Id := FId; lblID.Caption := IntToStr(FId); SetLength(aItem, 1); FItem := Item.Create; FItem.Pro_codigo := 'MED'; FItem.Pro_ds := 'MEDIAS'; FItem.Pro_qty := 5; FItem.Pro_umed := 7; FItem.Pro_precio_uni := 1000; FItem.Pro_total_item := 5000; aItem[0] := FItem; Cmp.Items := aItem; { $parameters->Cmp->Tipo_expo = 1; $permisos = array(); $permisos[0]->Id_permiso = 'xxyyxxyyxxyyxxyy'; $permisos[0]->Dst_merc = 225; $permisos[1]->Id_permiso = 'xxyyxxyyxxyyxxyy'; $permisos[1]->Dst_merc = 225; $parameters->Cmp->Permiso_existente = 'S'; $parameters->Cmp->Permisos = $permisos; $results=$client->FEXAuthorize($parameters); CheckErrors($results, 'FEXAuthorize', $client); PrintCbte($results->FEXAuthorizeResult->FEXResultAuth); } IRespuesta := IFactura.FEXAuthorize(Auth, Cmp); if Assigned( IRespuesta.FEXResultAuth ) then begin Log('ID: ' + IntToStr(IRespuesta.FEXResultAuth.Id)); FCae := IRespuesta.FEXResultAuth.Cae; FId := IRespuesta.FEXResultAuth.Id; lblID.Caption := IntToStr(FId); Log('CAE: ' + FCae); end else begin Log('Error en asignacion de ID'); FCae := 'Error'; end; if assigned(IRespuesta.FEXErr) then Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); if assigned(IRespuesta.FEXEvents) then Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); edCte.Text := IntToStr(FNumeroCte); finally Auth.Free; Cmp.Free; SetLength(aItem, 0); end; end; procedure TFFacturaExpo.bPtosVtaClick(Sender: TObject); begin consultarPuntosVenta; end; procedure TFFacturaExpo.bMonedasClick(Sender: TObject); begin ConsultarMonedas; end; procedure TFFacturaExpo.bTiposExpoClick(Sender: TObject); var Auth: ClsFEXAuthRequest; IRespuesta: FEXResponse_Tex; i: Integer; begin try Auth := ClsFEXAuthRequest.Create; setFactura; autorizarTicket; getDatosAutorizacion; setAutorizacion(Auth); // ShowMessage( IntToStr(Auth.Cuit )); IRespuesta := IFactura.FEXGetPARAM_Tipo_Expo(Auth); for i:=0 to High(IRespuesta.FEXResultGet) do begin Log(IntToStr(IRespuesta.FEXResultGet[i].Tex_Id) + '-' + IRespuesta.FEXResultGet[i].Tex_Ds ); end; Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); finally Auth.Free; end; end; procedure TFFacturaExpo.bUltimoClick(Sender: TObject); begin Log('Ultimo numero: ' + IntToStr(getUltimoNumero)); end; procedure TFFacturaExpo.bUmedClick(Sender: TObject); var Auth: ClsFEXAuthRequest; IRespuesta: FEXResponse_Umed; i: Integer; begin try Auth := ClsFEXAuthRequest.Create; setFactura; autorizarTicket; getDatosAutorizacion; setAutorizacion(Auth); // ShowMessage( IntToStr(Auth.Cuit )); IRespuesta := IFactura.FEXGetPARAM_UMed(Auth); for I := 0 to High(IRespuesta.FEXResultGet) do begin Log(IntToStr(IRespuesta.FEXResultGet[i].Umed_Id) + '-' + IRespuesta.FEXResultGet[i].Umed_Ds); end; Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); finally Auth.Free; end; end; procedure TFFacturaExpo.bCotizacionClick(Sender: TObject); var Auth: ClsFEXAuthRequest; IRespuesta: FEXResponse_Ctz; i: Integer; begin try Auth := ClsFEXAuthRequest.Create; setFactura; autorizarTicket; getDatosAutorizacion; setAutorizacion(Auth); // ShowMessage( IntToStr(Auth.Cuit )); IRespuesta := IFactura.FEXGetPARAM_Ctz(Auth, edMoneda.Text ); Log(IRespuesta.FEXResultGet.Mon_fecha + '-' + FloatToStr(IRespuesta.FEXResultGet.Mon_ctz)); Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); finally Auth.Free; end; end; procedure TFFacturaExpo.bTicketClick(Sender: TObject); begin crearTicket; end; procedure TFFacturaExpo.bIDClick(Sender: TObject); begin FId := GetID; lblID.Caption := IntToStr(FId); end; procedure TFFacturaExpo.bIdiomasClick(Sender: TObject); var Auth: ClsFEXAuthRequest; IRespuesta: FEXResponse_Idi; i: Integer; begin try Auth := ClsFEXAuthRequest.Create; setFactura; autorizarTicket; getDatosAutorizacion; setAutorizacion(Auth); // ShowMessage( IntToStr(Auth.Cuit )); IRespuesta := IFactura.FEXGetPARAM_Idiomas(Auth); for i:=0 to High(IRespuesta.FEXResultGet) do begin Log(IntToStr(IRespuesta.FEXResultGet[i].Idi_Id) + '-' + IRespuesta.FEXResultGet[i].Idi_Ds ); end; Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); finally Auth.Free; end; end; procedure TFFacturaExpo.bIncotermsClick(Sender: TObject); var Auth: ClsFEXAuthRequest; IRespuesta: FEXResponse_Inc; i: Integer; begin try Auth := ClsFEXAuthRequest.Create; setFactura; autorizarTicket; getDatosAutorizacion; setAutorizacion(Auth); // ShowMessage( IntToStr(Auth.Cuit )); IRespuesta := IFactura.FEXGetPARAM_Incoterms(Auth); for i:=0 to High(IRespuesta.FEXResultGet) do begin Log(IRespuesta.FEXResultGet[i].Inc_Id + '-' + IRespuesta.FEXResultGet[i].Inc_Ds ); end; Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); finally Auth.Free; end; end; procedure TFFacturaExpo.bPaisesClick(Sender: TObject); var Auth: ClsFEXAuthRequest; IRespuesta: FEXResponse_DST_pais; i: Integer; begin try Auth := ClsFEXAuthRequest.Create; setFactura; autorizarTicket; getDatosAutorizacion; setAutorizacion(Auth); // ShowMessage( IntToStr(Auth.Cuit )); IRespuesta := IFactura.FEXGetPARAM_DST_pais(Auth); for i:=0 to High(IRespuesta.FEXResultGet) do begin Log(IRespuesta.FEXResultGet[i].DST_Codigo + '-' + IRespuesta.FEXResultGet[i].DST_Ds ); end; Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); finally Auth.Free; end; end; procedure TFFacturaExpo.bPermisosClick(Sender: TObject); var Auth: ClsFEXAuthRequest; IRespuesta: FEXResponse_CheckPermiso; i: Integer; begin try Auth := ClsFEXAuthRequest.Create; setFactura; autorizarTicket; getDatosAutorizacion; setAutorizacion(Auth); // ShowMessage( IntToStr(Auth.Cuit )); IRespuesta := IFactura.FEXCheck_Permiso(Auth, edpermiso.text, StrToInt(Pais.Text )); Log(IRespuesta.FEXResultGet.Status ); Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); finally Auth.Free; end; end; procedure TFFacturaExpo.consultarComprobante( tipo: integer = 1 ); var Auth: ClsFEXAuthRequest; IRespuesta: FEXGetCMPResponse; i: Integer; aID: ClsFEXGetCMP; begin try Auth := ClsFEXAuthRequest.Create; aId := ClsFEXGetCMP.Create; setFactura; autorizarTicket; getDatosAutorizacion; setAutorizacion(Auth); // ShowMessage( IntToStr(Auth.Cuit )); aId.Tipo_cbte := ctFactura; aId.Punto_vta := ctPuntoDeVenta; aID.Cbte_nro := StrToInt64Def( edCte.Text, 1 ); IRespuesta := IFactura.FEXGetCMP(Auth, aId ); log( IntToStr(IRespuesta.FEXResultGet.Id) + ' - ' + IRespuesta.FEXResultGet.Fecha_cbte + ' - ' + IntToStr(IRespuesta.FEXResultGet.Tipo_cbte) + ' - ' + IntToStr(IRespuesta.FEXResultGet.Punto_vta) + ' - ' + IntToStr(IRespuesta.FEXResultGet.Cbte_nro) + ' - ' + IntToStr(IRespuesta.FEXResultGet.Tipo_expo) + ' - ' + IRespuesta.FEXResultGet.Permiso_existente + ' - ' + IRespuesta.FEXResultGet.Cliente + ' - ' + IRespuesta.FEXResultGet.Domicilio_cliente + ' - ' + IntToStr(IRespuesta.FEXResultGet.Cuit_pais_cliente) + ' - ' + IRespuesta.FEXResultGet.Id_impositivo + ' - ' + IRespuesta.FEXResultGet.Cae + ' - ' + IRespuesta.FEXResultGet.Moneda_Id + ' - ' + FloatToStr(IRespuesta.FEXResultGet.Moneda_ctz) + ' - ' + IRespuesta.FEXResultGet.Obs_comerciales + ' - ' + FloatToStr(IRespuesta.FEXResultGet.Imp_total) + ' - ' + IRespuesta.FEXResultGet.Obs + ' - ' + IRespuesta.FEXResultGet.Forma_pago + ' - ' + IRespuesta.FEXResultGet.Incoterms + ' - ' + IRespuesta.FEXResultGet.Incoterms_Ds + ' - ' + IRespuesta.FEXResultGet.Fecha_cbte_cae + ' - ' + IRespuesta.FEXResultGet.Fecha_cbte + ' - ' + IRespuesta.FEXResultGet.Resultado + ' - ' + IRespuesta.FEXResultGet.Motivos_Obs ); for i:= 0 to High(IRespuesta.FEXResultGet.Items) do Log( IRespuesta.FEXResultGet.Items[i].Pro_codigo + IRespuesta.FEXResultGet.Items[i].Pro_ds + FloatToStr(IRespuesta.FEXResultGet.Items[i].Pro_qty ) + inttostr(IRespuesta.FEXResultGet.Items[i].Pro_umed) + FloatToStr(IRespuesta.FEXResultGet.Items[i].Pro_precio_uni) + FloatToStr(IRespuesta.FEXResultGet.Items[i].Pro_total_item) ); for i:= 0 to High(IRespuesta.FEXResultGet.Permisos) do Log( IRespuesta.FEXResultGet.Permisos[i].Id_permiso + IntToStr(IRespuesta.FEXResultGet.Permisos[i].Dst_merc) ); for i:= 0 to High(IRespuesta.FEXResultGet.Cmps_asoc) do Log( IntToStr(IRespuesta.FEXResultGet.Cmps_asoc[i].CBte_tipo) + ' - ' + IntToStr(IRespuesta.FEXResultGet.Cmps_asoc[i].Cbte_punto_vta) + ' - ' + IntToStr(IRespuesta.FEXResultGet.Cmps_asoc[i].Cbte_nro) ); FId := IRespuesta.FEXResultGet.Id; lblID.Caption := IntToStr(FId); Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); finally Auth.Free; aId.Free; end; end; procedure TFFacturaExpo.consultarDoctos; begin try setFactura; getDatosAutorizacion; finally end; end; procedure TFFacturaExpo.consultarMonedas; var Auth: ClsFEXAuthRequest; IRespuesta: FEXResponse_Mon; i: Integer; begin try Auth := ClsFEXAuthRequest.Create; setFactura; autorizarTicket; getDatosAutorizacion; setAutorizacion(Auth); IRespuesta := IFactura.FEXGetPARAM_MON(Auth); for i:=0 to High(IRespuesta.FEXResultGet) do begin Log(IRespuesta.FEXResultGet[i].Mon_Id + '-' + IRespuesta.FEXResultGet[i].Mon_Ds ); end; Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); finally Auth.Free; end; end; procedure TFFacturaExpo.consultarPuntosVenta; var Auth: ClsFEXAuthRequest; IRespuesta: FEXResponse_PtoVenta; i: Integer; begin try Auth := ClsFEXAuthRequest.Create; setFactura; autorizarTicket; getDatosAutorizacion; setAutorizacion(Auth); // ShowMessage( IntToStr(Auth.Cuit )); IRespuesta := IFactura.FEXGetPARAM_PtoVenta(Auth); for i:=0 to High(IRespuesta.FEXResultGet) do begin Log(IntToStr(IRespuesta.FEXResultGet[i].Pve_Nro) + '-' + IRespuesta.FEXResultGet[i].Pve_Bloqueado ); end; Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); finally Auth.Free; end; end; procedure TFFacturaExpo.consultarTipoCompte; var Auth: ClsFEXAuthRequest; IRespuesta: FEXResponse_Tipo_Cbte; i: Integer; begin try Auth := ClsFEXAuthRequest.Create; setFactura; autorizarTicket; getDatosAutorizacion; setAutorizacion(Auth); // ShowMessage( IntToStr(Auth.Cuit )); IRespuesta := IFactura.FEXGetPARAM_Tipo_Cbte(Auth); for i:=0 to High(IRespuesta.FEXResultGet) do begin Log(IntToStr(IRespuesta.FEXResultGet[i].Cbte_Id) + '-' + IRespuesta.FEXResultGet[i].Cbte_Ds ); end; Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); finally Auth.Free; end; end; procedure TFFacturaExpo.consultarTiposComprobante; begin end; procedure TFFacturaExpo.crearTicket; var arch : string; begin arch := ExtractFilePath(application.ExeName)+'fe\loginTicketRequest.xml'; xmlDoc.FileName := arch; xmlDoc.Active := True; setTicketRequest( xmlDoc ); xmlDoc.SaveToFile(arch); xmlDoc.Active := False; Log( 'ticket ha sido creado. en espera de envio a autorizacion' ); end; constructor TFFacturaExpo.create(AOwner: TComponent; log: boolean); begin FLoguear := log; inherited create( AOwner ); end; procedure TFFacturaExpo.dummy; begin end; function TFFacturaExpo.emitirCompte(const tipo: string; const DatosFac: aDatosFac): string; begin setFactura; crearTicket; // autenticacion con datos de certificado digital encriptados autorizarTicket; // generar la autorizacion getDatosAutorizacion; // leo los datos devueltos por AFIP en archivo y lo asigno a variables. // TODO: validar errores! { if Tipo = 'FCA' then FTipoComprobante := ctFacturaA else if Tipo = 'NCA' then FTipoComprobante := ctCreditoA else if Tipo = 'FCB' then FTipoComprobante := ctFacturaB else if Tipo = 'NCB' then FTipoComprobante := ctCreditoB; consultarComprobante2485( FTipoComprobante ); // corresponde a factura tipo A. Deja en FNumeroCte el ultimo numero usado Inc( FNumeroCte ); ICte := FECAERequest.Create; // creo objeto de clase generadora de factura IAuth := FEAuthRequest.Create; // objeto de autorizacion setAutorizacion2485(IAuth ); // leo y asigno los datos de autorizacion obtenidos en getDatosAutorizacion ICab := FECAECabRequest.Create; // creo cabecera de factura; ICab.CantReg := 1; // cantidad de items -> 1 siempre por ahora ICab.PtoVta := ctPuntoDeventa; // punto de venta hard-coded (MEJORAR: Pasar a archivo de configuracion) ICab.CbteTipo := FTipoComprobante; // tipo de comprobante hard-coded (MEJORAR: Pasar a archivo de configuracion) ICte.FeCabReq := ICab; // asignamos a comprobante SetLength( FItems, 1 ); // asignamos cantidad de lineas de detalle de factura. Será 1 ya que se pasa la info por lote; // (MEJORAR: permitir mas de uno si lleva diferentes tasas de IVA) FItem := FECAEDetRequest.Create; // creo detalle FItem.Concepto := 1; // productos (MEJORAR: Permitir Servicios) FItem.DocTipo := datosfac.DocTipo; // 80 es cuit FItem.DocNro := datosfac.DocNumero; // numero de CUIT FItem.CbteDesde := FNumeroCte; FItem.CbteHasta := FNumeroCte; FItem.CbteFch := FormatDateTime('yyyymmdd', DatosFac.fecha ); FItem.ImpTotal := DatosFac.Total; FItem.ImpNeto := DatosFac.ImpNeto + DatosFac.ImpExcento; FItem.ImpOpEx := 0; // DatosFac.ImpExcento; FItem.ImpIVA := DatosFac.ImpIVA; FItem.MonId := DatosFac.Moneda; FItem.MonCotiz := 1; // para $ SetLength(FIVAS, 1); FIVA:= AlicIva.Create; FIVA.Id := DatosFac.TasaIVA; // Tasa Normal (TODO: recibir array con tasas de IVA e importes if DatosFac.TasaIVA = ctTasaIVA00 then FIVA.BaseImp := DatosFac.ImpExcento else FIVA.BaseImp := DatosFac.ImpNeto; FIVA.Importe := DatosFac.ImpIVA; FIVAs[0] := FIva; FItem.Iva := FIVAs; // asigno vector de IVA (por ahora 1) a detalle de facturas FItems[0] := FItem; // asigno item con detalle al vector de detalles ICte.FeDetReq := FItems; // asigno al detalle de factura IRespuesta := ISoap.FECAESolicitar( IAuth, ICte); // solicito comprobante a AFIP if IRespuesta.FeCabResp <> nil then begin Log( 'factura valor devuelto: ' + resul ); Log( 'codigo comprobante ' + IntToStr(IRespuesta.FeCabResp.CbteTipo )); Log( 'Punto de venta ' + IntToStr(IRespuesta.FeCabResp.PtoVta )); Log( 'Numero de comprobante ' + IntToStr(IRespuesta.FeDetResp[0].CbteDesde )); Log( 'CAE ' + IRespuesta.FeDetResp[0].CAE ); Log( 'Vto. CAE ' + IRespuesta.FEDetResp[0].CAEFchVto ); verErroresfactura2485( IRespuesta ); result := IRespuesta.FEDetResp[0].CAE; end else begin resul := 'Resultado "R" ERROR!'; verErroresfactura2485( IRespuesta ); result := ''; end; finally ICte.Free; end; } end; function TFFacturaExpo.extractMimeHeader(msg: Widestring): Widestring; var x, iPos: Integer; begin for x:=1 to 4 do begin iPos := Pos( #10, msg ); if (iPos>0) then msg := Copy( msg, iPos+1, Length(msg)); end; result := msg; end; function TFFacturaExpo.FacturaE: boolean; begin ShowMessage('a completar' ); end; procedure TFFacturaExpo.FormClose(Sender: TObject; var Action: TCloseAction); var arch: string; begin if bLoguear then begin arch := 'LogFE-' + FormatDateTime('yyyymmdd-hhss', now ) + '.log'; MLog.Lines.SaveToFile(arch); end; end; procedure TFFacturaExpo.FormCreate(Sender: TObject); begin FErrores := ''; bLoguear := True; end; procedure TFFacturaExpo.bTiposCteClick(Sender: TObject); begin consultarTipoCompte; end; procedure TFFacturaExpo.getdatosAutorizacion; var arch: string; begin arch := ExtractFilePath(application.ExeName)+'fe\loginTicketResponse.xml'; xmlDoc.FileName := arch; FToken := getNodo( xmlDoc, 'credentials', 'token' ); FSign := getNodo( xmlDoc, 'credentials', 'sign' ); // FCuit := DCons.getCUIT; FCuit := ctCUIT; end; function TFFacturaExpo.getErrores: string; begin result := Ferrores; end; function TFFacturaExpo.getfileContent(const archivo: string): string; var FArch: TextFile; buffer: string; begin AssignFile(FArch, archivo); Reset( FArch ); while not Eof(FArch) do begin Readln( FArch, buffer ); Result := Result + buffer end; CloseFile(FArch); end; function TFFacturaExpo.getID: Integer; var Auth: ClsFEXAuthRequest; IRespuesta: FEXResponse_LastID; i: Integer; begin try Auth := ClsFEXAuthRequest.Create; setFactura; autorizarTicket; getDatosAutorizacion; setAutorizacion(Auth); // ShowMessage( IntToStr(Auth.Cuit )); IRespuesta := IFactura.FEXGetLast_ID(Auth ); Log(IntToStr(IRespuesta.FEXResultGet.Id)); Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); Result := IRespuesta.FEXResultGet.Id; finally Auth.Free; end; end; function TFFacturaExpo.getNodo(XDoc: TXMlDocument; const seccion, Nombre: string): string; var N, Nodo: IXMLNode; begin XDoc.active := true; if ( seccion <> '') then Nodo := XDoc.DocumentElement.ChildNodes[seccion] else Nodo := XDoc.DocumentElement; N := Nodo.ChildNodes.FindNode(nombre); if ( n <> nil ) and ( N.IsTextElement ) then result := N.Text else raise Exception.Create( 'Nodo no existe (' + seccion + ' - ' + nombre + ')'); XDoc.active := false; end; procedure TFFacturaExpo.getTiposUni; begin try setFactura; getDatosAutorizacion; finally end; end; function TFFacturaExpo.getUltimoNumero: Integer; var Auth: ClsFEX_LastCMP; IRespuesta: FEXResponseLast_CMP; i: Integer; begin try Auth := ClsFEX_LastCMP.Create; setFactura; autorizarTicket; getDatosAutorizacion; // setAutorizacion(Auth); // ShowMessage( IntToStr(Auth.Cuit )); Auth.token := FToken; Auth.sign := FSign; Auth.cuit := StrToInt64(FCuit); Auth.Pto_venta := ctPuntoDeVenta; Auth.Tipo_cbte := ctFactura; IRespuesta := IFactura.FEXGetLast_CMP(Auth ); Log(IRespuesta.FEXResult_LastCMP.Cbte_fecha + '-' + IntToStr(IRespuesta.FEXResult_LastCMP.Cbte_nro)); FNumeroCte := IRespuesta.FEXResult_LastCMP.Cbte_nro; Log(IntToStr(IRespuesta.FEXErr.ErrCode) + ' - ' + IRespuesta.FEXErr.ErrMsg ); Log(IntToStr(IRespuesta.FEXEvents.EventCode) + ' - ' + IRespuesta.FEXEvents.EventMsg ); result := FNumeroCte; finally Auth.Free; end; end; function TFFacturaExpo.getVersion: string; begin end; procedure TFFacturaExpo.Log(const cadena: string); begin if FLoguear then MLog.lines.add( cadena ); end; procedure TFFacturaExpo.setAutorizacion(Auth: ClsFEXAuthRequest ); begin Auth.token := FToken; Auth.sign := FSign; Auth.cuit := StrToInt64(FCuit); end; procedure TFFacturaExpo.SetCUIT(const Value: widestring); begin FCUIT := Value; end; procedure TFFacturaExpo.setFactura; begin IFactura := GetServiceSoap(true); end; procedure TFFacturaExpo.setFecha(fecha: TDateTime; var fecdes: TXSDate); begin end; procedure TFFacturaExpo.SetFExpo(const Value: boolean); begin end; procedure TFFacturaExpo.setLoginResponse(const cadena: string); begin xmlDoc.XML.Text := cadena; xmlDoc.Active := True; xmlDoc.SaveToFile(ExtractFilePath(application.ExeName)+'fe\LoginTicketResponse.xml'); xmlDoc.Active := False; end; procedure TFFacturaExpo.setLoguear(const Value: Boolean); begin FLoguear := Value; end; procedure TFFacturaExpo.setTicketRequest(XDoc: TXMLDocument); var Raiz, Nodo: IXMLNode; Hora: TDateTime; begin Raiz := XDoc.DocumentElement.ChildNodes['header']; Hora := now; Nodo := Raiz.ChildNodes['generationTime']; Nodo.Text := FormatDateTime( 'yyyy-mm-dd"T"hh:mm:ss"-03:00"', hora ); Hora := Hora + 0.5; Nodo := Raiz.ChildNodes['expirationTime']; Nodo.Text := FormatDateTime( 'yyyy-mm-dd"T"hh:mm:ss"-03:00"', hora ); Raiz := XDoc.DocumentElement; Nodo := Raiz.ChildNodes['service']; Nodo.Text := 'wsfex' end; procedure TFFacturaExpo.verErroresFactura(const I: FEXResponseAuthorize); var n, z: Integer; cadena: string; FError: ClsFEXErr; FEventos: ClsFEXEvents; begin //if High(I.FEXErr)>0 then cadena := 'ERRORES -> '; // for n := 0 to High(I.FEXErr) do cadena := cadena + IntToStr(I.FEXErr.ErrCode) + ' - ' + I.FEXErr.ErrMsg + #13; //if High(I.FEXErr)>0 then cadena := cadena + ' OBSERVACIONES -> '; //for n:=0 to High( I.FeDetResp ) do //for z:=0 to High( I.FeDetResp[n].Observaciones ) do cadena := cadena + #9 + IntToStr(I.FEXEvents.EventCode) + ' - ' + I.FEXEvents.EventMsg + #13; FErrores := cadena; Log( FErrores ); end; { function FEXAuthorize(const Auth: ClsFEXAuthRequest; const Cmp: ClsFEXRequest): FEXResponseAuthorize; stdcall; function FEXGetCMP(const Auth: ClsFEXAuthRequest; const Cmp: ClsFEXGetCMP): FEXGetCMPResponse; stdcall; function FEXGetPARAM_Tipo_Cbte(const Auth: ClsFEXAuthRequest): FEXResponse_Tipo_Cbte; stdcall; function FEXGetPARAM_Tipo_Expo(const Auth: ClsFEXAuthRequest): FEXResponse_Tex; stdcall; function FEXGetPARAM_Incoterms(const Auth: ClsFEXAuthRequest): FEXResponse_Inc; stdcall; function FEXGetPARAM_Idiomas(const Auth: ClsFEXAuthRequest): FEXResponse_Idi; stdcall; function FEXGetPARAM_UMed(const Auth: ClsFEXAuthRequest): FEXResponse_Umed; stdcall; function FEXGetPARAM_DST_pais(const Auth: ClsFEXAuthRequest): FEXResponse_DST_pais; stdcall; function FEXGetPARAM_DST_CUIT(const Auth: ClsFEXAuthRequest): FEXResponse_DST_cuit; stdcall; function FEXGetPARAM_MON(const Auth: ClsFEXAuthRequest): FEXResponse_Mon; stdcall; function FEXGetLast_CMP(const Auth: ClsFEX_LastCMP): FEXResponseLast_CMP; stdcall; function FEXDummy: DummyResponse; stdcall; function FEXGetPARAM_Ctz(const Auth: ClsFEXAuthRequest; const Mon_id: WideString): FEXResponse_Ctz; stdcall; function FEXGetLast_ID(const Auth: ClsFEXAuthRequest): FEXResponse_LastID; stdcall; function FEXGetPARAM_PtoVenta(const Auth: ClsFEXAuthRequest): FEXResponse_PtoVenta; stdcall; function FEXCheck_Permiso(const Auth: ClsFEXAuthRequest; const ID_Permiso: WideString; const Dst_merc: Integer): FEXResponse_CheckPermiso; stdcall; } end.
{ Subroutine SST_R_PAS_INIT * * Init the local state for routines used to read in PASCAL source code. } module sst_r_pas_INIT; define sst_r_pas_init; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_init; {init state for reading in PASCAL} const max_msg_parms = 1; {max parameters we can pass to a message} var i, j: sys_int_machine_t; {loop counters} bits: sys_int_machine_t; {number of bits in data type} sz: sys_int_adr_t; {number of machine addresses} dt_p: sst_dtype_p_t; {scratch data type descriptor pointer} token, token2: string_var80_t; {scratch strings for making intrinsic names} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; stat: sys_err_t; {completion status code} { ************************************************************* * * Local subroutine INTRINSIC_DTYPE_REF (NAME, DTYPE) * * Set the input name for the data type DTYPE to NAME. The input name will be * entered in the input symbol table. A symbol descriptor should already exist * for DTYPE. It is permissable for DTYPE to already have an existing input * name. The old name will still referr to this data type, but the data type * will only refer to NAME. } procedure intrinsic_dtype_ref ( in name: string; {input name for intrinsic data type symbol} in out dtype: sst_dtype_t); {data type descriptor block} var namev: string_var32_t; {var string symbol name} pos: string_hash_pos_t; {handle to position in hash table} found: boolean; {TRUE if symbol previously existed} sym_pp: sst_symbol_pp_t; {points to hash entry user data area} begin namev.max := sizeof(namev.str); {init local var string} string_vstring (namev, name, sizeof(name)); {name var string symbol name} if dtype.symbol_p = nil then begin {data type has no symbol descriptor ?} sys_msg_parm_vstr (msg_parm[1], namev); sys_message_bomb ('sst_pas_read', 'dtype_output_no_name', msg_parm, 1); end; string_hash_pos_lookup ( {get hash table position for new entry} sst_scope_p^.hash_h, {handle to hash table} namev, {name to add to hash table} pos, {returned hash table position handle} found); {returned TRUE if name already present} if found then begin {NAME already in input symbol table ?} sys_msg_parm_vstr (msg_parm[1], namev); sys_message_bomb ('sst_pas_read', 'name_dtype_dup_internal', msg_parm, 1); end; string_hash_ent_add ( {add symbol name to hash table} pos, {position handle of where to add symbol} dtype.symbol_p^.name_in_p, {returned pointer to stored symbol name} sym_pp); {returned pointing to hash ent user data area} sym_pp^ := dtype.symbol_p; {point hash entry to symbol descriptor} dtype.symbol_p^.flags := {indicate this is an intrinsic symbol} dtype.symbol_p^.flags + [sst_symflag_intrinsic_in_k]; end; { ************************************************************* * * Local subroutine INTRINSIC_DTYPE_COPY (NAME, DTYPE) * * Create a new data type symbol of name NAME. The data type will be a copy * of the data type descriptor DTYPE. An additional data type with symbol * will be created that will be a pointer to the main data type. The name * for the pointer data type will be the name of the main data type with * "_P" inserted before the last two characters. It is assumed that NAME * ends in "_T". } procedure intrinsic_dtype_copy ( in name: string_var80_t; {name of new data type symbol} in dtype: sst_dtype_t); {descriptor of data type to be copied} var namep: string_var80_t; {name of pointer data type} sym_p: sst_symbol_p_t; {points to new symbol descriptor} dt_p: sst_dtype_p_t; {points to new data type descriptor} dtp_p: sst_dtype_p_t; {points to new pointer data type descriptor} begin namep.max := sizeof(namep.str); {init local var string} sst_symbol_new_name (name, sym_p, stat); {create symbol descriptor for this name} sys_error_abort (stat, '', '', nil, 0); sst_dtype_new (dt_p); {create new data type descriptor} sym_p^.symtype := sst_symtype_dtype_k; {set up symbol to be a data type} sym_p^.dtype_dtype_p := dt_p; sym_p^.flags := [sst_symflag_def_k, sst_symflag_intrinsic_in_k]; dt_p^ := dtype; {init new data type as exact copy of DTYPE} dt_p^.symbol_p := sym_p; {customize the new data type descriptor} dt_p^.dtype := sst_dtype_copy_k; dt_p^.copy_symbol_p := dtype.symbol_p; dt_p^.copy_dtype_p := addr(dtype); { * Create pointer data type with symbol. } string_copy (name, namep); {make name of pointer data type} namep.len := namep.len - 2; string_appendn (namep, '_p_t', 4); sst_symbol_new_name (namep, sym_p, stat); {create symbol descriptor for this name} sys_error_abort (stat, '', '', nil, 0); sst_dtype_new (dtp_p); {create new data type descriptor} sym_p^.symtype := sst_symtype_dtype_k; {set up symbol to be a data type} sym_p^.dtype_dtype_p := dtp_p; sym_p^.flags := [sst_symflag_def_k, sst_symflag_intrinsic_in_k]; dtp_p^ := sst_config.int_adr_p^; {init dtype descriptor from SYS_INT_ADR_T} dtp_p^.symbol_p := sym_p; {customize the new data type descriptor} dtp_p^.dtype := sst_dtype_pnt_k; dtp_p^.pnt_dtype_p := dt_p; end; { ************************************************************* * * Local subroutine INTRINSIC_CONST_INT (NAME, VAL) * * Create an intrinsic constant with an integer value. NAME is the name * of the constant, and VAL is the constant's value. } procedure intrinsic_const_int ( in name: string; {name of new constant} in val: sys_int_machine_t); {value for new constant} var sym_p: sst_symbol_p_t; {pointer to new symbol descriptor} exp_p: sst_exp_p_t; {pointer to constant value expression} namev: string_var80_t; {var string name, upcased} begin namev.max := sizeof(namev.str); {init local var string} string_vstring (namev, name, sizeof(name)); {make var string constant name} string_downcase (namev); {these symbols are stored in lower case} sst_symbol_new_name (namev, sym_p, stat); {create new symbol descriptor} sys_error_abort (stat, '', '', nil, 0); sst_exp_const_int (val, exp_p); {create expression descriptor for const value} sym_p^.symtype := sst_symtype_const_k; {fill in symbol descriptor} sym_p^.flags := [sst_symflag_def_k, sst_symflag_intrinsic_in_k]; sym_p^.const_exp_p := exp_p; end; { ************************************************************* * * Local subroutine INTRINSIC_FUNCTION (NAME, ID) * * Add NAME to the symbol table as the front end intrinsic function with * id ID. The symbol will be installed indicating it is private to the * front end. } procedure intrinsic_function ( in name: string; {name of intrinsic function} in id: ifunc_k_t); {ID of intrinsic function} var namev: string_var32_t; {var string symbol name} sym_p: sst_symbol_p_t; {points to intrinsic func symbol descriptor} stat: sys_err_t; begin namev.max := sizeof(namev.str); {init local var string} string_vstring (namev, name, sizeof(name)); {name var string symbol name} string_downcase (namev); {these symbols are stored in lower case} sst_symbol_new_name (namev, sym_p, stat); {create and init new symbol} if sys_error(stat) then begin sys_msg_parm_vstr (msg_parm[1], namev); sys_error_abort (stat, 'sst_pas_read', 'name_ifunc_dup_internal', msg_parm, 1); end; sym_p^.symtype := sst_symtype_front_k; {symbol is private to front end} sym_p^.flags := sym_p^.flags + {symbol is defined and front-end intrinsic} [sst_symflag_def_k, sst_symflag_intrinsic_in_k]; sst_mem_alloc_scope ( {allocate memory for private front-end data} sizeof(sym_p^.front_p^), sym_p^.front_p); sym_p^.front_p^.ifunc := id; end; { ************************************************************* * * Start of main routine. } begin token.max := sizeof(token.str); {init local var strings} token2.max := sizeof(token2.str); sst_r.doit := addr(sst_r_pas_doit); {set up front end call table} intrinsic_dtype_ref ('univ_ptr', sst_dtype_uptr_p^); dtype_i16_p := nil; dtype_i32_p := nil; for i := 1 to sst_config.n_size_int do begin {loop thru available output integers} bits := sst_config.size_int[i].dtype_p^.bits_min; {number of bits this data type} if bits = 16 then begin {16 bit integer exists ?} intrinsic_dtype_ref ('integer', sst_config.size_int[i].dtype_p^); intrinsic_dtype_ref ('integer16', sst_config.size_int[i].dtype_p^); dtype_i16_p := sst_config.size_int[i].dtype_p; end; {done with 16 bit integers} if bits = 32 then begin {32 bit integer exists ?} intrinsic_dtype_ref ('integer32', sst_config.size_int[i].dtype_p^); dtype_i32_p := sst_config.size_int[i].dtype_p; end; {done with 32 bit integers} end; {back and check next available integer size} if dtype_i16_p = nil then begin {16 bit integers not available directly ?} sst_intrinsic_dtype ( 'integer', sst_dtype_int_k, (16 + sst_config.bits_adr - 1) div sst_config.bits_adr, dtype_i16_p); dtype_i16_p^.bits_min := 16; sst_intrinsic_dtype ( 'integer16', sst_dtype_int_k, (16 + sst_config.bits_adr - 1) div sst_config.bits_adr, dtype_i16_p); dtype_i16_p^.bits_min := 16; end; if dtype_i32_p = nil then begin {32 bit integer not available directly ?} sst_intrinsic_dtype ( 'integer32', sst_dtype_int_k, (32 + sst_config.bits_adr - 1) div sst_config.bits_adr, dtype_i32_p); dtype_i32_p^.bits_min := 32; end; intrinsic_dtype_ref ('single', sst_config.float_single_p^); intrinsic_dtype_ref ('double', sst_config.float_double_p^); intrinsic_dtype_ref ('real', sst_config.float_machine_p^); intrinsic_dtype_ref ('boolean', sst_dtype_bool_p^); intrinsic_dtype_ref ('char', sst_dtype_char_p^); sz := {machine addresses needed for 80 chars} ((80 * sst_config.bits_char) + sst_config.bits_adr - 1) div sst_config.bits_adr; sst_intrinsic_dtype ( 'string', sst_dtype_array_k, sz, dtype_str_p); dtype_str_p^.align_nat := sst_dtype_char_p^.align_nat; dtype_str_p^.align := sst_dtype_char_p^.align; dtype_str_p^.ar_dtype_ele_p := sst_dtype_char_p; dtype_str_p^.ar_dtype_rem_p := nil; sst_exp_const_int (1, dtype_str_p^.ar_ind_first_p); sst_exp_const_int (80, dtype_str_p^.ar_ind_last_p); dtype_str_p^.ar_ind_n := 80; dtype_str_p^.ar_n_subscr := 1; dtype_str_p^.ar_string := true; { * Create the implicit SYS_ constants. } intrinsic_const_int ('sys_bits_adr_k', sst_config.bits_adr); intrinsic_const_int ('sys_bits_char_k', sst_config.bits_char); { * Create the implicit integer type SYS_INT_ADR_T. This must be an UNSIGNED * integer of the size specified by SST_CONFIG.INT_ADR_P^. The only way we * have of faking unsigned integer data types is with subranges that start * at zero. } sst_intrinsic_dtype ( {create data type and symbol descriptors} 'sys_int_adr_t', {symbol name} sst_dtype_range_k, {basic data type ID} sst_config.int_adr_p^.size_used, {number of machine addresses actually used} dt_p); {pointer to new data type descriptor} dt_p^.range_dtype_p := sst_config.int_adr_p; {point to subrange base data type} dt_p^.range_ord_first := 0; {start of range ordinal value} dt_p^.range_n_vals := lshft(1, dt_p^.bits_min - 1); {number of values in range} sst_exp_const_int ( {create range start value expression} dt_p^.range_ord_first, {integer expression value} dt_p^.range_first_p); {returned expression descriptor pointer} sst_exp_const_int ( {create range end value expression} dt_p^.range_n_vals - 1, {integer expression value} dt_p^.range_last_p); {returned expression descriptor pointer} sst_config.int_adr_p := dt_p; {update official SYS_INT_ADR_T pointer} sst_intrinsic_dtype ( {make dtype and symbol for SYS_INT_ADR_P_T} 'sys_int_adr_p_t', {symbol name} sst_dtype_pnt_k, {basic data type ID} sst_config.int_adr_p^.size_used, {number of machine addresses actually used} dt_p); {pointer to new data type descriptor} dt_p^.pnt_dtype_p := sst_config.int_adr_p; {pointer to SYS_INT_ADR_T data type} { * Create the other implicit SYS_ data types. } intrinsic_dtype_copy (string_v('sys_int_machine_t'), sst_config.int_machine_p^); intrinsic_dtype_copy (string_v('sys_int_max_t'), sst_config.size_int[sst_config.n_size_int].dtype_p^); intrinsic_dtype_copy (string_v('sys_fp1_t'), sst_config.float_single_p^); intrinsic_dtype_copy (string_v('sys_fp2_t'), sst_config.float_double_p^); intrinsic_dtype_copy (string_v('sys_fp_machine_t'), sst_config.float_machine_p^); intrinsic_dtype_copy (string_v('sys_fp_max_t'), sst_config.size_float[sst_config.n_size_float].dtype_p^); for i := 1 to sst_config.n_size_int do begin {look thru all the integer sizes} if sst_config.size_int[i].size = sst_config.float_single_p^.size_used then begin intrinsic_dtype_copy (string_v('sys_int_fp1_t'), sst_config.size_int[i].dtype_p^); end; if sst_config.size_int[i].size = sst_config.float_double_p^.size_used then begin intrinsic_dtype_copy (string_v('sys_int_fp2_t'), sst_config.size_int[i].dtype_p^); end; end; bits := 0; {init number of bits in curr dtype} j := 0; {init index into SIZE_INT array} for i := 1 to sst_config.size_int[sst_config.n_size_int].dtype_p^.bits_min do begin if i > bits then begin {we need the next integer size up ?} j := j + 1; {make index to next integer size up} bits := sst_config.size_int[j].size * sst_config.bits_adr; end; string_f_int (token2, i); {make number of bits name string} token.len := 0; {declare this MIN data type} string_appends (token, 'sys_int_min'); string_append (token, token2); string_appendn (token, '_t', 2); intrinsic_dtype_copy (token, sst_config.size_int[j].dtype_p^); token.len := 0; {declare this CONV data type} string_appends (token, 'sys_int_conv'); string_append (token, token2); string_appendn (token, '_t', 2); if i >= sst_config.int_machine_p^.size_used then begin {same size of larger than machine int} intrinsic_dtype_copy (token, sst_config.size_int[j].dtype_p^); end else begin {smaller than machine int} intrinsic_dtype_copy (token, sst_config.int_machine_p^); end ; end; {back for next higher number of bits} { * Create intrinsic functions. } intrinsic_function ('abs', ifunc_abs_k); intrinsic_function ('addr', ifunc_addr_k); intrinsic_function ('arctan', ifunc_arctan_k); intrinsic_function ('arshft', ifunc_arshft_k); intrinsic_function ('chr', ifunc_chr_k); intrinsic_function ('cos', ifunc_cos_k); intrinsic_function ('exp', ifunc_exp_k); intrinsic_function ('firstof', ifunc_firstof_k); intrinsic_function ('lastof', ifunc_lastof_k); intrinsic_function ('ln', ifunc_ln_k); intrinsic_function ('lshft', ifunc_lshft_k); intrinsic_function ('max', ifunc_max_k); intrinsic_function ('min', ifunc_min_k); intrinsic_function ('odd', ifunc_odd_k); intrinsic_function ('ord', ifunc_ord_k); intrinsic_function ('pred', ifunc_pred_k); intrinsic_function ('round', ifunc_round_k); intrinsic_function ('rshft', ifunc_rshft_k); intrinsic_function ('sin', ifunc_sin_k); intrinsic_function ('sizeof', ifunc_sizeof_k); intrinsic_function ('sqr', ifunc_sqr_k); intrinsic_function ('sqrt', ifunc_sqrt_k); intrinsic_function ('succ', ifunc_succ_k); intrinsic_function ('trunc', ifunc_trunc_k); intrinsic_function ('xor', ifunc_xor_k); intrinsic_function ('alignof', ifunc_alignof_k); intrinsic_function ('arctan2', ifunc_arctan2_k); intrinsic_function ('offset', ifunc_offset_k); intrinsic_function ('shift', ifunc_shift_k); intrinsic_function ('size_align', ifunc_sizeof_k); intrinsic_function ('size_char', ifunc_szchar_k); intrinsic_function ('size_min', ifunc_szmin_k); intrinsic_function ('setof', ifunc_setof_k); intrinsic_function ('val', ifunc_val_k); { * Init other values in the common block. } error_syo_found := false; {init to no syntax error} addr_of := false; {init to not doing arg of ADDR function} top_block := top_block_none_k; {not in top block yet} nest_level := 0; {init block nesting level} end;
unit ControlTestForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Panel3D, OutputEngine, RMEngineInt, Engine3D, Dresser, ClassLibrary, VisualClasses, Notifications, ExtCtrls; type TfrmControlTest = class(TForm, IHook) procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); private fInitialized : boolean; fActive : boolean; fDresser : IMeshDresser; fClassRenderer : IVisualClassesRenderer; fClassLibrary : TClassLibrary; fClassContainer : TClassContainer; fAnimated : I3DAnimated; fCamera : I3DCamera; fPanel3D : T3DPanel; procedure InitNotifications; procedure InitClasses; procedure CreateScene; procedure OnIdle(Sender: TObject; var Done: Boolean); function InsertObject( x, y, z : T3DValue; Parent : I3DObject; ClassId : cardinal ) : I3DMesh; procedure Notify( Event : TEventClass; const Info ); end; var frmControlTest: TfrmControlTest; implementation uses RMDresser, AmbientEffectsInt, AmbientEffects, D3DRMDef, Events; const CLASSID_GUY = 100; {$R *.DFM} procedure TfrmControlTest.FormCreate(Sender: TObject); begin InitNotifications; fPanel3D := T3DPanel.Create( self ); fPanel3D.Parent := self; fPanel3D.Top := 100; fPanel3D.Left := 100; fPanel3D.Width := 200; fPanel3D.Height := 200; fInitialized := false; fActive := false; Application.OnIdle := OnIdle; end; procedure TfrmControlTest.FormActivate(Sender: TObject); var VideoModeId : TVideoModeId; begin fActive := Application.Active; if fActive then begin if not fInitialized then begin if fPanel3D.Initialize3D( DMMODE_WINDOWED ) then begin fInitialized := true; fInitialized := fPanel3D.DDOutputEngine.FindVideoMode( 640, 480, 16, VideoModeId ) and SUCCEEDED(fPanel3D.DDOutputEngine.setVideoMode( VideoModeId )); InitClasses; CreateScene; end; end; end; end; type TDrawArea = class( TInterfacedObject, IDrawArea ) public x, y, width, height : DWORD; function getX : DWORD; function getY : DWORD; function getWidth : DWORD; function getHeight : DWORD; end; // TDrawArea function TDrawArea.getX : DWORD; begin result := x; end; function TDrawArea.getY : DWORD; begin result := y; end; function TDrawArea.getWidth : DWORD; begin result := width; end; function TDrawArea.getHeight : DWORD; begin result := height; end; function CreateDrawArea( x, y, width, height : DWORD ) : IDrawArea; var DA : TDrawArea; begin DA := TDrawArea.Create; DA.x := x; DA.y := y; DA.width := width; DA.height := height; result := DA; end; procedure TfrmControlTest.InitNotifications; begin InitNotificationEngine; RegisterEventClass( evAnimationFinishes, 0 ); RegisterEventClass( evCameraMove, 0 ); RegisterEventClass( evCameraCreated, 0 ); RegisterEventClass( evCameraRemoved, 0 ); end; procedure TfrmControlTest.InitClasses; var i : integer; begin fClassContainer := TClassContainer.Create; fClassContainer.AddSearchPath( '\work\pd client\release\classes' ); fClassContainer.RegisterClasses; fClassLibrary := TClassLibrary.Create; fDresser := TRetainedModeDresser.Create( fClassLibrary, fPanel3D.Engine3D as ID3DRMEngine ); fClassRenderer := fDresser as IVisualClassesRenderer; for i := 0 to pred(fClassContainer.Count) do fClassRenderer.RenderVisualClass( fClassContainer.Classes[i] ); end; procedure TfrmControlTest.CreateScene; var XCamera : I3DCamera; Viewport1 : I3DViewport; Viewport2 : I3DViewport; Light : I3DLight; Mesh : I3DMesh; begin fPanel3D.Engine3D.AddEventHook( evAnimationFinishes, self ); fPanel3D.Engine3D.CreateCamera( 0, nil, fCamera ); fPanel3D.Engine3D.CreateViewport( CreateDrawArea( 0, 0, 200, 200 ), fCamera, Viewport1 ); fCamera.setVisualRange( 1, 50000 ); fPanel3D.Engine3D.CreateLight( LIGHT_DIRECTIONAL, nil, Light ); Light.setPosition( 0, 0, 500 ); Light.SetOrientation(0, 0, -1, 0, 1, 0); Light.setRGBColor( 1, 1, 1 ); fPanel3D.Engine3D.CreateLight( LIGHT_AMBIENT, nil, Light ); Light.setRGBColor( 0.6, 0.6, 0.6 ); Mesh := InsertObject( 0, 0, 150, nil, CLASSID_GUY ) as I3DMesh; Mesh.SetOrientation(0, 0, 1, 0, 1, 0); fAnimated := Mesh as I3DAnimated; fAnimated.Animate( 105 ); fPanel3D.Engine3D.CreateCamera( 0, Mesh, XCamera ); XCamera.SetPosition( 0, 0, 300 ); XCamera.SetOrientation(0, 0, -1, 0, 1, 0); XCamera.setVisualRange(1, 600 ); fPanel3D.Engine3D.CreateViewport( CreateDrawArea( 0, 200, 200, 200 ), XCamera, Viewport2 ); end; procedure TfrmControlTest.OnIdle(Sender: TObject; var Done: Boolean); begin try if (fInitialized and fActive) then begin fPanel3D.Engine3D.Move( 1 ); fPanel3D.Engine3D.Render; Done := false; end; except end; end; function TfrmControlTest.InsertObject( x, y, z : T3DValue; Parent : I3DObject; ClassId : cardinal ) : I3DMesh; var Obj : I3DObject; Mesh : I3DMesh; begin if SUCCEEDED(fPanel3D.Engine3D.CreateObject( OBJTYPE_MESH, Parent, 0, Obj )) then begin Mesh := Obj as I3DMesh; fDresser.DressMesh( Mesh, ClassId ); Mesh.SetPosition( x, y, z ); result := Mesh; end; end; procedure TfrmControlTest.Notify( Event : TEventClass; const Info ); begin fAnimated.Animate( 100 + random(6) ); end; end.
unit ConsultationMarkKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы ConsultationMark } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Consultation\ConsultationMarkKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "ConsultationMarkKeywordsPack" MUID: (18755A78D1B1) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3IntfUses , vtGroupBox , vtRadioButton , vtPanel , vtLabel , eeMemoWithEditOperations ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3ImplUses , ConsultationMark_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_ConsultationMark = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы ConsultationMark ---- *Пример использования*: [code] 'aControl' форма::ConsultationMark TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_ConsultationMark Tkw_ConsultationMark_Control_gbMark = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола gbMark ---- *Пример использования*: [code] контрол::gbMark TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_gbMark Tkw_ConsultationMark_Control_gbMark_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола gbMark ---- *Пример использования*: [code] контрол::gbMark:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_gbMark_Push Tkw_ConsultationMark_Control_rbNotSure = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола rbNotSure ---- *Пример использования*: [code] контрол::rbNotSure TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_rbNotSure Tkw_ConsultationMark_Control_rbNotSure_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола rbNotSure ---- *Пример использования*: [code] контрол::rbNotSure:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_rbNotSure_Push Tkw_ConsultationMark_Control_rbTwo = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола rbTwo ---- *Пример использования*: [code] контрол::rbTwo TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_rbTwo Tkw_ConsultationMark_Control_rbTwo_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола rbTwo ---- *Пример использования*: [code] контрол::rbTwo:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_rbTwo_Push Tkw_ConsultationMark_Control_rbThree = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола rbThree ---- *Пример использования*: [code] контрол::rbThree TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_rbThree Tkw_ConsultationMark_Control_rbThree_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола rbThree ---- *Пример использования*: [code] контрол::rbThree:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_rbThree_Push Tkw_ConsultationMark_Control_rbFour = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола rbFour ---- *Пример использования*: [code] контрол::rbFour TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_rbFour Tkw_ConsultationMark_Control_rbFour_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола rbFour ---- *Пример использования*: [code] контрол::rbFour:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_rbFour_Push Tkw_ConsultationMark_Control_rbFive = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола rbFive ---- *Пример использования*: [code] контрол::rbFive TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_rbFive Tkw_ConsultationMark_Control_rbFive_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола rbFive ---- *Пример использования*: [code] контрол::rbFive:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_rbFive_Push Tkw_ConsultationMark_Control_pnlHelp = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола pnlHelp ---- *Пример использования*: [code] контрол::pnlHelp TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_pnlHelp Tkw_ConsultationMark_Control_pnlHelp_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола pnlHelp ---- *Пример использования*: [code] контрол::pnlHelp:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_pnlHelp_Push Tkw_ConsultationMark_Control_lblHelp = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола lblHelp ---- *Пример использования*: [code] контрол::lblHelp TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_lblHelp Tkw_ConsultationMark_Control_lblHelp_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола lblHelp ---- *Пример использования*: [code] контрол::lblHelp:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_lblHelp_Push Tkw_ConsultationMark_Control_gbComment = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола gbComment ---- *Пример использования*: [code] контрол::gbComment TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_gbComment Tkw_ConsultationMark_Control_gbComment_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола gbComment ---- *Пример использования*: [code] контрол::gbComment:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_gbComment_Push Tkw_ConsultationMark_Control_mComment = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола mComment ---- *Пример использования*: [code] контрол::mComment TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_mComment Tkw_ConsultationMark_Control_mComment_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола mComment ---- *Пример использования*: [code] контрол::mComment:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ConsultationMark_Control_mComment_Push TkwEnConsultationMarkGbMark = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_ConsultationMark.gbMark } private function gbMark(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtGroupBox; {* Реализация слова скрипта .Ten_ConsultationMark.gbMark } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnConsultationMarkGbMark TkwEnConsultationMarkRbNotSure = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_ConsultationMark.rbNotSure } private function rbNotSure(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtRadioButton; {* Реализация слова скрипта .Ten_ConsultationMark.rbNotSure } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnConsultationMarkRbNotSure TkwEnConsultationMarkRbTwo = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_ConsultationMark.rbTwo } private function rbTwo(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtRadioButton; {* Реализация слова скрипта .Ten_ConsultationMark.rbTwo } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnConsultationMarkRbTwo TkwEnConsultationMarkRbThree = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_ConsultationMark.rbThree } private function rbThree(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtRadioButton; {* Реализация слова скрипта .Ten_ConsultationMark.rbThree } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnConsultationMarkRbThree TkwEnConsultationMarkRbFour = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_ConsultationMark.rbFour } private function rbFour(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtRadioButton; {* Реализация слова скрипта .Ten_ConsultationMark.rbFour } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnConsultationMarkRbFour TkwEnConsultationMarkRbFive = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_ConsultationMark.rbFive } private function rbFive(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtRadioButton; {* Реализация слова скрипта .Ten_ConsultationMark.rbFive } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnConsultationMarkRbFive TkwEnConsultationMarkPnlHelp = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_ConsultationMark.pnlHelp } private function pnlHelp(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtPanel; {* Реализация слова скрипта .Ten_ConsultationMark.pnlHelp } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnConsultationMarkPnlHelp TkwEnConsultationMarkLblHelp = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_ConsultationMark.lblHelp } private function lblHelp(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtLabel; {* Реализация слова скрипта .Ten_ConsultationMark.lblHelp } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnConsultationMarkLblHelp TkwEnConsultationMarkGbComment = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_ConsultationMark.gbComment } private function gbComment(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtGroupBox; {* Реализация слова скрипта .Ten_ConsultationMark.gbComment } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnConsultationMarkGbComment TkwEnConsultationMarkMComment = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_ConsultationMark.mComment } private function mComment(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TeeMemoWithEditOperations; {* Реализация слова скрипта .Ten_ConsultationMark.mComment } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnConsultationMarkMComment function Tkw_Form_ConsultationMark.GetString: AnsiString; begin Result := 'en_ConsultationMark'; end;//Tkw_Form_ConsultationMark.GetString class function Tkw_Form_ConsultationMark.GetWordNameForRegister: AnsiString; begin Result := 'форма::ConsultationMark'; end;//Tkw_Form_ConsultationMark.GetWordNameForRegister function Tkw_ConsultationMark_Control_gbMark.GetString: AnsiString; begin Result := 'gbMark'; end;//Tkw_ConsultationMark_Control_gbMark.GetString class procedure Tkw_ConsultationMark_Control_gbMark.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtGroupBox); end;//Tkw_ConsultationMark_Control_gbMark.RegisterInEngine class function Tkw_ConsultationMark_Control_gbMark.GetWordNameForRegister: AnsiString; begin Result := 'контрол::gbMark'; end;//Tkw_ConsultationMark_Control_gbMark.GetWordNameForRegister procedure Tkw_ConsultationMark_Control_gbMark_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('gbMark'); inherited; end;//Tkw_ConsultationMark_Control_gbMark_Push.DoDoIt class function Tkw_ConsultationMark_Control_gbMark_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::gbMark:push'; end;//Tkw_ConsultationMark_Control_gbMark_Push.GetWordNameForRegister function Tkw_ConsultationMark_Control_rbNotSure.GetString: AnsiString; begin Result := 'rbNotSure'; end;//Tkw_ConsultationMark_Control_rbNotSure.GetString class procedure Tkw_ConsultationMark_Control_rbNotSure.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtRadioButton); end;//Tkw_ConsultationMark_Control_rbNotSure.RegisterInEngine class function Tkw_ConsultationMark_Control_rbNotSure.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbNotSure'; end;//Tkw_ConsultationMark_Control_rbNotSure.GetWordNameForRegister procedure Tkw_ConsultationMark_Control_rbNotSure_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('rbNotSure'); inherited; end;//Tkw_ConsultationMark_Control_rbNotSure_Push.DoDoIt class function Tkw_ConsultationMark_Control_rbNotSure_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbNotSure:push'; end;//Tkw_ConsultationMark_Control_rbNotSure_Push.GetWordNameForRegister function Tkw_ConsultationMark_Control_rbTwo.GetString: AnsiString; begin Result := 'rbTwo'; end;//Tkw_ConsultationMark_Control_rbTwo.GetString class procedure Tkw_ConsultationMark_Control_rbTwo.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtRadioButton); end;//Tkw_ConsultationMark_Control_rbTwo.RegisterInEngine class function Tkw_ConsultationMark_Control_rbTwo.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbTwo'; end;//Tkw_ConsultationMark_Control_rbTwo.GetWordNameForRegister procedure Tkw_ConsultationMark_Control_rbTwo_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('rbTwo'); inherited; end;//Tkw_ConsultationMark_Control_rbTwo_Push.DoDoIt class function Tkw_ConsultationMark_Control_rbTwo_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbTwo:push'; end;//Tkw_ConsultationMark_Control_rbTwo_Push.GetWordNameForRegister function Tkw_ConsultationMark_Control_rbThree.GetString: AnsiString; begin Result := 'rbThree'; end;//Tkw_ConsultationMark_Control_rbThree.GetString class procedure Tkw_ConsultationMark_Control_rbThree.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtRadioButton); end;//Tkw_ConsultationMark_Control_rbThree.RegisterInEngine class function Tkw_ConsultationMark_Control_rbThree.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbThree'; end;//Tkw_ConsultationMark_Control_rbThree.GetWordNameForRegister procedure Tkw_ConsultationMark_Control_rbThree_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('rbThree'); inherited; end;//Tkw_ConsultationMark_Control_rbThree_Push.DoDoIt class function Tkw_ConsultationMark_Control_rbThree_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbThree:push'; end;//Tkw_ConsultationMark_Control_rbThree_Push.GetWordNameForRegister function Tkw_ConsultationMark_Control_rbFour.GetString: AnsiString; begin Result := 'rbFour'; end;//Tkw_ConsultationMark_Control_rbFour.GetString class procedure Tkw_ConsultationMark_Control_rbFour.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtRadioButton); end;//Tkw_ConsultationMark_Control_rbFour.RegisterInEngine class function Tkw_ConsultationMark_Control_rbFour.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbFour'; end;//Tkw_ConsultationMark_Control_rbFour.GetWordNameForRegister procedure Tkw_ConsultationMark_Control_rbFour_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('rbFour'); inherited; end;//Tkw_ConsultationMark_Control_rbFour_Push.DoDoIt class function Tkw_ConsultationMark_Control_rbFour_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbFour:push'; end;//Tkw_ConsultationMark_Control_rbFour_Push.GetWordNameForRegister function Tkw_ConsultationMark_Control_rbFive.GetString: AnsiString; begin Result := 'rbFive'; end;//Tkw_ConsultationMark_Control_rbFive.GetString class procedure Tkw_ConsultationMark_Control_rbFive.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtRadioButton); end;//Tkw_ConsultationMark_Control_rbFive.RegisterInEngine class function Tkw_ConsultationMark_Control_rbFive.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbFive'; end;//Tkw_ConsultationMark_Control_rbFive.GetWordNameForRegister procedure Tkw_ConsultationMark_Control_rbFive_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('rbFive'); inherited; end;//Tkw_ConsultationMark_Control_rbFive_Push.DoDoIt class function Tkw_ConsultationMark_Control_rbFive_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbFive:push'; end;//Tkw_ConsultationMark_Control_rbFive_Push.GetWordNameForRegister function Tkw_ConsultationMark_Control_pnlHelp.GetString: AnsiString; begin Result := 'pnlHelp'; end;//Tkw_ConsultationMark_Control_pnlHelp.GetString class procedure Tkw_ConsultationMark_Control_pnlHelp.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_ConsultationMark_Control_pnlHelp.RegisterInEngine class function Tkw_ConsultationMark_Control_pnlHelp.GetWordNameForRegister: AnsiString; begin Result := 'контрол::pnlHelp'; end;//Tkw_ConsultationMark_Control_pnlHelp.GetWordNameForRegister procedure Tkw_ConsultationMark_Control_pnlHelp_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('pnlHelp'); inherited; end;//Tkw_ConsultationMark_Control_pnlHelp_Push.DoDoIt class function Tkw_ConsultationMark_Control_pnlHelp_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::pnlHelp:push'; end;//Tkw_ConsultationMark_Control_pnlHelp_Push.GetWordNameForRegister function Tkw_ConsultationMark_Control_lblHelp.GetString: AnsiString; begin Result := 'lblHelp'; end;//Tkw_ConsultationMark_Control_lblHelp.GetString class procedure Tkw_ConsultationMark_Control_lblHelp.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtLabel); end;//Tkw_ConsultationMark_Control_lblHelp.RegisterInEngine class function Tkw_ConsultationMark_Control_lblHelp.GetWordNameForRegister: AnsiString; begin Result := 'контрол::lblHelp'; end;//Tkw_ConsultationMark_Control_lblHelp.GetWordNameForRegister procedure Tkw_ConsultationMark_Control_lblHelp_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('lblHelp'); inherited; end;//Tkw_ConsultationMark_Control_lblHelp_Push.DoDoIt class function Tkw_ConsultationMark_Control_lblHelp_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::lblHelp:push'; end;//Tkw_ConsultationMark_Control_lblHelp_Push.GetWordNameForRegister function Tkw_ConsultationMark_Control_gbComment.GetString: AnsiString; begin Result := 'gbComment'; end;//Tkw_ConsultationMark_Control_gbComment.GetString class procedure Tkw_ConsultationMark_Control_gbComment.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtGroupBox); end;//Tkw_ConsultationMark_Control_gbComment.RegisterInEngine class function Tkw_ConsultationMark_Control_gbComment.GetWordNameForRegister: AnsiString; begin Result := 'контрол::gbComment'; end;//Tkw_ConsultationMark_Control_gbComment.GetWordNameForRegister procedure Tkw_ConsultationMark_Control_gbComment_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('gbComment'); inherited; end;//Tkw_ConsultationMark_Control_gbComment_Push.DoDoIt class function Tkw_ConsultationMark_Control_gbComment_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::gbComment:push'; end;//Tkw_ConsultationMark_Control_gbComment_Push.GetWordNameForRegister function Tkw_ConsultationMark_Control_mComment.GetString: AnsiString; begin Result := 'mComment'; end;//Tkw_ConsultationMark_Control_mComment.GetString class procedure Tkw_ConsultationMark_Control_mComment.RegisterInEngine; begin inherited; TtfwClassRef.Register(TeeMemoWithEditOperations); end;//Tkw_ConsultationMark_Control_mComment.RegisterInEngine class function Tkw_ConsultationMark_Control_mComment.GetWordNameForRegister: AnsiString; begin Result := 'контрол::mComment'; end;//Tkw_ConsultationMark_Control_mComment.GetWordNameForRegister procedure Tkw_ConsultationMark_Control_mComment_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('mComment'); inherited; end;//Tkw_ConsultationMark_Control_mComment_Push.DoDoIt class function Tkw_ConsultationMark_Control_mComment_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::mComment:push'; end;//Tkw_ConsultationMark_Control_mComment_Push.GetWordNameForRegister function TkwEnConsultationMarkGbMark.gbMark(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtGroupBox; {* Реализация слова скрипта .Ten_ConsultationMark.gbMark } begin Result := aen_ConsultationMark.gbMark; end;//TkwEnConsultationMarkGbMark.gbMark class function TkwEnConsultationMarkGbMark.GetWordNameForRegister: AnsiString; begin Result := '.Ten_ConsultationMark.gbMark'; end;//TkwEnConsultationMarkGbMark.GetWordNameForRegister function TkwEnConsultationMarkGbMark.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtGroupBox); end;//TkwEnConsultationMarkGbMark.GetResultTypeInfo function TkwEnConsultationMarkGbMark.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnConsultationMarkGbMark.GetAllParamsCount function TkwEnConsultationMarkGbMark.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_ConsultationMark)]); end;//TkwEnConsultationMarkGbMark.ParamsTypes procedure TkwEnConsultationMarkGbMark.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству gbMark', aCtx); end;//TkwEnConsultationMarkGbMark.SetValuePrim procedure TkwEnConsultationMarkGbMark.DoDoIt(const aCtx: TtfwContext); var l_aen_ConsultationMark: Ten_ConsultationMark; begin try l_aen_ConsultationMark := Ten_ConsultationMark(aCtx.rEngine.PopObjAs(Ten_ConsultationMark)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_ConsultationMark: Ten_ConsultationMark : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(gbMark(aCtx, l_aen_ConsultationMark)); end;//TkwEnConsultationMarkGbMark.DoDoIt function TkwEnConsultationMarkRbNotSure.rbNotSure(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtRadioButton; {* Реализация слова скрипта .Ten_ConsultationMark.rbNotSure } begin Result := aen_ConsultationMark.rbNotSure; end;//TkwEnConsultationMarkRbNotSure.rbNotSure class function TkwEnConsultationMarkRbNotSure.GetWordNameForRegister: AnsiString; begin Result := '.Ten_ConsultationMark.rbNotSure'; end;//TkwEnConsultationMarkRbNotSure.GetWordNameForRegister function TkwEnConsultationMarkRbNotSure.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtRadioButton); end;//TkwEnConsultationMarkRbNotSure.GetResultTypeInfo function TkwEnConsultationMarkRbNotSure.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnConsultationMarkRbNotSure.GetAllParamsCount function TkwEnConsultationMarkRbNotSure.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_ConsultationMark)]); end;//TkwEnConsultationMarkRbNotSure.ParamsTypes procedure TkwEnConsultationMarkRbNotSure.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству rbNotSure', aCtx); end;//TkwEnConsultationMarkRbNotSure.SetValuePrim procedure TkwEnConsultationMarkRbNotSure.DoDoIt(const aCtx: TtfwContext); var l_aen_ConsultationMark: Ten_ConsultationMark; begin try l_aen_ConsultationMark := Ten_ConsultationMark(aCtx.rEngine.PopObjAs(Ten_ConsultationMark)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_ConsultationMark: Ten_ConsultationMark : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(rbNotSure(aCtx, l_aen_ConsultationMark)); end;//TkwEnConsultationMarkRbNotSure.DoDoIt function TkwEnConsultationMarkRbTwo.rbTwo(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtRadioButton; {* Реализация слова скрипта .Ten_ConsultationMark.rbTwo } begin Result := aen_ConsultationMark.rbTwo; end;//TkwEnConsultationMarkRbTwo.rbTwo class function TkwEnConsultationMarkRbTwo.GetWordNameForRegister: AnsiString; begin Result := '.Ten_ConsultationMark.rbTwo'; end;//TkwEnConsultationMarkRbTwo.GetWordNameForRegister function TkwEnConsultationMarkRbTwo.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtRadioButton); end;//TkwEnConsultationMarkRbTwo.GetResultTypeInfo function TkwEnConsultationMarkRbTwo.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnConsultationMarkRbTwo.GetAllParamsCount function TkwEnConsultationMarkRbTwo.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_ConsultationMark)]); end;//TkwEnConsultationMarkRbTwo.ParamsTypes procedure TkwEnConsultationMarkRbTwo.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству rbTwo', aCtx); end;//TkwEnConsultationMarkRbTwo.SetValuePrim procedure TkwEnConsultationMarkRbTwo.DoDoIt(const aCtx: TtfwContext); var l_aen_ConsultationMark: Ten_ConsultationMark; begin try l_aen_ConsultationMark := Ten_ConsultationMark(aCtx.rEngine.PopObjAs(Ten_ConsultationMark)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_ConsultationMark: Ten_ConsultationMark : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(rbTwo(aCtx, l_aen_ConsultationMark)); end;//TkwEnConsultationMarkRbTwo.DoDoIt function TkwEnConsultationMarkRbThree.rbThree(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtRadioButton; {* Реализация слова скрипта .Ten_ConsultationMark.rbThree } begin Result := aen_ConsultationMark.rbThree; end;//TkwEnConsultationMarkRbThree.rbThree class function TkwEnConsultationMarkRbThree.GetWordNameForRegister: AnsiString; begin Result := '.Ten_ConsultationMark.rbThree'; end;//TkwEnConsultationMarkRbThree.GetWordNameForRegister function TkwEnConsultationMarkRbThree.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtRadioButton); end;//TkwEnConsultationMarkRbThree.GetResultTypeInfo function TkwEnConsultationMarkRbThree.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnConsultationMarkRbThree.GetAllParamsCount function TkwEnConsultationMarkRbThree.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_ConsultationMark)]); end;//TkwEnConsultationMarkRbThree.ParamsTypes procedure TkwEnConsultationMarkRbThree.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству rbThree', aCtx); end;//TkwEnConsultationMarkRbThree.SetValuePrim procedure TkwEnConsultationMarkRbThree.DoDoIt(const aCtx: TtfwContext); var l_aen_ConsultationMark: Ten_ConsultationMark; begin try l_aen_ConsultationMark := Ten_ConsultationMark(aCtx.rEngine.PopObjAs(Ten_ConsultationMark)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_ConsultationMark: Ten_ConsultationMark : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(rbThree(aCtx, l_aen_ConsultationMark)); end;//TkwEnConsultationMarkRbThree.DoDoIt function TkwEnConsultationMarkRbFour.rbFour(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtRadioButton; {* Реализация слова скрипта .Ten_ConsultationMark.rbFour } begin Result := aen_ConsultationMark.rbFour; end;//TkwEnConsultationMarkRbFour.rbFour class function TkwEnConsultationMarkRbFour.GetWordNameForRegister: AnsiString; begin Result := '.Ten_ConsultationMark.rbFour'; end;//TkwEnConsultationMarkRbFour.GetWordNameForRegister function TkwEnConsultationMarkRbFour.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtRadioButton); end;//TkwEnConsultationMarkRbFour.GetResultTypeInfo function TkwEnConsultationMarkRbFour.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnConsultationMarkRbFour.GetAllParamsCount function TkwEnConsultationMarkRbFour.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_ConsultationMark)]); end;//TkwEnConsultationMarkRbFour.ParamsTypes procedure TkwEnConsultationMarkRbFour.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству rbFour', aCtx); end;//TkwEnConsultationMarkRbFour.SetValuePrim procedure TkwEnConsultationMarkRbFour.DoDoIt(const aCtx: TtfwContext); var l_aen_ConsultationMark: Ten_ConsultationMark; begin try l_aen_ConsultationMark := Ten_ConsultationMark(aCtx.rEngine.PopObjAs(Ten_ConsultationMark)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_ConsultationMark: Ten_ConsultationMark : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(rbFour(aCtx, l_aen_ConsultationMark)); end;//TkwEnConsultationMarkRbFour.DoDoIt function TkwEnConsultationMarkRbFive.rbFive(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtRadioButton; {* Реализация слова скрипта .Ten_ConsultationMark.rbFive } begin Result := aen_ConsultationMark.rbFive; end;//TkwEnConsultationMarkRbFive.rbFive class function TkwEnConsultationMarkRbFive.GetWordNameForRegister: AnsiString; begin Result := '.Ten_ConsultationMark.rbFive'; end;//TkwEnConsultationMarkRbFive.GetWordNameForRegister function TkwEnConsultationMarkRbFive.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtRadioButton); end;//TkwEnConsultationMarkRbFive.GetResultTypeInfo function TkwEnConsultationMarkRbFive.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnConsultationMarkRbFive.GetAllParamsCount function TkwEnConsultationMarkRbFive.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_ConsultationMark)]); end;//TkwEnConsultationMarkRbFive.ParamsTypes procedure TkwEnConsultationMarkRbFive.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству rbFive', aCtx); end;//TkwEnConsultationMarkRbFive.SetValuePrim procedure TkwEnConsultationMarkRbFive.DoDoIt(const aCtx: TtfwContext); var l_aen_ConsultationMark: Ten_ConsultationMark; begin try l_aen_ConsultationMark := Ten_ConsultationMark(aCtx.rEngine.PopObjAs(Ten_ConsultationMark)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_ConsultationMark: Ten_ConsultationMark : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(rbFive(aCtx, l_aen_ConsultationMark)); end;//TkwEnConsultationMarkRbFive.DoDoIt function TkwEnConsultationMarkPnlHelp.pnlHelp(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtPanel; {* Реализация слова скрипта .Ten_ConsultationMark.pnlHelp } begin Result := aen_ConsultationMark.pnlHelp; end;//TkwEnConsultationMarkPnlHelp.pnlHelp class function TkwEnConsultationMarkPnlHelp.GetWordNameForRegister: AnsiString; begin Result := '.Ten_ConsultationMark.pnlHelp'; end;//TkwEnConsultationMarkPnlHelp.GetWordNameForRegister function TkwEnConsultationMarkPnlHelp.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwEnConsultationMarkPnlHelp.GetResultTypeInfo function TkwEnConsultationMarkPnlHelp.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnConsultationMarkPnlHelp.GetAllParamsCount function TkwEnConsultationMarkPnlHelp.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_ConsultationMark)]); end;//TkwEnConsultationMarkPnlHelp.ParamsTypes procedure TkwEnConsultationMarkPnlHelp.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству pnlHelp', aCtx); end;//TkwEnConsultationMarkPnlHelp.SetValuePrim procedure TkwEnConsultationMarkPnlHelp.DoDoIt(const aCtx: TtfwContext); var l_aen_ConsultationMark: Ten_ConsultationMark; begin try l_aen_ConsultationMark := Ten_ConsultationMark(aCtx.rEngine.PopObjAs(Ten_ConsultationMark)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_ConsultationMark: Ten_ConsultationMark : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(pnlHelp(aCtx, l_aen_ConsultationMark)); end;//TkwEnConsultationMarkPnlHelp.DoDoIt function TkwEnConsultationMarkLblHelp.lblHelp(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtLabel; {* Реализация слова скрипта .Ten_ConsultationMark.lblHelp } begin Result := aen_ConsultationMark.lblHelp; end;//TkwEnConsultationMarkLblHelp.lblHelp class function TkwEnConsultationMarkLblHelp.GetWordNameForRegister: AnsiString; begin Result := '.Ten_ConsultationMark.lblHelp'; end;//TkwEnConsultationMarkLblHelp.GetWordNameForRegister function TkwEnConsultationMarkLblHelp.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtLabel); end;//TkwEnConsultationMarkLblHelp.GetResultTypeInfo function TkwEnConsultationMarkLblHelp.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnConsultationMarkLblHelp.GetAllParamsCount function TkwEnConsultationMarkLblHelp.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_ConsultationMark)]); end;//TkwEnConsultationMarkLblHelp.ParamsTypes procedure TkwEnConsultationMarkLblHelp.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству lblHelp', aCtx); end;//TkwEnConsultationMarkLblHelp.SetValuePrim procedure TkwEnConsultationMarkLblHelp.DoDoIt(const aCtx: TtfwContext); var l_aen_ConsultationMark: Ten_ConsultationMark; begin try l_aen_ConsultationMark := Ten_ConsultationMark(aCtx.rEngine.PopObjAs(Ten_ConsultationMark)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_ConsultationMark: Ten_ConsultationMark : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(lblHelp(aCtx, l_aen_ConsultationMark)); end;//TkwEnConsultationMarkLblHelp.DoDoIt function TkwEnConsultationMarkGbComment.gbComment(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TvtGroupBox; {* Реализация слова скрипта .Ten_ConsultationMark.gbComment } begin Result := aen_ConsultationMark.gbComment; end;//TkwEnConsultationMarkGbComment.gbComment class function TkwEnConsultationMarkGbComment.GetWordNameForRegister: AnsiString; begin Result := '.Ten_ConsultationMark.gbComment'; end;//TkwEnConsultationMarkGbComment.GetWordNameForRegister function TkwEnConsultationMarkGbComment.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtGroupBox); end;//TkwEnConsultationMarkGbComment.GetResultTypeInfo function TkwEnConsultationMarkGbComment.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnConsultationMarkGbComment.GetAllParamsCount function TkwEnConsultationMarkGbComment.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_ConsultationMark)]); end;//TkwEnConsultationMarkGbComment.ParamsTypes procedure TkwEnConsultationMarkGbComment.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству gbComment', aCtx); end;//TkwEnConsultationMarkGbComment.SetValuePrim procedure TkwEnConsultationMarkGbComment.DoDoIt(const aCtx: TtfwContext); var l_aen_ConsultationMark: Ten_ConsultationMark; begin try l_aen_ConsultationMark := Ten_ConsultationMark(aCtx.rEngine.PopObjAs(Ten_ConsultationMark)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_ConsultationMark: Ten_ConsultationMark : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(gbComment(aCtx, l_aen_ConsultationMark)); end;//TkwEnConsultationMarkGbComment.DoDoIt function TkwEnConsultationMarkMComment.mComment(const aCtx: TtfwContext; aen_ConsultationMark: Ten_ConsultationMark): TeeMemoWithEditOperations; {* Реализация слова скрипта .Ten_ConsultationMark.mComment } begin Result := aen_ConsultationMark.mComment; end;//TkwEnConsultationMarkMComment.mComment class function TkwEnConsultationMarkMComment.GetWordNameForRegister: AnsiString; begin Result := '.Ten_ConsultationMark.mComment'; end;//TkwEnConsultationMarkMComment.GetWordNameForRegister function TkwEnConsultationMarkMComment.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TeeMemoWithEditOperations); end;//TkwEnConsultationMarkMComment.GetResultTypeInfo function TkwEnConsultationMarkMComment.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnConsultationMarkMComment.GetAllParamsCount function TkwEnConsultationMarkMComment.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_ConsultationMark)]); end;//TkwEnConsultationMarkMComment.ParamsTypes procedure TkwEnConsultationMarkMComment.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству mComment', aCtx); end;//TkwEnConsultationMarkMComment.SetValuePrim procedure TkwEnConsultationMarkMComment.DoDoIt(const aCtx: TtfwContext); var l_aen_ConsultationMark: Ten_ConsultationMark; begin try l_aen_ConsultationMark := Ten_ConsultationMark(aCtx.rEngine.PopObjAs(Ten_ConsultationMark)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_ConsultationMark: Ten_ConsultationMark : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(mComment(aCtx, l_aen_ConsultationMark)); end;//TkwEnConsultationMarkMComment.DoDoIt initialization Tkw_Form_ConsultationMark.RegisterInEngine; {* Регистрация Tkw_Form_ConsultationMark } Tkw_ConsultationMark_Control_gbMark.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_gbMark } Tkw_ConsultationMark_Control_gbMark_Push.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_gbMark_Push } Tkw_ConsultationMark_Control_rbNotSure.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_rbNotSure } Tkw_ConsultationMark_Control_rbNotSure_Push.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_rbNotSure_Push } Tkw_ConsultationMark_Control_rbTwo.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_rbTwo } Tkw_ConsultationMark_Control_rbTwo_Push.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_rbTwo_Push } Tkw_ConsultationMark_Control_rbThree.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_rbThree } Tkw_ConsultationMark_Control_rbThree_Push.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_rbThree_Push } Tkw_ConsultationMark_Control_rbFour.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_rbFour } Tkw_ConsultationMark_Control_rbFour_Push.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_rbFour_Push } Tkw_ConsultationMark_Control_rbFive.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_rbFive } Tkw_ConsultationMark_Control_rbFive_Push.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_rbFive_Push } Tkw_ConsultationMark_Control_pnlHelp.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_pnlHelp } Tkw_ConsultationMark_Control_pnlHelp_Push.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_pnlHelp_Push } Tkw_ConsultationMark_Control_lblHelp.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_lblHelp } Tkw_ConsultationMark_Control_lblHelp_Push.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_lblHelp_Push } Tkw_ConsultationMark_Control_gbComment.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_gbComment } Tkw_ConsultationMark_Control_gbComment_Push.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_gbComment_Push } Tkw_ConsultationMark_Control_mComment.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_mComment } Tkw_ConsultationMark_Control_mComment_Push.RegisterInEngine; {* Регистрация Tkw_ConsultationMark_Control_mComment_Push } TkwEnConsultationMarkGbMark.RegisterInEngine; {* Регистрация en_ConsultationMark_gbMark } TkwEnConsultationMarkRbNotSure.RegisterInEngine; {* Регистрация en_ConsultationMark_rbNotSure } TkwEnConsultationMarkRbTwo.RegisterInEngine; {* Регистрация en_ConsultationMark_rbTwo } TkwEnConsultationMarkRbThree.RegisterInEngine; {* Регистрация en_ConsultationMark_rbThree } TkwEnConsultationMarkRbFour.RegisterInEngine; {* Регистрация en_ConsultationMark_rbFour } TkwEnConsultationMarkRbFive.RegisterInEngine; {* Регистрация en_ConsultationMark_rbFive } TkwEnConsultationMarkPnlHelp.RegisterInEngine; {* Регистрация en_ConsultationMark_pnlHelp } TkwEnConsultationMarkLblHelp.RegisterInEngine; {* Регистрация en_ConsultationMark_lblHelp } TkwEnConsultationMarkGbComment.RegisterInEngine; {* Регистрация en_ConsultationMark_gbComment } TkwEnConsultationMarkMComment.RegisterInEngine; {* Регистрация en_ConsultationMark_mComment } TtfwTypeRegistrator.RegisterType(TypeInfo(Ten_ConsultationMark)); {* Регистрация типа Ten_ConsultationMark } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtGroupBox)); {* Регистрация типа TvtGroupBox } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtRadioButton)); {* Регистрация типа TvtRadioButton } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtLabel)); {* Регистрация типа TvtLabel } TtfwTypeRegistrator.RegisterType(TypeInfo(TeeMemoWithEditOperations)); {* Регистрация типа TeeMemoWithEditOperations } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpBerSequence; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, ClpIProxiedInterface, ClpAsn1Tags, ClpDerSequence, ClpAsn1OutputStream, ClpBerOutputStream, ClpDerOutputStream, ClpIAsn1EncodableVector, ClpIBerSequence, ClpCryptoLibTypes; type TBerSequence = class(TDerSequence, IBerSequence) strict private class var FEmpty: IBerSequence; class constructor BerSequence(); class function GetEmpty: IBerSequence; static; inline; public class function FromVector(const v: IAsn1EncodableVector) : IBerSequence; static; /// <summary> /// create an empty sequence /// </summary> constructor Create(); overload; /// <summary> /// create a sequence containing one object /// </summary> constructor Create(const obj: IAsn1Encodable); overload; constructor Create(const v: array of IAsn1Encodable); overload; /// <summary> /// create a sequence containing a vector of objects. /// </summary> constructor Create(const v: IAsn1EncodableVector); overload; destructor Destroy(); override; /// <summary> /// A note on the implementation: <br />As Der requires the constructed, /// definite-length model to <br />be used for structured types, this /// varies slightly from the <br />ASN.1 descriptions given. Rather than /// just outputing Sequence, <br />we also have to specify Constructed, /// and the objects length. <br /> /// </summary> procedure Encode(const derOut: TStream); override; class property Empty: IBerSequence read GetEmpty; end; implementation { TBerSequence } class function TBerSequence.GetEmpty: IBerSequence; begin result := FEmpty; end; constructor TBerSequence.Create(const obj: IAsn1Encodable); begin Inherited Create(obj); end; constructor TBerSequence.Create; begin Inherited Create(); end; constructor TBerSequence.Create(const v: IAsn1EncodableVector); begin Inherited Create(v); end; destructor TBerSequence.Destroy; begin inherited Destroy; end; constructor TBerSequence.Create(const v: array of IAsn1Encodable); begin Inherited Create(v); end; class constructor TBerSequence.BerSequence; begin FEmpty := TBerSequence.Create(); end; procedure TBerSequence.Encode(const derOut: TStream); var o: IAsn1Encodable; LListAsn1Encodable: TCryptoLibGenericArray<IAsn1Encodable>; begin if ((derOut is TAsn1OutputStream) or (derOut is TBerOutputStream)) then begin (derOut as TDerOutputStream).WriteByte(TAsn1Tags.Sequence or TAsn1Tags.Constructed); (derOut as TDerOutputStream).WriteByte($80); LListAsn1Encodable := Self.GetEnumerable; for o in LListAsn1Encodable do begin (derOut as TDerOutputStream).WriteObject(o); end; (derOut as TDerOutputStream).WriteByte($00); (derOut as TDerOutputStream).WriteByte($00); end else begin (Inherited Encode(derOut)); end; end; class function TBerSequence.FromVector(const v: IAsn1EncodableVector) : IBerSequence; begin if v.Count < 1 then begin result := Empty; end else begin result := TBerSequence.Create(v); end; end; end.
unit Toolbars; {$TYPEINFO ON} interface uses FlicPlayer, SysUtils, Windows, Classes, Messages, Graphics, Controls, Forms, Menus, CommCtrl, ToolWin, ComCtrls; // TSpeedbar ======================================================================================= const CN_REQUESTALIGN = WM_USER + $1000; type TSpeedbarButtonStyle = ( tbsButton, tbsCheck, tbsDropDown, tbsSeparator, tbsDivider ); TSpeedbarButtonState = ( tbsChecked, tbsPressed, tbsEnabled, tbsHidden, tbsIndeterminate, tbsWrap ); TSpeedbar = class; TSpeedbarButton = class( TGraphicControl ) private fIndeterminate : boolean; fAllowAllUp : boolean; fDown : boolean; fGrouped : boolean; fImageIndex : integer; fDropdownMenu : TPopupMenu; fWrap : boolean; fStreamedDown : boolean; fStyle : TSpeedbarButtonStyle; fUpdateCount : integer; function CheckMenuDropdown : boolean; function GetButtonState : byte; function GetIndex : integer; procedure SetButtonState( State : byte ); procedure SetDown( Value : boolean ); procedure SetDropdownMenu( Value : TPopupMenu ); procedure SetGrouped( Value : boolean ); procedure SetImageIndex( Value : integer ); procedure SetIndeterminate( Value : boolean ); procedure SetStyle( Value : TSpeedbarButtonStyle ); procedure SetWrap( Value : boolean ); procedure CMEnabledChanged( var Message : TMessage ); message CM_ENABLEDCHANGED; procedure CMTextChanged( var Message : TMessage ); message CM_TEXTCHANGED; procedure CMVisibleChanged( var Message : TMessage ); message CM_VISIBLECHANGED; protected fToolbar : TSpeedbar; procedure BeginUpdate; virtual; procedure EndUpdate; virtual; 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; procedure Notification( aComponent : TComponent; Operation : TOperation ); override; procedure Paint; override; procedure SetBounds( aLeft, aTop, aWidth, aHeight : integer ); override; procedure SetToolbar( AToolbar : TSpeedbar ); procedure UpdateControl; virtual; property Index : integer read GetIndex; public constructor Create( AOwner : TComponent ); override; procedure Click; override; published property Indeterminate : boolean read fIndeterminate write SetIndeterminate default false; property Style : TSpeedbarButtonStyle read fStyle write SetStyle default tbsButton; property AllowAllUp : boolean read fAllowAllUp write fAllowAllUp default false; property Down : boolean read fDown write SetDown default false; property Grouped : boolean read fGrouped write SetGrouped default false; property Wrap : boolean read fWrap write SetWrap default false; property ImageIndex : integer read fImageIndex write SetImageIndex; property DropdownMenu : TPopupMenu read fDropdownMenu write SetDropdownMenu; published property Caption; property DragCursor; property DragMode; property Enabled; property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property OnClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; TSpeedbar = class( TToolWindow ) private fAutoSize : boolean; fButtonWidth : integer; fButtonHeight : integer; fButtons : TList; fShowCaptions : boolean; fList : boolean; fFlat : boolean; fWrapable : boolean; fImages : TImageList; fImageChangeLink : TChangeLink; fDisabledImages : TImageList; fDisabledImageChangeLink : TChangeLink; fHotImages : TImageList; fHotImageChangeLink : TChangeLink; fIndent : integer; fNewStyle : boolean; fNullBitmap : TBitmap; fOldHandle : HBitmap; fUpdateCount : integer; fHeightMargin : integer; fOnResize : TNotifyEvent; procedure AdjustSize; function ButtonIndex( OldIndex, aLeft, aTop : integer ) : integer; procedure LoadImages( aImages : TImageList ); procedure SetAutoSize( Value : boolean ); function GetButton( Index : integer ) : TSpeedbarButton; function GetButtonCount : integer; procedure GetButtonSize( var aWidth, aHeight : integer ); function GetRowCount : integer; procedure SetList( Value : boolean ); procedure SetShowCaptions( Value : boolean ); procedure SetFlat( Value : boolean ); procedure SetWrapable( Value : boolean ); procedure InsertButton( Control : TControl ); procedure RemoveButton( Control : TControl ); procedure UpdateButton( Index : integer ); procedure UpdateButtons; procedure UpdateButtonState( Index : integer ); procedure UpdateButtonStates; procedure UpdateItem( Message, FromIndex, ToIndex : integer ); procedure CreateButtons( NewWidth, NewHeight : integer ); procedure SetButtonWidth( Value : integer ); procedure SetButtonHeight( Value : integer ); procedure UpdateImages; procedure ImageListChange( Sender : TObject ); procedure SetImageList( Value : HImageList ); procedure SetImages( Value : TImageList ); procedure DisabledImageListChange( Sender : TObject ); procedure SetDisabledImageList( Value : HImageList ); procedure SetDisabledImages( Value : TImageList ); procedure HotImageListChange( Sender : TObject ); procedure SetHotImageList( Value : HImageList ); procedure SetHotImages( Value : TImageList ); procedure SetIndent( Value : integer ); procedure AdjustControl( Control : TControl ); procedure RecreateButtons; procedure BeginUpdate; procedure EndUpdate; procedure ResizeButtons; function InternalButtonCount : integer; function ReorderButton( OldIndex, aLeft, aTop : integer ) : boolean; procedure WMEraseBkgnd( var Message : TWMEraseBkgnd ); message WM_ERASEBKGND; procedure WMNotifyFormat( var Message : TMessage ); message WM_NOTIFYFORMAT; procedure WMSize( var Message : TWMSize ); message WM_SIZE; procedure WMWindowPosChanged( var Message : TWMWindowPosChanged ); message WM_WINDOWPOSCHANGED; procedure WMWindowPosChanging( var Message : TWMWindowPosChanging ); message WM_WINDOWPOSCHANGING; procedure CMColorChanged( var Message : TMessage ); message CM_COLORCHANGED; procedure CMControlChange( var Message : TCMControlChange ); message CM_CONTROLCHANGE; procedure CMEnabledChanged( var Message : TMessage ); message CM_ENABLEDCHANGED; procedure CMSysFontChanged( var Message : TMessage ); message CM_SYSFONTCHANGED; procedure CNRequestAlign( var Message : TMessage ); message CN_REQUESTALIGN; protected procedure AlignControls( AControl : TControl; var Rect : TRect ); override; procedure CreateParams( var Params : TCreateParams ); override; procedure CreateWnd; override; procedure GetChildren( Proc : TGetChildProc; Root : TComponent ); override; procedure Loaded; override; procedure Notification( aComponent : TComponent; Operation : TOperation ); override; procedure WndProc( var Message : TMessage ); override; procedure Resize; dynamic; procedure RepositionButton( Index : integer ); procedure RepositionButtons( Index : integer ); public constructor Create( AOwner : TComponent ); override; destructor Destroy; override; property Buttons[Index : integer] : TSpeedbarButton read GetButton; property ButtonCount : integer read GetButtonCount; property RowCount : integer read GetRowCount; published property AutoSize : boolean read fAutoSize write SetAutoSize default false; property ButtonHeight : integer read fButtonHeight write SetButtonHeight default 22; property ButtonWidth : integer read fButtonWidth write SetButtonWidth default 23; property Flat : boolean read fFlat write SetFlat default false; property Indent : integer read fIndent write SetIndent default 0; property List : boolean read fList write SetList default false; property ShowCaptions : boolean read fShowCaptions write SetShowCaptions default false; property Wrapable : boolean read fWrapable write SetWrapable default true; property DisabledImages : TImageList read fDisabledImages write SetDisabledImages; property HotImages : TImageList read fHotImages write SetHotImages; property Images : TImageList read fImages write SetImages; property OnResize : TNotifyEvent read fOnResize write fOnResize; published property Align default alTop; property EdgeBorders default [ebTop]; property Height default 32; property Color; property Ctl3D; property DragCursor; property DragMode; property EdgeInner; property EdgeOuter; property Enabled; property Font; property BorderWidth; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; // TReBar ======================================================================================= const CN_BANDCHANGE = WM_USER + $1000; type TReBar = class; TReBand = class( TCollectionItem ) private fHorizontalOnly : boolean; fBorderStyle : TBorderStyle; fBreak : boolean; fFixedSize : boolean; fVisible : boolean; fImageIndex : integer; fFixedBackground : boolean; fMinHeight : integer; fMinWidth : integer; fColor : TColor; fControl : TWinControl; fParentColor : boolean; fParentBitmap : boolean; fBitmap : TBitmap; fText : string; fWidth : integer; fDDB : TBitmap; fID : integer; function ReBar : TReBar; function IsColorStored : boolean; function IsBitmapStored : boolean; procedure BitmapChanged( Sender : TObject ); function GetHeight : integer; function GetVisible : boolean; procedure SetBorderStyle( Value : TBorderStyle ); procedure SetBreak( Value : boolean ); procedure SetFixedSize( Value : boolean ); procedure SetMinHeight( Value : integer ); procedure SetMinWidth( Value : integer ); procedure SetVisible( Value : boolean ); procedure SetHorizontalOnly( Value : boolean ); procedure SetImageIndex( Value : integer ); procedure SetFixedBackground( Value : boolean ); procedure SetColor( Value : TColor ); procedure SetControl( Value : TWinControl ); procedure SetParentColor( Value : boolean ); procedure SetParentBitmap( Value : boolean ); procedure SetBitmap( Value : TBitmap ); procedure SetText( const Value : string ); procedure SetWidth( Value : integer ); protected function GetDisplayName : string; override; procedure ParentColorChanged; dynamic; procedure ParentBitmapChanged; dynamic; public constructor Create( Collection : TCollection ); override; destructor Destroy; override; procedure Assign( Source : TPersistent ); override; property BorderStyle : TBorderStyle read fBorderStyle write SetBorderStyle default bsSingle; property Height : integer read GetHeight; published property Bitmap : TBitmap read fBitmap write SetBitmap stored IsBitmapStored; property Break : boolean read fBreak write SetBreak default true; property Color : TColor read fColor write SetColor stored IsColorStored default clBtnFace; property FixedBackground : boolean read fFixedBackground write SetFixedBackground default true; property FixedSize : boolean read fFixedSize write SetFixedSize default false; property HorizontalOnly : boolean read fHorizontalOnly write SetHorizontalOnly default false; property ParentColor : boolean read fParentColor write SetParentColor default true; property ParentBitmap : boolean read fParentBitmap write SetParentBitmap default true; property Visible : boolean read GetVisible write SetVisible default true; property MinHeight : integer read fMinHeight write SetMinHeight default 25; property MinWidth : integer read fMinWidth write SetMinWidth default 0; property Text : string read fText write SetText; property Width : integer read fWidth write SetWidth; property Control : TWinControl read fControl write SetControl; property ImageIndex : integer read fImageIndex write SetImageIndex; end; TReBands = class( TCollection ) private fReBar : TReBar; fVisibleCount : integer; function GetItem( Index : integer ) : TReBand; procedure SetItem( Index : integer; Value : TReBand ); protected function GetOwner : TPersistent; override; procedure Update( Item : TCollectionItem ); override; function FindBand( AControl : TControl ) : TReBand; function HaveGraphic : boolean; public constructor Create( ReBar : TReBar ); function Add : TReBand; property ReBar : TReBar read fReBar; property Items[Index : integer] : TReBand read GetItem write SetItem; default; end; TReBar = class( TToolWindow ) private fAutoSize : boolean; fBands : TReBands; fBandBorderStyle : TBorderStyle; fBitmap : TBitmap; fCaptionFont : TFont; fCaptionFontHeight : integer; fDDB : TBitmap; fFixedSize : boolean; fFixedOrder : boolean; fImages : TImageList; fImageChangeLink : TChangeLink; fShowText : boolean; fVertical : boolean; fTrackDrag : TSmallPoint; fUpdateCount : integer; fOnChange : TNotifyEvent; fOnResize : TNotifyEvent; procedure AdjustSize; procedure BeginUpdate; procedure BitmapChanged( Sender : TObject ); procedure DisableBands; procedure EndUpdate; function IsAutoSized : boolean; function IsBackgroundDirty : boolean; function GetAlign : TAlign; function GetCaptionFont : HFONT; function GetCaptionFontHeight : integer; function GetCaptionSize( Band : TReBand ) : integer; function GetRowHeight( Index : integer ) : integer; procedure SetAlign( Value : TAlign ); procedure SetAutoSize( Value : boolean ); procedure SetBands( Value : TReBands ); procedure SetBandBorderStyle( Value : TBorderStyle ); procedure SetBitmap( Value : TBitmap ); procedure SetFixedSize( Value : boolean ); procedure SetFixedOrder( Value : boolean ); procedure SetImageList( Value : HImageList ); procedure SetImages( Value : TImageList ); procedure SetShowText( Value : boolean ); procedure SetVertical( Value : boolean ); procedure ImageListChange( Sender : TObject ); function PtInGripRect( const Pos : TPoint ) : integer; function ReadBands : boolean; function UpdateItem( Message, FromIndex, ToIndex : integer ) : boolean; procedure UpdateBand( Index : integer ); procedure UpdateBands; procedure WMCaptureChanged( var Message : TMessage ); message WM_CAPTURECHANGED; procedure WMEraseBkgnd( var Message : TWMEraseBkgnd ); message WM_ERASEBKGND; procedure WMLButtonDown( var Message : TWMLButtonDown ); message WM_LBUTTONDOWN; procedure WMLButtonUp( var Message : TWMLButtonUp ); message WM_LBUTTONUP; procedure WMNotifyFormat( var Message : TMessage ); message WM_NOTIFYFORMAT; procedure WMSetCursor( var Message : TWMSetCursor ); message WM_SETCURSOR; procedure WMSize( var Message : TWMSize ); message WM_SIZE; procedure WMWindowPosChanged( var Message : TWMWindowPosChanged ); message WM_WINDOWPOSCHANGED; procedure CMColorChanged( var Message : TMessage ); message CM_COLORCHANGED; procedure CMControlChange( var Message : TCMControlChange ); message CM_CONTROLCHANGE; procedure CMDesignHitTest( var Message : TCMDesignHitTest ); message CM_DESIGNHITTEST; procedure CNBandChange( var Message : TMessage ); message CN_BANDCHANGE; procedure CNNotify( var Message : TWMNotify ); message CN_NOTIFY; procedure CMSysColorChange( var Message : TMessage ); message CM_SYSCOLORCHANGE; procedure CMSysFontChanged( var Message : TMessage ); message CM_SYSFONTCHANGED; procedure CMWinIniChange( var Message : TWMWinIniChange ); message CM_WININICHANGE; protected procedure AlignControls( AControl : TControl; var Rect : TRect ); override; procedure Change; dynamic; procedure CreateParams( var Params : TCreateParams ); override; procedure CreateWnd; override; function GetPalette : HPALETTE; override; procedure Loaded; override; procedure Notification( aComponent : TComponent; Operation : TOperation ); override; procedure Resize; dynamic; procedure WndProc( var Message : TMessage ); override; public constructor Create( AOwner : TComponent ); override; destructor Destroy; override; published property Align read GetAlign write SetAlign default alTop; property AutoSize : boolean read fAutoSize write SetAutoSize default false; property BandBorderStyle : TBorderStyle read fBandBorderStyle write SetBandBorderStyle default bsSingle; property FixedSize : boolean read fFixedSize write SetFixedSize default false; property FixedOrder : boolean read fFixedOrder write SetFixedOrder default false; property ShowText : boolean read fShowText write SetShowText default true; property Vertical : boolean read fVertical write SetVertical default false; property Bands : TReBands read fBands write SetBands; property Images : TImageList read fImages write SetImages; property Bitmap : TBitmap read fBitmap write SetBitmap; property OnChange : TNotifyEvent read fOnChange write fOnChange; property OnResize : TNotifyEvent read fOnResize write fOnResize; published property BorderWidth; property Color; property Ctl3D; property DragCursor; property DragMode; property EdgeBorders; property EdgeInner; property EdgeOuter; property Enabled; property Font; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; // Helper functions ======================================================================================= function CreateNewButton( Speedbar : TSpeedbar; aStyle : TSpeedbarButtonStyle ) : TSpeedbarButton; // VCL Registration ======================================================================================= procedure Register; implementation uses VclUtils; // Helper functions ======================================================================================= function CreateNewButton( Speedbar : TSpeedbar; aStyle : TSpeedbarButtonStyle ) : TSpeedbarButton; var LastButton : TSpeedbarButton; begin Result := TSpeedbarButton.Create( Speedbar.Owner ); with Speedbar do begin if ButtonCount = 0 then LastButton := nil else LastButton := Buttons[ButtonCount - 1]; Result.Name := UniqueComponentName( Owner, 'ToolButton' ); end; if Assigned( LastButton ) then with LastButton do begin Result.Left := Left + Width; Result.ImageIndex := ImageIndex + 1; end; with Result do begin Style := aStyle; if Style = tbsSeparator then Width := 8; Caption := Name; Parent := Speedbar; end; end; // TSpeedbarButton ======================================================================================= constructor TSpeedbarButton.Create( AOwner : TComponent ); begin inherited; ControlStyle := [csCaptureMouse, csSetCaption]; Width := 23; Height := 22; fStyle := tbsButton; end; procedure TSpeedbarButton.MouseDown( Button : TMouseButton; Shift : TShiftState; X, Y : integer ); begin if ( Style = tbsDropDown ) and ( Button = mbLeft ) and Enabled then Down := not Down; inherited; end; procedure TSpeedbarButton.MouseMove( Shift : TShiftState; X, Y : integer ); begin inherited; if ( Style = tbsDropDown ) and MouseCapture then Down := ( X >= 0 ) and ( X < ClientWidth ) and ( Y >= 0 ) and ( Y <= ClientHeight ); end; procedure TSpeedbarButton.MouseUp( Button : TMouseButton; Shift : TShiftState; X, Y : integer ); begin inherited; if ( Button = mbLeft ) and ( X >= 0 ) and ( X < ClientWidth ) and ( Y >= 0 ) and ( Y <= ClientHeight ) then begin if Style = tbsDropDown then Down := false; Click; end; end; procedure TSpeedbarButton.Click; begin inherited; end; procedure TSpeedbarButton.Notification( aComponent : TComponent; Operation : TOperation ); begin inherited; if ( aComponent = DropdownMenu ) and ( Operation = opRemove ) then DropdownMenu := nil; end; procedure TSpeedbarButton.CMTextChanged( var Message : TMessage ); begin inherited; UpdateControl; if Assigned( fToolbar ) and fToolbar.ShowCaptions then fToolbar.RecreateButtons; end; procedure TSpeedbarButton.SetBounds( aLeft, aTop, aWidth, aHeight : integer ); var Pos : integer; Reordered, NeedsUpdate : boolean; ResizeWidth, ResizeHeight : boolean; begin if ( fUpdateCount = 0 ) and not ( csLoading in ComponentState ) and Assigned( fToolbar ) then begin Pos := Index; Reordered := fToolbar.ReorderButton( Index, aLeft, aTop ); if Reordered then begin NeedsUpdate := false; if Index < Pos then Pos := Index; end else begin NeedsUpdate := ( Style in [tbsDropDown, tbsSeparator, tbsDivider] ) and ( aWidth <> Width ); Reordered := NeedsUpdate; end; if {not fToolbar.Flat and} ( Style = tbsDropDown ) then aWidth := ( Width div 3 ) * 2 + ( Width mod 3 ) + aWidth - Width; ResizeWidth := not ( Style in [tbsDropDown, tbsSeparator, tbsDivider] ) and ( aWidth <> fToolbar.ButtonWidth ); ResizeHeight := aHeight <> fToolbar.ButtonHeight; if NeedsUpdate then inherited SetBounds( aLeft, aTop, aWidth, aHeight ); if ResizeWidth then fToolbar.ButtonWidth := aWidth; if ResizeHeight then fToolbar.ButtonHeight := aHeight; if Reordered and not ResizeWidth and not ResizeHeight then begin if NeedsUpdate then fToolbar.UpdateButton( Pos ); fToolbar.ResizeButtons; fToolbar.RepositionButtons( 0 ); end else fToolbar.RepositionButton( Pos ); end else inherited SetBounds( aLeft, aTop, aWidth, aHeight ); end; procedure TSpeedbarButton.Paint; var R : TRect; begin if Assigned( fToolbar ) then begin if Style = tbsDivider then with Canvas do begin R := Rect( Width div 2 - 1, 1, Width, Height - 1 ); DrawEdge( Handle, R, EDGE_ETCHED, BF_LEFT ); end; if csDesigning in ComponentState then if Style in [tbsSeparator, tbsDivider] // Draw separator outline then with Canvas do begin Pen.Style := psDot; Pen.Color := clBtnShadow; Brush.Style := bsClear; Rectangle( 0, 0, ClientWidth, ClientHeight ); end else // Draw Flat button face if fToolbar.Flat then with Canvas do begin R := Rect( 0, 0, Width, Height ); if not Down then DrawEdge( Handle, R, BDR_RAISEDINNER, BF_RECT ); end; end; end; const ButtonStates : array[TSpeedbarButtonState] of word = ( TBSTATE_CHECKED, TBSTATE_PRESSED, TBSTATE_ENABLED, TBSTATE_HIDDEN, TBSTATE_INDETERMINATE, TBSTATE_WRAP ); ButtonStyles : array[TSpeedbarButtonStyle] of word = ( TBSTYLE_BUTTON, TBSTYLE_CHECK, TBSTYLE_DROPDOWN, TBSTYLE_SEP, TBSTYLE_SEP ); function TSpeedbarButton.GetButtonState : byte; begin Result := 0; if fDown then if Style = tbsCheck then Result := Result or ButtonStates[tbsChecked] else Result := Result or ButtonStates[tbsPressed]; if Enabled and ( not Assigned( fToolbar ) or fToolbar.Enabled ) then Result := Result or ButtonStates[tbsEnabled]; if not Visible then Result := Result or ButtonStates[tbsHidden]; if fIndeterminate then Result := Result or ButtonStates[tbsIndeterminate]; if fWrap then Result := Result or ButtonStates[tbsWrap]; end; procedure TSpeedbarButton.SetButtonState( State : byte ); begin fDown := State and ( TBSTATE_CHECKED or TBSTATE_PRESSED ) <> 0; Enabled := State and TBSTATE_ENABLED <> 0; Visible := State and TBSTATE_HIDDEN = 0; fIndeterminate := not fDown and ( State and TBSTATE_INDETERMINATE <> 0 ); fWrap := State and TBSTATE_WRAP <> 0; end; procedure TSpeedbarButton.SetToolbar( AToolbar : TSpeedbar ); begin if fToolbar <> AToolbar then begin if fToolbar <> nil then fToolbar.RemoveButton( Self ); Parent := AToolbar; if AToolbar <> nil then AToolbar.InsertButton( Self ); end; end; procedure TSpeedbarButton.CMVisibleChanged( var Message : TMessage ); begin UpdateControl; end; procedure TSpeedbarButton.CMEnabledChanged( var Message : TMessage ); begin UpdateControl; end; procedure TSpeedbarButton.SetDown( Value : boolean ); begin if ( csReading in ComponentState ) then begin if Value then fStreamedDown := Value; end else if Value <> fDown then begin fIndeterminate := false; fDown := Value; UpdateControl; // Invalidate background only when Speedbar is flat and button is changing // from down to up position. if not Value and Assigned( fToolbar ) and fToolbar.Flat then Invalidate; end; end; procedure TSpeedbarButton.SetDropdownMenu( Value : TPopupMenu ); begin if Value <> fDropdownMenu then begin fDropdownMenu := Value; if Value <> nil then Value.FreeNotification( Self ); end; end; procedure TSpeedbarButton.SetGrouped( Value : boolean ); begin if fGrouped <> Value then begin fGrouped := Value; UpdateControl; end; end; procedure TSpeedbarButton.SetImageIndex( Value : integer ); begin if fImageIndex <> Value then begin fImageIndex := Value; UpdateControl; end; end; procedure TSpeedbarButton.SetIndeterminate( Value : boolean ); begin if fIndeterminate <> Value then begin fDown := false; fIndeterminate := Value; UpdateControl; end; end; procedure TSpeedbarButton.SetStyle( Value : TSpeedbarButtonStyle ); begin if fStyle <> Value then begin fStyle := Value; if Value in [tbsSeparator, tbsDivider] then ControlStyle := ControlStyle + [csNoDesignVisible] else ControlStyle := ControlStyle - [csNoDesignVisible]; if Assigned( fToolbar ) then begin UpdateControl; fToolbar.ResizeButtons; fToolbar.RepositionButtons( Index ); end; end; end; procedure TSpeedbarButton.SetWrap( Value : boolean ); begin if fWrap <> Value then begin fWrap := Value; UpdateControl; if Assigned( fToolbar ) then fToolbar.RepositionButtons( Index ); end; end; procedure TSpeedbarButton.BeginUpdate; begin Inc( fUpdateCount ); end; procedure TSpeedbarButton.EndUpdate; begin Dec( fUpdateCount ); end; function TSpeedbarButton.GetIndex : integer; begin if Assigned( fToolbar ) then Result := fToolbar.fButtons.IndexOf( Self ) else Result := -1; end; procedure TSpeedbarButton.UpdateControl; begin if Assigned( fToolbar ) then fToolbar.UpdateButton( Index ); end; function TSpeedbarButton.CheckMenuDropdown : boolean; begin Result := false; if not ( csDesigning in ComponentState ) and Assigned( DropdownMenu ) and DropdownMenu.AutoPopup then begin SendCancelMode( nil ); DropdownMenu.PopupComponent := Self; with ClientToScreen( Point( 0, ClientHeight ) ) do DropdownMenu.Popup( X, Y ); Result := true; end; end; // TSpeedbar ======================================================================================= constructor TSpeedbar.Create( AOwner : TComponent ); begin inherited; ControlStyle := [csAcceptsControls, csCaptureMouse, csClickEvents, csDoubleClicks]; Height := 32; Align := alTop; fNewStyle := true; fWrapable := true; fButtons := TList.Create; fButtonWidth := 23; fButtonHeight := 22; EdgeBorders := [ebTop]; fImageChangeLink := TChangeLink.Create; fImageChangeLink.OnChange := ImageListChange; fDisabledImageChangeLink := TChangeLink.Create; fDisabledImageChangeLink.OnChange := DisabledImageListChange; fHotImageChangeLink := TChangeLink.Create; fHotImageChangeLink.OnChange := HotImageListChange; fNullBitmap := TBitmap.Create; with fNullBitmap do begin Width := 1; Height := 1; Canvas.Brush.Color := clBtnFace; Canvas.FillRect( Rect( 0, 0, 1, 1 ) ); end; end; destructor TSpeedbar.Destroy; var i : integer; begin fNullBitmap.Free; fHotImageChangeLink.Free; fDisabledImageChangeLink.Free; fImageChangeLink.Free; for i := 0 to fButtons.Count - 1 do if TControl( fButtons[i] ) is TSpeedbarButton then TSpeedbarButton( fButtons[i] ).fToolbar := nil; fButtons.Free; inherited; end; procedure TSpeedbar.CreateParams( var Params : TCreateParams ); const DefaultStyles = CCS_NOPARENTALIGN or CCS_NOMOVEY or CCS_NORESIZE or CCS_NODIVIDER; const ListStyles : array[boolean] of integer = ( 0, TBSTYLE_LIST ); FlatStyles : array[boolean] of integer = ( 0, TBSTYLE_FLAT ); WrapStyles : array[boolean] of integer = ( 0, TBSTYLE_WRAPABLE ); begin fNewStyle := InitCommonControl( ICC_BAR_CLASSES ); inherited; CreateSubClass( Params, ToolbarCLASSNAME ); with Params do begin Style := Style or DefaultStyles or FlatStyles[fFlat] or ListStyles[fList] or WrapStyles[fWrapable]; WindowClass.Style := WindowClass.Style and not ( CS_HREDRAW or CS_VREDRAW ); end; end; procedure TSpeedbar.CreateWnd; var DisplayDC : HDC; SaveFont, StockFont : HFONT; TxtMetric : TTextMetric; begin inherited; fOldHandle := 0; StockFont := GetStockObject( SYSTEM_FONT ); if StockFont <> 0 then begin DisplayDC := GetDC( 0 ); if ( DisplayDC <> 0 ) then begin SaveFont := SelectObject( DisplayDC, StockFont ); if ( GetTextMetrics( DisplayDC, TxtMetric ) ) then with TxtMetric do fHeightMargin := tmHeight - tmInternalLeading - tmExternalLeading + 1; SelectObject( DisplayDC, SaveFont ); ReleaseDC( 0, DisplayDC ); end; end; RecreateButtons; Invalidate; end; procedure TSpeedbar.CreateButtons( NewWidth, NewHeight : integer ); var ImageWidth, ImageHeight : integer; begin BeginUpdate; try HandleNeeded; Perform( TB_BUTTONSTRUCTSIZE, SizeOf( TTBButton ), 0 ); Perform( TB_SETINDENT, fIndent, 0 ); if Assigned( fImages ) then begin ImageWidth := fImages.Width; ImageHeight := fImages.Height; end else if Assigned( fDisabledImages ) then begin ImageWidth := fDisabledImages.Width; ImageHeight := fDisabledImages.Height; end else if Assigned( fHotImages ) then begin ImageWidth := fHotImages.Width; ImageHeight := fHotImages.Height; end else begin ImageWidth := 0; ImageHeight := 0; end; Perform( TB_SETBITMAPSIZE, 0, MakeLParam( ImageWidth, ImageHeight ) ); if ShowCaptions then Dec( NewHeight, fHeightMargin ); Perform( TB_SETBUTTONSIZE, 0, MakeLParam( NewWidth, NewHeight ) ); finally EndUpdate; end; // Retrieve current button sizes GetButtonSize( fButtonWidth, fButtonHeight ); UpdateButtons; UpdateImages; end; procedure TSpeedbar.AdjustSize; begin if HandleAllocated then SetWindowPos( Handle, 0, 0, 0, Width, Height, SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOZORDER ); end; procedure TSpeedbar.RepositionButton( Index : integer ); var TBButton : TTBButton; Button : TControl; R : TRect; AdjustY : integer; begin if not ( csLoading in ComponentState ) and ( Perform( TB_GETBUTTON, Index, Longint( @TBButton ) ) <> 0 ) then begin Button := TControl( TBButton.dwData ); if Button is TSpeedbarButton then TSpeedbarButton( Button ).BeginUpdate; try Perform( TB_GETITEMRECT, Index, Longint( @R ) ); if ( Button is TWinControl ) then with TWinControl( Button ) do begin HandleNeeded; // Check for a control that doesn't size and center it BoundsRect := R; if Height < R.Bottom - R.Top then begin AdjustY := ( R.Bottom - R.Top - Height ) div 2; SetBounds( R.Left, R.Top + AdjustY, R.Right - R.Left, Height ); end; end else Button.BoundsRect := R; finally if Button is TSpeedbarButton then TSpeedbarButton( Button ).EndUpdate; end; end; end; procedure TSpeedbar.RepositionButtons( Index : integer ); var i : integer; begin if not ( csLoading in ComponentState ) and ( fUpdateCount <= 0 ) then begin BeginUpdate; try for i := InternalButtonCount - 1 downto Index do RepositionButton( i ); finally EndUpdate; end; end; end; procedure TSpeedbar.GetButtonSize( var aWidth, aHeight : integer ); var LastIndex : integer; R : TRect; TBButton : TTBButton; begin aWidth := fButtonWidth; aHeight := fButtonHeight; if HandleAllocated then begin LastIndex := InternalButtonCount - 1; if LastIndex >= 0 then begin while ( LastIndex >= 0 ) and ( Perform( TB_GETBUTTON, LastIndex, integer( @TBButton ) ) <> 0 ) and ( TBButton.fsStyle and ( TBSTYLE_SEP ) <> 0 ) do Dec( LastIndex ); if LastIndex < 0 then begin if Perform( TB_GETITEMRECT, 0, Longint( @R ) ) <> 0 then begin aHeight := R.Bottom - R.Top; if ShowCaptions then Inc( aHeight, fHeightMargin ); end; end else if Perform( TB_GETITEMRECT, LastIndex, Longint( @R ) ) <> 0 then begin aHeight := R.Bottom - R.Top; if ShowCaptions then Inc( aHeight, fHeightMargin ); // Adjust size for drop-down and separator buttons !! if {not Flat and }( TBButton.fsStyle and ( TBSTYLE_DROPDOWN ) <> 0 ) then aWidth := ( ( R.Right - R.Left ) div 3 ) * 2 + ( ( R.Right - R.Left ) mod 3 ) else aWidth := R.Right - R.Left; end; end; end; end; procedure TSpeedbar.SetButtonHeight( Value : integer ); begin if Value <> fButtonHeight then begin fButtonHeight := Value; RecreateButtons; end; end; procedure TSpeedbar.SetButtonWidth( Value : integer ); begin if Value <> fButtonWidth then begin fButtonWidth := Value; RecreateButtons; end; end; procedure TSpeedbar.InsertButton( Control : TControl ); var Pos : integer; begin if Control is TSpeedbarButton then TSpeedbarButton( Control ).fToolbar := Self; Pos := fButtons.Add( Control ); UpdateButton( Pos ); ResizeButtons; if Wrapable then RepositionButtons( 0 ) else RepositionButtons( Pos ); end; procedure TSpeedbar.RemoveButton( Control : TControl ); var i, Pos : integer; begin i := fButtons.IndexOf( Control ); if i >= 0 then begin if Control is TSpeedbarButton then TSpeedbarButton( Control ).fToolbar := nil; Pos := fButtons.Remove( Control ); Perform( TB_DELETEBUTTON, Pos, 0 ); ResizeButtons; if Wrapable then RepositionButtons( 0 ) else RepositionButtons( Pos ); end; end; procedure TSpeedbar.UpdateItem( Message, FromIndex, ToIndex : integer ); var Button : TTBButton; Buffer : array[0..4095] of Char; begin with TControl( fButtons[FromIndex] ) do begin if ClassType = TSpeedbarButton then with TSpeedbarButton( fButtons[FromIndex] ) do begin FillChar( Button, SizeOf( Button ), 0 ); if Style in [tbsSeparator, tbsDivider] then begin Button.iBitmap := Width; Button.idCommand := -1; end else begin Button.iBitmap := ImageIndex; Button.idCommand := FromIndex; end; Button.fsStyle := ButtonStyles[Style]; Button.fsState := GetButtonState; if fGrouped then Button.fsStyle := Button.fsStyle or TBSTYLE_GROUP; Button.dwData := Longint( fButtons[FromIndex] ); if ShowCaptions then begin StrPCopy( Buffer, Caption ); // TB_ADDSTRING requires two null terminators Buffer[Length( Caption ) + 1] := #0; Button.iString := Self.Perform( TB_ADDSTRING, 0, Longint( @Buffer ) ); end else Button.iString := -1; end else begin FillChar( Button, SizeOf( Button ), 0 ); Button.fsStyle := ButtonStyles[tbsSeparator]; Button.iBitmap := Width; Button.idCommand := -1; Button.dwData := Longint( fButtons[FromIndex] ); Button.iString := -1; end; Self.Perform( Message, ToIndex, integer( @Button ) ); end; end; procedure TSpeedbar.UpdateButton( Index : integer ); begin if fUpdateCount <= 0 then begin BeginUpdate; try HandleNeeded; Perform( WM_SETREDRAW, 0, 0 ); try if Perform( TB_DELETEBUTTON, Index, 0 ) = 1 then UpdateItem( TB_INSERTBUTTON, Index, Index ) else UpdateItem( TB_ADDBUTTONS, Index, 1 ) finally Perform( WM_SETREDRAW, 1, 0 ); end; RedrawWindow( Handle, nil, 0, RDW_INVALIDATE or RDW_ALLCHILDREN ); finally EndUpdate; end; end; end; procedure TSpeedbar.UpdateButtons; var i : integer; begin if fUpdateCount <= 0 then begin BeginUpdate; try HandleNeeded; Perform( WM_SETREDRAW, 0, 0 ); try for i := 0 to InternalButtonCount - 1 do Perform( TB_DELETEBUTTON, 0, 0 ); for i := 0 to fButtons.Count - 1 do UpdateItem( TB_ADDBUTTONS, i, 1 ); finally Perform( WM_SETREDRAW, 1, 0 ); end; RedrawWindow( Handle, nil, 0, RDW_INVALIDATE or RDW_ALLCHILDREN ); finally EndUpdate; end; RepositionButtons( 0 ); end; end; procedure TSpeedbar.UpdateButtonState( Index : integer ); var TBButton : TTBButton; begin if ( Perform( TB_GETBUTTON, Index, integer( @TBButton ) ) <> 0 ) then with TSpeedbarButton( TBButton.dwData ) do begin SetButtonState( TBButton.fsState ); Self.Perform( TB_SETSTATE, Index, MakeLong( GetButtonState, 0 ) ); end; end; procedure TSpeedbar.UpdateButtonStates; var i : integer; begin for i := 0 to fButtons.Count - 1 do if TControl( fButtons[i] ).ClassType = TSpeedbarButton then UpdateButtonState( i ); end; procedure TSpeedbar.SetAutoSize( Value : boolean ); begin if fAutoSize <> Value then begin fAutoSize := Value; if Value and not ( csLoading in ComponentState ) then AdjustSize; end; end; procedure TSpeedbar.SetShowCaptions( Value : boolean ); begin if fShowCaptions <> Value then begin fShowCaptions := Value; RecreateWnd; end; end; function TSpeedbar.GetButton( Index : integer ) : TSpeedbarButton; begin Result := fButtons[Index]; end; function TSpeedbar.GetButtonCount : integer; begin Result := fButtons.Count; end; function TSpeedbar.GetRowCount : integer; begin Result := Perform( TB_GETROWS, 0, 0 ); end; procedure TSpeedbar.SetList( Value : boolean ); begin if fList <> Value then begin fList := Value; RecreateWnd; end; end; procedure TSpeedbar.SetFlat( Value : boolean ); begin if fFlat <> Value then begin fFlat := Value; RecreateWnd; end; end; procedure TSpeedbar.SetWrapable( Value : boolean ); begin if fWrapable <> Value then begin fWrapable := Value; RecreateWnd; end; end; procedure TSpeedbar.Resize; begin if Assigned( fOnResize ) then fOnResize( Self ); end; procedure TSpeedbar.Notification( aComponent : TComponent; Operation : TOperation ); begin inherited Notification( aComponent, Operation ); if Operation = opRemove then begin if aComponent = fImages then Images := nil; if aComponent = fHotImages then HotImages := nil; if aComponent = fDisabledImages then DisabledImages := nil; end; end; procedure TSpeedbar.LoadImages( aImages : TImageList ); var AddBitmap : TTBAddBitmap; ReplaceBitmap : TTBReplaceBitmap; NewHandle : HBITMAP; function GetImageBitmap( ImageList : TImageList ) : HBITMAP; var i : integer; Bitmap : TBitmap; R : TRect; begin Bitmap := TBitmap.Create; try Bitmap.Width := ImageList.Width * ImageList.Count; Bitmap.Height := ImageList.Height; R := Rect( 0, 0, Width, Height ); with Bitmap.Canvas do begin Brush.Color := clBtnFace; FillRect( R ); end; for i := 0 to ImageList.Count - 1 do ImageList_Draw( ImageList.Handle, i, Bitmap.Canvas.Handle, i * ImageList.Width, 0, ILD_TRANSPARENT ); Result := Bitmap.ReleaseHandle; finally Bitmap.Free; end; end; begin if Assigned( aImages ) then NewHandle := GetImageBitmap( aImages ) else with TBitmap.Create do try Assign( fNullBitmap ); NewHandle := ReleaseHandle; finally Free; end; if fOldHandle = 0 then begin AddBitmap.hInst := 0; AddBitmap.nID := NewHandle; Perform( TB_ADDBITMAP, ButtonCount, Longint( @AddBitmap ) ); end else begin with ReplaceBitmap do begin hInstOld := 0; nIDOld := fOldHandle; hInstNew := 0; nIDNew := NewHandle; nButtons := ButtonCount; end; Perform( TB_REPLACEBITMAP, 0, Longint( @ReplaceBitmap ) ); if fOldHandle <> 0 then DeleteObject( fOldHandle ); end; fOldHandle := NewHandle; end; procedure TSpeedbar.UpdateImages; begin if fNewStyle then begin if fImages <> nil then SetImageList( fImages.Handle ); if fDisabledImages <> nil then SetDisabledImageList( fDisabledImages.Handle ); if fHotImages <> nil then SetHotImageList( fHotImages.Handle ); end else if HandleAllocated then LoadImages( fImages ); end; procedure TSpeedbar.ImageListChange( Sender : TObject ); begin if HandleAllocated and ( Sender = Images ) then RecreateButtons; end; procedure TSpeedbar.SetImageList( Value : HImageList ); begin if HandleAllocated then Perform( TB_SETIMAGELIST, 0, Value ); Invalidate; end; procedure TSpeedbar.SetImages( Value : TImageList ); begin if fImages <> nil then fImages.UnRegisterChanges( fImageChangeLink ); fImages := Value; if fImages <> nil then fImages.RegisterChanges( fImageChangeLink ) else SetImageList( 0 ); RecreateButtons; end; procedure TSpeedbar.DisabledImageListChange( Sender : TObject ); begin if HandleAllocated and ( Sender = DisabledImages ) then RecreateButtons; end; procedure TSpeedbar.SetDisabledImageList( Value : HImageList ); begin if HandleAllocated then Perform( TB_SETDISABLEDIMAGELIST, 0, Value ); Invalidate; end; procedure TSpeedbar.SetDisabledImages( Value : TImageList ); begin if fDisabledImages <> nil then fDisabledImages.UnRegisterChanges( fDisabledImageChangeLink ); fDisabledImages := Value; if fDisabledImages <> nil then fDisabledImages.RegisterChanges( fDisabledImageChangeLink ) else SetDisabledImageList( 0 ); RecreateButtons; end; procedure TSpeedbar.HotImageListChange( Sender : TObject ); begin if HandleAllocated and ( Sender = HotImages ) then RecreateButtons; end; procedure TSpeedbar.SetHotImageList( Value : HImageList ); begin if HandleAllocated then Perform( TB_SETHOTIMAGELIST, 0, Value ); Invalidate; end; procedure TSpeedbar.SetHotImages( Value : TImageList ); begin if fHotImages <> nil then fHotImages.UnRegisterChanges( fHotImageChangeLink ); fHotImages := Value; if fHotImages <> nil then fHotImages.RegisterChanges( fHotImageChangeLink ) else SetHotImageList( 0 ); RecreateButtons; end; procedure TSpeedbar.SetIndent( Value : integer ); begin if fIndent <> Value then begin fIndent := Value; RecreateWnd; end; end; procedure TSpeedbar.RecreateButtons; begin CreateButtons( fButtonWidth, fButtonHeight ); ResizeButtons; end; procedure TSpeedbar.GetChildren( Proc : TGetChildProc; Root : TComponent ); var i : integer; Control : TControl; begin for i := 0 to fButtons.Count - 1 do Proc( TComponent( fButtons[i] ) ); for i := 0 to ControlCount - 1 do begin Control := Controls[i]; if ( Control.Owner = Root ) and ( fButtons.IndexOf( Control ) = -1 ) then Proc( Control ); end; end; procedure TSpeedbar.Loaded; var i : integer; begin inherited; ResizeButtons; RepositionButtons( 0 ); for i := 0 to fButtons.Count - 1 do if ( TControl( fButtons[i] ) is TSpeedbarButton ) then with TSpeedbarButton( fButtons[i] ) do if fStreamedDown then begin Down := true; fStreamedDown := false; end; end; procedure TSpeedbar.BeginUpdate; begin Inc( fUpdateCount ); end; procedure TSpeedbar.EndUpdate; begin Dec( fUpdateCount ); end; procedure TSpeedbar.ResizeButtons; begin if Wrapable and not ( csLoading in ComponentState ) and HandleAllocated then begin Perform( TB_AUTOSIZE, 0, 0 ); if AutoSize then AdjustSize; end; end; function TSpeedbar.InternalButtonCount : integer; begin Result := Perform( TB_BUTTONCOUNT, 0, 0 ); end; function TSpeedbar.ButtonIndex( OldIndex, aLeft, aTop : integer ) : integer; var Adjust : boolean; PosTop, PosBottom : integer; Candidates : TList; RowTop, RowBottom : integer; begin Candidates := TList.Create; try PosTop := 0; PosBottom := 0; Adjust := false; for Result := 0 to fButtons.Count - 1 do begin if aLeft <= TControl( fButtons[Result] ).Left then begin RowTop := TControl( fButtons[Result] ).Top; RowBottom := RowTop + TControl( fButtons[Result] ).Height; Adjust := true; if ( Candidates.Count > 0 ) and ( ( PosTop in [RowTop..RowBottom] ) or ( PosBottom in [RowTop..RowBottom] ) ) then Continue; Candidates.Add( Pointer( Result ) ); PosTop := TControl( fButtons[Result] ).Top; PosBottom := PosTop + TControl( fButtons[Result] ).Height; end; end; if Adjust then begin if ( Candidates.Count > 1 ) then begin for Result := Candidates.Count - 1 downto 0 do if ( aTop >= TControl( fButtons[integer( Candidates[Result] )] ).Top ) then Break; if Result >= 0 then Result := integer( Candidates[Result] ); end else Result := integer( Candidates[0] ); end else if aLeft > TControl( fButtons.Last ).Left then Result := fButtons.Count else Result := OldIndex; // No re-ordering finally Candidates.Free; end; end; function TSpeedbar.ReorderButton( OldIndex, aLeft, aTop : integer ) : boolean; var NewIndex : integer; Control : TControl; begin Result := false; NewIndex := ButtonIndex( OldIndex, aLeft, aTop ); if NewIndex <> OldIndex then begin // If we are inserting to the right of our deletion then account for shift if OldIndex < NewIndex then Dec( NewIndex ); Control := fButtons[OldIndex]; fButtons.Delete( OldIndex ); fButtons.Insert( NewIndex, Control ); BeginUpdate; try Perform( TB_DELETEBUTTON, OldIndex, 0 ); UpdateItem( TB_INSERTBUTTON, NewIndex, NewIndex ); finally EndUpdate; end; Result := true; end; end; procedure TSpeedbar.AdjustControl( Control : TControl ); var i, Pos : integer; R : TRect; Reordered, NeedsUpdate : boolean; begin Pos := fButtons.IndexOf( Control ); if Pos <> -1 then begin Reordered := ReorderButton( Pos, Control.Left, Control.Top ); NeedsUpdate := false; if Reordered then begin i := fButtons.IndexOf( Control ); if i < Pos then Pos := i; end else if Perform( TB_GETITEMRECT, Pos, Longint( @R ) ) <> 0 then begin NeedsUpdate := Control.Width <> R.Right - R.Left; Reordered := NeedsUpdate; end; if Control.Height <> ButtonHeight then ButtonHeight := Control.Height else if Reordered then begin if NeedsUpdate then UpdateButton( Pos ); ResizeButtons; RepositionButtons( 0 ); end else RepositionButton( Pos ); end; end; procedure TSpeedbar.AlignControls( AControl : TControl; var Rect : TRect ); begin if (fUpdateCount <= 0) and Assigned( AControl ) and not ( AControl is TSpeedbarButton ) then AdjustControl( AControl ); end; procedure TSpeedbar.WMEraseBkgnd( var Message : TWMEraseBkgnd ); begin if Flat and ( Parent is TReBar ) then begin DefaultHandler( Message ); RedrawWindow( Handle, nil, 0, RDW_INVALIDATE or RDW_ALLCHILDREN ); end else inherited; end; procedure TSpeedbar.WMNotifyFormat( var Message : TMessage ); begin with Message do Result := DefWindowProc( Handle, Msg, WParam, LParam ); end; procedure TSpeedbar.WMSize( var Message : TWMSize ); var LastIndex : integer; PrevR, NewR : TRect; Resized : boolean; begin if Wrapable then begin // Detect change in height and adjust if necessary LastIndex := InternalButtonCount - 1; if LastIndex >= 0 then Perform( TB_GETITEMRECT, LastIndex, integer( @PrevR ) ); inherited; if LastIndex >= 0 then begin Perform( TB_GETITEMRECT, LastIndex, integer( @NewR ) ); if ( NewR.Right <> PrevR.Right ) or ( NewR.Bottom <> PrevR.Bottom ) then begin Resized := ( Align in [alNone, alLeft, alRight] ) and ( NewR.Right <> PrevR.Right ) or not ( Align in [alNone, alLeft, alRight] ) and ( NewR.Bottom <> PrevR.Bottom ); if Resized and AutoSize then AdjustSize; RepositionButtons( 0 ); end; end; end else inherited; if Flat and HandleAllocated then RedrawWindow( Handle, nil, 0, RDW_INVALIDATE or RDW_FRAME ); end; procedure TSpeedbar.WMWindowPosChanged( var Message : TWMWindowPosChanged ); begin inherited; if not ( csLoading in ComponentState ) and ( Message.WindowPos^.flags and SWP_NOSIZE = 0 ) then Resize; end; procedure TSpeedbar.WMWindowPosChanging( var Message : TWMWindowPosChanging ); var LastIndex : integer; OldSize : integer; Resized : boolean; R : TRect; function BorderSize( Vertical : boolean ) : integer; const EdgeWidths : array[boolean, boolean] of integer = ( ( 0, 1 ), ( 1, 2 ) ); var Adjust : integer; begin Result := 2 * BorderWidth; Adjust := EdgeWidths[EdgeInner <> esNone, EdgeOuter <> esNone]; if Adjust <> 0 then if Vertical then begin if ebTop in EdgeBorders then Inc( Result, Adjust ); if ebBottom in EdgeBorders then Inc( Result, Adjust ); end else begin if ebLeft in EdgeBorders then Inc( Result, Adjust ); if ebRight in EdgeBorders then Inc( Result, Adjust ); end; end; begin if AutoSize then begin LastIndex := InternalButtonCount - 1; if ( ( LastIndex >= 0 ) or not ( csDesigning in ComponentState ) ) and ( Message.WindowPos^.flags and SWP_NOSIZE = 0 ) then begin if LastIndex >= 0 then Perform( TB_GETITEMRECT, LastIndex, integer( @R ) ) else R := Rect( 0, 0, 0, 0 ); with Message.WindowPos^ do case Align of alNone : begin OldSize := cx; cx := R.Right + BorderSize( false ); // Take maximum size if cx > OldSize then Resized := true else begin cx := OldSize; Resized := false; end; OldSize := cy; cy := R.Bottom + BorderSize( true ); // Take maximum size if cy > OldSize then Resized := true else cy := OldSize; end; alLeft, alRight : begin OldSize := cx; cx := R.Right + BorderSize( false ); Resized := cx <> OldSize; end; alTop, alBottom : begin OldSize := cy; cy := R.Bottom + BorderSize( true ); Resized := cy <> OldSize; end; else Resized := false; end; if Resized then PostMessage( Handle, CN_REQUESTALIGN, 0, 0 ); end; end; inherited; end; procedure TSpeedbar.WndProc( var Message : TMessage ); var Control : TControl; CapControl : TControl; function IsSpeedbarButtonMouseMsg( var Message : TWMMouse ) : boolean; begin if GetCapture = Handle then begin CapControl := GetCaptureControl; if Assigned( CapControl ) and ( CapControl.Parent <> Self ) then CapControl := nil; end; Control := ControlAtPos( SmallPointToPoint( Message.Pos ), false ); Result := Assigned( Control ) and ( Control is TSpeedbarButton ) and not Control.Dragging; end; begin if not ( csDesigning in ComponentState ) then case Message.Msg of WM_MOUSEMOVE : if Flat then begin // Default hit-test for flat style buttons in Speedbar is off by 1 // pixel in x and y. Adjust here so that default painting will occur // for tool buttons. Inc( Message.LParamLo ); Inc( Message.LParamHi ); DefaultHandler( Message ); Dec( Message.LParamLo ); Dec( Message.LParamHi ); end else DefaultHandler( Message ); WM_LBUTTONUP : if IsSpeedbarButtonMouseMsg( TWMMouse( Message ) ) and ( CapControl = Control ) then begin DefaultHandler( Message ); UpdateButtonStates; end; WM_LBUTTONDOWN, WM_LBUTTONDBLCLK : if IsSpeedbarButtonMouseMsg( TWMMouse( Message ) ) then begin inherited WndProc( Message ); if not Control.Dragging then begin DefaultHandler( Message ); if TSpeedbarButton( Control ).CheckMenuDropDown then begin Message.Msg := WM_LBUTTONUP; DefaultHandler( Message ); inherited; end; end; exit; end; end; inherited; end; procedure TSpeedbar.CMControlChange( var Message : TCMControlChange ); begin with Message do if Inserting then InsertButton( Control ) else RemoveButton( Control ); end; procedure TSpeedbar.CMEnabledChanged( var Message : TMessage ); begin inherited; Broadcast( Message ); end; procedure TSpeedbar.CMColorChanged( var Message : TMessage ); begin inherited; RecreateWnd; end; procedure TSpeedbar.CMSysFontChanged( var Message : TMessage ); begin inherited; RecreateWnd; end; procedure TSpeedbar.CNRequestAlign( var Message : TMessage ); begin RequestAlign; end; // TReBand ======================================================================================= constructor TReBand.Create( Collection : TCollection ); begin fWidth := 40; fBreak := true; fColor := clBtnFace; fFixedBackground := true; fImageIndex := -1; fMinHeight := 25; fParentColor := true; fParentBitmap := true; fBitmap := TBitmap.Create; fBitmap.OnChange := BitmapChanged; fVisible := true; fDDB := TBitmap.Create; inherited; ParentColorChanged; ParentBitmapChanged; end; destructor TReBand.Destroy; var AControl : TWinControl; begin fDDB.Free; fBitmap.Free; AControl := Control; fControl := nil; inherited; if Assigned( AControl ) and not ( csDestroying in AControl.ComponentState ) and AControl.HandleAllocated then begin AControl.BringToFront; AControl.Perform( CM_SHOWINGCHANGED, 0, 0 ); end; end; procedure TReBand.Assign( Source : TPersistent ); function FindControl( AControl : TWinControl ) : TWinControl; begin if Assigned( AControl ) then Result := ReBar.Owner.FindComponent( AControl.Name ) as TWinControl else Result := nil; end; begin if Source is TReBand then begin Bitmap := TReBand( Source ).Bitmap; Break := TReBand( Source ).Break; Color := TReBand( Source ).Color; FixedBackground := TReBand( Source ).FixedBackground; FixedSize := TReBand( Source ).FixedSize; HorizontalOnly := TReBand( Source ).HorizontalOnly; ImageIndex := TReBand( Source ).ImageIndex; MinHeight := TReBand( Source ).MinHeight; MinWidth := TReBand( Source ).MinWidth; ParentBitmap := TReBand( Source ).ParentBitmap; ParentColor := TReBand( Source ).ParentColor; Text := TReBand( Source ).Text; Visible := TReBand( Source ).Visible; Width := TReBand( Source ).Width; Control := FindControl( TReBand( Source ).Control ); end else inherited; end; function TReBand.GetDisplayName : string; begin Result := fText; if Result = '' then Result := inherited GetDisplayName; end; function TReBand.GetVisible : boolean; begin Result := fVisible and ( not ReBar.Vertical or not fHorizontalOnly ); end; function TReBand.ReBar : TReBar; begin Result := TReBands( Collection ).fReBar; end; procedure TReBand.ParentColorChanged; begin if fParentColor then begin SetColor( ReBar.Color ); fParentColor := true; end; end; procedure TReBand.ParentBitmapChanged; begin BitmapChanged( Self ); end; procedure TReBand.BitmapChanged( Sender : TObject ); begin if not ParentBitmap then begin fDDB.Assign( fBitmap ); if not fDDB.Empty then fDDB.HandleType := bmDDB; end else fDDB.Assign( nil ); Changed( false ); end; procedure TReBand.SetBitmap( Value : TBitmap ); begin fParentBitmap := false; fBitmap.Assign( Value ); Changed( true ); end; function TReBand.GetHeight : integer; begin if Visible then Result := ReBar.GetRowHeight( fID ) else Result := 0; end; procedure TReBand.SetBorderStyle( Value : TBorderStyle ); begin if fBorderStyle <> Value then begin fBorderStyle := Value; Changed( false ); end; end; procedure TReBand.SetBreak( Value : boolean ); begin if fBreak <> Value then begin fBreak := Value; Changed( false ); end; end; procedure TReBand.SetFixedSize( Value : boolean ); begin if fFixedSize <> Value then begin if Value then begin fBreak := false; fFixedSize := true; Changed( true ); end else begin fFixedSize := false; Changed( false ); end; end; end; procedure TReBand.SetMinHeight( Value : integer ); begin if fMinHeight <> Value then begin fMinHeight := Value; Changed( false ); end; end; procedure TReBand.SetMinWidth( Value : integer ); begin if fMinWidth <> Value then begin fMinWidth := Value; Changed( FixedSize ); end; end; procedure TReBand.SetVisible( Value : boolean ); begin if fVisible <> Value then begin fVisible := Value; Changed( true ); end; end; procedure TReBand.SetHorizontalOnly( Value : boolean ); begin if fHorizontalOnly <> Value then begin fHorizontalOnly := Value; Changed( ReBar.Vertical ); end; end; procedure TReBand.SetImageIndex( Value : integer ); begin if fImageIndex <> Value then begin fImageIndex := Value; Changed( false ); end; end; procedure TReBand.SetFixedBackground( Value : boolean ); begin if fFixedBackground <> Value then begin fFixedBackground := Value; Changed( false ); end; end; procedure TReBand.SetColor( Value : TColor ); begin if fColor <> Value then begin fColor := Value; fParentColor := false; Changed( false ); end; end; procedure TReBand.SetControl( Value : TWinControl ); var Band : TReBand; PrevControl : TWinControl; begin if fControl <> Value then begin if Assigned( Value ) then begin Band := TReBands( Collection ).FindBand( Value ); if Assigned( Band ) and ( Band <> Self ) then Band.SetControl( nil ); end; PrevControl := fControl; fControl := Value; Changed( true ); if Assigned( PrevControl ) then PrevControl.Perform( CM_SHOWINGCHANGED, 0, 0 ); end; end; procedure TReBand.SetText( const Value : string ); begin if fText <> Value then begin fText := Value; Changed( true ); end; end; function TReBand.IsColorStored : boolean; begin Result := not ParentColor; end; procedure TReBand.SetParentColor( Value : boolean ); begin if fParentColor <> Value then begin fParentColor := Value; Changed( false ); end; end; function TReBand.IsBitmapStored : boolean; begin Result := not ParentBitmap; end; procedure TReBand.SetParentBitmap( Value : boolean ); begin if fParentBitmap <> Value then begin fParentBitmap := Value; ParentBitmapChanged; end; end; procedure TReBand.SetWidth( Value : integer ); begin if fWidth <> Value then begin fWidth := Value; Changed( false ); end; end; // TReBands ======================================================================================= constructor TReBands.Create( ReBar : TReBar ); begin inherited Create( TReBand ); fReBar := ReBar; end; function TReBands.Add : TReBand; begin Result := TReBand( inherited Add ); end; function TReBands.FindBand( AControl : TControl ) : TReBand; var i : integer; begin for i := 0 to Count - 1 do begin Result := TReBand( inherited GetItem( i ) ); if Result.fControl = AControl then Exit; end; Result := nil; end; function TReBands.HaveGraphic : boolean; var i : integer; begin Result := false; for i := 0 to Count - 1 do if not Items[i].fDDB.Empty then begin Result := true; Exit; end; end; function TReBands.GetItem( Index : integer ) : TReBand; begin Result := TReBand( inherited GetItem( Index ) ); end; function TReBands.GetOwner : TPersistent; begin Result := fReBar; end; procedure TReBands.SetItem( Index : integer; Value : TReBand ); begin inherited SetItem( Index, Value ); end; procedure TReBands.Update( Item : TCollectionItem ); begin if ( Item <> nil ) then fReBar.UpdateBand( Item.Index ) else fReBar.UpdateBands; end; // TReBar ======================================================================================= const GripSize = 6; // Results for PtInGripRect grNone = 0; grGrip = 1; grCaption = 2; constructor TReBar.Create( AOwner : TComponent ); begin CheckCommonControl( ICC_COOL_CLASSES ); inherited; FComponentStyle := ComponentStyle - [csInheritable]; ControlStyle := [csAcceptsControls, csCaptureMouse, csClickEvents, csOpaque, csDoubleClicks]; Height := 75; Align := alTop; ParentColor := true; ParentFont := true; fBandBorderStyle := bsSingle; fBitmap := TBitmap.Create; fBitmap.OnChange := BitmapChanged; fCaptionFont := TFont.Create; fShowText := true; fDoubleBuffered := true; fDDB := TBitmap.Create; fBands := TReBands.Create( Self ); fImageChangeLink := TChangeLink.Create; fImageChangeLink.OnChange := ImageListChange; end; destructor TReBar.Destroy; begin fBands.Free; fImageChangeLink.Free; fDDB.Free; fCaptionFont.Free; fBitmap.Free; inherited; end; procedure TReBar.CreateParams( var Params : TCreateParams ); const DefaultStyles = CCS_NOPARENTALIGN or CCS_NODIVIDER; AutoSizeStyles : array[boolean] of integer = ( CCS_NORESIZE, 0 ); BandBorderStyles : array[TBorderStyle] of integer = ( 0, RBS_BANDBORDERS ); FixedStyles : array[boolean] of integer = ( 0, RBS_FIXEDORDER ); HeightStyles : array[boolean] of integer = ( RBS_VARHEIGHT, 0 ); VerticalStyles : array[boolean] of integer = ( 0, CCS_VERT ); begin inherited; CreateSubClass( Params, REBARCLASSNAME ); with Params do begin Style := Style or DefaultStyles or AutoSizeStyles[IsAutoSized] or BandBorderStyles[fBandBorderStyle] or FixedStyles[fFixedOrder] or HeightStyles[fFixedSize] or VerticalStyles[fVertical]; WindowClass.style := WindowClass.style and not ( CS_HREDRAW or CS_VREDRAW ) or CS_DBLCLKS; end; end; procedure TReBar.CreateWnd; begin inherited; fCaptionFont.Handle := GetCaptionFont; fCaptionFontHeight := GetCaptionFontHeight; if not ( csLoading in ComponentState ) then UpdateBands; end; procedure TReBar.AdjustSize; begin Perform( WM_SIZE, SIZE_RESTORED, word( Width ) or word( Height ) shl 16 ); end; procedure TReBar.Loaded; begin inherited; UpdateBands; end; procedure TReBar.AlignControls( AControl : TControl; var Rect : TRect ); var Band : TReBand; NewWidth, NewMinHeight, CaptionSize, W, H : integer; DoUpdate : boolean; function IsBandCurrent : boolean; var BandInfo : TReBarBandInfo; begin BandInfo.cbSize := SizeOf( TReBarBandInfo ); BandInfo.fMask := RBBIM_CHILD; Result := TWinControl( AControl ).HandleAllocated and ( Perform( RB_GETBANDINFO, Band.fID, integer( @BandInfo ) ) <> 0 ) and ( BandInfo.hwndChild = TWinControl( AControl ).Handle ); end; begin if not ( csDestroying in ComponentState ) and ( not Assigned( AControl ) or ( AControl is TWinControl ) ) and ( fUpdateCount = 0 ) then begin // Refresh bands if any control changed if Assigned( AControl ) then begin ReadBands; Band := fBands.FindBand( AControl as TWinControl ); if Assigned( Band ) then begin BeginUpdate; try CaptionSize := GetCaptionSize( Band ); if Vertical then begin W := AControl.Height; H := AControl.Width; end else begin W := AControl.Width; H := AControl.Height; end; NewWidth := W + CaptionSize; NewMinHeight := H; if ( NewWidth <> Band.Width ) or ( NewMinHeight <> Band.MinHeight ) or not IsBandCurrent then begin DoUpdate := true; Band.Width := NewWidth; Band.MinHeight := NewMinHeight; end else DoUpdate := false; finally EndUpdate; end; if DoUpdate then begin Bands.Update( Band ); ReadBands; end else AdjustSize; // Let Rebar reposition child windows end; end; end; end; procedure TReBar.Change; var Form : TCustomForm; begin if csDesigning in ComponentState then begin Form := GetParentForm( Self ); if ( Form <> nil ) and ( Form.Designer <> nil ) then Form.Designer.Modified; end; if Assigned( fOnChange ) then fOnChange( Self ); end; procedure TReBar.Resize; begin if Assigned( fOnResize ) then fOnResize( Self ); end; function TReBar.GetAlign : TAlign; begin Result := inherited Align; end; // Rebars take their text font from Windows' caption font minus any bold // characteristics it may have. function TReBar.GetCaptionFont : HFONT; var NonClientMetrics : TNonClientMetrics; begin with NonClientMetrics do begin cbSize := sizeof( TNonClientMetrics ); if not SystemParametersInfo( SPI_GETNONCLIENTMETRICS, 0, @NonClientMetrics, 0 ) then GetObject( GetStockObject( SYSTEM_FONT ), SizeOf( lfCaptionFont ), @lfCaptionFont ); // Remove any bold styles lfCaptionFont.lfWeight := FW_NORMAL; Result := CreateFontIndirect( lfCaptionFont ) end; end; function TReBar.GetCaptionFontHeight : integer; var TxtMetric : TTextMetric; begin Result := 0; if HandleAllocated then with TControlCanvas.Create do try Control := Self; Font := fCaptionFont; if ( GetTextMetrics( Handle, TxtMetric ) ) then Result := TxtMetric.tmHeight; finally Free; end; end; // Return height/width ( depending on Vertical property ) of Rebar grip area function TReBar.GetCaptionSize( Band : TReBand ) : integer; const Margin = 10; var Text : string; Adjust : boolean; begin Result := 0; Adjust := false; if Assigned( Band ) and ( ( csDesigning in ComponentState ) or Band.Visible ) then begin if ( csDesigning in ComponentState ) and not Assigned( Band.Control ) and ( Band.Text = '' ) then Text := Band.DisplayName else Text := Band.Text; if ShowText and ( Text <> '' ) then begin Adjust := true; with TControlCanvas.Create do try Control := Self; Font := fCaptionFont; if Vertical then Result := fCaptionFontHeight else Result := TextWidth( Text ); finally Free; end; end; if Band.ImageIndex >= 0 then begin if Adjust then Inc( Result, 2 ); if Assigned( fImages ) then begin Adjust := true; if Vertical then Inc( Result, fImages.Height ) else Inc( Result, fImages.Width ); end else if not Adjust then Inc( Result, GripSize - 2 ); end; if Adjust then Inc( Result, GripSize - 2 ); if ( not FixedOrder or ( Band.fID > 0 ) ) and not Band.FixedSize then Inc( Result, GripSize + Margin ); end; end; procedure TReBar.SetAlign( Value : TAlign ); var PrevAlign, NewAlign : TAlign; begin PrevAlign := inherited Align; inherited Align := Value; NewAlign := inherited Align; if NewAlign <> PrevAlign then begin case NewAlign of alLeft, alRight : fVertical := true; alTop, alBottom : fVertical := false; end; if not ( csLoading in ComponentState ) then begin Perform( WM_SETREDRAW, 0, 0 ); try RecreateWnd; finally Perform( WM_SETREDRAW, 1, 0 ); end; end; end; end; procedure TReBar.SetAutoSize( Value : boolean ); begin if fAutoSize <> Value then begin RequestAlign; fAutoSize := Value; if not ( csLoading in ComponentState ) then begin Perform( WM_SETREDRAW, 0, 0 ); try RecreateWnd; finally Perform( WM_SETREDRAW, 1, 0 ); end; end; end; end; procedure TReBar.SetBands( Value : TReBands ); begin fBands.Assign( Value ); end; procedure TReBar.SetBandBorderStyle( Value : TBorderStyle ); begin if fBandBorderStyle <> Value then begin fBandBorderStyle := Value; RecreateWnd; end; end; procedure TReBar.SetFixedSize( Value : boolean ); begin if fFixedSize <> Value then begin fFixedSize := Value; RecreateWnd; end; end; procedure TReBar.SetFixedOrder( Value : boolean ); begin if fFixedOrder <> Value then begin fFixedOrder := Value; RecreateWnd; end; end; procedure TReBar.ImageListChange( Sender : TObject ); begin if HandleAllocated and ( Sender = Images ) then SetImageList( Images.Handle ); end; procedure TReBar.SetImageList( Value : HImageList ); var BarInfo : TReBarInfo; begin if HandleAllocated then begin if Value = 0 then RecreateWnd else begin BarInfo.cbSize := SizeOf( TReBarInfo ); BarInfo.fMask := RBIM_IMAGELIST; BarInfo.himl := Value; Perform( RB_SETBARINFO, 0, integer( @BarInfo ) ); Invalidate; end; end; end; procedure TReBar.SetImages( Value : TImageList ); begin if fImages <> nil then fImages.UnRegisterChanges( fImageChangeLink ); fImages := Value; if fImages <> nil then begin fImages.RegisterChanges( fImageChangeLink ); SetImageList( fImages.Handle ); end else SetImageList( 0 ); end; procedure TReBar.SetShowText( Value : boolean ); begin if fShowText <> Value then begin fShowText := Value; if not ( csLoading in ComponentState ) then UpdateBands; end; end; procedure TReBar.Notification( aComponent : TComponent; Operation : TOperation ); var Band : TReBand; begin inherited; if not ( csDestroying in ComponentState ) and ( Operation = opRemove ) then begin if ( aComponent is TWinControl ) then begin Band := Bands.FindBand( TControl( aComponent ) ); if Assigned( Band ) then Band.fControl := nil; end else if aComponent = fImages then Images := nil; end; end; function TReBar.GetPalette : HPALETTE; begin if not fDDB.Empty then Result := fDDB.Palette else Result := inherited GetPalette; end; procedure TReBar.BitmapChanged( Sender : TObject ); var i : integer; begin fDDB.Assign( fBitmap ); if not fDDB.Empty then fDDB.HandleType := bmDDB; for i := 0 to fBands.Count - 1 do Bands[i].ParentBitmapChanged; if HandleAllocated then RedrawWindow( Handle, nil, 0, RDW_INVALIDATE or RDW_ERASE or RDW_ALLCHILDREN ); end; procedure TReBar.BeginUpdate; begin Inc( fUpdateCount ); end; procedure TReBar.EndUpdate; begin Dec( fUpdateCount ); end; function TReBar.IsAutoSized : boolean; begin Result := fAutoSize and ( ( fVertical and ( Align in [alLeft, alRight] ) ) or not fVertical and ( Align in [alTop, alBottom] ) ); end; function TReBar.IsBackgroundDirty : boolean; begin Result := HandleAllocated and not IsAutoSized; end; procedure TReBar.SetBitmap( Value : TBitmap ); begin fBitmap.Assign( Value ); end; procedure TReBar.SetVertical( Value : boolean ); var R : TRect; begin if fVertical <> Value then begin fVertical := Value; R := BoundsRect; Perform( WM_SETREDRAW, 0, 0 ); try RecreateWnd; finally Perform( WM_SETREDRAW, 1, 0 ); end; BoundsRect := R; Invalidate; end; end; procedure TReBar.DisableBands; var i : integer; BandInfo : TReBarBandInfo; begin if HandleAllocated then begin BandInfo.cbSize := SizeOf( TReBarBandInfo ); BandInfo.fMask := RBBIM_CHILD; BandInfo.hwndChild := 0; for i := 0 to fBands.fVisibleCount - 1 do Perform( RB_SETBANDINFO, i, integer( @BandInfo ) ); end; end; function TReBar.UpdateItem( Message, FromIndex, ToIndex : integer ) : boolean; const BorderStyles : array[TBorderStyle] of integer = ( 0, RBBS_CHILDEDGE ); BreakStyles : array[boolean] of integer = ( 0, RBBS_BREAK ); FixedBmpStyles : array[boolean] of integer = ( 0, RBBS_FIXEDBMP ); FixedSizeStyles : array[boolean] of integer = ( 0, RBBS_FIXEDSIZE ); var BandInfo : TReBarBandInfo; Band : TReBand; Text : string; begin Result := false; if HandleAllocated then begin Band := Bands[FromIndex]; if Assigned( Band.Control ) then with Band.Control do begin BeginUpdate; try Parent := Self; finally EndUpdate; end; if not ( csDesigning in Self.ComponentState ) then Visible := Band.Visible; end; if not ( csDesigning in ComponentState ) and not Band.Visible then Exit; FillChar( BandInfo, SizeOf( BandInfo ), 0 ); with BandInfo do begin cbSize := SizeOf( TReBarBandInfo ); wID := integer( Band ); if Band.ParentColor then clrBack := ColorToRGB( Color ) else clrBack := ColorToRGB( Band.Color ); with Band do fStyle := BreakStyles[Break] or FixedSizeStyles[FixedSize] or BorderStyles[BorderStyle] or FixedBmpStyles[FixedBackground]; fMask := RBBIM_STYLE or RBBIM_COLORS or RBBIM_SIZE or RBBIM_BACKGROUND or RBBIM_IMAGE or RBBIM_ID; if Band.ParentBitmap then hbmBack := fDDB.Handle else hbmBack := Band.fDDB.Handle; iImage := Band.ImageIndex; if Assigned( Band.Control ) and Band.Control.Visible then hwndChild := Band.Control.Handle; cx := Band.Width; if Band.FixedSize and ( Band.MinWidth <= 0 ) and Assigned( Band.Control ) then cxMinChild := Band.Control.Width else cxMinChild := Band.MinWidth; cyMinChild := Band.MinHeight; fMask := fMask or RBBIM_CHILD or RBBIM_CHILDSIZE; if ShowText then begin if ( csDesigning in ComponentState ) and not Assigned( Band.Control ) and ( Band.Text = '' ) then Text := Band.DisplayName else Text := Band.Text; lpText := PChar( Text ); fMask := fMask or RBBIM_TEXT; end; end; Result := Perform( Message, ToIndex, integer( @BandInfo ) ) <> 0; end; end; procedure TReBar.UpdateBand( Index : integer ); begin if HandleAllocated and ( fUpdateCount = 0 ) then with Bands[Index] do UpdateItem( RB_SETBANDINFO, fID, fID ) end; function TReBar.ReadBands : boolean; var i : integer; BandInfo : TReBarBandInfo; Band : TReBand; NewBreak : boolean; NewWidth : integer; NewIndex : integer; function FindNextVisible( Position : integer ) : integer; begin if Position >= fBands.Count - 1 then Result := Position else for Result := Position to fBands.Count - 2 do if fBands[Result].Visible then Break; end; begin Result := false; if HandleAllocated and ( fUpdateCount = 0 ) then begin // Retrieve current band settings BandInfo.cbSize := SizeOf( TReBarBandInfo ); BandInfo.fMask := RBBIM_STYLE or RBBIM_SIZE or RBBIM_ID; BeginUpdate; try for i := 0 to fBands.fVisibleCount - 1 do if ( Perform( RB_GETBANDINFO, i, integer( @BandInfo ) ) <> 0 ) and ( BandInfo.wID <> 0 ) then with BandInfo do begin Band := TReBand( wID ); with Band do begin fID := i; NewBreak := fStyle and RBBS_BREAK <> 0; if Visible then NewIndex := FindNextVisible( i ) else NewIndex := i; NewWidth := cx; if ( Break <> NewBreak ) or ( Index <> NewIndex ) or ( Width <> NewWidth ) then begin Result := true; Break := NewBreak; Index := NewIndex; Width := NewWidth; end; end; end; finally EndUpdate; end; end; if Result then Change; end; procedure TReBar.UpdateBands; var i : integer; begin if HandleAllocated and ( fUpdateCount = 0 ) then begin BeginUpdate; Perform( WM_SETREDRAW, 0, 0 ); try DisableBands; for i := 0 to Perform( RB_GETBANDCOUNT, 0, 0 ) - 1 do Perform( RB_DELETEBAND, 0, 0 ); if FixedOrder then // Add bands from first to last for i := 0 to Bands.Count - 1 do UpdateItem( RB_INSERTBAND, i, -1 ) else // Add bands from last to first for i := Bands.Count - 1 downto 0 do UpdateItem( RB_INSERTBAND, i, 0 ); if Assigned( fImages ) then SetImageList( fImages.Handle ); finally Perform( WM_SETREDRAW, 1, 0 ); EndUpdate; end; fBands.fVisibleCount := Perform( RB_GETBANDCOUNT, 0, 0 ); ReadBands; if IsAutoSized then AdjustSize; RedrawWindow( Handle, nil, 0, RDW_INVALIDATE or RDW_ALLCHILDREN ); end; end; // Return height of row for given band function TReBar.GetRowHeight( Index : integer ) : integer; var BandInfo : TReBarBandInfo; i, Len, MaxMinHeight, BandCount : integer; begin Result := 0; if ( fBands.fVisibleCount > 0 ) and ( Index < fBands.fVisibleCount ) then begin BandInfo.cbSize := SizeOf( TReBarBandInfo ); BandInfo.fMask := RBBIM_STYLE; BandCount := 0; MaxMinHeight := 0; for i := 0 to fBands.fVisibleCount - 1 do if Perform( RB_GETBANDINFO, i, integer( @BandInfo ) ) <> 0 then begin Len := Perform( RB_GETROWHEIGHT, i, 0 ); if ( i = 0 ) or ( BandInfo.fStyle and RBBS_BREAK <> 0 ) then begin if Index < i then begin if ( BandCount > 0 ) and ( Len = Result ) then Result := MaxMinHeight; Break; end else begin BandCount := 0; MaxMinHeight := Len; Result := 0 end; end else begin Inc( BandCount ); if ( Index > i ) and ( Len > MaxMinHeight ) then MaxMinHeight := Len; end; if Len > Result then Result := Len; end; end; end; // Return true if given point is within one of the grip areas function TReBar.PtInGripRect( const Pos : TPoint ) : integer; const BandBorderSize : array[TBorderStyle] of integer = ( 0, 2 ); var BandInfo : TReBarBandInfo; i : integer; W, H : integer; x, y, PrevW, PrevH : integer; R : TRect; begin Result := grNone; if fBands.fVisibleCount > 0 then begin x := 0; y := 0; PrevW := 0; PrevH := 0; BandInfo.cbSize := SizeOf( TReBarBandInfo ); BandInfo.fMask := RBBIM_STYLE or RBBIM_SIZE or RBBIM_ID; for i := 0 to fBands.fVisibleCount - 1 do if ( Perform( RB_GETBANDINFO, i, integer( @BandInfo ) ) <> 0 ) and ( BandInfo.wID <> 0 ) then begin if ( i = 0 ) or ( BandInfo.fStyle and RBBS_BREAK <> 0 ) then begin x := 2; Inc( y, PrevH ); end else Inc( x, PrevW ); W := GetCaptionSize( TReBand( BandInfo.wID ) ); H := GetRowHeight( i ); if Vertical then R := Rect( y, x, y + H, x + W ) else R := Rect( x, y, x + W, y + H ); if PtInRect( R, Pos ) then begin // Check if point is in caption only if Vertical then Inc( R.Top, GripSize ) else Inc( R.Left, GripSize ); if PtInRect( R, Pos ) then Result := grCaption else Result := grGrip; Exit; end; PrevH := H + BandBorderSize[BandBorderStyle]; if BandBorderStyle = bsNone then Inc( PrevH ); PrevW := BandInfo.cx + BandBorderSize[BandBorderStyle]; end; end; end; procedure TReBar.WMCaptureChanged( var Message : TMessage ); begin inherited; // Synchronize band properties - something may have changed if not ( csClicked in ControlState ) then PostMessage( Handle, CN_BANDCHANGE, 0, 0 ) end; procedure TReBar.WMEraseBkgnd( var Message : TWMEraseBkgnd ); begin if IsBackgroundDirty or ( IsAutoSized and ( Bands.Count = 0 ) ) then inherited; DefaultHandler( Message ); end; procedure TReBar.WMLButtonDown( var Message : TWMLButtonDown ); begin if ( PtInGripRect( SmallPointToPoint( Message.Pos ) ) = grNone ) then inherited else begin fTrackDrag := Message.Pos; DefaultHandler( Message ); end; end; procedure TReBar.WMLButtonUp( var Message : TWMLButtonUp ); begin if not ( csDesigning in ComponentState ) or ( csClicked in ControlState ) or ( ( fTrackDrag.x < Message.XPos - 1 ) and ( fTrackDrag.x > Message.XPos + 1 ) and ( fTrackDrag.y < Message.YPos - 1 ) and ( fTrackDrag.y > Message.YPos + 1 ) ) then inherited else MouseCapture := false; end; procedure TReBar.WMNotifyFormat( var Message : TMessage ); begin with Message do Result := DefWindowProc( Handle, Msg, WParam, LParam ); end; procedure TReBar.WMSetCursor( var Message : TWMSetCursor ); var P : TPoint; Grip : integer; begin with Message do if ( CursorWnd = Handle ) and ( Smallint( HitTest ) = HTCLIENT ) then begin Result := 1; GetCursorPos( P ); Grip := PtInGripRect( ScreenToClient( P ) ); if Grip <> grNone then begin if Grip = grCaption then Windows.SetCursor( Screen.Cursors[crHandPoint] ) else if Vertical then Windows.SetCursor( Screen.Cursors[crSizeNS] ) else Windows.SetCursor( Screen.Cursors[crSizeWE] ); end else Windows.SetCursor( Screen.Cursors[crDefault] ); end else inherited; end; procedure TReBar.WMSize( var Message : TWMSize ); begin inherited; if IsAutoSized then RequestAlign; ReadBands; if IsBackgroundDirty then Invalidate; end; procedure TReBar.WMWindowPosChanged( var Message : TWMWindowPosChanged ); var R : TRect; Wnd : HWnd; begin if IsAutoSized then R := BoundsRect; inherited; if IsAutoSized then begin Wnd := GetParentHandle; if Wnd <> 0 then InvalidateRect( Wnd, @R, true ); end; if not ( csLoading in ComponentState ) and ( Message.WindowPos^.flags and SWP_NOSIZE = 0 ) then Resize; end; procedure TReBar.WndProc( var Message : TMessage ); begin if ( csDesigning in ComponentState ) then case Message.Msg of WM_MOUSEMOVE, WM_RBUTTONDBLCLK : begin // Enabled csDesignInteractive temporarily so that we may handle the // design-time dragging of bands ControlStyle := ControlStyle + [csDesignInteractive]; try inherited; finally ControlStyle := ControlStyle - [csDesignInteractive]; end; Exit; end; // We just dragged a band disable any drag events WM_LBUTTONUP : MouseCapture := false; end; inherited; end; procedure TReBar.CMColorChanged( var Message : TMessage ); var i : integer; begin inherited; if Assigned( fBands ) then for i := 0 to fBands.Count - 1 do Bands[i].ParentColorChanged; if HandleAllocated then InvalidateRect( Handle, nil, true ); end; procedure TReBar.CMControlChange( var Message : TCMControlChange ); var Band : TReBand; begin if fUpdateCount = 0 then begin // Can only accept TWinControl descendants if not ( csLoading in ComponentState ) and ( Message.Control is TWinControl ) then if Message.Inserting then with TReBand( Bands.Add ) do SetControl( TWinControl( Message.Control ) ) else begin Band := Bands.FindBand( Message.Control ); if Assigned( Band ) then begin Band.Free; Change; end; end; end; end; procedure TReBar.CMDesignHitTest( var Message : TCMDesignHitTest ); begin if PtInGripRect( SmallPointToPoint( Message.Pos ) ) <> grNone then Message.Result := 1 else inherited; end; procedure TReBar.CMSysColorChange( var Message : TMessage ); begin inherited; if not ( csLoading in ComponentState ) then begin Message.Msg := WM_SYSCOLORCHANGE; DefaultHandler( Message ); end; end; procedure TReBar.CMSysFontChanged( var Message : TMessage ); begin inherited; RecreateWnd; end; procedure TReBar.CMWinIniChange( var Message : TWMWinIniChange ); begin inherited; fCaptionFont.Handle := GetCaptionFont; fCaptionFontHeight := GetCaptionFontHeight; end; procedure TReBar.CNBandChange( var Message : TMessage ); begin ReadBands; end; procedure TReBar.CNNotify( var Message : TWMNotify ); begin if ( Message.NMHdr^.code = RBN_HEIGHTCHANGE ) and IsBackgroundDirty then Invalidate; end; // VCL Registration ======================================================================================= procedure Register; begin RegisterComponents( 'Merchise', [TSpeedbar, TRebar] ); RegisterNoIcon( [TSpeedbarButton] ); RegisterClasses( [TSpeedbarButton, TReBand, TReBands] ); end; end.
unit FH.LIBLTC; interface uses System.SysUtils, System.Classes, System.Types, System.Generics.Collections, FH.LIBLTC.LTC, FH.LIBLTC.TIMECODE, FH.LIBLTC.DECODER; Type TfhVer = record name : string; version : cardinal; versionStr : string; dateRelease : TDateTime; end; Const FHLIBLTSVER : TfhVer = (Name : 'FH.LIBLTC'; version : $01000011; versionStr : ''; dateRelease : 41534.0); Const MSG_READ = 1; MSG_DEBUG = 1; type TReadMessage = record Msg: DWORD; TC : TDateTime end; type TDecoderOnRead = procedure(Sender: TObject; timecode : TDateTime) of object; TNotifyEvent = procedure(Sender: TObject) of object; TGetStrProc = procedure(const S: string) of object; type TLibLTC = class(TThread) private FOnError : TGetStrProc; FOnDebug : TGetStrProc; FOnRead : TDecoderOnRead; FDecoder : TLTCDecoder; Function GetVersion : TfhVer; procedure DoError(const str : string); procedure DoDebug(const str : string); procedure DoRead(var Msg: TReadMessage); message MSG_READ; procedure QueueNotifyEvent(Sender: TObject; const Item: TLTCFrameExt; Action: TCollectionNotification); protected procedure Execute; override; public constructor create(); overload; destructor Destroy; override; procedure Terminate; property decoder: TLTCDecoder read FDecoder write FDecoder; property Version : TfhVer read GetVersion; procedure Write(buf: array of ltcsnd_sample_t; size : size_t; posinfo : ltc_off_t); function Read: TLTCFrameExt; property OnError: TGetStrProc read FOnError write FOnError; property OnDebug: TGetStrProc read FOnDebug write FOnDebug; property OnRead: TDecoderOnRead read FOnRead write FOnRead; end; implementation constructor TLibLTC.create(); begin inherited Create(true); FDecoder := TLTCDecoder.create(); FDecoder.queue_len:=32; //FDecoder.Queue.OnNotify:=QueueNotifyEvent; // Priority := TThreadPriority.tpLower; FreeOnTerminate:=false; end; destructor TLibLTC.Destroy; begin FDecoder.Destroy; inherited Destroy; end; procedure TLibLTC.Terminate; begin inherited Terminate; end; procedure TLibLTC.Execute; var LTCFrameExt: TLTCFrameExt; SMPTETimecode : TSMPTETimecode; r_time: TDateTime; r_date : TDateTime; DateTimeTimecode : TDateTime; begin while not Terminated do begin if FDecoder.Read(LTCFrameExt) then begin ltc_frame_to_time(SMPTETimecode, LTCFrameExt.ltc, 0); TryEncodeTime(SMPTETimecode.hours, SMPTETimecode.mins, SMPTETimecode.secs, SMPTETimecode.frame * 40, r_time); TryEncodeDate(SMPTETimecode.years, SMPTETimecode.months, SMPTETimecode.days, r_date); DateTimeTimecode:=r_date+r_time; synchronize(procedure begin if assigned(FOnRead) then FOnRead(self, DateTimeTimecode); end); end; sleep(10); end; end; Function TLibLTC.GetVersion : TfhVer; begin result.name:=FHLIBLTSVER.name; result.version:=FHLIBLTSVER.version; result.versionStr:=format('%s-%d.%d.%d.%d', [FHLIBLTSVER.name, FHLIBLTSVER.version shr 24 and $FF, FHLIBLTSVER.version shr 16 and $FF, FHLIBLTSVER.version shr 8 and $FF, FHLIBLTSVER.version and $FF]); result.dateRelease:=FHLIBLTSVER.dateRelease; end; procedure TLibLTC.DoError(const str : string); begin if assigned(FOnError) then FOnError(str); {$IfDef OnDebug} DoDebug(format('TfhDSPlayer.DoError(str=%s)', [str])); {$EndIf} end; procedure TLibLTC.DoDebug(const str : string); begin if assigned(FOnDebug) then FOnDebug(str); end; procedure TLibLTC.QueueNotifyEvent(Sender: TObject; const Item: TLTCFrameExt; Action: TCollectionNotification); var stime : TSMPTETimecode; r_time: TDateTime; r_date : TDateTime; Msg: TReadMessage; begin case Action of cnAdded: begin ltc_frame_to_time(stime, Item.ltc, 0); TryEncodeTime(stime.hours, stime.mins, stime.secs, stime.frame * 40, r_time); TryEncodeDate(stime.years, stime.months, stime.days, r_date); with Msg do begin Msg := MSG_READ; TC := r_date+r_time; end; self.Dispatch(Msg); end; end; end; procedure TLibLTC.DoRead(var Msg: TReadMessage); begin if assigned(FOnRead) then begin TMonitor.Enter(Self); try FOnRead(self, Msg.TC); TMonitor.PulseAll(Self); finally TMonitor.Exit(Self); end; end; end; procedure TLibLTC.Write(buf: array of ltcsnd_sample_t; size : size_t; posinfo : ltc_off_t); begin FDecoder.Write(buf, size, posinfo); end; function TLibLTC.Read: TLTCFrameExt; var LTCFrameExt: TLTCFrameExt; begin FDecoder.Read(LTCFrameExt); result:=LTCFrameExt; end; end.
{Search history author: (ERT) Ferenc Kiffer, Hungary <kifferferenc@yahoo.com>} unit GX_GrepExpert; interface uses Classes, Graphics, GX_Experts, GX_ConfigurationInfo, GX_GrepBackend, IniFiles; type TGrepExpert = class(TGX_Expert) private FHistoryIniVersion: Integer; //0: old, 1: renamed new, 2: multiINI/indexed new FGrepMiddle: Boolean; FGrepExpandAll: Boolean; FGrepExpandIf: Boolean; FGrepExpandIfFiles: Integer; FGrepExpandIfMatches: Integer; FGrepExpandFew: Boolean; FGrepExpandFewLines: Integer; FSearchList: TStrings; FReplaceList: TStrings; FMaskList: TStrings; FDirList: TStrings; FExcludedDirsList: TStrings; FGrepCaseSensitive: Boolean; FGrepCode: Boolean; FGrepStrings: Boolean; FGrepComments: Boolean; FGrepInterface: Boolean; FGrepImplementation: Boolean; FGrepInitialization: Boolean; FGrepFinalization: Boolean; FGrepForms: Boolean; FGrepSQLFiles: Boolean; FGrepSearch: Integer; FGrepSub: Boolean; FGrepWholeWord: Boolean; FGrepRegEx: Boolean; FGrepSaveOption: TGrepSaveOption; FGrepUseCurrentIdent: Boolean; FNumContextLines: Integer; FListFont: TFont; FListUseDefaultColors: Boolean; FListMatchTextColor: TColor; FListMatchBrushColor: TColor; FContextFont: TFont; FContextMatchColor: TColor; FAutoHide: Boolean; FContextMatchLineColor: TColor; FGrepSaveHistoryListItems: Integer; FHistoryList: TGrepHistoryList; FContextSaveFixedHeight: Boolean; FGrepOnlySaveParamsAction: Integer; FGrepFileListDeleteAfterDays: Boolean; FGrepHistoryListDefaultPage: Integer; FGrepDeleteAfterDays: Integer; FGrepSaveOptionDefaultValue: Integer; FGrepOpenSaveOptionDefaultValue: Integer; FGrepEmptyMoveToOnlySaveParams: Boolean; FGrepAdvancedOptions: Boolean; FGrepQuickRefresh: Boolean; FGrepHistoryPagesTabMultiline: Boolean; FGrepHistoryPagesTabWidth: Integer; FGrepMouseWheelPrevNextMatch: Boolean; function GetGrepSaveHistoryListItems(AIndex: Integer): Boolean; procedure SetSearchList(New: TStrings); procedure SetReplaceList(New: TStrings); procedure SetMaskList(New: TStrings); procedure SetDirList(New: TStrings); procedure SetExcludedDirsList(const Value: TStrings); procedure LoadHistoryList(AGrepSettings : TGrepSettings); function FillGrepSettings: TGrepSettings; function GetSaveOption: TGrepSaveOption; function GetOpenSaveOption: TGrepSaveOption; protected function CreateSettings: TCustomIniFile; procedure SetActive(New: Boolean); override; procedure InternalLoadSettings(Settings: TExpertSettings); override; procedure InternalSaveSettings(Settings: TExpertSettings); override; public constructor Create; override; destructor Destroy; override; procedure ShowModal; function GetDefaultShortCut: TShortCut; override; function GetActionCaption: string; override; class function ConfigurationKey: string; override; class function GetName: string; override; function GetHelpString: string; override; function GrepConfigPath: String; function GrepHistorySettingsFileName: String; procedure Execute(Sender: TObject); override; procedure Configure; override; procedure HistoryListSaveSettings(AItemIndex: Integer = -1); //if -1 then all procedure HistoryListSaveSearchListSettings; procedure HistoryListDeleteFromSettings(ADelMode: TGrepDeleteMode; AItemIndex: Integer = -1); //if -1 then all property GrepMiddle: Boolean read FGrepMiddle write FGrepMiddle; property GrepExpandAll: Boolean read FGrepExpandAll write FGrepExpandAll; property GrepExpandIf: Boolean read FGrepExpandIf write FGrepExpandIf; property GrepExpandIfFiles: Integer read FGrepExpandIfFiles write FGrepExpandIfFiles; property GrepExpandIfMatches: Integer read FGrepExpandIfMatches write FGrepExpandIfMatches; property GrepExpandFew: Boolean read FGrepExpandFew write FGrepExpandFew; property GrepExpandFewLines: Integer read FGrepExpandFewLines write FGrepExpandFewLines; property GrepCaseSensitive: Boolean read FGrepCaseSensitive write FGrepCaseSensitive; property GrepCode: Boolean read FGrepCode write FGrepCode; property GrepStrings: Boolean read FGrepStrings write FGrepStrings; property GrepComments: Boolean read FGrepComments write FGrepComments; property GrepInterface: Boolean read FGrepInterface write FGrepInterface; property GrepImplementation: Boolean read FGrepImplementation write FGrepImplementation; property GrepInitialization: Boolean read FGrepInitialization write FGrepInitialization; property GrepFinalization: Boolean read FGrepFinalization write FGrepFinalization; property GrepForms: Boolean read FGrepForms write FGrepForms; property GrepSQLFiles: Boolean read FGrepSQLFiles write FGrepSQLFiles; property GrepSearch: Integer read FGrepSearch write FGrepSearch; property GrepSub: Boolean read FGrepSub write FGrepSub; property GrepWholeWord: Boolean read FGrepWholeWord write FGrepWholeWord; property GrepRegEx: Boolean read FGrepRegEx write FGrepRegEx; property GrepSaveOption: TGrepSaveOption read FGrepSaveOption write FGrepSaveOption; property GrepUseCurrentIdent: Boolean read FGrepUseCurrentIdent write FGrepUseCurrentIdent; property NumContextLines: Integer read FNumContextLines write FNumContextLines; property GrepAdvancedOptions: Boolean read FGrepAdvancedOptions write FGrepAdvancedOptions; property GrepSaveOptionDefaultValue: Integer read FGrepSaveOptionDefaultValue write FGrepSaveOptionDefaultValue; property GrepOpenSaveOptionDefaultValue: Integer read FGrepOpenSaveOptionDefaultValue write FGrepOpenSaveOptionDefaultValue; property GrepFileListDeleteAfterDays: Boolean read FGrepFileListDeleteAfterDays write FGrepFileListDeleteAfterDays; property GrepDeleteAfterDays: Integer read FGrepDeleteAfterDays write FGrepDeleteAfterDays; property GrepEmptyMoveToOnlySaveParams: Boolean read FGrepEmptyMoveToOnlySaveParams write FGrepEmptyMoveToOnlySaveParams; property GrepOnlySaveParamsAction: Integer read FGrepOnlySaveParamsAction write FGrepOnlySaveParamsAction; property GrepHistoryListDefaultPage: Integer read FGrepHistoryListDefaultPage write FGrepHistoryListDefaultPage; property GrepQuickRefresh: Boolean read FGrepQuickRefresh write FGrepQuickRefresh; property GrepHistoryPagesTabMultiline: Boolean read FGrepHistoryPagesTabMultiline write FGrepHistoryPagesTabMultiline; property GrepHistoryPagesTabWidth: Integer read FGrepHistoryPagesTabWidth write FGrepHistoryPagesTabWidth; property GrepMouseWheelPrevNextMatch: Boolean read FGrepMouseWheelPrevNextMatch write FGrepMouseWheelPrevNextMatch; property SaveOption: TGrepSaveOption read GetSaveOption; property OpenSaveOption: TGrepSaveOption read GetOpenSaveOption; property ListFont: TFont read FListFont write FListFont; property ListUseDefaultColors: Boolean read FListUseDefaultColors write FListUseDefaultColors; property ListMatchTextColor: TColor read FListMatchTextColor write FListMatchTextColor; property ListMatchBrushColor: TColor read FListMatchBrushColor write FListMatchBrushColor; property ContextFont: TFont read FContextFont write FContextFont; property ContextMatchColor: TColor read FContextMatchColor write FContextMatchColor; property ContextMatchLineColor: TColor read FContextMatchLineColor write FContextMatchLineColor; property AutoHide: Boolean read FAutoHide write FAutoHide; property GrepSaveHistoryListItems: Boolean index 3 read GetGrepSaveHistoryListItems; property GrepSaveHistoryListItemsToIni: Boolean index 1 read GetGrepSaveHistoryListItems; property GrepSaveHistoryListItemsToReg: Boolean index 2 read GetGrepSaveHistoryListItems; property ContextSaveFixedHeight: Boolean read FContextSaveFixedHeight write FContextSaveFixedHeight; property SearchList: TStrings read FSearchList write SetSearchList; property ReplaceList: TStrings read FReplaceList write SetReplaceList; property MaskList: TStrings read FMaskList write SetMaskList; property DirList: TStrings read FDirList write SetDirList; property ExcludedDirsList: TStrings read FExcludedDirsList write SetExcludedDirsList; property HistoryIniVersion: Integer read FHistoryIniVersion; property HistoryList: TGrepHistoryList read FHistoryList; end; var GrepStandAlone: TGrepExpert = nil; procedure ShowGrep; {$IFNDEF GX_BCB} export; {$ENDIF GX_BCB} implementation uses SysUtils, Menus, Controls, ComCtrls, {$IFOPT D+} GX_DbugIntf, {$ENDIF D+} GX_OtaUtils, GX_GenericUtils, GX_GrepResults, GX_GrepResultsOptions, GX_IdeDock, GX_GExperts; { TGrepExpert } constructor TGrepExpert.Create; begin inherited Create; FSearchList := TStringList.Create; FReplaceList := TStringList.Create; FMaskList := TStringList.Create; FDirList := TStringList.Create; FExcludedDirsList := TStringList.Create; FListFont := TFont.Create; FListUseDefaultColors := True; FListMatchTextColor := clHighlightText; FListMatchBrushColor := clHighlight; FContextFont := TFont.Create; FContextMatchColor := clHighlight; FContextMatchLineColor := clHighlight; FNumContextLines := 2; FAutoHide := False; FHistoryList := TGrepHistoryList.Create; FGrepAdvancedOptions := False; FGrepExpandAll := False; FGrepExpandIf := False; FGrepExpandIfFiles := 25; FGrepExpandIfMatches := 150; FGrepExpandFew := False; FGrepExpandFewLines := 20; FGrepUseCurrentIdent := False; FGrepSaveHistoryListItems := 0; FGrepHistoryPagesTabMultiline := True; FGrepSaveOption := gsoOnlySaveSettings; FGrepSaveOptionDefaultValue := Integer(gsoOnlySaveSettings); FGrepOpenSaveOptionDefaultValue := Integer(gsoNoSave); FGrepFileListDeleteAfterDays := True; FGrepDeleteAfterDays := 30; FGrepEmptyMoveToOnlySaveParams := False; FGrepOnlySaveParamsAction := 0; FGrepHistoryListDefaultPage := 0; FGrepQuickRefresh := False; FContextSaveFixedHeight := False; FHistoryIniVersion := 0; fmGrepResults := TfmGrepResults.Create(nil); SetFormIcon(fmGrepResults); if not IsStandAlone then IdeDockManager.RegisterDockableForm(TfmGrepResults, fmGrepResults, 'fmGrepResults'); fmGrepResults.GrepExpert := Self; end; destructor TGrepExpert.Destroy; begin IdeDockManager.UnRegisterDockableForm(fmGrepResults, 'fmGrepResults'); HistoryListSaveSettings; SaveSettings; FreeAndNil(FHistoryList); FreeAndNil(fmGrepResults); FreeAndNil(FSearchList); FreeAndNil(FReplaceList); FreeAndNil(FMaskList); FreeAndNil(FDirList); FreeAndNil(FExcludedDirsList); FreeAndNil(FListFont); FreeAndNil(FContextFont); inherited Destroy; end; function TGrepExpert.GetActionCaption: string; resourcestring SMenuCaption = 'Grep &Results'; begin Result := SMenuCaption; end; function TGrepExpert.GetDefaultShortCut: TShortCut; begin Result := Menus.ShortCut(Word('R'), [ssCtrl, ssAlt]); end; class function TGrepExpert.GetName: string; begin Result := 'GrepResults'; end; procedure TGrepExpert.Execute(Sender: TObject); begin SetFormIcon(fmGrepResults); IdeDockManager.ShowForm(fmGrepResults); EnsureFormVisible(fmGrepResults); end; procedure TGrepExpert.ShowModal; begin fmGrepResults.ShowModal; end; procedure TGrepExpert.Configure; var Dialog: TfmGrepResultsOptions; begin Dialog := TfmGrepResultsOptions.Create(nil); try Dialog.chkAdvanced.Checked := GrepAdvancedOptions; Dialog.chkAdvancedClick(nil); Dialog.chkGrepMiddle.Checked := GrepMiddle; Dialog.chkGrepExpandAll.Checked := GrepExpandAll; Dialog.chkGrepExpandIf.Checked := GrepExpandIf; Dialog.eExpandIfFiles.Text := IntToStr(GrepExpandIfFiles); Dialog.eExpandIfMatches.Text := IntToStr(GrepExpandIfMatches); Dialog.chkGrepExpandFew.Checked := GrepExpandFew; Dialog.eExpandFewLines.Text := IntToStr(GrepExpandFewLines); Dialog.chkDefaultListColors.Checked := ListUseDefaultColors; Dialog.pnlListFont.Font.Assign(ListFont); Dialog.pnlListMatchTextColor.Font.Assign(ListFont); Dialog.pnlListMatchTextColor.Font.Color := ListMatchTextColor; Dialog.pnlListMatchTextColor.Color := ListMatchBrushColor; Dialog.pnlListMatchBackgroundColor.Font.Assign(ListFont); Dialog.pnlListMatchBackgroundColor.Font.Color := ListMatchTextColor; Dialog.pnlListMatchBackgroundColor.Color := ListMatchBrushColor; Dialog.pnlContextFont.Font.Assign(ContextFont); Dialog.pnlContextMacthLineFontColor.Font.Assign(ContextFont); Dialog.pnlContextMacthLineFontColor.Font.Color := ContextMatchLineColor; Dialog.pnlContextMatchFontColor.Font.Assign(ContextFont); Dialog.pnlContextMatchFontColor.Font.Color := ContextMatchColor; Dialog.udContextLines.Position := NumContextLines; Dialog.chkGrepSaveHistoryListItems.Checked := GrepSaveHistoryListItems; Dialog.rbSaveToIniFile.Checked := GrepSaveHistoryListItemsToIni; Dialog.rbSaveToRegistry.Checked := GrepSaveHistoryListItemsToReg; Dialog.chkGrepAutoHide.Checked := AutoHide; Dialog.chkFileListDeleteAfterDays.Checked := GrepFileListDeleteAfterDays; Dialog.eDeleteAfterDays.Text := IntToStr(GrepDeleteAfterDays); Dialog.chkEmptyMoveToParams.Checked := GrepEmptyMoveToOnlySaveParams; Dialog.cbxSearchSaveOptionDefaultValue.ItemIndex := GrepSaveOptionDefaultValue; Dialog.cbxOpenSaveOptionDefaultValue.ItemIndex := GrepOpenSaveOptionDefaultValue; Dialog.cbxOnlySaveParamsAction.ItemIndex := GrepOnlySaveParamsAction; Dialog.cbxHistoryListDefaultPage.ItemIndex := GrepHistoryListDefaultPage; Dialog.chkQuickRefreshMode.Checked := GrepQuickRefresh; Dialog.chkHistoryPagesTabMultiLine.Checked := GrepHistoryPagesTabMultiline; Dialog.eHistoryPagesTabWidth.Text := IntToStr(GrepHistoryPagesTabWidth); Dialog.chkMouseWheelMoveItemIndex.Checked := GrepMouseWheelPrevNextMatch; Dialog.chkSaveContextFixedHeight.Checked := ContextSaveFixedHeight; if Dialog.ShowModal = mrOk then begin GrepAdvancedOptions := Dialog.chkAdvanced.Checked; GrepMiddle := Dialog.chkGrepMiddle.Checked; GrepExpandAll := Dialog.chkGrepExpandAll.Checked; GrepExpandIf := GrepAdvancedOptions and Dialog.chkGrepExpandIf.Checked; GrepExpandIfFiles := StrToIntDef(Dialog.eExpandIfFiles.Text, 25); GrepExpandIfMatches := StrToIntDef(Dialog.eExpandIfMatches.Text, 150); GrepExpandFew := GrepAdvancedOptions and Dialog.chkGrepExpandFew.Checked; GrepExpandFewLines := StrToIntDef(Dialog.eExpandFewLines.Text, 20); ListUseDefaultColors := Dialog.chkDefaultListColors.Checked; FListFont.Assign(Dialog.pnlListFont.Font); FContextFont.Assign(Dialog.pnlContextFont.Font); ListMatchTextColor := Dialog.pnlListMatchTextColor.Font.Color; ListMatchBrushColor := Dialog.pnlListMatchBackgroundColor.Color; ContextMatchLineColor := Dialog.pnlContextMacthLineFontColor.Font.Color; ContextMatchColor := Dialog.pnlContextMatchFontColor.Font.Color; NumContextLines := Dialog.udContextLines.Position; if GrepAdvancedOptions then begin if not Dialog.chkGrepSaveHistoryListItems.Checked then FGrepSaveHistoryListItems := 0 else if Dialog.rbSaveToIniFile.Checked then FGrepSaveHistoryListItems := 1 else if Dialog.rbSaveToRegistry.Checked then FGrepSaveHistoryListItems := 2; end else begin if not Dialog.chkGrepSaveHistoryListItems.Checked then FGrepSaveHistoryListItems := 0 else FGrepSaveHistoryListItems := 1; end; GrepFileListDeleteAfterDays := Dialog.chkFileListDeleteAfterDays.Checked; GrepDeleteAfterDays := StrToIntDef(Dialog.eDeleteAfterDays.Text, 30); GrepSaveOptionDefaultValue := Dialog.cbxSearchSaveOptionDefaultValue.ItemIndex; GrepOpenSaveOptionDefaultValue := Dialog.cbxOpenSaveOptionDefaultValue.ItemIndex; GrepEmptyMoveToOnlySaveParams := GrepAdvancedOptions and Dialog.chkEmptyMoveToParams.Checked; GrepOnlySaveParamsAction := Dialog.cbxOnlySaveParamsAction.ItemIndex; GrepHistoryListDefaultPage := Dialog.cbxHistoryListDefaultPage.ItemIndex; GrepQuickRefresh := Dialog.chkQuickRefreshMode.Checked; if GrepAdvancedOptions then begin GrepHistoryPagesTabMultiline := Dialog.chkHistoryPagesTabMultiLine.Checked; GrepHistoryPagesTabWidth := StrToIntDef(Dialog.eHistoryPagesTabWidth.Text, GrepHistoryPagesTabWidth); end; GrepMouseWheelPrevNextMatch := GrepAdvancedOptions and Dialog.chkMouseWheelMoveItemIndex.Checked; ContextSaveFixedHeight := GrepAdvancedOptions and Dialog.chkSaveContextFixedHeight.Checked; AutoHide := DIalog.chkGrepAutoHide.Checked; SaveSettings; end; finally FreeAndNil(Dialog); end; end; procedure TGrepExpert.InternalSaveSettings(Settings: TExpertSettings); begin inherited InternalSaveSettings(Settings); // do not localize any of the following lines Settings.WriteInteger( 'HistoryIniVersion', FHistoryIniVersion); Settings.WriteBool('CaseSensitive', GrepCaseSensitive); Settings.WriteBool('Code', GrepCode); Settings.WriteBool('Strings', GrepStrings); Settings.WriteBool('NoComments', not GrepComments); Settings.WriteBool('Interface', GrepInterface); Settings.WriteBool('Implementation', GrepImplementation); Settings.WriteBool('Initialization', GrepInitialization); Settings.WriteBool('Finalization', GrepFinalization); Settings.WriteBool('Forms', GrepForms); Settings.WriteBool('SQLFiles', GrepSQLFiles); Settings.WriteInteger('Search', GrepSearch); Settings.WriteBool('SubDirectories', GrepSub); Settings.WriteBool('ExpandAll', GrepExpandAll); Settings.WriteBool('ExpandIf', GrepExpandIf); Settings.WriteInteger('ExpandIfFiles', GrepExpandIfFiles); Settings.WriteInteger('ExpandIfMatches', GrepExpandIfMatches); Settings.WriteBool('ExpandFew', GrepExpandFew); Settings.WriteInteger('ExpandFewLines', GrepExpandFewLines); Settings.WriteBool('Whole Word', GrepWholeWord); Settings.WriteBool('Middle', GrepMiddle); Settings.WriteBool('AutoHide', AutoHide); Settings.WriteBool('RegEx', GrepRegEx); Settings.WriteInteger('SaveOption', Integer(GrepSaveOption)); Settings.WriteBool('UseCurrentIdent', GrepUseCurrentIdent); Settings.WriteBool('AdvancedOptions', GrepAdvancedOptions); Settings.WriteInteger('SaveOptionDeafult', GrepSaveOptionDefaultValue); Settings.WriteInteger('SaveOptionDeafult4Open', GrepOpenSaveOptionDefaultValue); Settings.WriteBool('FileListDeleteAfterDays', GrepFileListDeleteAfterDays); Settings.WriteInteger('DeleteAfterDays', GrepDeleteAfterDays); Settings.WriteBool('EmptyResultsMoveToOnlySaveParams', GrepEmptyMoveToOnlySaveParams); Settings.WriteInteger('OnlySaveParamsAction', GrepOnlySaveParamsAction); Settings.WriteInteger('HistoryListDefaultPage', GrepHistoryListDefaultPage); Settings.WriteBool('QuickRefresh', GrepQuickRefresh); Settings.WriteBool('ListUseDefaultColors', ListUseDefaultColors); Settings.SaveFont('ListFont', ListFont, [ffColor]); Settings.WriteInteger('ListMatchTextColor', ListMatchTextColor); Settings.WriteInteger('ListMatchBrushColor', ListMatchBrushColor); Settings.SaveFont('ContextFont', ContextFont, [ffColor]); Settings.WriteInteger('ContextMatchColor', ContextMatchColor); Settings.WriteInteger('ContextMatchLineColor', ContextMatchLineColor); Settings.WriteInteger('NumContextLines', NumContextLines); Settings.WriteInteger('SaveHistoryListItems', FGrepSaveHistoryListItems); Settings.WriteBool('ContextSaveFixedHeight', ContextSaveFixedHeight); Settings.WriteBool('HistoryPagesTabMultilin', GrepHistoryPagesTabMultiline); Settings.WriteInteger('HistoryPagesTabWidth', GrepHistoryPagesTabWidth); Settings.WriteBool('MouseWheelPrevNextMatch', GrepMouseWheelPrevNextMatch); Settings.WriteStrings('DirectoryList', DirList, 'GrepDir'); Settings.WriteStrings('SearchList', SearchList, 'GrepSearch'); Settings.WriteStrings('ReplaceList', ReplaceList, 'GrepReplace'); Settings.WriteStrings('MaskList', MaskList, 'GrepMask'); Settings.WriteStrings('ExcludedDirsList', ExcludedDirsList, 'GrepExcludedDirs'); end; function TGrepExpert.FillGrepSettings: TGrepSettings; begin Result.CaseSensitive := GrepCaseSensitive; Result.WholeWord := GrepWholeWord; Result.RegEx := GrepRegEx; Result.Pattern := ''; Result.IncludeForms := GrepForms; Result.IncludeSQLs := GrepSQLFiles; Result.SaveOption := GrepSaveOption; Result.Mask := ''; Result.Directories := ''; Result.ExcludedDirs := ''; Result.IncludeSubdirs := GrepSub; Result.IncludeCode := GrepCode; Result.IncludeStrings := GrepStrings; Result.IncludeComments := GrepComments; Result.SectionInterface := GrepInterface; Result.SectionImplementation := GrepImplementation; Result.SectionInitialization := GrepInitialization; Result.SectionFinalization := GrepFinalization; case GrepSearch of 0: Result.GrepAction := gaCurrentOnlyGrep; 1: Result.GrepAction := gaProjGrep; 2: Result.GrepAction := gaOpenFilesGrep; 3: begin Result.GrepAction := gaDirGrep; if MaskList.Count > 0 then Result.Mask := MaskList[0]; if DirList.Count > 0 then Result.Directories := DirList[0]; if ExcludedDirsList.Count > 0 then Result.ExcludedDirs := ExcludedDirsList[0]; end; 4: Result.GrepAction := gaProjGroupGrep; 5: Result.GrepAction := gaResults; else Result.GrepAction := gaProjGrep; end; end; function TGrepExpert.GrepConfigPath: String; begin Result := AddSlash(ConfigInfo.ConfigPath); if FHistoryIniVersion >= 2 then Result := AddSlash(Result + ConfigurationKey + '.' + TGrepHistoryList.KeyName); end; function TGrepExpert.GrepHistorySettingsFileName: String; begin if FHistoryIniVersion = 0 then Result := 'GrepFound.ini' else Result := TGrepHistoryList.SettingsFileName; end; function TGrepExpert.CreateSettings: TCustomIniFile; begin Result := nil; case FGrepSaveHistoryListItems of 1: begin ForceDirectories(GrepConfigPath); Result := TGrepIniFile.Create(GrepConfigPath + GrepHistorySettingsFileName); end; 2: Result := TGExpertsSettings.Create; end; end; procedure TGrepExpert.LoadHistoryList(AGrepSettings : TGrepSettings); var Settings: TCustomIniFile; BaseKey: String; AIniMode: TIniFileMode; begin if not GrepSaveHistoryListItems then Exit; BaseKey := ''; if GrepSaveHistoryListItemsToReg then BaseKey := ConfigurationKey + PathDelim; AIniMode := ifmMulti; if FHistoryIniVersion < 2 then AIniMode := ifmSingle; Settings := CreateSettings; try HistoryList.LoadFromSettings(AGrepSettings, Settings, HistoryIniVersion, AIniMode, BaseKey, SaveOption); finally FreeAndNil(Settings); end; end; procedure TGrepExpert.HistoryListSaveSettings(AItemIndex: Integer); var Settings: TCustomIniFile; BaseKey: String; begin if not GrepSaveHistoryListItems then Exit; BaseKey := ''; if GrepSaveHistoryListItemsToReg then BaseKey := ConfigurationKey + PathDelim; Settings := CreateSettings; try HistoryList.SaveToSettings(Settings, HistoryIniVersion, BaseKey, AItemIndex, GrepEmptyMoveToOnlySaveParams, GrepFileListDeleteAfterDays, GrepDeleteAfterDays); finally FreeAndNil(Settings); end; end; procedure TGrepExpert.HistoryListSaveSearchListSettings; var Settings: TCustomIniFile; BaseKey: String; begin if not GrepSaveHistoryListItems then Exit; BaseKey := ''; if GrepSaveHistoryListItemsToReg then BaseKey := ConfigurationKey + PathDelim; Settings := CreateSettings; try HistoryList.SaveSearchListToSettings(Settings, BaseKey); finally FreeAndNil(Settings); end; end; procedure TGrepExpert.HistoryListDeleteFromSettings(ADelMode: TGrepDeleteMode; AItemIndex: Integer); var Settings: TCustomIniFile; BaseKey: String; begin if not GrepSaveHistoryListItems then Exit; BaseKey := ''; if GrepSaveHistoryListItemsToReg then BaseKey := ConfigurationKey + PathDelim; //if you delete one file must be at least if GrepSaveHistoryListItemsToIni and ((ADelMode <> delOneItem) or (HistoryIniVersion >= 2)) and (HistoryList.ListMode <> hlmSearch) then HistoryList.DeleteINIFiles(GrepConfigPath + GrepHistorySettingsFileName, ADelMode, HistoryIniVersion, AItemIndex) else //only deleting keys begin Settings := CreateSettings; try HistoryList.RemoveFromSettings(Settings, BaseKey, ADelMode, AItemIndex); finally FreeAndNil(Settings); end; end; end; procedure TGrepExpert.InternalLoadSettings(Settings: TExpertSettings); // Build a guess for the RTL path from a passed in VCL path. function RtlPath(const VisualPath: string): string; const cCLX = 'clx'; cVCL = 'vcl'; cRTL = 'rtl'; var SubPos: Integer; begin Result := ''; SubPos := AnsiCaseInsensitivePos(cVCL, VisualPath); if SubPos > 0 then begin Result := VisualPath; Delete(Result, SubPos, Length(cVCL)); Insert(cRTL, Result, SubPos); end; if Result <> '' then Exit; SubPos := AnsiCaseInsensitivePos(cCLX, VisualPath); if SubPos > 0 then begin Result := VisualPath; Delete(Result, SubPos, Length(cCLX)); Insert(cRTL, Result, SubPos); end; end; var TempPath: string; begin inherited InternalLoadSettings(Settings); // Do not localize any of the following lines FHistoryIniVersion := Settings.ReadInteger('HistoryIniVersion', 0); FGrepCaseSensitive := Settings.ReadBool('CaseSensitive', False); FGrepCode := Settings.ReadBool('Code', True); FGrepStrings := Settings.ReadBool('Strings', True); FGrepComments := not Settings.ReadBool('NoComments', False); FGrepInterface := Settings.ReadBool('Interface', True); FGrepImplementation := Settings.ReadBool('Implementation', True); FGrepInitialization := Settings.ReadBool('Initialization', True); FGrepFinalization := Settings.ReadBool('Finalization', True); FGrepForms := Settings.ReadBool('Forms', False); FGrepSQLFiles := Settings.ReadBool('SQLFiles', False); FGrepSearch := Settings.ReadInteger('Search', 1); FGrepSub := Settings.ReadBool('SubDirectories', True); FGrepExpandAll := Settings.ReadBool('ExpandAll', False); FGrepExpandIf := Settings.ReadBool('ExpandIf', False); FGrepExpandIfFiles := Settings.ReadInteger('ExpandIfFiles', FGrepExpandIfFiles); FGrepExpandIfMatches := Settings.ReadInteger('ExpandIfMatches', FGrepExpandIfMatches); FGrepExpandFew := Settings.ReadBool('ExpandFew', False); FGrepExpandFewLines := Settings.ReadInteger('ExpandFewLines', FGrepExpandFewLines); FGrepWholeWord := Settings.ReadBool('Whole Word', True); FGrepMiddle := Settings.ReadBool('Middle', True); FAutoHide := Settings.ReadBool('AutoHide', False); FGrepRegEx := Settings.ReadBool('RegEx', False); FGrepSaveOption := TGrepSaveOption(Settings.ReadInteger('SaveOption', Integer(GrepSaveOption))); FGrepUseCurrentIdent := Settings.ReadBool('UseCurrentIdent', False); FGrepAdvancedOptions := Settings.ReadBool('AdvancedOptions', GrepAdvancedOptions); FGrepSaveOptionDefaultValue := Settings.ReadInteger('SaveOptionDeafult', GrepSaveOptionDefaultValue); FGrepOpenSaveOptionDefaultValue := Settings.ReadInteger('SaveOptionDeafult4Open', GrepOpenSaveOptionDefaultValue); FGrepFileListDeleteAfterDays := Settings.ReadBool('FileListDeleteAfterDays', GrepFileListDeleteAfterDays); FGrepDeleteAfterDays := Settings.ReadInteger('DeleteAfterDays', GrepDeleteAfterDays); FGrepEmptyMoveToOnlySaveParams := Settings.ReadBool('EmptyResultsMoveToOnlySaveParams', GrepEmptyMoveToOnlySaveParams); FGrepOnlySaveParamsAction := Settings.ReadInteger('OnlySaveParamsAction', GrepOnlySaveParamsAction); FGrepHistoryListDefaultPage := Settings.ReadInteger('HistoryListDefaultPage', GrepHistoryListDefaultPage); FGrepQuickRefresh := Settings.ReadBool('QuickRefresh', GrepQuickRefresh); FListUseDefaultColors := Settings.ReadBool('ListUseDefaultColors', False); Settings.LoadFont('ListFont', ListFont, [ffColor]); FListMatchTextColor := Settings.ReadInteger('ListMatchTextColor', FListMatchTextColor); FListMatchBrushColor := Settings.ReadInteger('ListMatchBrushColor', FListMatchBrushColor); Settings.LoadFont('ContextFont', ContextFont, [ffColor]); FContextMatchColor := Settings.ReadInteger('ContextMatchColor', FContextMatchColor); if Settings.ValueExists('ContextMatchLineColor') then FContextMatchLineColor := Settings.ReadInteger('ContextMatchLineColor', FContextMatchLineColor) else FContextMatchLineColor := FContextMatchColor; FNumContextLines := Settings.ReadInteger('NumContextLines', FNumContextLines); FContextSaveFixedHeight := Settings.ReadBool('ContextSaveFixedHeight', FContextSaveFixedHeight); FGrepHistoryPagesTabMultiline := Settings.ReadBool('HistoryPagesTabMultilin', GrepHistoryPagesTabMultiline); FGrepHistoryPagesTabWidth := Settings.ReadInteger('HistoryPagesTabWidth', GrepHistoryPagesTabWidth); FGrepMouseWheelPrevNextMatch := Settings.ReadBool('MouseWheelPrevNextMatch', GrepMouseWheelPrevNextMatch); Settings.ReadStrings('DirectoryList', DirList, 'GrepDir'); Settings.ReadStrings('SearchList', SearchList, 'GrepSearch'); Settings.ReadStrings('ReplaceList', ReplaceList, 'GrepReplace'); Settings.ReadStrings('MaskList', MaskList, 'GrepMask'); Settings.ReadStrings('ExcludedDirsList', ExcludedDirsList, 'GrepExcludedDirs'); if FHistoryIniVersion = 0 then FGrepSaveHistoryListItems := Settings.ReadInteger('SaveResultListItems', 0) else FGrepSaveHistoryListItems := Settings.ReadInteger('SaveHistoryListItems', 0); if MaskList.Count = 0 then begin MaskList.Add('*.pas;*.dpr;*.inc'); MaskList.Add('*.txt;*.html;*.htm;.rc;*.xml;*.todo;*.me'); if IsStandAlone or GxOtaHaveCPPSupport then MaskList.Add('*.cpp;*.hpp;*.h;*.pas;*.dpr'); if IsStandAlone or GxOtaHaveCSharpSupport then MaskList.Add('*.cs'); end; if DirList.Count = 0 then begin TempPath := RemoveSlash(ConfigInfo.VCLPath); if NotEmpty(TempPath) and DirectoryExists(TempPath) then DirList.Add(TempPath); TempPath := RtlPath(ConfigInfo.VCLPath); if NotEmpty(TempPath) and DirectoryExists(TempPath) then DirList.Add(RemoveSlash(TempPath)); end; fmGrepResults.InitGrepSettings(FillGrepSettings); LoadHistoryList(fmGrepResults.GrepSettings); fmGrepResults.UpdateFromSettings; if FHistoryIniVersion = 0 then begin HistoryListDeleteFromSettings(delAll); FHistoryIniVersion := 2; Settings.EraseSection(ConfigurationKey); InternalSaveSettings(Settings); fmGrepResults.InternalSaveSettings(Settings); HistoryListSaveSettings; end else if FHistoryIniVersion = 1 then begin HistoryListDeleteFromSettings(delAll); FHistoryIniVersion := 2; InternalSaveSettings(Settings); HistoryListSaveSettings; end; end; function TGrepExpert.GetGrepSaveHistoryListItems(AIndex: Integer): Boolean; begin if AIndex = 3 then Result := FGrepSaveHistoryListItems in [1..2] else Result := FGrepSaveHistoryListItems = AIndex; end; function TGrepExpert.GetHelpString: string; resourcestring SHelpString = ' The Grep Results window is where the results of a Grep Search are shown.'#13#10 + ' It also provides an interface for multi-file search and replace on matches.'; begin Result := SHelpString; end; procedure TGrepExpert.SetSearchList(New: TStrings); begin FSearchList.Assign(New); end; procedure TGrepExpert.SetReplaceList(New: TStrings); begin FReplaceList.Assign(New); end; procedure TGrepExpert.SetMaskList(New: TStrings); begin FMaskList.Assign(New); end; procedure TGrepExpert.SetDirList(New: TStrings); begin FDirList.Assign(New); end; procedure TGrepExpert.SetExcludedDirsList(const Value: TStrings); begin FExcludedDirsList.Assign(Value); end; procedure TGrepExpert.SetActive(New: Boolean); begin if New <> Active then begin inherited SetActive(New); if New then begin if fmGrepResults = nil then fmGrepResults := TfmGrepResults.Create(nil); fmGrepResults.GrepExpert := Self; end else FreeAndNil(fmGrepResults); end; end; class function TGrepExpert.ConfigurationKey: string; begin Result := 'Grep'; end; procedure ShowGrep; begin {$IFOPT D+} SendDebug('Showing grep expert'); {$ENDIF} InitSharedResources; try GrepStandAlone := TGrepExpert.Create; try {$IFOPT D+} SendDebug('Created grep window'); {$ENDIF} GrepStandAlone.LoadSettings; GrepStandAlone.ShowModal; GrepStandAlone.HistoryListSaveSettings; GrepStandAlone.SaveSettings; finally FreeAndNil(GrepStandAlone); end; finally FreeSharedResources; end; end; function TGrepExpert.GetSaveOption: TGrepSaveOption; begin if FGrepSaveOptionDefaultValue <= Integer(High(TGrepSaveOption)) then Result := TGrepSaveOption(FGrepSaveOptionDefaultValue) else Result := FGrepSaveOption; end; function TGrepExpert.GetOpenSaveOption: TGrepSaveOption; begin if FGrepOpenSaveOptionDefaultValue <= Integer(High(TGrepSaveOption)) then Result := TGrepSaveOption(FGrepOpenSaveOptionDefaultValue) else Result := SaveOption; end; initialization RegisterGX_Expert(TGrepExpert); end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; type TForm1 = class(TForm) Button1: TButton; ProgressBar1: TProgressBar; Edit1: TEdit; Edit2: TEdit; Edit3: TEdit; Button2: TButton; Button3: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses RC4; procedure TForm1.Button1Click(Sender: TObject); const BLOCKSIZE: Integer = 1024; var RC4: TRC4Context; Filename: string; source, dest: TFileStream; Len: Int64; SourceBuffer, DestBuffer: Pointer; begin Filename := 'D:\Tmp\RC4Demo\Unit1.pas'; source := TFileStream.Create(Filename, fmOpenRead); dest := TFileStream.Create(Filename + '.foo', fmCreate); try GetMem(SourceBuffer, BLOCKSIZE); GetMem(DestBuffer, BLOCKSIZE); try RC4Init(RC4, 'Foobar'); Progressbar1.Max := source.Size; while source.Position < source.Size do begin if source.Size - source.Position > BLOCKSIZE then Len := BLOCKSIZE else Len := source.Size - source.Position; Progressbar1.Position := source.Position; Progressbar1.Refresh; source.ReadBuffer(SourceBuffer^, Len); RC4Code(RC4, SourceBuffer^, DestBuffer^, len); dest.WriteBuffer(DestBuffer^, Len); end; RC4Done(RC4); finally FreeMemory(SourceBuffer); FreeMemory(DestBuffer); end; finally FreeAndNil(source); FreeAndnIl(dest); end; end; procedure TForm1.Button2Click(Sender: TObject); var RC4: TRC4Context; s, s1: String; begin s := Edit1.Text; setlength(s1, length(s)); RC4Init(RC4, 'foo'); RC4Code(RC4, s[1], s1[1], length(Edit1.Text)); RC4Done(RC4); Edit2.Text := s1; end; procedure TForm1.Button3Click(Sender: TObject); var RC4: TRC4Context; s, s1: String; begin s := Edit2.Text; setlength(s1, length(s)); RC4Init(RC4, 'foo'); RC4Code(RC4, s[1], s1[1], length(Edit1.Text)); RC4Done(RC4); Edit3.Text := s1; end; end.
unit eeMemo; {------------------------------------------------------------------------------} { Модуль : eeMemo; } { Автор : ; } { Назначение : Публикуемые в DesignTime многострочные поля ввода. } {------------------------------------------------------------------------------} {$Include eeDefine.inc} interface uses Classes, Controls, evEditorWithOperations, evCustomMemo ; type TeeCustomMemo = class(TevCustomMemo) {*} public // public methods constructor Create(AOwner: TComponent); override; {-} property NeedDefaultPopupMenu default false; {-} end;//TeeCustomMemo TeeMemo = class(TeeCustomMemo) {* - компонент используемый в DesignTime. } published // published properties property AutoSelect; property Canvas; property TextSource; property Align; property Anchors; property BevelEdges; property BevelInner; property BevelKind default bkNone; property BevelOuter; property BiDiMode; property BorderStyle; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Text; property Wrap; property NeedDefaultPopupMenu; property Font; property ImeMode; property ImeName; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end;//TeeMemo TeeMemoWithEditOperations = class(TeeMemo) {* - многострочное поле вводе без операций редактирования таблицы и печати. } protected // protected methods function DefineProvideOperations: TevEditorProvideOperationTypes; override; {* - Какие операции публикуются компонентом. } end;//TeeMemoWithEditOperations implementation // start class TeeCustomMemo constructor TeeCustomMemo.Create(AOwner: TComponent); //override; {-} begin inherited; NeedDefaultPopupMenu := false; end; // start class TeeMemoWithEditOperations function TeeMemoWithEditOperations.DefineProvideOperations: TevEditorProvideOperationTypes; begin Result := [potEdit]; end; end.
unit define_dealstore_file; interface //uses // define_dealitem; const FilePath_StockData = 'sdata'; FilePath_StockIndexData = 'sidat'; FilePath_FutureData = 'fdat'; // 股票及股票指数 //FilePath_DBType_Item = DBType_Item_China; //FilePath_DBType_Index = DBType_Index_China; DataType_TimeEventItem = 1001; // 股票及股票指数 DataType_Item = 3; // 股票分类信息 DataType_Class = 5; // 股票日线行情数据 DataType_DayData = 11; // 股票日交易明细 DataType_DetailData = 21; DataType_MinuteData = 25; // 股票信息 DataType_Info = 31; // 多股票汇总数据 DataType_InstantData = 41; DataType_WeightData = 42; DataType_ValueData = 43; // 日线 // sd_31 sdw_31 // 5日线 // sd5_31 sdw5_31 FileExt_StockDay = 'd'; FileExt_StockDayWeight = 'dw'; FileExt_StockDetail = 'sdt'; // rename to se // 分钟线 由 detail 线 分析总结来的 // sm60_31 60 分钟线 如果不带 分钟数 则为月线 // smw60_31 smw60_32 FileExt_StockMinute = 'm'; FileExt_StockWeek = 'wk'; // sm_31 smw_31 FileExt_StockMonth = 'mt'; FileExt_StockAnalysis = 'as'; FileExt_StockInstant = 'it'; FileExt_StockWeight = 'wt'; // 总体统计分析 FileExt_StockSummaryValue = 'sv'; FileExt_FuturesDetail = 'qe'; FileExt_FuturesAnalysis = 'qa'; implementation end.
unit LogViewerMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, TabNotBk, ImgList, ToolWin, ExtCtrls, StdCtrls,About,StrUtils,MemoSearch, Buttons; type TForm12 = class(TForm) ToolBar1: TToolBar; TbtnOpen: TToolButton; ImageList1: TImageList; Timer1: TTimer; FontDialog1: TFontDialog; FindDialog1: TFindDialog; ColorDialog1: TColorDialog; OpenDialog1: TOpenDialog; TbtnRefresh: TToolButton; ImageList2: TImageList; PageControl1: TPageControl; TabSheet1: TTabSheet; ToolButton1: TToolButton; tbtnClose: TToolButton; btnAbout: TToolButton; GroupBox1: TGroupBox; Label1: TLabel; edtfind: TEdit; btnfind: TBitBtn; procedure TbtnOpenClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure TbtnRefreshClick(Sender: TObject); procedure FindDialog1Find(Sender: TObject); procedure ToolButton1Click(Sender: TObject); procedure PageControl1Change(Sender: TObject); procedure FormCreate(Sender: TObject); procedure tbtnCloseClick(Sender: TObject); procedure btnAboutClick(Sender: TObject); procedure btnfindClick(Sender: TObject); private FLastLogLine: Integer; Frefresh:Boolean; FLogFile:string; fcurrentmemo:TMemo; FfirstLoad:Boolean; FSelPos:Integer; procedure ProcessLogFile(currentmemo:TMemo); procedure MemoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); public { Public declarations } end; type TSearchOption = (soIgnoreCase, soFromStart, soWrap); TSearchOptions = set of TSearchOption; function SearchText( Control: TCustomEdit; Search: string; SearchOptions: TSearchOptions): Boolean; procedure SelectMemoLine(Memo : TCustomMemo) ; function MyPos(stringtofind, stringtosearch: string; CaseInsensitive: boolean = true): integer; var Form12: TForm12; implementation {$R *.dfm} procedure TForm12.TbtnOpenClick(Sender: TObject); var activeidx:Integer; i:Integer; begin activeidx:=PageControl1.ActivePageIndex; if OpenDialog1.Execute then begin FLogFile:=OpenDialog1.FileName; PageControl1.Pages[activeidx].Caption:=FLogFile; for I := Form12.PageControl1.Pages[activeidx].ComponentCount-1 downto 0 do begin if (Form12.PageControl1.Pages[activeidx].Components[i] is TMemo) then fcurrentmemo:=Form12.PageControl1.Pages[activeidx].Components[i] as TMemo; fcurrentmemo.Lines.Clear; end; Timer1.Enabled:=True; FfirstLoad:=True; end; end; procedure TForm12.TbtnRefreshClick(Sender: TObject); begin if Timer1.Enabled then begin Timer1.Enabled:=False; TbtnRefresh.Down:=False; end else begin Timer1.Enabled:=True; TbtnRefresh.Down:=True; end; end; procedure TForm12.btnAboutClick(Sender: TObject); begin AboutBox.ShowModal; end; { The following OnFind event handler searches a memo component for the text specified in the FindText property of a find dialog component. If found, the first occurrence of the text in Memo1 is selected. The code uses the Pos function to compare strings, and stores the number of characters to skip when determining the selection position in the SkipChars variable. Because there is no handling of case, whole word, or search direction in this algorithm, it is assumed that the Options property of FindDialog1 is set to [frHideMatchCase, frHideWholeWord, frHideUpDown]. } procedure TForm12.btnfindClick(Sender: TObject); begin SearchText(fcurrentmemo,edtfind.Text,[soIgnoreCase]); end; procedure TForm12.FindDialog1Find(Sender: TObject); var Soptions:TSearchOptions; begin { with Sender as TFindDialog do begin GetMem(FT, Length(FindText) + 1); fcurrentmemo.GetTextBuf(Buff, BuffLen); StrPCopy(FT, FindText); BuffLen := fcurrentmemo.GetTextLen + 1; GetMem(Buff, BuffLen); P := Buff + fcurrentmemo.SelStart + fcurrentmemo.SelLength; P := mypos(string(P), string(FT)); if P = NIL then MessageBeep(0) else begin fcurrentmemo.SelStart := P - Buff; fcurrentmemo.SelLength := Length(FindText); end; FreeMem(FT, Length(FindText) + 1); FreeMem(Buff, BuffLen); end; } if (frMatchCase in FindDialog1.Options) then begin Soptions:=Soptions - [soIgnoreCase]; end else begin Soptions:=Soptions + [soIgnoreCase]; end; // Soptions:=Soptions + [soFromStart]; Soptions:=Soptions + [soWrap]; SearchText(fcurrentmemo,FindDialog1.FindText,Soptions); end; procedure TForm12.FormCreate(Sender: TObject); var TabSheet: TTabSheet; newmemo:TMemo; count:Integer; begin newmemo:=TMemo.Create(PageControl1.Pages[0]); newmemo.Parent:=PageControl1.Pages[0]; newmemo.Align:=alClient; newmemo.Color:=clCream; newmemo.Lines.Clear; newmemo.WordWrap:=False; newmemo.ScrollBars:=ssBoth; newmemo.HideSelection:=False; newmemo.OnKeyDown:=MemoKeyDown; fcurrentmemo:=newmemo; FLogFile:=OpenDialog1.FileName; Timer1.Enabled:=True; end; procedure TForm12.MemoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and ((Key = ord('f')) or (Key = ord('F'))) then begin FSelPos := 0; // FindDialog1.Execute(); frmsearch.ShowModal; end; end; procedure TForm12.PageControl1Change(Sender: TObject); var activeidx:Integer; i:Integer; begin activeidx:=PageControl1.ActivePageIndex; for I := Form12.PageControl1.Pages[activeidx].ComponentCount-1 downto 0 do begin if (Form12.PageControl1.Pages[activeidx].Components[i] is TMemo) then fcurrentmemo:=Form12.PageControl1.Pages[activeidx].Components[i] as TMemo; end; FLogFile:=PageControl1.Pages[activeidx].Caption; //fcurrentmemo:= end; procedure TForm12.ProcessLogFile(currentmemo:TMemo); var Log: TStringList; LogStream: TFileStream; i: Integer; begin Log := TStringList.Create; try if not FileExists(FLogFile) then begin Exit; end; LogStream := TFileStream.Create(FLogFile,fmOpenRead or fmShareDenyNone); try Log.LoadFromStream(LogStream); if FfirstLoad then begin LogStream.Seek(0,0); currentmemo.Lines.LoadFromStream(LogStream); // SelectMemoLine(currentmemo); // currentmemo.Lines.LoadFromFile(FLogFile); end else begin while Log.Count > currentmemo.Lines.Count do currentmemo.Lines.Append(Log[currentmemo.Lines.Count]); end; finally LogStream.Free; end; finally Log.Free; end; end; procedure TForm12.tbtnCloseClick(Sender: TObject); var activeidx:Integer; i:Integer; count:Integer; begin activeidx:=PageControl1.ActivePageIndex; count:=PageControl1.PageCount; if (activeidx=0) then Exit; if (activeidx <(count-1)) then begin PageControl1.ActivePage.Free; for I := Form12.PageControl1.Pages[activeidx].ComponentCount-1 downto 0 do begin if (Form12.PageControl1.Pages[activeidx].Components[i] is TMemo) then fcurrentmemo:=Form12.PageControl1.Pages[activeidx].Components[i] as TMemo; end; FLogFile:=PageControl1.Pages[activeidx].Caption; end else begin PageControl1.ActivePage.Free; for I := Form12.PageControl1.Pages[activeidx-1].ComponentCount-1 downto 0 do begin if (Form12.PageControl1.Pages[activeidx-1].Components[i] is TMemo) then fcurrentmemo:=Form12.PageControl1.Pages[activeidx-1].Components[i] as TMemo; end; FLogFile:=PageControl1.Pages[activeidx-1].Caption; end; end; procedure TForm12.Timer1Timer(Sender: TObject); begin Timer1.Enabled := False; try ProcessLogFile(fcurrentmemo); finally Timer1.Enabled := True; end; FfirstLoad:=False; end; procedure TForm12.ToolButton1Click(Sender: TObject); var TabSheet: TTabSheet; newmemo:TMemo; count:Integer; begin if OpenDialog1.Execute then begin count:=PageControl1.PageCount+1; TabSheet := TTabSheet.Create(PageControl1); TabSheet.Caption := OpenDialog1.FileName; TabSheet.PageControl := PageControl1; PageControl1.ActivePage:=TabSheet; newmemo:=TMemo.Create(TabSheet); newmemo.Parent:=TabSheet; newmemo.Align:=alClient; newmemo.Color:=clCream; newmemo.Lines.Clear; newmemo.ScrollBars:=ssBoth; newmemo.WordWrap:=False; newmemo.HideSelection:=False; newmemo.OnKeyDown:=MemoKeyDown; fcurrentmemo:=newmemo; FLogFile:=OpenDialog1.FileName; Timer1.Enabled:=True; FfirstLoad:=True; end; end; procedure SelectMemoLine(Memo : TCustomMemo) ; var Line : integer; begin with Memo do begin Line := Perform(EM_LINEFROMCHAR, SelStart, 0) ; SelStart := Perform(EM_LINEINDEX, Line, 0); SelLength := Length(Lines[Line]) ; end; end; function MyPos(stringtofind, stringtosearch: string; CaseInsensitive: boolean = true): integer; begin if CaseInsensitive then begin stringtofind := LowerCase(stringtofind); stringtosearch := LowerCase(stringtosearch); end; Result := Pos(stringtofind, stringtosearch); end; function SearchText( Control: TCustomEdit; Search: string; SearchOptions: TSearchOptions): Boolean; var Text: string; Index: Integer; itext,ictext:Integer; begin if soIgnoreCase in SearchOptions then begin Search := UpperCase(Search); Text := UpperCase(Control.Text); end else Text := Control.Text; {$O-} itext:= length(text); ictext:=length(control.text); Index := 0; if not (soFromStart in SearchOptions) then Index := PosEx(Search, Text, Control.SelStart + Control.SelLength + 1); if (Index = 0) and ((soFromStart in SearchOptions) or (soWrap in SearchOptions)) then Index := PosEx(Search, Text, 1); Result := Index > 0; if Result then begin Control.SelStart := Index - 1; Control.SelLength := Length(Search); end; end; end.
unit K605843892; {* [Requestlink:605843892] } // Модуль: "w:\common\components\rtl\Garant\Daily\K605843892.pas" // Стереотип: "TestCase" // Элемент модели: "K605843892" MUID: (55D726B80326) // Имя типа: "TK605843892" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , RTFtoEVDWriterTest ; type TK605843892 = class(TRTFtoEVDWriterTest) {* [Requestlink:605843892] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK605843892 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *55D726B80326impl_uses* //#UC END# *55D726B80326impl_uses* ; function TK605843892.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.11'; end;//TK605843892.GetFolder function TK605843892.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '55D726B80326'; end;//TK605843892.GetModelElementGUID initialization TestFramework.RegisterTest(TK605843892.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
inherited dmRcboRepresentantes: TdmRcboRepresentantes OldCreateOrder = True inherited qryManutencao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWACRTRECR' ' (FIL_RECIBO, NRO_RECIBO, EMISSAO, REFERENCIA_I, REFERENCIA_F, ' + 'AGRUPAMENTO, CONSIDERAR, COMISSIONAR_POR, UNIDADE, VLR_COMISSOES' + ', VLR_CREDITOS, VLR_DESCONTOS, VLR_LIQUIDO, OBS, STATUS, FIL_ORI' + 'GEM, AUTORIZACAO, PARCELA, DT_ALTERACAO, OPERADOR)' 'VALUES' ' (:FIL_RECIBO, :NRO_RECIBO, :EMISSAO, :REFERENCIA_I, :REFERENCI' + 'A_F, :AGRUPAMENTO, :CONSIDERAR, :COMISSIONAR_POR, :UNIDADE, :VLR' + '_COMISSOES, :VLR_CREDITOS, :VLR_DESCONTOS, :VLR_LIQUIDO, :OBS, :' + 'STATUS, :FIL_ORIGEM, :AUTORIZACAO, :PARCELA, :DT_ALTERACAO, :OPE' + 'RADOR)') SQLDelete.Strings = ( 'DELETE FROM STWACRTRECR' 'WHERE' ' FIL_RECIBO = :Old_FIL_RECIBO AND NRO_RECIBO = :Old_NRO_RECIBO') SQLUpdate.Strings = ( 'UPDATE STWACRTRECR' 'SET' ' FIL_RECIBO = :FIL_RECIBO, NRO_RECIBO = :NRO_RECIBO, EMISSAO = ' + ':EMISSAO, REFERENCIA_I = :REFERENCIA_I, REFERENCIA_F = :REFERENC' + 'IA_F, AGRUPAMENTO = :AGRUPAMENTO, CONSIDERAR = :CONSIDERAR, COMI' + 'SSIONAR_POR = :COMISSIONAR_POR, UNIDADE = :UNIDADE, VLR_COMISSOE' + 'S = :VLR_COMISSOES, VLR_CREDITOS = :VLR_CREDITOS, VLR_DESCONTOS ' + '= :VLR_DESCONTOS, VLR_LIQUIDO = :VLR_LIQUIDO, OBS = :OBS, STATUS' + ' = :STATUS, FIL_ORIGEM = :FIL_ORIGEM, AUTORIZACAO = :AUTORIZACAO' + ', PARCELA = :PARCELA, DT_ALTERACAO = :DT_ALTERACAO, OPERADOR = :' + 'OPERADOR' 'WHERE' ' FIL_RECIBO = :Old_FIL_RECIBO AND NRO_RECIBO = :Old_NRO_RECIBO') SQLRefresh.Strings = ( 'SELECT FIL_RECIBO, NRO_RECIBO, EMISSAO, REFERENCIA_I, REFERENCIA' + '_F, AGRUPAMENTO, CONSIDERAR, COMISSIONAR_POR, UNIDADE, VLR_COMIS' + 'SOES, VLR_CREDITOS, VLR_DESCONTOS, VLR_LIQUIDO, OBS, STATUS, FIL' + '_ORIGEM, AUTORIZACAO, PARCELA, DT_ALTERACAO, OPERADOR FROM STWAC' + 'RTRECR' 'WHERE' ' FIL_RECIBO = :Old_FIL_RECIBO AND NRO_RECIBO = :Old_NRO_RECIBO') SQLLock.Strings = ( 'SELECT NULL FROM STWACRTRECR' 'WHERE' 'FIL_RECIBO = :Old_FIL_RECIBO AND NRO_RECIBO = :Old_NRO_RECIBO' 'FOR UPDATE WITH LOCK') SQL.Strings = ( 'SELECT ECR.FIL_RECIBO, ' ' ECR.NRO_RECIBO, ' ' ECR.EMISSAO, ' ' ECR.REFERENCIA_I, ' ' ECR.REFERENCIA_F, ' ' ECR.AGRUPAMENTO, ' ' ECR.CONSIDERAR, ' ' ECR.COMISSIONAR_POR, ' ' ECR.UNIDADE, ' ' ECR.VLR_COMISSOES, ' ' ECR.VLR_CREDITOS, ' ' ECR.VLR_DESCONTOS, ' ' ECR.VLR_LIQUIDO, ' ' ECR.OBS, ' ' ECR.STATUS, ' ' ECR.FIL_ORIGEM, ' ' ECR.AUTORIZACAO, ' ' ECR.PARCELA, ' ' ECR.DT_ALTERACAO, ' ' ECR.OPERADOR,' ' FIL.NOME NM_UNIDADE' 'FROM STWACRTRECR ECR' 'LEFT JOIN STWOPETFIL FIL ON FIL.FILIAL = ECR.UNIDADE') object qryManutencaoFIL_RECIBO: TStringField FieldName = 'FIL_RECIBO' Required = True Size = 3 end object qryManutencaoNRO_RECIBO: TFloatField FieldName = 'NRO_RECIBO' Required = True end object qryManutencaoEMISSAO: TDateTimeField FieldName = 'EMISSAO' end object qryManutencaoREFERENCIA_I: TDateTimeField FieldName = 'REFERENCIA_I' end object qryManutencaoREFERENCIA_F: TDateTimeField FieldName = 'REFERENCIA_F' end object qryManutencaoAGRUPAMENTO: TIntegerField FieldName = 'AGRUPAMENTO' end object qryManutencaoCONSIDERAR: TIntegerField FieldName = 'CONSIDERAR' end object qryManutencaoCOMISSIONAR_POR: TIntegerField FieldName = 'COMISSIONAR_POR' end object qryManutencaoUNIDADE: TStringField FieldName = 'UNIDADE' Size = 3 end object qryManutencaoVLR_COMISSOES: TFloatField FieldName = 'VLR_COMISSOES' end object qryManutencaoVLR_CREDITOS: TFloatField FieldName = 'VLR_CREDITOS' end object qryManutencaoVLR_DESCONTOS: TFloatField FieldName = 'VLR_DESCONTOS' end object qryManutencaoVLR_LIQUIDO: TFloatField FieldName = 'VLR_LIQUIDO' end object qryManutencaoOBS: TBlobField FieldName = 'OBS' end object qryManutencaoSTATUS: TStringField FieldName = 'STATUS' Size = 2 end object qryManutencaoFIL_ORIGEM: TStringField FieldName = 'FIL_ORIGEM' Size = 3 end object qryManutencaoAUTORIZACAO: TFloatField FieldName = 'AUTORIZACAO' end object qryManutencaoPARCELA: TIntegerField FieldName = 'PARCELA' end object qryManutencaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryManutencaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryManutencaoNM_UNIDADE: TStringField FieldName = 'NM_UNIDADE' ReadOnly = True Size = 40 end end inherited qryLocalizacao: TIBCQuery SQL.Strings = ( 'SELECT ECR.FIL_RECIBO, ' ' ECR.NRO_RECIBO, ' ' ECR.EMISSAO, ' ' ECR.REFERENCIA_I, ' ' ECR.REFERENCIA_F, ' ' ECR.AGRUPAMENTO, ' ' ECR.CONSIDERAR, ' ' ECR.COMISSIONAR_POR, ' ' ECR.UNIDADE, ' ' ECR.VLR_COMISSOES, ' ' ECR.VLR_CREDITOS, ' ' ECR.VLR_DESCONTOS, ' ' ECR.VLR_LIQUIDO, ' ' ECR.OBS, ' ' ECR.STATUS, ' ' ECR.FIL_ORIGEM, ' ' ECR.AUTORIZACAO, ' ' ECR.PARCELA, ' ' ECR.DT_ALTERACAO, ' ' ECR.OPERADOR,' ' FIL.NOME NM_UNIDADE' 'FROM STWACRTRECR ECR' 'LEFT JOIN STWOPETFIL FIL ON FIL.FILIAL = ECR.UNIDADE') object qryLocalizacaoFIL_RECIBO: TStringField FieldName = 'FIL_RECIBO' Required = True Size = 3 end object qryLocalizacaoNRO_RECIBO: TFloatField FieldName = 'NRO_RECIBO' Required = True end object qryLocalizacaoEMISSAO: TDateTimeField FieldName = 'EMISSAO' end object qryLocalizacaoREFERENCIA_I: TDateTimeField FieldName = 'REFERENCIA_I' end object qryLocalizacaoREFERENCIA_F: TDateTimeField FieldName = 'REFERENCIA_F' end object qryLocalizacaoAGRUPAMENTO: TIntegerField FieldName = 'AGRUPAMENTO' end object qryLocalizacaoCONSIDERAR: TIntegerField FieldName = 'CONSIDERAR' end object qryLocalizacaoCOMISSIONAR_POR: TIntegerField FieldName = 'COMISSIONAR_POR' end object qryLocalizacaoUNIDADE: TStringField FieldName = 'UNIDADE' Size = 3 end object qryLocalizacaoVLR_COMISSOES: TFloatField FieldName = 'VLR_COMISSOES' end object qryLocalizacaoVLR_CREDITOS: TFloatField FieldName = 'VLR_CREDITOS' end object qryLocalizacaoVLR_DESCONTOS: TFloatField FieldName = 'VLR_DESCONTOS' end object qryLocalizacaoVLR_LIQUIDO: TFloatField FieldName = 'VLR_LIQUIDO' end object qryLocalizacaoOBS: TBlobField FieldName = 'OBS' end object qryLocalizacaoSTATUS: TStringField FieldName = 'STATUS' Size = 2 end object qryLocalizacaoFIL_ORIGEM: TStringField FieldName = 'FIL_ORIGEM' Size = 3 end object qryLocalizacaoAUTORIZACAO: TFloatField FieldName = 'AUTORIZACAO' end object qryLocalizacaoPARCELA: TIntegerField FieldName = 'PARCELA' end object qryLocalizacaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryLocalizacaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryLocalizacaoNM_UNIDADE: TStringField FieldName = 'NM_UNIDADE' ReadOnly = True Size = 40 end end end
unit smChangeableTree; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "MainMenu" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/MainMenu/smChangeableTree.pas" // Начат: 16.09.2011 14:23 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Интерфейсные элементы::MainMenu::MainMenu::MainMenuTrees::TsmChangeableTree // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses l3TreeInterfaces, smTree, MainMenuUnit, l3Interfaces, l3Tree_TLB ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type TsmChangeableTree = class(TsmTree) private // private fields f_SectionType : TSectionType; protected // overridden protected methods function MakeRoot: Il3RootNode; override; {* Создаёт корень дерева } public // public methods constructor Create(aSectionType: TSectionType); reintroduce; class function Make(aSectionType: TSectionType): Il3SimpleTree; reintroduce; {* Сигнатура фабрики TsmChangeableTree.Make } end;//TsmChangeableTree {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} // start class TsmChangeableTree constructor TsmChangeableTree.Create(aSectionType: TSectionType); //#UC START# *4E73249703A9_4E73239003D0_var* //#UC END# *4E73249703A9_4E73239003D0_var* begin //#UC START# *4E73249703A9_4E73239003D0_impl* inherited Create; f_SectionType := aSectionType; //#UC END# *4E73249703A9_4E73239003D0_impl* end;//TsmChangeableTree.Create class function TsmChangeableTree.Make(aSectionType: TSectionType): Il3SimpleTree; var l_Inst : TsmChangeableTree; begin l_Inst := Create(aSectionType); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TsmChangeableTree.MakeRoot: Il3RootNode; //#UC START# *4909EF6E0361_4E73239003D0_var* //#UC END# *4909EF6E0361_4E73239003D0_var* begin //#UC START# *4909EF6E0361_4E73239003D0_impl* Result := inherited MakeRoot; AddItems2011(Result, f_SectionType); //#UC END# *4909EF6E0361_4E73239003D0_impl* end;//TsmChangeableTree.MakeRoot {$IfEnd} //not Admin AND not Monitorings end.
unit Control.Menus; interface uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Control.Sistema, Model.Menus; type TMenusControl = class private FMenus: TMenus; public constructor Create(); destructor Destroy(); override; property Menus: TMenus read FMenus write FMenus; function ValidaCampos(): Boolean; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; end; implementation { TMenusControl } constructor TMenusControl.Create; begin FMenus := TMenus.Create; end; destructor TMenusControl.Destroy; begin FMenus.Free; inherited; end; function TMenusControl.Gravar: Boolean; begin Result := False; if not ValidaCampos() then Exit; Result := FMenus.Gravar(); end; function TMenusControl.Localizar(aParam: array of variant): TFDQuery; begin Result := FMenus.Localizar(aParam); end; function TMenusControl.ValidaCampos: Boolean; var FDQuery : TFDQuery; aParam: Array of variant; begin try Result := False; FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; if FMenus.Codigo = 0 then begin Application.MessageBox('Informe um código para o menu!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; if FMenus.Sistema = 0 then begin Application.MessageBox('Informe um código de sistema!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; if FMenus.Modulo = 0 then begin Application.MessageBox('Informe um código de módulo!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; SetLength(aParam,4); aParam[0] := 'MENU'; aParam[1] := FMenus.Sistema; aParam[2] := FMenus.Modulo; aParam[3] := FMenus.Codigo; FDQuery := FMenus.Localizar(aParam); Finalize(aParam); if FDQuery.RecordCount >= 1 then begin if FMenus.Acao = tacIncluir then begin Application.MessageBox('Menu já cadastrado!', 'Atenção', MB_OK + MB_ICONWARNING); FDQuery.Close; Exit; end; end else begin if (FMenus.Acao = tacAlterar) or (FMenus.Acao = tacExcluir) then begin Application.MessageBox('Menu não cadastrado!', 'Atenção', MB_OK + MB_ICONWARNING); FDQuery.Close; Exit; end; end; if FMenus.Descricao.IsEmpty then begin Application.MessageBox('Informe uma descrição para o menu!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; Result := True; finally FDQuery.Free; end; end; end.
unit wndMain; {$mode objfpc}{$H+} interface uses wndTestCORE, Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type TmainWnd = class(TForm) Button1: TButton; ListBox1: TListBox; procedure Button1Click(Sender: TObject); public constructor Create(TheOwner: TComponent); override; public procedure ListTest_add_Frame(const tFRM:TCustomFrameClass; NameItem:string=''); end; var mainWnd: TmainWnd; implementation uses SetUpListTests; {$R *.lfm} procedure TmainWnd.ListTest_add_Frame(const tFRM:TCustomFrameClass; NameItem:string=''); var tmpName:string; begin if assigned(tFRM) then begin if NameItem='' then NameItem:=tFRM.ClassName; ListBox1.AddItem(NameItem,tObject(tFRM)); end; end; constructor TmainWnd.Create(TheOwner:TComponent); begin inherited; ListBox1.Clear; SetUpListTest_DO; end; procedure TmainWnd.Button1Click(Sender: TObject); var tmp:TCustomFrameClass; begin tmp:=TCustomFrameClass(ListBox1.Items.Objects[ListBox1.ItemIndex]); if Assigned(tmp) then begin if true{(tmp is TCustomFrameClass)} then begin with TTestCOREwnd.Create(Application,TCustomFrameClass(tmp)) do begin Show; end; end; end; end; end.
unit FindUnit.AutoImport; interface uses IniFiles, SysUtils, Log4Pascal, Classes, Contnrs, FindUnit.Header, Generics.Defaults, Generics.Collections, FindUnit.StringPositionList; type TAutoImport = class(TObject) private FIniFilePath: string; FSearchMemory: TIniFile; procedure LoadIniFile; procedure SaveIniFile; function LoadClassesToImport: TStringPositionList; public constructor Create(const IniFilePath: string); destructor Destroy; override; procedure Load; function GetMemorizedUnit(Search: string; out MemUnit: string): Boolean; procedure SetMemorizedUnit(NameClass, MemUnit: string); function LoadUnitListToImport: TStringPositionList; end; implementation uses FindUnit.OTAUtils, ToolsAPI, FindUnit.Utils; const SECTION = 'MEMORIZEDUNIT'; { TAutoImport } constructor TAutoImport.Create(const IniFilePath: string); begin inherited Create; FIniFilePath := IniFilePath; end; destructor TAutoImport.Destroy; begin inherited; end; function TAutoImport.GetMemorizedUnit(Search: string; out MemUnit: string): Boolean; begin Search := UpperCase(Search); MemUnit := FSearchMemory.ReadString(SECTION, Search, ''); Result := MemUnit <> ''; end; function TAutoImport.LoadUnitListToImport: TStringPositionList; var ClassesList: TStringPositionList; ClassItem: TStringPosition; UnitItem: string; ItemReturn: TStringPosition; begin Result := TStringPositionList.Create; Result.Duplicates := dupIgnore; ClassesList := LoadClassesToImport; try for ClassItem in ClassesList do begin UnitItem := FSearchMemory.ReadString(SECTION, ClassItem.Value, ''); if UnitItem <> '' then begin ItemReturn.Value := UnitItem; ItemReturn.Line := ClassItem.Line; Result.Add(ItemReturn); end; end; finally ClassesList.Free; end; end; procedure TAutoImport.Load; begin LoadIniFile; end; procedure TAutoImport.LoadIniFile; var DirPath: string; begin Logger.Debug('TAutoImport.LoadIniFile: %s', [FIniFilePath]); DirPath := ExtractFilePath(FIniFilePath); ForceDirectories(DirPath); FSearchMemory := TIniFile.Create(FIniFilePath); end; function TAutoImport.LoadClassesToImport: TStringPositionList; var Errors: TOTAErrors; ErrorItem: TOTAError; Item: TStringPosition; function GetUndeclaredIdentifier(Text: string): string; const ERROR_CODE = 'Undeclared identifier'; begin Result := ''; if Pos(ERROR_CODE, Text) = 0 then Exit; Fetch(Text, #39); Result := Fetch(Text, #39); end; begin Result := TStringPositionList.Create; Errors := GetErrorListFromActiveModule; for ErrorItem in Errors do begin Item.Value := UpperCase(GetUndeclaredIdentifier(ErrorItem.Text)); if Item.Value = '' then Continue; Item.Line := ErrorItem.Start.Line; Result.Add(Item); end end; procedure TAutoImport.SaveIniFile; begin FSearchMemory.UpdateFile; end; procedure TAutoImport.SetMemorizedUnit(NameClass, MemUnit: string); begin NameClass := UpperCase(NameClass); FSearchMemory.WriteString(SECTION, NameClass, MemUnit); SaveIniFile; end; end.
program linkedList; (* procedures: 1. init 2. insertBegin (to the beginning) 3. searchFreeNode 4. search 5. searchPrevPos 6. delete 7. insertAfter (after a node) *) const size = 10; null = -1; type nodeType = record next : integer; data : string; end; listType = record list : array[1..size] of nodeType; //**NODE TYPE */ head : Integer; end; var l : listType; response, input, s : string; procedure init(var l : listType); var i : Integer; begin for i := 1 to size do begin l.list[i].data := ''; l.list[i].next := Null; //** -1 means end of list */ end; l.head := Null; end; function searchFreeNode(l : listType):Integer; (*Search for position of free node*) (*return null for full linked list*) var i : Integer; begin i := 1; while (i <= size) and (l.list[i].data <> '') do //**MUST PUT (i <= size) FIRST because [i] may overflow */ i := i + 1; if i > size then searchFreeNode := Null // full else searchFreeNode := i; end; procedure insertBegin(data : string; var l : listType); var freepos : Integer; begin freepos := searchFreeNode(l); //**find empty node */ if freepos = null then WriteLn('Error') //**NO FREE POSITION to insert data*/ else begin l.list[freepos].data := data; l.list[freepos].next := l.head; //the next value of this node is the original head l.head := freepos; // it becomes the head end; end; {function search(x : string; l: listType; p : integer): Integer; //p := l.head begin if (p<>Null) and (l.list[p].data <> data) then search := search(l.list[p], l, l.list[p].next) else search := p; end;} function search(data : string; l: listType): Integer; var p : Integer; begin p := l.head; while (p<>Null) and (l.list[p].data <> data) do //**P<>null must be put first */ p := l.list[p].next; //**advance to next pointer, make use of next */ search := p; // returns null of searching failed end; procedure insertAfter(after, data : string; var l : listType); var freepos, afterpos : Integer; begin freepos := searchFreeNode(l); if freepos = null then WriteLn('Error') //**NO FREE POSITION to insert data*/ else begin afterpos := search(after, l); {set the next of new data to one after} l.list[freepos].next := l.list[afterpos].next; //inherit the *next* values of *after* {store data into free node} l.list[freepos].data := data; {update next of after to the pos of the new node} l.list[afterpos].next := freepos; // set the next value of *after* to become freepos end; end; function searchPrevPos(data : string; l : listType): integer; var p : Integer; begin p := l.head; while (l.list[p].next <> Null) and (l.list[l.list[p].next].data <> data) do //**P<>null must be put first */ p := l.list[p].next; //**advance to next pointer, make use of next */ searchPrevPos := p; end; procedure delete(data : string; var l: listType); var p : integer; begin p := search(data, l); if p = l.head then begin l.list[l.head].data := ''; l.head := l.list[l.head].next; l.list[p].next := null; end else begin l.list[searchPrevPos(data, l)].next := l.list[p].next; // [prev]->[one u need to delete]->[next] set prev.next be delete.next l.list[p].data := ''; l.list[p].next := null; end; end; procedure printListdumb(l : listType); var i : integer; begin for i := 1 to size do writeln(i:3, l.list[i].data:5, l.list[i].next:5); end; procedure printList(l : listType); var i : integer; begin i := l.head; write('Head: ', i); while i <> null do begin write(' ----> ', l.list[i].data, '(', l.list[i].next, ')' ); i := l.list[i].next; end; writeln; end; begin init(l); repeat writeln('1. Insert at the beginning of the linked list.'); WriteLn('2. Insert to a certain item.'); WriteLn('3. Delete a node.'); WriteLn('4. Search for a node.'); write(' >'); readln(response); if response = '1' then begin write('pls enter the data: ');; readln(input); insertBegin(input, l); end else if response = '2' then begin write('enter the data to search: '); readln(s); write('Enter the data to input: '); readln(input); insertAfter(s, input, l); end else if response = '3' then begin write('delete what? >'); readln(s); delete(s, l); end else if response = '4' then begin write('Enter the data to search: '); readln(s); writeln('The data is on the ', search(s, l), ' pos.'); end; writeln('--------------------------------------------------'); printList(l); writeln('--------------------------------------------------'); printListdumb(l); writeln('--------------------------------------------------'); writeln; until upcase(response) = 'EXIT'; end.
unit uEmailModelo2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs , IdBaseComponent, IdComponent // Units Genéricas do Indy , IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL // Objeto SSL , IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP // Objeto SMTP , IdMessage // Objeto de Mensagem , IdAttachmentFile, Vcl.StdCtrls, uEmailBase, System.Generics.Collections; type TEmail2 = class(TEmailBase) public function EnviarEmail: Boolean; override; end; implementation { TEmail2 } function TEmail2.EnviarEmail: Boolean; var AuthSSL : TIdSSLIOHandlerSocketOpenSSL; IdSMTP : TIdSMTP; IdMessage : TIdMessage; Lista: TList<string>; i: Integer; sNomeArquivoAnexo: string; begin Result:= False; IdSMTP := TIdSMTP.Create(nil); IdMessage := TIdMessage.Create(nil); try IdSMTP.Host := Host; IdSMTP.Port := Porta; IdSMTP.AuthType := satDefault; IdSMTP.Username := UserName; IdSMTP.Password := Password; if AutenticarSSL then begin AuthSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil); IdSMTP.IOHandler := AuthSSL; if Porta = 465 then IdSMTP.UseTLS := utUseImplicitTLS else IdSMTP.UseTLS := utUseExplicitTLS; AuthSSL.SSLOptions.Method := sslvSSLv3; AuthSSL.SSLOptions.Mode := sslmClient; end; if Autenticar then IdSMTP.AuthType := satDefault else IdSMTP.AuthType := satNone; try IdSMTP.Connect; case NivelPrioridade of 0: IdMessage.Priority := mpLow; 1: IdMessage.Priority := mpNormal; 2: IdMessage.Priority := mpHigh; end; IdMessage.From.Address := MeuEmail; IdMessage.Recipients.EMailAddresses := Destinatario; IdMessage.Subject := Assunto; IdMessage.Body.Text := Texto; IdMessage.Encoding := meMIME; if Copia.Trim <> '' then IdMessage.CCList.EMailAddresses := Copia; if CopiaOculta.Trim <> '' then IdMessage.BccList.EMailAddresses := CopiaOculta; // auto resposta if ConfirmarLeitura then IdMessage.ReceiptRecipient.Text := IdMessage.From.Text; if ArquivoAnexo = '' then IdMessage.ContentType := 'text/html'; IdMessage.CharSet := 'ISO-8859-1'; // Anexo da mensagem (opcional) if ArquivoAnexo.Trim() <> '' then begin IdMessage.MessageParts.Clear; // Limpa os anexos da lista Lista := RetornarAnexos(ArquivoAnexo); for I := 0 to Lista.Count -1 do begin sNomeArquivoAnexo := Lista.Items[i]; if not (FileExists(sNomeArquivoAnexo)) then raise Exception.Create('Arquivo Anexo não Encontrado para enviar!'); TIdAttachmentFile.Create(IdMessage.MessageParts, sNomeArquivoAnexo); end; FreeAndNil(Lista); end; IdSMTP.Send(IdMessage); Result := True; except on E: Exception do begin Result := False; ShowMessage('Erro ao enviar E-Mail:'+#13#10+e.Message); Exit; end; end; finally IdSMTP.Disconnect; FreeAndNil(IdSMTP); FreeAndNil(IdMessage); if AuthSSL <> nil then FreeAndNil(AuthSSL); end; Result:= True; end; end.
(****) Program Fishing; (*****) uses Constants; (****) const yMin = 1800; yMax = 3000; var yOffset: Cardinal; procedure Move(); var yInicial: Cardinal; begin yInicial := GetY(Self); if ((yInicial <= yMin) or (yInicial >= yMax)) then begin UOSay('Turn Around'); yOffset := yOffset * -1; end; while GetY(Self) = yInicial do begin UOSay('Forward'); Wait(250); end; UOSay('Stop'); end; procedure FishTile(x: Integer; y: Integer); var option, tries: Cardinal; begin AddToDebugJournal(' Fishing(' + IntToStr(x) + ', ' + IntToStr(y) + ', -3) ...'); tries := 0; repeat if TargetPresent() then CancelTarget(); Disarm(); UseObject(FindType(fishingPoleType, BackPack())); WaitTargetXYZ(x, y, GetZ(Self) - 3); tries := tries + 1; WaitJournalLineSystem(Now(), 'elsewhere|no fish|try|fail|put', 10000); option := FoundedParamId; AddToDebugJournal(' ' + Journal(LineIndex())); until ((option <= 2) or (tries > 2)); end; procedure FishAround(); var x, y, xIdx : Integer; begin x := GetX(Self); y := GetY(Self); xIdx := -4; AddToDebugJournal(' Starting to fish around (' + IntToStr(x) + ', ' + IntToStr(y) + ') ...'); while (xIdx <= 4) do begin FishTile(x + xIdx, y + yOffset); xIdx := xIdx + 1; end; AddToDebugJournal(' Done fishing around (' + IntToStr(x) + ', ' + IntToStr(y) + ').'); end; procedure StoreFish(); var i: Integer; item, storageContainer: Cardinal; begin for i:= Low(fishTypes) to High(fishTypes) do begin while FindType(fishTypes[i], BackPack) > 0 do begin item := FindItem; storageContainer := FindType(shipContainerType, Ground); MoveItem(item, 100, storageContainer, 0, 0, 0); Wait(1000); end; end; end; begin yOffset := -3; while not Dead() do begin StoreFish(); FishAround(); Move(); end; end.
unit nsQuestions; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/nsQuestions.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> F1 Core::Base Operations::View::Исключительно для мерджа с 7.7::nsQuestions // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses l3StringIDEx, l3MessageID ; var { Локализуемые строки Asks } str_DocumentEMailSelection : Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'DocumentEMailSelection'; rValue : 'Переслать по E-mail:'); { 'Переслать по E-mail:' } str_ListEMailSelection : Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'ListEMailSelection'; rValue : 'Пересылка по EMail'); { 'Пересылка по EMail' } str_ListPrintSelectedConfirmation : Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'ListPrintSelectedConfirmation'; rValue : 'Печатать:'); { 'Печатать:' } str_PrintSelectedConfirmation : Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'PrintSelectedConfirmation'; rValue : 'Печатать:'); { 'Печатать:' } str_ExportSelectionToWord : Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'ExportSelectionToWord'; rValue : 'Экспортировать в MS-Word'); { 'Экспортировать в MS-Word' } str_ListExportSelectionToWord : Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'ListExportSelectionToWord'; rValue : 'Экспортировать в MS-Word:'); { 'Экспортировать в MS-Word:' } str_ConsultDocumentsNotFound : Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'ConsultDocumentsNotFound'; rValue : 'Информация по данному запросу отсутствует в установленном у Вас комплекте.'); { 'Информация по данному запросу отсутствует в установленном у Вас комплекте.' } str_DocumentEMailSelection_CheckCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DocumentEMailSelection_CheckCaption'; rValue : 'Всегда пересылать выделенный фрагмент'); { undefined } str_DocumentEMailSelection_SettingsCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DocumentEMailSelection_SettingsCaption'; rValue : 'Пересылка по EMail'); { undefined } str_DocumentEMailSelection_LongHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DocumentEMailSelection_LongHint'; rValue : 'Подтверждение при пересылке выделенного фрагмента'); { undefined } str_ListEMailSelection_CheckCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListEMailSelection_CheckCaption'; rValue : 'Всегда пересылать выделенные элементы '); { undefined } str_ListEMailSelection_SettingsCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListEMailSelection_SettingsCaption'; rValue : 'Пересылка по EMail'); { undefined } str_ListEMailSelection_LongHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListEMailSelection_LongHint'; rValue : 'Подтверждение при пересылке выделенных элементов'); { undefined } str_ListPrintSelectedConfirmation_CheckCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListPrintSelectedConfirmation_CheckCaption'; rValue : 'Всегда печатать выделенные элементы'); { undefined } str_ListPrintSelectedConfirmation_SettingsCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListPrintSelectedConfirmation_SettingsCaption'; rValue : 'Печать'); { undefined } str_ListPrintSelectedConfirmation_LongHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListPrintSelectedConfirmation_LongHint'; rValue : 'Подтверждение при печати выделенных элементов'); { undefined } str_PrintSelectedConfirmation_CheckCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintSelectedConfirmation_CheckCaption'; rValue : 'Всегда печатать выделенный фрагмент'); { undefined } str_PrintSelectedConfirmation_SettingsCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintSelectedConfirmation_SettingsCaption'; rValue : 'Печать'); { undefined } str_PrintSelectedConfirmation_LongHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintSelectedConfirmation_LongHint'; rValue : 'Подтверждение при печати выделенного фрагмента'); { undefined } str_ExportSelectionToWord_CheckCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ExportSelectionToWord_CheckCaption'; rValue : 'Всегда экспортировать выделенный фрагмент'); { undefined } str_ExportSelectionToWord_SettingsCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ExportSelectionToWord_SettingsCaption'; rValue : 'Экспорт в MS-Word'); { undefined } str_ExportSelectionToWord_LongHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ExportSelectionToWord_LongHint'; rValue : 'Подтверждение при открытии в MS-Word выделенного фрагмента'); { undefined } str_ListExportSelectionToWord_CheckCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListExportSelectionToWord_CheckCaption'; rValue : 'Всегда экспортировать выделенные элементы'); { undefined } str_ListExportSelectionToWord_SettingsCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListExportSelectionToWord_SettingsCaption'; rValue : 'Экспорт в MS-Word'); { undefined } str_ListExportSelectionToWord_LongHint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListExportSelectionToWord_LongHint'; rValue : 'Подтверждение при открытии в MS-Word выделенных элементов'); { undefined } {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses Dialogs ; var { Варианты выбора для диалога DocumentEMailSelection } str_DocumentEMailSelection_Choice_Selection : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DocumentEMailSelection_Choice_Selection'; rValue : 'Выделенный фрагмент'); { 'Выделенный фрагмент' } str_DocumentEMailSelection_Choice_WholeDocument : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DocumentEMailSelection_Choice_WholeDocument'; rValue : 'Документ целиком'); { 'Документ целиком' } var { Варианты выбора для диалога ListEMailSelection } str_ListEMailSelection_Choice_Selected : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListEMailSelection_Choice_Selected'; rValue : 'Выделенные элементы'); { 'Выделенные элементы' } str_ListEMailSelection_Choice_WholeList : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListEMailSelection_Choice_WholeList'; rValue : 'Список целиком'); { 'Список целиком' } var { Варианты выбора для диалога ListPrintSelectedConfirmation } str_ListPrintSelectedConfirmation_Choice_Selected : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListPrintSelectedConfirmation_Choice_Selected'; rValue : 'Выделенные элементы'); { 'Выделенные элементы' } str_ListPrintSelectedConfirmation_Choice_WholeList : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListPrintSelectedConfirmation_Choice_WholeList'; rValue : 'Список целиком'); { 'Список целиком' } var { Варианты выбора для диалога PrintSelectedConfirmation } str_PrintSelectedConfirmation_Choice_Selected : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintSelectedConfirmation_Choice_Selected'; rValue : 'Выделенный фрагмент'); { 'Выделенный фрагмент' } str_PrintSelectedConfirmation_Choice_WholeDocument : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintSelectedConfirmation_Choice_WholeDocument'; rValue : 'Документ целиком'); { 'Документ целиком' } var { Варианты выбора для диалога ExportSelectionToWord } str_ExportSelectionToWord_Choice_Selected : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ExportSelectionToWord_Choice_Selected'; rValue : 'Выделенный фрагмент'); { 'Выделенный фрагмент' } str_ExportSelectionToWord_Choice_WholeDocument : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ExportSelectionToWord_Choice_WholeDocument'; rValue : 'Документ целиком'); { 'Документ целиком' } var { Варианты выбора для диалога ListExportSelectionToWord } str_ListExportSelectionToWord_Choice_Selected : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListExportSelectionToWord_Choice_Selected'; rValue : 'Выделенные элементы'); { 'Выделенные элементы' } str_ListExportSelectionToWord_Choice_WholeList : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ListExportSelectionToWord_Choice_WholeList'; rValue : 'Список целиком'); { 'Список целиком' } var { Варианты выбора для диалога ConsultDocumentsNotFound } str_ConsultDocumentsNotFound_Choice_Spec : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ConsultDocumentsNotFound_Choice_Spec'; rValue : 'Обратиться к специалистам Правовой поддержки онлайн'); { 'Обратиться к специалистам Правовой поддержки онлайн' } str_ConsultDocumentsNotFound_Choice_Back : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ConsultDocumentsNotFound_Choice_Back'; rValue : 'Вернуться в карточку и изменить условия запроса'); { 'Вернуться в карточку и изменить условия запроса' } {$IfEnd} //not Admin AND not Monitorings initialization {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_DocumentEMailSelection_Choice_Selection str_DocumentEMailSelection_Choice_Selection.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_DocumentEMailSelection_Choice_WholeDocument str_DocumentEMailSelection_Choice_WholeDocument.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListEMailSelection_Choice_Selected str_ListEMailSelection_Choice_Selected.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListEMailSelection_Choice_WholeList str_ListEMailSelection_Choice_WholeList.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListPrintSelectedConfirmation_Choice_Selected str_ListPrintSelectedConfirmation_Choice_Selected.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListPrintSelectedConfirmation_Choice_WholeList str_ListPrintSelectedConfirmation_Choice_WholeList.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_PrintSelectedConfirmation_Choice_Selected str_PrintSelectedConfirmation_Choice_Selected.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_PrintSelectedConfirmation_Choice_WholeDocument str_PrintSelectedConfirmation_Choice_WholeDocument.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ExportSelectionToWord_Choice_Selected str_ExportSelectionToWord_Choice_Selected.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ExportSelectionToWord_Choice_WholeDocument str_ExportSelectionToWord_Choice_WholeDocument.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListExportSelectionToWord_Choice_Selected str_ListExportSelectionToWord_Choice_Selected.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListExportSelectionToWord_Choice_WholeList str_ListExportSelectionToWord_Choice_WholeList.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ConsultDocumentsNotFound_Choice_Spec str_ConsultDocumentsNotFound_Choice_Spec.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ConsultDocumentsNotFound_Choice_Back str_ConsultDocumentsNotFound_Choice_Back.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_DocumentEMailSelection str_DocumentEMailSelection.Init; str_DocumentEMailSelection.AddChoice(str_DocumentEMailSelection_Choice_Selection); str_DocumentEMailSelection.AddChoice(str_DocumentEMailSelection_Choice_WholeDocument); str_DocumentEMailSelection.AddDefaultChoice(str_DocumentEMailSelection_Choice_Selection); str_DocumentEMailSelection.SetDlgType(mtConfirmation); str_DocumentEMailSelection.SetNeedCheck(true); str_DocumentEMailSelection.SetCheckCaption(str_DocumentEMailSelection_CheckCaption); str_DocumentEMailSelection.SetSettingsCaption(str_DocumentEMailSelection_SettingsCaption); str_DocumentEMailSelection.SetLongHint(str_DocumentEMailSelection_LongHint); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListEMailSelection str_ListEMailSelection.Init; str_ListEMailSelection.AddChoice(str_ListEMailSelection_Choice_Selected); str_ListEMailSelection.AddChoice(str_ListEMailSelection_Choice_WholeList); str_ListEMailSelection.AddDefaultChoice(str_ListEMailSelection_Choice_Selected); str_ListEMailSelection.SetDlgType(mtConfirmation); str_ListEMailSelection.SetNeedCheck(true); str_ListEMailSelection.SetCheckCaption(str_ListEMailSelection_CheckCaption); str_ListEMailSelection.SetSettingsCaption(str_ListEMailSelection_SettingsCaption); str_ListEMailSelection.SetLongHint(str_ListEMailSelection_LongHint); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListPrintSelectedConfirmation str_ListPrintSelectedConfirmation.Init; str_ListPrintSelectedConfirmation.AddChoice(str_ListPrintSelectedConfirmation_Choice_Selected); str_ListPrintSelectedConfirmation.AddChoice(str_ListPrintSelectedConfirmation_Choice_WholeList); str_ListPrintSelectedConfirmation.AddDefaultChoice(str_ListPrintSelectedConfirmation_Choice_Selected); str_ListPrintSelectedConfirmation.SetDlgType(mtConfirmation); str_ListPrintSelectedConfirmation.SetNeedCheck(true); str_ListPrintSelectedConfirmation.SetCheckCaption(str_ListPrintSelectedConfirmation_CheckCaption); str_ListPrintSelectedConfirmation.SetSettingsCaption(str_ListPrintSelectedConfirmation_SettingsCaption); str_ListPrintSelectedConfirmation.SetLongHint(str_ListPrintSelectedConfirmation_LongHint); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_PrintSelectedConfirmation str_PrintSelectedConfirmation.Init; str_PrintSelectedConfirmation.AddChoice(str_PrintSelectedConfirmation_Choice_Selected); str_PrintSelectedConfirmation.AddChoice(str_PrintSelectedConfirmation_Choice_WholeDocument); str_PrintSelectedConfirmation.AddDefaultChoice(str_PrintSelectedConfirmation_Choice_Selected); str_PrintSelectedConfirmation.SetDlgType(mtConfirmation); str_PrintSelectedConfirmation.SetNeedCheck(true); str_PrintSelectedConfirmation.SetCheckCaption(str_PrintSelectedConfirmation_CheckCaption); str_PrintSelectedConfirmation.SetSettingsCaption(str_PrintSelectedConfirmation_SettingsCaption); str_PrintSelectedConfirmation.SetLongHint(str_PrintSelectedConfirmation_LongHint); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ExportSelectionToWord str_ExportSelectionToWord.Init; str_ExportSelectionToWord.AddChoice(str_ExportSelectionToWord_Choice_Selected); str_ExportSelectionToWord.AddChoice(str_ExportSelectionToWord_Choice_WholeDocument); str_ExportSelectionToWord.AddDefaultChoice(str_ExportSelectionToWord_Choice_Selected); str_ExportSelectionToWord.SetDlgType(mtConfirmation); str_ExportSelectionToWord.SetNeedCheck(true); str_ExportSelectionToWord.SetCheckCaption(str_ExportSelectionToWord_CheckCaption); str_ExportSelectionToWord.SetSettingsCaption(str_ExportSelectionToWord_SettingsCaption); str_ExportSelectionToWord.SetLongHint(str_ExportSelectionToWord_LongHint); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListExportSelectionToWord str_ListExportSelectionToWord.Init; str_ListExportSelectionToWord.AddChoice(str_ListExportSelectionToWord_Choice_Selected); str_ListExportSelectionToWord.AddChoice(str_ListExportSelectionToWord_Choice_WholeList); str_ListExportSelectionToWord.AddDefaultChoice(str_ListExportSelectionToWord_Choice_Selected); str_ListExportSelectionToWord.SetDlgType(mtConfirmation); str_ListExportSelectionToWord.SetNeedCheck(true); str_ListExportSelectionToWord.SetCheckCaption(str_ListExportSelectionToWord_CheckCaption); str_ListExportSelectionToWord.SetSettingsCaption(str_ListExportSelectionToWord_SettingsCaption); str_ListExportSelectionToWord.SetLongHint(str_ListExportSelectionToWord_LongHint); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ConsultDocumentsNotFound str_ConsultDocumentsNotFound.Init; str_ConsultDocumentsNotFound.AddChoice(str_ConsultDocumentsNotFound_Choice_Spec); str_ConsultDocumentsNotFound.AddChoice(str_ConsultDocumentsNotFound_Choice_Back); str_ConsultDocumentsNotFound.AddCustomChoice(str_ConsultDocumentsNotFound_Choice_Spec); str_ConsultDocumentsNotFound.SetDlgType(mtWarning); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_DocumentEMailSelection_CheckCaption str_DocumentEMailSelection_CheckCaption.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_DocumentEMailSelection_SettingsCaption str_DocumentEMailSelection_SettingsCaption.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_DocumentEMailSelection_LongHint str_DocumentEMailSelection_LongHint.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListEMailSelection_CheckCaption str_ListEMailSelection_CheckCaption.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListEMailSelection_SettingsCaption str_ListEMailSelection_SettingsCaption.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListEMailSelection_LongHint str_ListEMailSelection_LongHint.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListPrintSelectedConfirmation_CheckCaption str_ListPrintSelectedConfirmation_CheckCaption.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListPrintSelectedConfirmation_SettingsCaption str_ListPrintSelectedConfirmation_SettingsCaption.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListPrintSelectedConfirmation_LongHint str_ListPrintSelectedConfirmation_LongHint.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_PrintSelectedConfirmation_CheckCaption str_PrintSelectedConfirmation_CheckCaption.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_PrintSelectedConfirmation_SettingsCaption str_PrintSelectedConfirmation_SettingsCaption.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_PrintSelectedConfirmation_LongHint str_PrintSelectedConfirmation_LongHint.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ExportSelectionToWord_CheckCaption str_ExportSelectionToWord_CheckCaption.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ExportSelectionToWord_SettingsCaption str_ExportSelectionToWord_SettingsCaption.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ExportSelectionToWord_LongHint str_ExportSelectionToWord_LongHint.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListExportSelectionToWord_CheckCaption str_ListExportSelectionToWord_CheckCaption.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListExportSelectionToWord_SettingsCaption str_ListExportSelectionToWord_SettingsCaption.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ListExportSelectionToWord_LongHint str_ListExportSelectionToWord_LongHint.Init; {$IfEnd} //not Admin AND not Monitorings end.
unit PCN; interface uses System.Classes, Global, System.SysUtils, Windows, System.DateUtils, XSuperobject, EventUnit; type TPcnEvent = record Good :boolean; SysNum :byte; PrdNum :integer; KodEv :integer; DateTime :TDateTime; Signal :string; PackNum : word; Slot : TSlot; end; type TPultHolder = class(TObject) public PultID : integer; Control : TPCN; CommHandle : integer; Childs : array of TSlot; CommandNum : Word; Event : TPcnEvent; SysEvent : TEvents; function OpenComPort: boolean; function ReadAsProton: TPcnEvent; procedure WorkMessage(Event: TPcnEvent); procedure CloseComPort; function HexToInt(HexStr : string) : Int64; constructor Create; private type TArrayOfChar = array of Char; ArrOfByte = array[0..7] of byte; { Private declarations } protected // Prefix : integer; ReadBuf : array of byte; // буфер приема RxOver : boolean; // прием закончен WaitByte : byte; // Ожидаемое кол-во байт считанное с порта qByte : byte; // реальное кол-во байт считанное с порта TimeSetup : boolean; function BinToInt(Value: string): Integer; function IntToBin(Value: Longint; Digits: Integer): string; function InvValue(Chislo:integer):integer; function BufDataToInt(LowByte: byte; HigthByte: byte):integer; function CreateControlSum(Value:integer):integer; function HighLowByte(Val:byte;var LowB:byte;var HighB:byte):Boolean; function IntToOct(Value: Longint; digits: Integer): string; function Format2(Value:integer):string; function IntToBinAr(Value: Longint; Digits: Integer):ArrOfByte; function RetrData(Value:integer;var RetrLevel:byte):byte; procedure Work; procedure OnTerminate(Sender: TObject); // procedure Execute; override; end; var PHolders : array of TPultHolder; implementation uses Constants, Service, DataUnit; constructor TPultHolder.Create; begin PultID := InvalidID; Control := nil; CommHandle := InvalidID; SetLength(Childs, 0); CommandNum := 0; SysEvent := nil; end; function TPultHolder.OpenComPort:boolean; var DCB : TDCB; cto: TCommTimeOuts; ctModem: DWORD; PortString:string; begin //создание и иницализация порта Result := False; PortString := '\\.\' + Control.ComPortName; CommHandle := CreateFile(PChar(PortString), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, 0, 0); //ставим маску - "по пришествии определенного символа" //SetCommMask(CommHandle,EV_RXFLAG); if CommHandle < 0 then begin if Control.State <> PcnStateDown then LogOut('Не удалось открыть порт - ' + PortString); // RaiseLastOSError; CommHandle := InvalidID; Exit; end; Result := True; LogOut('Компорт открыт -' + PortString); //Выставляем параметры COM-порта if not GetCommState(CommHandle,dcb) //uses Windows then RaiseLastOSError; if Control.BAUDRATE = '300' then dcb.BaudRate:=CBR_300; if Control.BAUDRATE = '600' then dcb.BaudRate:=CBR_600; if Control.BAUDRATE = '1200' then dcb.BaudRate:=CBR_1200; if Control.BAUDRATE = '2400' then dcb.BaudRate:=CBR_2400; if Control.BAUDRATE = '4800' then dcb.BaudRate:=CBR_4800; if Control.BAUDRATE = '9600' then dcb.BaudRate:=CBR_9600; if Control.BAUDRATE = '14400' then dcb.BaudRate:=CBR_14400; if Control.BAUDRATE = '19200' then dcb.BaudRate:=CBR_19200; if Control.BAUDRATE = '38400' then dcb.BaudRate:=CBR_38400; if Control.BAUDRATE = '56000' then dcb.BaudRate:=CBR_56000; if Control.BAUDRATE = '57600' then dcb.BaudRate:=CBR_57600; if Control.BAUDRATE = '115200' then dcb.BaudRate:=CBR_115200; dcb.ByteSize := 8; dcb.Parity := NOPARITY; // if AnsiUpperCase(RadioType) = '5' then dcb.StopBits:=ONESTOPBIT else dcb.StopBits:=TWOSTOPBITS; dcb.StopBits := TWOSTOPBITS; dcb.EvtChar := Chr(0); dcb.XonLim := 80; dcb.XoffLim := 1024; //dcb.Flags:=(dcb.Flags And $FFFFC0FF) Or $00000100; dcb.Flags := 1; if not SetCommState(CommHandle, dcb) //uses Windows then RaiseLastOSError; if not PurgeComm(CommHandle, PURGE_TXABORT or PURGE_RXABORT) then raise Exception.Create('Error purging port'); //Выставляем параметры COM-порта if not GetCommTimeOuts(CommHandle, cto) //uses Windows then RaiseLastOSError; cto.ReadIntervalTimeout := 10000; cto.ReadTotalTimeoutMultiplier := 5; cto.ReadTotalTimeoutConstant := 0; cto.WriteTotalTimeoutMultiplier := 100; cto.WriteTotalTimeoutConstant := 1000; if not SetCommTimeOuts(CommHandle, cto) //uses Windows then RaiseLastOSError; if not SetupComm(CommHandle, 1024, 1024) then RaiseLastOSError; if not SetCommMask(CommHandle, EV_RXCHAR) then RaiseLastOSError; if not GetCommModemStatus(CommHandle,ctModem) then RaiseLastOSError; end; procedure TPultHolder.CloseComPort; var i: integer; begin if CommHandle = InvalidID then Exit; CloseHandle(CommHandle); CommHandle := InvalidID; LogOut('Закрыт порт - ' + Control.ComPortName); Control.State := PcnStateDown; for i := 0 to High(Childs) do begin Childs[i].STATE := PcnStateDown; end; end; function TPultHolder.BinToInt(Value: string): Integer; var i, iValueSize: Integer; begin Result := 0; iValueSize := Length(Value); for i := iValueSize downto 1 do if Value[i] = '1' then Result := Result + (1 shl (iValueSize - i)); end; function TPultHolder.IntToBin(Value: Longint; Digits: Integer): string; var i: Integer; begin Result := ''; for i := Digits downto 0 do if Value and (1 shl i) <> 0 then Result := Result + '1' else Result := Result + '0'; end; function TPultHolder.HexToInt(HexStr : string) : Int64; var RetVar : Int64; i : byte; begin HexStr := UpperCase(HexStr); if HexStr[length(HexStr)] = 'H' then Delete(HexStr,length(HexStr),1); RetVar := 0; for i := 1 to length(HexStr) do begin RetVar := RetVar shl 4; //CharInSet(HexStr[i],['0'..'9']); if CharInSet(HexStr[i],['0'..'9']) then RetVar := RetVar + (byte(HexStr[i]) - 48) else if CharInSet(HexStr[i],['A'..'F']) then RetVar := RetVar + (byte(HexStr[i]) - 55) else begin Retvar := 0; break; end; end; Result := RetVar; end; function TPultHolder.InvValue(Chislo:integer):integer; var BinValue:string; i:integer; Invert,Hex:string; begin Invert := ''; BinValue := IntToBin(Chislo,8); for i:= 1 to Length(BinValue) do begin if BinValue[i] = '0' then Invert := Invert + '1' else Invert := Invert + '0'; end; Hex := IntToHex(BinToInt(Invert),4); Hex := Copy(Hex,3,2); Result := HexToInt(Hex); end; function TPultHolder.CreateControlSum(Value:integer):integer; var Hex:string; begin Hex := IntToHex(Value,4); Hex := Copy(Hex,3,2); Result := 256 - HexToInt(Hex); end; function TPultHolder.HighLowByte(Val:byte;var LowB:byte;var HighB:byte):Boolean; var HexVal:string; begin HexVal:=IntToHex(Val,2); LowB:=HexToInt(Copy(HexVal,2,1)); HighB:=HexToInt(Copy(HexVal,1,1)); Result:=True; end; function TPultHolder.IntToOct(Value: Longint; digits: Integer): string; var rest: Longint; oct: string; begin oct := ''; while Value <> 0 do begin rest := Value mod 8; Value := Value div 8; oct := IntToStr(rest) + oct; end; //for i := Length(oct) + 1 to digits do //oct := '0' + oct; Result := oct; end; function TPultHolder.Format2(Value:integer):string; begin Result := IntToStr(Value); if Length(Result) = 1 then Result := '0'+Result; end; function TPultHolder.IntToBinAr(Value: Longint; Digits: Integer):ArrOfByte; var i: Integer; Mas:ArrOfByte; begin for i := Digits downto 0 do begin if Value and (1 shl i) <> 0 then Mas[i]:=1 else Mas[i]:=0; end; Result := Mas; end; function TPultHolder.RetrData(Value:integer;var RetrLevel:byte):byte; var BinStr:string; Mas:ArrOfByte; i:integer; BinVal:String; begin BinStr := IntToBin(Value,7); Mas := IntToBinAr(Value,7); BinStr:=''; for i:=0 to 7 do BinStr:=BinStr+IntToStr(Mas[i]); BinVal:=''; for i := 5 to 7 do BinVal:=BinVal+IntToStr(Mas[i]); Result:= BinToInt(BinVal); BinVal:=''; for i := 0 to 4 do BinVal:=BinVal+IntToStr(Mas[i]); RetrLevel := BinToInt(BinVal); end; function TPultHolder.BufDataToInt(LowByte: byte; HigthByte: byte):integer; var i:integer; Hex:string; begin Hex := IntToHex(HigthByte, 2) + IntToHex(LowByte, 2); Result := HexToInt(Hex); end; procedure TPultHolder.OnTerminate(Sender: TObject); begin LogOut('Terminate thread ' + Control.NAME); // DisConnectFromPult; // TCPClient.Free; // TCPClient := nil; // DisconnectFromDB; // tDS.Destroy; // tTrans2.Destroy; // tSQL.Destroy; // tTrans.Destroy; // tDB.Destroy; end; procedure TPultHolder.Work; var Event: TPcnEvent; begin if CommHandle = InvalidID then if not OpenComPort then begin LogOut('Поток работы с пультом будет остановлен. ' + Control.NAME); GenEvent(PultID, Control.PULT_CLASS, Byte(EventTypeError), 'Ошибка открытия ком. порта ' + Control.ComPortName); end; if Control.PULT_CLASS = Byte(DevClassRadioPcnProton) then begin Event := ReadAsProton; WorkMessage(Event); end; if (SecondsBetween(Now, Control.LastEvent) > 4) and (Control.State <> PcnStateDown) then begin Control.State := PcnStateDown; GenEvent(PultID, Control.PULT_CLASS, Byte(EventTypeDamageDevice), 'Ком. порт - ' + Control.ComPortName); end; end; procedure TPultHolder.WorkMessage(Event: TPcnEvent); var i : integer; SysMesID : integer; Ppk : TPpk; Prd : TPrd; Zone : TZone; LarsCode : TLarsCodes; Razdel,PPkNum,ZoneNum, XoNum : byte; Bind : boolean; AddInfo: string; EventCode: TEventCode; Test: TTest; begin if not Event.Good then Exit; SysEvent.Clear; SysEvent.Signal := Event.Signal; // LogOut('PrdNum = ' + IntToStr(Event.PrdNum) + ' HEX = ' + IntToStr(Event.KodEv) + ' SIGNAL = ' + Event.Signal); // определение передатчика Prd := AData.GetPrdByRadioNum(Event.PrdNum, Event.SysNum); if Prd = nil then // передатчик не найден begin SysEvent.DevID := RCore.DevID; SysEvent.DevClass := RCore.DevClass; SysEvent.AddInfo := 'Не найден передатчик '+ IntToStr(Event.PrdNum)+'. Код сообщ. = ' + IntToHex(Event.KodEv, 4); SysEvent.EventCode := Byte(EventTypeError); SysEvent.Write; Exit; end; SysEvent.DevID := Prd.ID; SysEvent.CustID := Prd.CUST; SysEvent.DevClass := Byte(DevClassPrd); if not Prd.IS_ACTIVE then // прд не активен begin SysEvent.EventCode := Byte(EventTypeDeviceNotActive); SysEvent.AddInfo := 'Прд № = ' + IntToStr(Event.PrdNum) + '. Код сообщ. = ' + IntToHex(Event.KodEv, 4); SysEvent.Write; Exit; end; SysMesID := -1; LarsCode := AData.GetLarsCode(Prd.CODEPAGE, Event.KodEv); if LarsCode = nil then begin SysEvent.DevID := RCore.DevID; SysEvent.DevClass := RCore.DevClass; SysEvent.EventCode := Byte(EventTypeError); SysEvent.AddInfo := 'Не найден Шаблон события. Прд № = ' + IntToStr(Prd.RADIO_NUM) + '. Код сообщ. = ' + IntToHex(Event.KodEv, 4); LogOut(SysEvent.AddInfo); SysEvent.Write; Exit; end; Razdel := LarsCode.RAZDELNUM; PPKNum := LarsCode.PPK; ZoneNum := LarsCode.ZONENUM; XoNum := LarsCode.XONUM; SysMesID := LarsCode.SYS_MES; // LogOut('SysMesID = ' + IntToStr(SysMesID)); EventCode := AData.EventCodeUO(SysMesID, nil, AGet); if EventCode = nil then begin SysEvent.DevID := RCore.DevID; SysEvent.DevClass := RCore.DevClass; LogOut('Фатальная ошибка не найдено событие ИД = ' + IntToStr(SysMesID)); Exit; end; SysEvent.EventCode := SysMesID; if EventCode.ID_CLASS = Byte(EvTypeTestUp) then begin Test := AData.GetTest(Prd); Test.NEXT_TEST := IncMinute(Now, Prd.TEST_PER); SysEvent.Write; Exit; end; if PPkNum = 0 then begin SysEvent.Write; Exit; end; Ppk := AData.GetPPK(Prd, PPkNum); if Ppk = nil then begin SysEvent.DevID := RCore.DevID; SysEvent.DevClass := RCore.DevClass; SysEvent.EventCode := Byte(EventTypeError); SysEvent.AddInfo := 'Не найден ППКОП №=' + IntToStr(PPkNum) + ' Прд №=' + IntToStr(Event.PrdNum) + '. Код сообщ.=' + IntToHex(Event.KodEv, 4); LogOut(SysEvent.AddInfo); SysEvent.Write; Exit; end; if (Razdel = 0) and (ZoneNum = 0) and ((EventCode.ID_CLASS = Byte(EvTypeArm)) or (EventCode.ID_CLASS = Byte(EvTypeDisArm)) or (EventCode.ID_CLASS = Byte(EvTypeAlarm))) then begin SysEvent.DevID := RCore.DevID; SysEvent.DevClass := RCore.DevClass; SysEvent.EventCode := Byte(EventTypeError); //Ошибка. Событию не привязаны ни раздел ни зон SysEvent.AddInfo := 'Ошибка. Нет привязки события к зоне или разделу.' + ' Прд №=' + IntToStr(Event.PrdNum) + '. Код сообщ.=' + IntToHex(Event.KodEv, 4); LogOut(SysEvent.AddInfo); SysEvent.Write; Exit; end; if (Razdel > 0) and (ZoneNum > 0) then begin SysEvent.DevID := RCore.DevID; SysEvent.DevClass := RCore.DevClass; SysEvent.EventCode := Byte(EventTypeError); //Ошибка. Событию не привязаны ни раздел ни зон SysEvent.AddInfo := 'Ошибка. Cобытие определено и по зоне и по разделу.' + ' Прд № = ' + IntToStr(Event.PrdNum) + '. Код сообщ. = ' + IntToHex(Event.KodEv, 4); LogOut(SysEvent.AddInfo); SysEvent.Write; Exit; end; if Razdel > 0 then begin ZoneNum := 0; for i := 0 to High(Zones) do begin if Zones[i].PARID <> Ppk.ID then Continue; Zone := Zones[i]; if Zone.RAZDEL = Razdel then begin SysEvent.DevID := Zone.ID; SysEvent.DevClass := Byte(DevClassZone); SysEvent.CustID := Zone.CUST; SysEvent.XoID := AData.GetXO(Zone, XoNum); ZoneNum := Zone.NUM; SysEvent.AddInfo := 'Раздел №' + IntToStr(Razdel); SysEvent.Write; end; end; if ZoneNum = 0 then // не было событий по зонам begin SysEvent.DevID := RCore.DevID; SysEvent.DevClass := RCore.DevClass; SysEvent.EventCode := Byte(EventTypeError); //Ошибка. В разделе нет зон SysEvent.AddInfo := 'В разделе нет зон. Раздел ' + IntToStr(Razdel) + '. Прд № = ' + IntToStr(Event.PrdNum) + '. Код сообщ.=' + IntToHex(Event.KodEv, 4); LogOut(SysEvent.AddInfo); SysEvent.Write; end; Exit; end; if ZoneNum > 0 then begin Razdel := 0; for i := 0 to High(Zones) do begin if (Zones[i].PARID = Ppk.ID) and (Zones[i].NUM = ZoneNum) then //поиск зоны у ППК begin Zone := Zones[i]; SysEvent.DevID := Zone.ID; SysEvent.DevClass := Byte(DevClassZone); SysEvent.CustID := Zone.CUST; Razdel := Zone.NUM; SysEvent.XoID := AData.GetXO(Zone, XoNum); SysEvent.Write; Break; end; end; if Razdel = 0 then // не было событий по зонам begin SysEvent.DevID := RCore.DevID; SysEvent.DevClass := RCore.DevClass; SysEvent.EventCode := Byte(EventTypeError); //Ошибка. НЕ найдена зона SysEvent.AddInfo := 'Не найдена зона №' +IntToStr(ZoneNum)+'. Прд №=' + IntToStr(Event.PrdNum)+'. Код сообщ.=' + IntToHex(Event.KodEv, 4); LogOut(SysEvent.AddInfo); SysEvent.Write; end; Exit; end; end; function TPultHolder.ReadAsProton: TPcnEvent; var Resive:array [0..255] of Ansichar; i,tmpKod,Group:integer; PacketNum : byte; LowByteNum, // младший байт номера объекта HighByteNum, // Старший байт номера объекта MesType :byte; KodObject: string; KodEv : integer; j,c:integer; Stat : TComStat; TX:array[0..255] of Char; TmTX :TArrayOfChar; Day,Month,Year:Word; TimeStr:string; KolByte,Kols,Errs : DWord; Ovr : TOverlapped; ByteStr, MesStr:string; SysNum, Protokol, SlotNum, RxLevel, RetrNum, RetrLevel : byte; PrdNum:integer; Pcn_Time:TDateTime; Stroka :string; JSON : ISuperObject; rcMes : TPcnEvent; Prefix : integer; Slot: TSlot; AddInfo : string; begin Result.Good := False; Result.SysNum := 0; Result.PrdNum := 0; Result.KodEv := -1; Result.DateTime := Now; Result.Signal := ''; Result.PackNum := 0; ClearCommError(CommHandle,Errs,@Stat);//сбрасываем флаг Kols := Stat.cbInQue; ReadFile(CommHandle,Resive,Kols,Kols,@Ovr);//читаем if Kols = 0 then Exit; if Kols = 1 then begin if Ord(Resive[0]) = 5 then begin KolByte := 1; TX[0] := Char(4); WriteFile(CommHandle,TX,KolByte,KolByte,@Ovr); end; // if Ord(Resive[0]) = 4 then // готовность ПЦН к приему данных // begin // qByte:=0; // TmTX := TimeTX(CommPort); //буфер с установками времени для ПЦН // for j:=0 to 10 do TX[j]:= TmTX[j]; // KolByte:=11; // WriteFile(CommHandle,TX,KolByte,KolByte,@Ovr); //установка времени на ПЦН // TimeSetup := true; // end; if (Ord(Resive[0]) = 5) or (Ord(Resive[0]) = 4) then begin qByte := 0; SetLength(ReadBuf,0); RxOver := False; Exit; end; end; if qByte = 0 then // старт кадра begin WaitByte := Ord(Resive[0]) + 2; // ожидаемое колво байт qByte := Kols; if Kols > WaitByte then // ошибка получено байт больше чем заявлено begin LogOut('Frame overflow'); qByte := 0; SetLength(ReadBuf,0); RxOver := False; Exit; end; SetLength(ReadBuf, WaitByte); for c:=0 to Kols -1 do ReadBuf[c] := Ord(Resive[c]); if qByte = WaitByte then RxOver := True;//кадр принят за один раз end else begin if qByte + Kols > WaitByte then //сбой принято большее колво байт begin LogOut('Frame overflow'); qByte := 0; SetLength(ReadBuf, 0); RxOver := False; Exit; end; for c := qByte to qByte + Kols -1 do ReadBuf[c] := Ord(Resive[c - qByte]); //добавляем в буфер пришедшие байты qByte := qByte + Kols; //общее колво принятых байт if qByte = WaitByte then RxOver := True;//кадр принят end; if RxOver then begin Control.LastEvent := now; // устанавливаем время последнего сигнала с ком. порта if Length(ReadBuf) < 4 then begin qByte := 0; SetLength(ReadBuf,0); RxOver := False; Exit; end; try MesType := ReadBuf[2]; except LogOut('except MesType := RX[2]'); KolByte := 1; TX[0] := Char(21); WriteFile(CommHandle,TX,KolByte,KolByte,@Ovr); qByte := 0; SetLength(ReadBuf,0); RxOver := False; Exit; end; if MesType = 0 then // код тишины begin Control.LastEvent := Now; if Control.State <> PcnStateWork then begin AddInfo := ' Восстановление связи с ПЦН. Ком порт - ' + Control.ComPortName; LogOut(AddInfo); Control.State := PcnStateWork; GenEvent(PultID, Control.PULT_CLASS, Byte(EventTypeRestoreDevice), AddInfo); Control.State := PcnStateWork; end; if not TimeSetup then begin KolByte := 1; TX[0] := Char(6); WriteFile(CommHandle,TX,KolByte,KolByte,@Ovr); KolByte := 1; TX[0] := Char(5); WriteFile(CommHandle,TX,KolByte,KolByte,@Ovr); end else begin KolByte := 1; TX[0] := Char(6); WriteFile(CommHandle,TX,KolByte,KolByte,@Ovr); end; RxOver := False; SetLength(ReadBuf,0); Exit; end; if MesType = 255 then begin KolByte := 1; TX[0] := Char(6); WriteFile(CommHandle,TX,KolByte,KolByte,@Ovr); end; if MesType = 11 then begin // Stroka :=''; // for j:=0 to Length(ReadBuf) -1 do Stroka := Stroka + ', ' + IntToStr(Readbuf[j]); // LogOut(stroka); Control.LastEvent := Now; if Control.State <> PcnStateWork then begin AddInfo := ' Восстановление связи с ПЦН. Ком порт - ' + Control.ComPortName; LogOut(AddInfo); Control.State := PcnStateWork; GenEvent(PultID, Control.PULT_CLASS, Byte(EventTypeRestoreDevice), AddInfo); Control.State := PcnStateWork; end; if Length(ReadBuf) < 24 then begin qByte := 0; SetLength(ReadBuf, 0); RxOver := False; Exit; end; // 16 58 0B 19 08 00 00 1F 02 00 00 00 00 11 1E 00 37 25 08 09 0B 0B A7 02 //Protokol := RX[2]; HighLowByte(ReadBuf[3], Protokol, SlotNum); PacketNum := ReadBuf[1]; SysNum := ReadBuf[4] - 8; LowByteNum := ReadBuf[7]; HighByteNum := ReadBuf[8]; Group := Trunc(HighByteNum/2); KodObject:= IntToOct(LowByteNum + 1,0); tmpKod:= StrToInt(KodObject+IntToStr(Group)); PrdNum:= tmpKod; // KodEv := BufDataToInt(ReadBuf[10], ReadBuf[11]); KodEv := ReadBuf[10]; DecodeDate(Now,Year,Month,Day); TimeStr := Format2(ReadBuf[20])+'.'+ Format2(ReadBuf[19])+'.'+IntToStr(Year)+' ' + Format2(ReadBuf[18])+':'+Format2(ReadBuf[17])+':'+Format2(ReadBuf[16]); Pcn_Time := Now; RxLevel := ReadBuf[13]; RetrNum := RetrData(ReadBuf[14],RetrLevel); MesStr:=''; Result.Good := True; Result.SysNum := SysNum; Slot := AData.GetSlot(PultID, SlotNum); if Slot = nil then begin LogOut('У радио ПЦН < ' + Control.NAME + ' > не найден слот №' + IntToStr(SlotNum)); LogOut('PrdNum = ' + IntToStr(PrdNum) + ' RodEv = ' + IntToStr(KodEv)); // RdDriver.StopThreads; // StopService; end else begin Prefix := Slot.PREFIX; Slot.LastEvent := Now; end; Result.Slot := Slot; Result.PrdNum := PrdNum + Prefix; Result.KodEv := KodEv; Result.DateTime := IncSecond(Now, RCore.DeltaTime); Result.Signal := IntToHex(KodEv, 4) + ' pr' + IntToStr(Protokol) + ';sl' + IntToStr(SlotNum) + ';rx' + IntToStr(RxLevel) + ';rn' + IntToStr(RetrNum) + ';rl' + IntToStr(RetrLevel); Result.PackNum := PacketNum; KolByte := 1; TX[0] := Char(6); WriteFile(CommHandle,TX,KolByte,KolByte,@Ovr); if (Slot <> nil) and (Slot.STATE <> PcnStateWork) then begin AddInfo := 'Слот № ' + IntToStr(Slot.SlotNum) + ' - ' + Slot.NAME + ' восстановление связи с приемником'; LogOut(AddInfo); GenEvent(Slot.ID, Slot.PULT_CLASS, Byte(EventTypeRestoreDevice), AddInfo); Slot.STATE := PcnStateWork; end; end; qByte := 0; SetLength(ReadBuf,0); RxOver := False; end; end; end.
unit formVenderProdutoParaProf; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, formBase, StdCtrls, Gradient, ExtCtrls, ZMysqlQuery, strUtils; procedure createfrmVenderProdutoParaProf; type TfrmVenderProdutoParaProf = class(TfrmBase) Label2: TLabel; Gradient1: TGradient; edtEntrada: TEdit; lbProfissional: TLabel; lbProduto: TLabel; lbLegenda: TLabel; lbQuantidade: TLabel; Label3: TLabel; Label1: TLabel; lbPreco: TLabel; Label4: TLabel; lbPrecoTotal: TLabel; Bevel1: TBevel; Bevel4: TBevel; Bevel2: TBevel; procedure FormDestroy(Sender: TObject); procedure FormActivate(Sender: TObject); procedure edtEntradaKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } quantidade: integer; preco, total: Real; idprof: integer; idprod: integer; procedure ResetFields; procedure update_labels; procedure recalc_preco; public { Public declarations } end; var frmVenderProdutoParaProf: TfrmVenderProdutoParaProf; const caption_profissional='Profissional: '; caption_produto='Produto: '; implementation {$R *.dfm} uses unitTheWayUtils, DM_main, formMain; procedure createfrmVenderProdutoParaProf; begin if (frmVenderProdutoParaProf=nil) then frmVenderProdutoParaProf:= TfrmVenderProdutoParaProf.create(Application); frmVenderProdutoParaProf.Show; end; procedure TfrmVenderProdutoParaProf.ResetFields; begin lbProfissional.Caption := caption_profissional; quantidade:=1; preco:=0.0; total:=0.0; idprof:=0; idprod:=0; recalc_preco; update_labels; end; procedure TfrmVenderProdutoParaProf.update_labels; begin if (lbProfissional.caption=caption_profissional) then lbLegenda.Caption := 'Passe o código de barras no crachá do profissional que está comprando o produto' else if (lbProduto.caption=caption_produto) then lbLegenda.Caption := 'Passe o código de barras no produto a ser comprado pelo profissional ou digite a quantidade' else lbLegenda.Caption := 'Tecle <ENTER> sem digitar nada para concluir a venda'; end; procedure TfrmVenderProdutoParaProf.FormDestroy(Sender: TObject); begin inherited; frmVenderProdutoParaProf:=nil; end; procedure TfrmVenderProdutoParaProf.recalc_preco; begin total := preco * quantidade; lbPrecoTotal.Caption := format('%m',[total]); lbPreco.Caption := format('%f',[preco]); lbQuantidade.Caption := format('%d',[Quantidade]); end; procedure TfrmVenderProdutoParaProf.FormActivate(Sender: TObject); begin inherited; ResetFields; end; procedure TfrmVenderProdutoParaProf.edtEntradaKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var dts: TZMysqlQuery; dia, mes, ano: word; hora, minuto, segundo, msegundo: word; qtd_estoque: integer; begin inherited; if key=VK_ESCAPE then ResetFields; if (key<>13) and (key<>9) then exit; edtEntrada.Text:=trim(edtEntrada.Text); edtEntrada.text := processaCodigo(edtEntrada.text); dts:=TZMysqlQuery.Create(Self); try dts.Database := DMMain.Database; dts.Transaction := DMMain.Transaction; if edtEntrada.text=''then begin //Finaliza operações //Primeiro verifica if (total=0.0) or (lbProduto.Caption=caption_produto) or (lbProfissional.caption=caption_profissional) then begin beep; edtEntrada.clear; update_labels; exit; end; //Finaliza de fato decodeDate(date, ano, mes, dia); decodeTime(time, hora, minuto, segundo, msegundo); dts.Active:=False; dts.Sql.Clear; dts.Sql.Add('insert into vendasinternas set'); dts.Sql.Add('IDProfissional='+IntToStr(idprof)+', '); dts.Sql.Add('IDProduto='+IntToStr(IDprod)+', '); dts.Sql.Add('TotalCobrado='+FloatToStr(total)+', '); dts.Sql.Add('Quantidade='+IntToStr(Quantidade)+', '); dts.Sql.Add('DataHoraVenda="'+format('%.4d-%.2d-%.2d %.2d:%.2d:%.2d', [ano, mes, dia, hora, minuto, segundo])+'"'); dts.ExecSql; BaixaDeEstoque(DMMain.options.IDLoja, idprod, Quantidade); end; if length(edtEntrada.Text)<13 then begin //Digitou a quantidade try quantidade := StrToInt(edtEntrada.Text); except ShowMessage('Quantidade inválida!'); end; lbQuantidade.Caption := IntToStr(quantidade); edtEntrada.Clear; recalc_preco; exit; end; if leftStr(edtEntrada.text, 2)='20' then begin //Profissional try idprof := StrToInt(rightStr(edtEntrada.Text, 11)); except ShowMessage('Profissional inválido'); end; if not verificaProfissionalNaLoja(rightStr(edtEntrada.text, 11), DMMain.options.IDLoja) then begin edtEntrada.Clear; ResetFields; lbLegenda.caption:='Profissional não está na loja ou não foi cadastrado, fale com a gerente. <ESC> reinicia operações.'; exit; end; dts.Active:=False; dts.Sql.Clear; dts.Sql.Add('select * from profissionais where IDProfissional='+rightStr(edtEntrada.text, 11)); dts.Active := True; if dts.IsEmpty then begin edtEntrada.Clear; ResetFields; lbLegenda.caption:='Profissional não foi cadastrado, fale com a gerente. <ESC> reinicia operações.'; exit; end; lbProfissional.Caption := caption_profissional + dts.fieldByName('Nome').AsString; edtEntrada.Clear; recalc_preco; update_labels; exit; end else if leftStr(edtEntrada.text, 1)<>'2' then begin //Produto dts.Active:=False; dts.Sql.Clear; dts.Sql.Add('select * from produtos where CodBarras="'+edtEntrada.text+'"'); dts.Active := True; if dts.IsEmpty then begin edtEntrada.Clear; lbLegenda.caption:='Produto inválido ou não cadastrado!'; exit; end; idprod:= dts.FieldByName('IDProduto').asInteger; preco := dts.FieldByName('ValorCusto').AsFloat * DMMain.options.porc_profissionais; //Verifica produto no estoque if not podeVenderProdutoEmEstoque(DMMain.options.IDLoja, idprod, qtd_estoque) then begin beep; ResetFields; lbLegenda.Caption := 'Produto não consta em estoque! <ESC> Reinicia.'; exit; end; edtEntrada.Clear; recalc_preco; update_labels; exit; end; finally edtEntrada.Clear; dts.Destroy; end; end; end.
{ *************************************************************************** Copyright (c) 2016-2020 Kike Pérez Unit : Quick.Pooling Description : Pooling objects Author : Kike Pérez Version : 1.9 Created : 28/02/2020 Modified : 29/02/2020 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** 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.Pooling; {$i QuickLib.inc} interface uses {$IFDEF DEBUG_OBJPOOL} Quick.Debug.Utils, {$ENDIF} System.SysUtils, System.SyncObjs, System.DateUtils, Quick.Commons, Quick.Threads; type IPoolItem<T : class, constructor> = interface ['{D52E794B-FDC1-42C1-94BA-823DB74703E4}'] function Item : T; function GetRefCount : Integer; function GetItemIndex : Integer; function GetLastAccess: TDateTime; property RefCount: Integer read GetRefCount; property ItemIndex : Integer read GetItemIndex; property LastAccess: TDateTime read GetLastAccess; end; TCreateDelegator<T> = reference to procedure(var aInstance : T); TPoolItem<T : class, constructor> = class(TInterfacedObject,IPoolItem<T>) private fItem : T; fItemIndex : Integer; fLastAccess : TDateTime; function GetRefCount : Integer; function GetLastAccess: TDateTime; function GetItemIndex : Integer; protected fLock : TCriticalSection; fSemaphore : TSemaphore; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; public constructor Create(aSemaphore : TSemaphore; aLock : TCriticalSection; aItemIndex : Integer; aCreateProc : TCreateDelegator<T>); destructor Destroy; override; function Item : T; property RefCount: Integer read GetRefCount; property ItemIndex : Integer read GetItemIndex; property LastAccess: TDateTime read GetLastAccess; end; IObjectPool<T : class, constructor> = interface ['{AA856DFB-AE8C-46FE-A107-034677010A58}'] function GetPoolSize: Integer; function Get : IPoolItem<T>; property PoolSize : Integer read GetPoolSize; function TimeoutMs(aTimeout : Integer) : IObjectPool<T>; function CreateDelegate(aCreateProc : TCreateDelegator<T>) : IObjectPool<T>; function AutoFreeIdleItemTimeMs(aIdleTimeMs : Integer) : IObjectPool<T>; end; TObjectPool<T : class, constructor> = class(TInterfacedObject,IObjectPool<T>) private fPool : TArray<IPoolItem<T>>; fPoolSize : Integer; fWaitTimeoutMs : Integer; fLock : TCriticalSection; fDelegate : TCreateDelegator<T>; fSemaphore : TSemaphore; fAutoFreeIdleItemTimeMs : Integer; fScheduler : TScheduledTasks; function GetPoolSize: Integer; procedure CreateScheduler; procedure CheckForIdleItems; public constructor Create(aPoolSize : Integer; aAutoFreeIdleItemTimeMs : Integer = 30000; aCreateProc : TCreateDelegator<T> = nil); destructor Destroy; override; property PoolSize : Integer read GetPoolSize; function TimeoutMs(aTimeout : Integer) : IObjectPool<T>; function CreateDelegate(aCreateProc : TCreateDelegator<T>) : IObjectPool<T>; function AutoFreeIdleItemTimeMs(aIdleTimeMs : Integer) : IObjectPool<T>; function Get : IPoolItem<T>; end; implementation { TObjectPool<T> } function TObjectPool<T>.AutoFreeIdleItemTimeMs(aIdleTimeMs: Integer): IObjectPool<T>; begin Result := Self; fAutoFreeIdleItemTimeMs := aIdleTimeMs; end; constructor TObjectPool<T>.Create(aPoolSize : Integer; aAutoFreeIdleItemTimeMs : Integer = 30000; aCreateProc : TCreateDelegator<T> = nil); begin fLock := TCriticalSection.Create; fPoolSize := aPoolSize; fWaitTimeoutMs := 30000; fDelegate := aCreateProc; fAutoFreeIdleItemTimeMs := aAutoFreeIdleItemTimeMs; fSemaphore := TSemaphore.Create(nil,fPoolSize,fPoolSize,''); CreateScheduler; end; procedure TObjectPool<T>.CreateScheduler; begin fScheduler := TScheduledTasks.Create; fScheduler.AddTask('IdleCleaner',[],True,procedure(task : ITask) begin CheckForIdleItems; end) .StartInSeconds(10).RepeatEvery(fAutoFreeIdleItemTimeMs,TTimeMeasure.tmMilliseconds); fScheduler.Start; end; procedure TObjectPool<T>.CheckForIdleItems; var i : Integer; begin fLock.Enter; try for i := low(fPool) to High(fPool) do begin //check if item was not used for long time if (fPool[i] <> nil) and (fPool[i].RefCount = 1) and (MilliSecondsBetween(Now,fPool[i].LastAccess) > fAutoFreeIdleItemTimeMs) then begin fPool[i] := nil; end; end; finally fLock.Leave; end; end; function TObjectPool<T>.CreateDelegate(aCreateProc: TCreateDelegator<T>): IObjectPool<T>; begin Result := Self; fDelegate := aCreateProc; end; destructor TObjectPool<T>.Destroy; var i: Integer; begin fScheduler.Stop; fScheduler.Free; fLock.Enter; try for i := Low(fPool) to High(fPool) do fPool[i] := nil; SetLength(FPool,0); finally fLock.Leave; end; fLock.Free; fSemaphore.Free; inherited; end; function TObjectPool<T>.Get: IPoolItem<T>; var i : Integer; waitResult: TWaitResult; begin Result := nil; {$IFDEF DEBUG_OBJPOOL} TDebugger.Trace(Self,'Waiting for get idle Pool Item...'); {$ENDIF} waitResult := fSemaphore.WaitFor(fWaitTimeoutMs); if waitResult <> TWaitResult.wrSignaled then raise Exception.Create('Connection Pool Timeout: Cannot obtain a connection'); fLock.Enter; try if High(fPool) < fPoolSize then SetLength(fPool,High(fPool)+2); for i := Low(fPool) to High(fPool) do begin if fPool[i] = nil then begin fPool[i] := TPoolItem<T>.Create(fSemaphore,fLock,i,fDelegate); {$IFDEF DEBUG_OBJPOOL} TDebugger.Trace(Self,'Create Pool Item: %d',[i]); {$ENDIF} Exit(fPool[i]); end; if fPool[i].RefCount = 1 then begin //writeln('get ' + i.ToString); {$IFDEF DEBUG_OBJPOOL} TDebugger.Trace(Self,'Get Idle Pool Item: %d',[i]); {$ENDIF} Exit(fPool[i]); end {$IFDEF DEBUG_OBJPOOL} else TDebugger.Trace(Self,'Pool Item: %d is busy (RefCount: %d)',[i,fPool[i].RefCount]); {$ENDIF} end; finally fLock.Leave; end; end; function TObjectPool<T>.GetPoolSize: Integer; begin Result := fPoolSize; end; function TObjectPool<T>.TimeoutMs(aTimeout: Integer): IObjectPool<T>; begin fWaitTimeoutMs := aTimeout; end; { TPoolItem<T> } function TPoolItem<T>.Item: T; begin fLastAccess := Now(); Result := fItem; end; constructor TPoolItem<T>.Create(aSemaphore : TSemaphore; aLock : TCriticalSection; aItemIndex : Integer; aCreateProc : TCreateDelegator<T>); begin fLastAccess := Now(); fItemIndex := aItemIndex; if Assigned(aCreateProc) then aCreateProc(fItem) else fItem := T.Create; fLock := aLock; fSemaphore := aSemaphore; end; destructor TPoolItem<T>.Destroy; begin if Assigned(fItem) then fItem.Free; inherited; end; function TPoolItem<T>.GetItemIndex: Integer; begin Result := fItemIndex; end; function TPoolItem<T>.GetLastAccess: TDateTime; begin Result := fLastAccess; end; function TPoolItem<T>.GetRefCount: Integer; begin Result := FRefCount; end; function TPoolItem<T>._AddRef: Integer; begin fLock.Enter; {$IFDEF DEBUG_OBJPOOL} TDebugger.Trace(Self,'Got Pool item'); {$ENDIF} try Inc(FRefCount); Result := FRefCount; finally fLock.Leave; end; end; function TPoolItem<T>._Release: Integer; begin fLock.Enter; {$IFDEF DEBUG_OBJPOOL} TDebugger.Trace(Self,'Released Pool item'); {$ENDIF} try Dec(fRefCount); Result := fRefCount; if Result = 0 then begin FreeAndNil(fItem); Destroy; end else fLastAccess := Now; finally if fRefCount = 1 then fSemaphore.Release; fLock.Leave; end; end; end.
unit UPrincipal; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Sensors, FMX.Layouts, FMX.Controls.Presentation, FMX.Edit, System.Sensors.Components, FMX.Maps, FMX.StdCtrls, FMX.EditBox, FMX.SpinBox, System.Generics.Collections, FMX.ListBox, FMX.Colors, System.Permissions, System.ImageList, FMX.ImgList, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView; type TF_Principal = class(TForm) ToolBar: TToolBar; edtOrigem: TEdit; ListViewDestinos: TListView; edtDestino1: TEdit; btnIncluiDestino: TSpeedButton; lblRotas: TLabel; LayPrincipal: TLayout; VertScrollBox1: TVertScrollBox; layDestino: TLayout; layOrigem: TLayout; LayEnderecos: TLayout; layEnderecoDestino: TLayout; ColorBox1: TColorBox; layBotaoAvancar: TLayout; layEnderecoOrigem: TLayout; LocationSensor: TLocationSensor; btnAvancar: TSpeedButton; btnLocalizacao: TButton; ImageList1: TImageList; procedure btnIncluiDestinoClick(Sender: TObject); procedure btnAvancarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnLocalizacaoClick(Sender: TObject); procedure lblRotasClick(Sender: TObject); private procedure OnGeocodeReverseEvent(const Address: TCivicAddress); procedure BuscarLocalizacaoAtual; procedure validaCampos; procedure RequestResult(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>); procedure RequisitaPermissoes; { Private declarations } public { Public declarations } FOrigem: string; FGeocoder: TGeocoder; end; var F_Principal: TF_Principal; implementation {$R *.fmx} uses UDM, UBuscaRotas, uFunctions, {$IFDEF ANDROID} Androidapi.Jni.OS, FMX.Helpers.Android, AndroidApi.JNI.GraphicsContentViewText, Androidapi.Jni.Net, Androidapi.Jni.JavaTypes, AndroidApi.Helpers, System.Android.Sensors, {$ENDIF ANDROID} UMapa; procedure TF_Principal.btnAvancarClick(Sender: TObject); var lDestino: TDestino; begin validaCampos; Application.CreateForm(TF_BuscaRotas, F_BuscaRotas); try TRota.Rota.ListaDestinos.Free; TRota.Rota.ListaDestinos := TListaDestinos.Create; for var cont := 0 to pred(ListViewDestinos.Items.Count) do begin lDestino := TDestino.Create; lDestino.Destino := ListViewDestinos.Items[cont].Text; TRota.Rota.ListaDestinos.Add(lDestino); end; F_BuscaRotas.BuscarRotasPossiveis; finally F_BuscaRotas.Show; end; end; procedure TF_Principal.validaCampos; begin if edtOrigem.Text = '' then raise Exception.Create('É necessário especificar a origem'); if FOrigem = '' then FOrigem := edtOrigem.Text; if ListViewDestinos.Items.Count <=0 then raise Exception.Create('É necessário incluir pelo menos 1 destino'); end; procedure TF_Principal.btnIncluiDestinoClick(Sender: TObject); var lItem: TListViewItem; begin if edtDestino1.Text <> '' then begin lItem := ListViewDestinos.Items.Add; lItem.Text := edtDestino1.Text; btnAvancar.Visible := True; edtDestino1.Text := ''; end; end; procedure TF_Principal.btnLocalizacaoClick(Sender: TObject); begin BuscarLocalizacaoAtual; end; procedure TF_Principal.FormShow(Sender: TObject); begin ReportMemoryLeaksOnShutdown := True; RequisitaPermissoes; end; procedure TF_Principal.lblRotasClick(Sender: TObject); begin Application.CreateForm(TF_GMaps, F_GMaps); F_GMaps.Show; end; procedure TF_Principal.RequisitaPermissoes; begin PermissionsService.RequestPermissions([ JStringToString(TJManifest_permission.JavaClass.ACCESS_FINE_LOCATION) ], RequestResult, nil); end; procedure TF_Principal.RequestResult(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>); begin var LocationPermissionGranted := (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted); if LocationPermissionGranted then begin LocationSensor.Active := True; DM.KeyMaps := 'sua-chave-api-aqui'; end; end; procedure TF_Principal.BuscarLocalizacaoAtual; var lCoordenadas: TLocationCoord2D; begin RequisitaPermissoes; LocationSensor.Active := True; lCoordenadas := TLocationCoord2D.Create(LocationSensor.Sensor.Latitude, LocationSensor.Sensor.Longitude); if not lCoordenadas.Latitude.IsNan then begin //FOrigem := lCoordenadas.Latitude.ToString+','+lCoordenadas.Longitude.ToString; FGeocoder := TGeocoder.Current.Create; if Assigned(FGeocoder) then FGeocoder.OnGeocodeReverse := OnGeocodeReverseEvent; if Assigned(FGeocoder) and not FGeocoder.Geocoding then FGeocoder.GeocodeReverse(lCoordenadas); FGeocoder.Free; end; end; procedure TF_Principal.OnGeocodeReverseEvent(const Address: TCivicAddress); begin edtOrigem.Text := Address.Thoroughfare +', '+ //Endereco Address.SubThoroughfare +', '+ //Número Address.PostalCode +', '+ //CEP Address.SubLocality +', '+ //Bairro Address.AdminArea +', '+ //Estado Address.CountryName; //País end; end.
{$I ok_sklad.inc} unit fUserGroups; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, BaseFrame, Menus, ActnList, dxTL6, dxDBCtrl6, dxDBGrid6, dxCntner6, DB, DBClient, ssBaseConst, TB2Item; type TfmUserGroups = class(TssBaseFrame) cdsView: TClientDataSet; colName: TdxDBGridColumn; dsEqType: TDataSource; grdMain: TdxDBGrid; procedure grdMainDblClick(Sender: TObject); procedure grdMainCustomDrawCell(Sender: TObject; ACanvas: TCanvas; ARect: TRect; ANode: TdxTreeListNode; AColumn: TdxTreeListColumn; ASelected, AFocused, ANewItemRow: Boolean; var AText: String; var AColor: TColor; AFont: TFont; var AAlignment: TAlignment; var ADone: Boolean); protected function GetIDForUpdate: integer; override; public procedure UpdateActionList; override; procedure DoOpen(AParam: Variant); override; procedure DoClose; override; procedure DoDelete; override; procedure DoRefresh(const AID: integer; AParam: integer = 0); override; procedure SetCaptions; override; end; var fmUserGroups: TfmUserGroups; implementation uses ClientData, prFun, prConst, UserGroupsEdit, Udebug; var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = ''; {$R *.dfm} const _ID_ = 'grpid'; //============================================================================================== procedure TfmUserGroups.DoClose; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfmUserGroups.DoClose') else _udebug := nil;{$ENDIF} cdsView.Close; inherited; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfmUserGroups.DoDelete; var FNode: TdxTreeListNode; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfmUserGroups.DoDelete') else _udebug := nil;{$ENDIF} if MessageDlg(rs('common','DelConfirm'), mtWarning, [mbYes, mbNo], 0) = mrYes then with TClientDataSet.Create(nil) do try TrStart; try RemoteServer := dmData.SConnection; if not DeleteData(dmData.SConnection, 'usergroups', cdsView.fieldbyname(_ID_).AsInteger) then raise Exception.Create(rs('common','DeleteError')); if not DelToRecycleBin then TrCommit else begin TrRollback; if not AddToRecycleBin(dmData.SConnection, Self.ClassName, cdsView.fieldbyname(_ID_).AsInteger, cdsView.fieldbyname('name').AsString, False, Self.FunID) then begin MessageDlg(rs('common','ErrorInsToRecycleBin'), mtError, [mbOk], 0); begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end; end; end; aRefresh.Execute; UpdateActionList; except on e:exception do begin TrRollback; MessageDlg(rs('common','NoDelete')+#10#13+e.Message, mtError, [mbOk], 0); end; end; finally Free; end; inherited; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfmUserGroups.DoOpen(AParam: Variant); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfmUserGroups.DoOpen') else _udebug := nil;{$ENDIF} EditingClass := TfrmUserGroupsEdit; cdsView.Open; inherited; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfmUserGroups.SetCaptions; var t: string; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfmUserGroups.SetCaptions') else _udebug := nil;{$ENDIF} Self.Caption := rs(Self.Name,'Title'); colName.Caption := rs(Self.Name,'Name'); t := rs(Self.Name, 'Title'); SendMessage(ParentHandle, WM_SETPARENTCAPTION, integer(@t), 0); inherited; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfmUserGroups.grdMainDblClick(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfmUserGroups.grdMainDblClick') else _udebug := nil;{$ENDIF} if grdMain.Count > 0 then DoProperties; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfmUserGroups.UpdateActionList; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfmUserGroups.UpdateActionList') else _udebug := nil;{$ENDIF} aProperties.Enabled := not cdsView.IsEmpty; aDel.Enabled := aProperties.Enabled; aDynamic.Enabled := False; inherited; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfmUserGroups.DoRefresh(const AID: integer; AParam: integer = 0); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfmUserGroups.DoRefresh') else _udebug := nil;{$ENDIF} DSRefresh(cdsView, _ID_, AID); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== function TfmUserGroups.GetIDForUpdate: integer; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfmUserGroups.GetIDForUpdate') else _udebug := nil;{$ENDIF} Result := cdsView.fieldbyname(_ID_).AsInteger; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfmUserGroups.grdMainCustomDrawCell(Sender: TObject; ACanvas: TCanvas; ARect: TRect; ANode: TdxTreeListNode; AColumn: TdxTreeListColumn; ASelected, AFocused, ANewItemRow: Boolean; var AText: String; var AColor: TColor; AFont: TFont; var AAlignment: TAlignment; var ADone: Boolean); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfmUserGroups.grdMainCustomDrawCell') else _udebug := nil;{$ENDIF} if UseGridOddColor and not ASelected and Odd(ANode.AbsoluteIndex) then AColor := GridOddLinesColor; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; initialization {$IFDEF UDEBUG}Debugging := False; DEBUG_unit_ID := debugRegisterUnit('fUserGroups', @Debugging, DEBUG_group_ID);{$ENDIF} finalization //{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF} end.
unit AddDestinationToOptimizationUnit; interface uses SysUtils, BaseExampleUnit, DataObjectUnit; type TAddDestinationToOptimization = class(TBaseExample) public function Execute(OptimizationId: String; AndReOptimize: boolean): TDataObject; end; implementation uses AddressUnit, OptimizationParametersUnit, EnumsUnit; function TAddDestinationToOptimization.Execute(OptimizationId: String; AndReOptimize: boolean): TDataObject; var Address: TAddress; Parameters: TOptimizationParameters; ErrorString: String; begin Address := TAddress.Create; Address.AddressString := '717 5th Ave New York, NY 10021'; Address.Alias := 'Giorgio Armani'; Address.Latitude := 40.7669692; Address.Longitude := -73.9693864; Address.Time := 0; Parameters := TOptimizationParameters.Create; try Parameters.OptimizationProblemID := OptimizationId; Parameters.AddAddress(Address); Parameters.ReOptimize := AndReOptimize; Result := Route4MeManager.Optimization.Update(Parameters, ErrorString); WriteLn(''); if (Result <> nil) then begin WriteLn('AddDestinationToOptimization executed successfully'); WriteLn(Format('Optimization Problem ID: %s', [Result.OptimizationProblemId])); WriteLn(Format('State: %s', [TOptimizationDescription[TOptimizationState(Result.State)]])); end else WriteLn(Format('AddDestinationToOptimization error: %s', [ErrorString])); finally FreeAndNil(Parameters); end; end; end.
inherited dmTelsContato: TdmTelsContato OldCreateOrder = True inherited qryManutencao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWCOLTTEL' ' (TELEFONE, CGC, NOME, ENDERECO, BAIRRO, CIDADE, ESTADO, CEP, I' + '_ESTADUAL, SETOR, CONTATO, MNH_ENTRADA, MNH_SAIDA, TRD_ENTRADA, ' + 'TRD_SAIDA, REFERENCIA, DT_ALTERACAO, END_NRO, OPERADOR)' 'VALUES' ' (:TELEFONE, :CGC, :NOME, :ENDERECO, :BAIRRO, :CIDADE, :ESTADO,' + ' :CEP, :I_ESTADUAL, :SETOR, :CONTATO, :MNH_ENTRADA, :MNH_SAIDA, ' + ':TRD_ENTRADA, :TRD_SAIDA, :REFERENCIA, :DT_ALTERACAO, :END_NRO, ' + ':OPERADOR)') SQLDelete.Strings = ( 'DELETE FROM STWCOLTTEL' 'WHERE' ' TELEFONE = :Old_TELEFONE') SQLUpdate.Strings = ( 'UPDATE STWCOLTTEL' 'SET' ' TELEFONE = :TELEFONE, CGC = :CGC, NOME = :NOME, ENDERECO = :EN' + 'DERECO, BAIRRO = :BAIRRO, CIDADE = :CIDADE, ESTADO = :ESTADO, CE' + 'P = :CEP, I_ESTADUAL = :I_ESTADUAL, SETOR = :SETOR, CONTATO = :C' + 'ONTATO, MNH_ENTRADA = :MNH_ENTRADA, MNH_SAIDA = :MNH_SAIDA, TRD_' + 'ENTRADA = :TRD_ENTRADA, TRD_SAIDA = :TRD_SAIDA, REFERENCIA = :RE' + 'FERENCIA, DT_ALTERACAO = :DT_ALTERACAO, END_NRO = :END_NRO, OPER' + 'ADOR = :OPERADOR' 'WHERE' ' TELEFONE = :Old_TELEFONE') SQLRefresh.Strings = ( 'SELECT TELEFONE, CGC, NOME, ENDERECO, BAIRRO, CIDADE, ESTADO, CE' + 'P, I_ESTADUAL, SETOR, CONTATO, MNH_ENTRADA, MNH_SAIDA, TRD_ENTRA' + 'DA, TRD_SAIDA, REFERENCIA, DT_ALTERACAO, END_NRO, END_COMPL OPER' + 'ADOR FROM STWCOLTTEL' 'WHERE' ' TELEFONE = :Old_TELEFONE') SQLLock.Strings = ( 'SELECT NULL FROM STWCOLTTEL' 'WHERE' 'TELEFONE = :Old_TELEFONE' 'FOR UPDATE WITH LOCK') SQL.Strings = ( 'SELECT' ' TEL.TELEFONE,' ' TEL.CGC,' ' TEL.NOME,' ' TEL.ENDERECO,' ' TEL.BAIRRO,' ' TEL.CIDADE,' ' TEL.ESTADO,' ' TEL.CEP,' ' TEL.I_ESTADUAL,' ' TEL.SETOR,' ' TEL.CONTATO,' ' TEL.MNH_ENTRADA,' ' TEL.MNH_SAIDA,' ' TEL.TRD_ENTRADA,' ' TEL.TRD_SAIDA,' ' TEL.REFERENCIA,' ' TEL.DT_ALTERACAO,' ' TEL.OPERADOR,' ' TEL.END_NRO,' ' SETOR.DESCRICAO NM_SETOR' 'FROM STWCOLTTEL TEL' 'LEFT JOIN STWCOLTSET SETOR ON SETOR.SETOR = TEL.SETOR') object qryManutencaoTELEFONE: TStringField FieldName = 'TELEFONE' Required = True Size = 15 end object qryManutencaoCGC: TStringField FieldName = 'CGC' Required = True Size = 18 end object qryManutencaoNOME: TStringField FieldName = 'NOME' Required = True Size = 40 end object qryManutencaoENDERECO: TStringField FieldName = 'ENDERECO' Size = 60 end object qryManutencaoBAIRRO: TStringField FieldName = 'BAIRRO' Size = 15 end object qryManutencaoCIDADE: TStringField FieldName = 'CIDADE' Size = 30 end object qryManutencaoESTADO: TStringField FieldName = 'ESTADO' Size = 2 end object qryManutencaoCEP: TStringField FieldName = 'CEP' Size = 9 end object qryManutencaoI_ESTADUAL: TStringField FieldName = 'I_ESTADUAL' Size = 18 end object qryManutencaoSETOR: TStringField FieldName = 'SETOR' Size = 5 end object qryManutencaoCONTATO: TStringField FieldName = 'CONTATO' end object qryManutencaoMNH_ENTRADA: TStringField FieldName = 'MNH_ENTRADA' EditMask = '!90:00;1;_' Size = 6 end object qryManutencaoMNH_SAIDA: TStringField FieldName = 'MNH_SAIDA' EditMask = '!90:00;1;_' Size = 6 end object qryManutencaoTRD_ENTRADA: TStringField FieldName = 'TRD_ENTRADA' EditMask = '!90:00;1;_' Size = 6 end object qryManutencaoTRD_SAIDA: TStringField FieldName = 'TRD_SAIDA' EditMask = '!90:00;1;_' Size = 6 end object qryManutencaoREFERENCIA: TStringField FieldName = 'REFERENCIA' Size = 60 end object qryManutencaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryManutencaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryManutencaoNM_SETOR: TStringField FieldName = 'NM_SETOR' ReadOnly = True Size = 40 end object qryManutencaoEND_NRO: TStringField FieldName = 'END_NRO' end end inherited qryLocalizacao: TIBCQuery SQL.Strings = ( 'SELECT' ' TEL.TELEFONE,' ' TEL.CGC,' ' TEL.NOME,' ' TEL.ENDERECO,' ' TEL.BAIRRO,' ' TEL.CIDADE,' ' TEL.ESTADO,' ' TEL.CEP,' ' TEL.I_ESTADUAL,' ' TEL.SETOR,' ' TEL.CONTATO,' ' TEL.MNH_ENTRADA,' ' TEL.MNH_SAIDA,' ' TEL.TRD_ENTRADA,' ' TEL.TRD_SAIDA,' ' TEL.REFERENCIA,' ' TEL.DT_ALTERACAO,' ' TEL.END_NRO,' ' TEL.OPERADOR,' ' SETOR.DESCRICAO NM_SETOR' 'FROM STWCOLTTEL TEL' 'LEFT JOIN STWCOLTSET SETOR ON SETOR.SETOR = TEL.SETOR') object qryLocalizacaoTELEFONE: TStringField FieldName = 'TELEFONE' Required = True Size = 15 end object qryLocalizacaoCGC: TStringField FieldName = 'CGC' Required = True Size = 18 end object qryLocalizacaoNOME: TStringField FieldName = 'NOME' Required = True Size = 40 end object qryLocalizacaoENDERECO: TStringField FieldName = 'ENDERECO' Size = 60 end object qryLocalizacaoBAIRRO: TStringField FieldName = 'BAIRRO' Size = 15 end object qryLocalizacaoCIDADE: TStringField FieldName = 'CIDADE' Size = 30 end object qryLocalizacaoESTADO: TStringField FieldName = 'ESTADO' Size = 2 end object qryLocalizacaoCEP: TStringField FieldName = 'CEP' Size = 9 end object qryLocalizacaoI_ESTADUAL: TStringField FieldName = 'I_ESTADUAL' Size = 18 end object qryLocalizacaoSETOR: TStringField FieldName = 'SETOR' Size = 5 end object qryLocalizacaoCONTATO: TStringField FieldName = 'CONTATO' end object qryLocalizacaoMNH_ENTRADA: TStringField FieldName = 'MNH_ENTRADA' Size = 6 end object qryLocalizacaoMNH_SAIDA: TStringField FieldName = 'MNH_SAIDA' Size = 6 end object qryLocalizacaoTRD_ENTRADA: TStringField FieldName = 'TRD_ENTRADA' Size = 6 end object qryLocalizacaoTRD_SAIDA: TStringField FieldName = 'TRD_SAIDA' Size = 6 end object qryLocalizacaoREFERENCIA: TStringField FieldName = 'REFERENCIA' Size = 60 end object qryLocalizacaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryLocalizacaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryLocalizacaoNM_SETOR: TStringField FieldName = 'NM_SETOR' ReadOnly = True Size = 40 end object qryLocalizacaoEND_NRO: TStringField FieldName = 'END_NRO' end end end
//-----------------------------------------------------------------+ // 파일명칭: Unit_Class_QueryReader // 프로젝트: InsightViewer // 처리개요: MS-SQL Server 및 SQLite 의 Query문을 XML에서 읽어 오기 // 개발언어: Delphi 2007 & XE2 // 작성수정: 아즈텍 장비개발팀 S/W 손준현s // 개발버전: Ver 1.1 (2011.10.10) //-----------------------------------------------------------------+ unit QueryReader; interface uses XMLDoc, xmldom; const XML_FILE_PATH = '..\config\query.xml'; type //-----------------------------------------------------------------+ // 클래스명: TQueryReader // 주요역할: DB관련 Query 처리시 코드내의 복잡하게 정의된 Query문을 대신하여 // 미리 XML 문서내에 정의해 둔 Query문을 가져오기 위한 클래스 이다. // 생성시 사용할 DB-Type과 S/W 이름을 매개 변수로써 넣어 주어야 한다. // //-----------------------------------------------------------------+ TQueryReader = Class(TObject) private xmlBaseData: IDOMNodeList; public Constructor Create(); overload; Constructor Create(dbType, product: String); overload; Destructor Destroy(); override; function GetQuery(content: String): String; function MixQuery(formatedQuery: String; values: array of String): String; function GetAndMixQuery(content: String; values: array of String): String; function Format(formatedQuery: String; values: array of String): String; function GetAndFormat(content: String; values: array of String): String; End; implementation uses SysUtils, DCLUtil, iniFiles, FileManager; { TQueryReader } //-----------------------------------------------------------------+ // 기본 생성자. // 오버로드된 다른 생성자를 불러들이며 // 사용되는 DB는 MS-SQL, S/W는 InsightViewer로 기본 설정 된다. //-----------------------------------------------------------------+ constructor TQueryReader.Create; begin self.Create( 'mssql', 'insightviewer' ); end; //-----------------------------------------------------------------+ // 생성자. 사용할 dbType, product 값을 이용하여 // query.xml(기본값)내에서 그에 해당되는 NodeList를 미리 추출 한다. // 추출된 NodeList는 후에 GetQuery를 수행시 Node 검색에 이용된다. //-----------------------------------------------------------------+ constructor TQueryReader.Create(dbType, product: String); var xmldoc: TXMLDocument; nodeList: IDOMNodeList; sID: String; i: Integer; begin xmldoc := TXMLDocument.Create( nil ); xmldoc.LoadFromFile( TFile.CurrentDir + '\' + XML_FILE_PATH ); //xmldoc.LoadFromFile( GetCurrentDir + '\' + XML_FILE_PATH ); nodeList := xmldoc.DOMDocument.getElementsByTagName( 'product' ); sID := dbType + '.' + product; for i := 0 to nodeList.length - 1 do begin if nodeList.item[ i ].attributes.getNamedItem( 'id' ).nodeValue = sID then begin xmlBaseData := nodeList.item[ i ].childNodes; exit; end; end; raise Exception.Create( 'Not exists data about DBType & Product.' ); end; destructor TQueryReader.Destroy; begin xmlBaseData._Release; inherited; end; function TQueryReader.Format(formatedQuery: String; values: array of String): String; begin result := Format(formatedQuery, values); end; function TQueryReader.GetAndFormat(content: String; values: array of String): String; begin result := Format(GetQuery(content), values); end; //-----------------------------------------------------------------+ // GetQuery와 MixQuery가 합쳐진 형태. // content로 가져온 Query에 값들을 넣고 결과 Query를 return 한다. //-----------------------------------------------------------------+ function TQueryReader.GetAndMixQuery(content: String; values: array of String): String; var sQuery: String; begin sQuery := GetQuery( content ); result := MixQuery( sQuery, values ); end; //-----------------------------------------------------------------+ // content 이름으로 Query를 가져 온다. //-----------------------------------------------------------------+ function TQueryReader.GetQuery(content: String): String; var i: Integer; node: IDOMNode; begin for i := 0 to xmlBaseData.length - 1 do begin node := xmlBaseData.item[i]; if ( node <> nil ) and ( node.attributes.getNamedItem( 'content' ).nodeValue = content ) then begin result := node.childNodes[ 0 ].nodeValue; exit; end; end; end; //-----------------------------------------------------------------+ // 미리 형식이 정의된 Query에 값들을 넣어 주고 그 결과를 return 한다. //-----------------------------------------------------------------+ function TQueryReader.MixQuery(formatedQuery: String; values: array of String): String; var i, iArrMax: Integer; sTemp: String; begin sTemp := formatedQuery; iArrMax := High( values ); for i := 0 to iArrMax do begin sTemp := StringReplace( sTemp, '{' + IntToStr( i ) + '}', values[ i ], [ rfReplaceAll, rfIgnoreCase ] ); end; result := sTemp; end; end.
unit ppi8255; interface {$IFDEF WINDOWS}uses windows;{$ELSE IF}uses main_engine;{$ENDIF} type tread_port_8255=function:byte; twrite_port_8255=procedure(valor:byte); pia8255_chip=class constructor create; destructor free; public procedure reset; procedure change_ports(pread_port_a,pread_port_b,pread_port_c:tread_port_8255;pwrite_port_a,pwrite_port_b,pwrite_port_c:twrite_port_8255); function read(port:byte):byte; procedure write(port,data:byte); function get_port(port:byte):byte; procedure set_port(port,data:byte); function save_snapshot(data:pbyte):word; procedure load_snapshot(data:pbyte); private group_a_mode,group_b_mode:byte; port_a_dir,port_b_dir,port_ch_dir,port_cl_dir:boolean; obf_a,obf_b:boolean; ibf_a,ibf_b:boolean; inte_a,inte_b:boolean; inte_1,inte_2:boolean; control:byte; in_mask,out_mask,read_val,latch,output_val:array[0..2] of byte; read_call:array[0..2] of tread_port_8255; write_call:array[0..2] of twrite_port_8255; procedure get_handshake_signals(val:pbyte); procedure set_mode(data:byte;call_handlers:boolean); procedure write_port(port:byte); function read_port(port:byte):byte; procedure input(port,data:byte); end; var pia8255_0,pia8255_1:pia8255_chip; implementation constructor pia8255_chip.create; begin end; destructor pia8255_chip.free; begin end; function pia8255_chip.save_snapshot(data:pbyte):word; var buffer:array[0..26] of byte; begin buffer[0]:=group_a_mode; buffer[1]:=group_b_mode; buffer[2]:=byte(port_a_dir); buffer[3]:=byte(port_b_dir); buffer[4]:=byte(port_ch_dir); buffer[5]:=byte(port_cl_dir); buffer[6]:=byte(obf_a); buffer[7]:=byte(obf_b); buffer[8]:=byte(ibf_a); buffer[9]:=byte(ibf_b); buffer[10]:=byte(inte_a); buffer[11]:=byte(inte_b); buffer[12]:=byte(inte_1); buffer[13]:=byte(inte_2); buffer[14]:=control; copymemory(@buffer[15],@in_mask[0],3); copymemory(@buffer[18],@read_val[0],3); copymemory(@buffer[21],@latch[0],3); copymemory(@buffer[24],@output_val[0],3); copymemory(data,@buffer[0],27); save_snapshot:=27; end; procedure pia8255_chip.load_snapshot(data:pbyte); var buffer:array[0..26] of byte; begin copymemory(@buffer[0],data,27); group_a_mode:=buffer[0]; group_b_mode:=buffer[1]; port_a_dir:=buffer[2]<>0; port_b_dir:=buffer[3]<>0; port_ch_dir:=buffer[4]<>0; port_cl_dir:=buffer[5]<>0; obf_a:=buffer[6]<>0; obf_b:=buffer[7]<>0; ibf_a:=buffer[8]<>0; ibf_b:=buffer[9]<>0; inte_a:=buffer[10]<>0; inte_b:=buffer[11]<>0; inte_1:=buffer[12]<>0; inte_2:=buffer[13]<>0; control:=buffer[14]; copymemory(@in_mask[0],@buffer[15],3); copymemory(@read_val[0],@buffer[18],3); copymemory(@latch[0],@buffer[21],3); copymemory(@output_val[0],@buffer[24],3); end; procedure pia8255_chip.change_ports(pread_port_a,pread_port_b,pread_port_c:tread_port_8255;pwrite_port_a,pwrite_port_b,pwrite_port_c:twrite_port_8255); begin self.read_call[0]:=pread_port_a; self.read_call[1]:=pread_port_b; self.read_call[2]:=pread_port_c; self.write_call[0]:=pwrite_port_a; self.write_call[1]:=pwrite_port_b; self.write_call[2]:=pwrite_port_c; end; procedure pia8255_chip.reset; var f:byte; begin self.group_a_mode:=0; self.group_b_mode:=0; self.port_a_dir:=false; self.port_b_dir:=false; self.port_ch_dir:=false; self.port_cl_dir:=false; self.obf_a:=false; self.ibf_a:=false; self.obf_b:=false; self.ibf_b:=false; self.inte_a:=false; self.inte_b:=false; self.inte_1:=false; self.inte_2:=false; for f:=0 to 2 do begin self.in_mask[f]:=0; self.out_mask[f]:=0; self.read_val[f]:=0; self.latch[f]:=0; self.output_val[f]:=0; end; self.set_mode($9b,false); end; procedure pia8255_chip.set_mode(data:byte;call_handlers:boolean); var f:byte; begin // parse out mode self.group_a_mode:=(data shr 5) and 3; self.group_b_mode:=(data shr 2) and 1; self.port_a_dir:=(data and $10)<>0; self.port_b_dir:=(data and 2)<>0; self.port_ch_dir:=(data and 8)<>0; self.port_cl_dir:=(data and 1)<>0; // normalize group_a_mode if (self.group_a_mode=3) then self.group_a_mode:=2; // Port A direction if (self.group_a_mode=2) then begin self.in_mask[0]:=$FF; self.out_mask[0]:=$FF; //bidirectional end else begin if self.port_a_dir then begin self.in_mask[0]:=$FF; self.out_mask[0]:=0; // input end else begin self.in_mask[0]:=0; self.out_mask[0]:=$FF; // output end; end; // Port B direction if self.port_b_dir then begin self.in_mask[1]:=$FF; self.out_mask[1]:=0; // input end else begin self.in_mask[1]:=0; self.out_mask[1]:=$FF; // output end; // Port C upper direction */ if self.port_ch_dir then begin self.in_mask[2]:=$F0; self.out_mask[2]:=0; // input end else begin self.in_mask[2]:=0; self.out_mask[2]:=$F0; // output end; // Port C lower direction if self.port_cl_dir then self.in_mask[2]:=self.in_mask[2] or $0F // input else self.out_mask[2]:=self.out_mask[2] or $0F; // output // now depending on the group modes, certain Port C lines may be replaced // * with varying control signals case self.group_a_mode of 0:; // Group A mode 0 no changes 1:begin // Group A mode 1 bits 5-3 are reserved by Group A mode 1 self.in_mask[2]:=self.in_mask[2] and $c7; self.out_mask[2]:=self.out_mask[2] and $c7; end; 2:begin // Group A mode 2 bits 7-3 are reserved by Group A mode 2 self.in_mask[2]:=self.in_mask[2] and $07; self.out_mask[2]:=self.out_mask[2] and $07; end; end; case self.group_b_mode of 0:; // Group B mode 0 no changes 1:begin // Group B mode 1 bits 2-0 are reserved by Group B mode 1 self.in_mask[2]:=self.in_mask[2] and $F8; self.out_mask[2]:=self.out_mask[2] and $F8; end; end; // KT: 25-Dec-99 - 8255 resets latches when mode set self.latch[0]:=0; self.latch[1]:=0; self.latch[2]:=0; if call_handlers then for f:=0 to 2 do self.write_port(f); // reset flip-flops self.obf_a:=false; self.ibf_a:=false; self.obf_b:=false; self.ibf_b:=false; self.inte_a:=false; self.inte_b:=false; self.inte_1:=false; self.inte_2:=false; // store control word self.control:=data; end; procedure pia8255_chip.get_handshake_signals(val:pbyte); var handshake,mask:byte; begin handshake:=0; mask:=0; // group A if (self.group_a_mode=1) then begin if self.port_a_dir then begin if self.ibf_a then handshake:=handshake or $20; if (self.ibf_a and self.inte_a) then handshake:=handshake or $8; mask:=mask or $28; end else begin if not(self.obf_a) then handshake:=handshake or $80; if (self.obf_a and self.inte_a) then handshake:=handshake or $8; mask:=mask or $88; end; end else if (self.group_a_mode=2) then begin if not(self.obf_a) then handshake:=handshake or $80; if self.ibf_a then handshake:=handshake or $20; if ((self.obf_a and self.inte_1) or (self.ibf_a and self.inte_2)) then handshake:=handshake or $8; mask:=mask or $a8; end; // group B if (self.group_b_mode=1) then begin if self.port_b_dir then begin if self.ibf_b then handshake:=handshake or $02; if (self.ibf_b and self.inte_b) then handshake:=handshake or $01; mask:=mask or $03; end else begin if not(self.obf_b) then handshake:=handshake or $02; if (self.obf_b and self.inte_b) then handshake:=handshake or $01; mask:=mask or $03; end; end; val^:=val^ and not(mask); val^:=val^ or (handshake and mask); end; procedure pia8255_chip.write_port(port:byte); var write_data:byte; begin write_data:=self.latch[port] and self.out_mask[port]; write_data:=write_data or ($FF and not(self.out_mask[port])); // write out special port 2 signals if (port=2) then self.get_handshake_signals(@write_data); self.output_val[port]:=write_data; if @self.write_call[port]<>nil then self.write_call[port](write_data); end; function pia8255_chip.read(port:byte):byte; var res:byte; begin res:=0; port:=port and $3; case port of 0,1,2:res:=self.read_port(port); // Port A,B,C read 3:res:=self.control; // Control word end; read:=res; end; function pia8255_chip.read_port(port:byte):byte; var res:byte; begin res:=$00; if (self.in_mask[port]<>0) then begin if @self.read_call[port]<>nil then self.input(port,self.read_call[port]); res:=res or (self.read_val[port] and self.in_mask[port]); end; res:=res or (self.latch[port] and self.out_mask[port]); case port of 0:self.ibf_a:=false; // clear input buffer full flag 1:self.ibf_b:=false; // clear input buffer full flag 2:self.get_handshake_signals(@res); // read special port 2 signals end; read_port:=res; end; procedure pia8255_chip.input(port,data:byte); var changed:boolean; begin changed:=false; self.read_val[port]:=data; // port C is special if (port=2) then begin if (((self.group_a_mode=1) and not(self.port_a_dir)) or (self.group_a_mode=2)) then begin // is !ACKA asserted? if (self.obf_a and ((not(data and $40))<>0)) then begin self.obf_a:=false; changed:=true; end; end; if (((self.group_a_mode=1) and self.port_a_dir) or (self.group_a_mode=2)) then begin // is !STBA asserted? if (not(self.ibf_a) and ((not(data and $10))<>0)) then begin self.ibf_a:=true; changed:=true; end; end; if ((self.group_b_mode=1) and not(self.port_b_dir)) then begin // is !ACKB asserted? if (self.obf_b and ((not(data and $04))<>0)) then begin self.obf_b:=false; changed:=true; end; end; if ((self.group_b_mode=1) and self.port_b_dir) then begin // is !STBB asserted? if (not(self.ibf_b) and ((not(data and $04))<>0)) then begin self.ibf_b:=true; changed:=true; end; end; if changed then self.write_port(2); end; //del if port2 end; procedure pia8255_chip.write(port,data:byte); var bit:byte; begin port:=port mod 4; case port of 0,1,2:begin // Port A,B,C write self.latch[port]:=data; self.write_port(port); case port of 0:if (not(self.port_a_dir) and (self.group_a_mode<>0)) then begin self.obf_a:=true; self.write_port(2); end; 1:if (not(self.port_b_dir) and (self.group_b_mode<>0)) then begin self.obf_b:=true; self.write_port(2); end; end; end; 3:begin // Control word if (data and $80)<>0 then begin self.set_mode(data and $7f,true); end else begin // bit set/reset bit:=(data shr 1) and $07; if (data and 1)<>0 then self.latch[2]:=self.latch[2] or (1 shl bit) // set bit else self.latch[2]:=self.latch[2] and (not(1 shl bit)); // reset bit if (self.group_b_mode=1) then if (bit=2) then self.inte_b:=(data and 1)<>0; if (self.group_a_mode=1) then begin if ((bit=4) and self.port_a_dir) then self.inte_a:=(data and 1)<>0; if ((bit=6) and not(self.port_a_dir)) then self.inte_a:=(data and 1)<>0; end; if (self.group_a_mode=2) then begin if (bit=4) then self.inte_2:=(data and 1)<>0; if (bit=6) then self.inte_1:=(data and 1)<>0; end; self.write_port(2); end; end; end; //del case end; function pia8255_chip.get_port(port:byte):byte; begin get_port:=self.output_val[port]; end; procedure pia8255_chip.set_port(port,data:byte); begin self.input(port,data); end; end.
{$MODE OBJFPC} program Task; const InputFile = 'MINIMUM.INP'; OutputFile = 'MINIMUM.OUT'; maxN = Round(5E5); var fi, fo: TextFile; a: array[1..maxN] of Integer; q: array[1..maxN] of Integer; i, n, k, front, rear: Integer; begin AssignFile(fi, InputFile); Reset(fi); AssignFile(fo, OutputFile); Rewrite(fo); try front := 1; rear := 0; ReadLn(fi, n, k); for i := 1 to n do begin Read(fi, a[i]); while (front <= rear) and (a[q[rear]] >= a[i]) do Dec(rear); Inc(rear); q[rear] := i; while (q[front] + k <= i) do Inc(front); if i >= k then WriteLn(fo, a[q[front]]); end; finally CloseFile(fi); CloseFile(fo); end; end.
unit evdConst; {* Константы физического представления формата evd. } // Модуль: "w:\common\components\rtl\Garant\EVD\evdConst.pas" // Стереотип: "Interfaces" // Элемент модели: "Const" MUID: (476C0699010D) {$Include w:\common\components\rtl\Garant\EVD\evdDefine.inc} interface uses l3IntfUses ; type TevTypeID = ( {* Тип данных тега. } ev_idChild , ev_idAtom , ev_idLong , ev_idString32 , ev_idComponent , ev_idSInt8 , ev_idUInt8 , ev_idSInt16 , ev_idUInt16 , ev_idSInt32 , ev_idUInt32 , ev_idSInt64 , ev_idUInt64 , ev_idString8 , ev_idString16 , ev_idStream , ev_idTransparent , ev_idCodePage , ev_idFontName , ev_idFontID , ev_idShortCodePage );//TevTypeID const unpack_idFill = 0; {* заполнитель выравнивания. } unpack_idFinish = 65535; {* закрывающая скобка тега. } unpack_idKey1 = $6525; {* признак завершения бинарных данных. } unpack_idKey2 = $4525; {* признак завершения бинарных данных. } unpack_idKey3 = $6225; {* признак начала бинарных данных. } unpack_idKey4 = $4225; {* признак начала бинарных данных. } unpack_idMask = unpack_idFinish - 2; {* маска распределения памяти. } unpack_idChildren = unpack_idFinish - 3; {* признак начала списка дочерних тегов. } unpack_idRollback = unpack_idFinish - 4; {* признак отката тега. } unpack_idMaskEx = unpack_idFinish - 5; {* расширенная маска распределения памяти. } unpack_idLink = unpack_idFinish - 6; {* ссылка на объект в другом IStorage. } unpack_idDefaultChild = unpack_idFinish - 7; {* дочерний тег с типом по умолчанию. } evd_pack_idFill = 0; {* заполнитель выравнивания. } evd_pack_idFinish = 255; {* закрывающая скобка тега. } evd_pack_idPercent = 37; {* символ % } evd_pack_idSmallE = 101; {* символ e } evd_pack_idCapitalE = 69; {* символ E } evd_pack_idSmallB = 98; {* символ b } evd_pack_idCapitalB = 66; {* символ B } evd_pack_idSmallP = 112; {* символ p } evd_pack_idCapitalP = 80; {* символ P } evd_pack_idChildren = evd_pack_idFinish - 1; {* признак начала списка дочерних тегов. } evd_pack_idRollback = evd_pack_idFinish - 2; {* признак отката тега. } evd_pack_idLink = evd_pack_idFinish - 3; {* ссылка на объект в другом IStorage. } evd_pack_idDefaultChild = evd_pack_idFinish - 4; {* дочерний тег с типом по умолчанию. } implementation uses l3ImplUses ; end.
unit nsLinkedObjectDescription; {----------------------------------------------------------------------------- Название: nsLinkedObjectDescription Автор: Лукьянец Р. В. Назначение: Реализация интерфайса InsLinkedObjectDescription Версия: $Id: nsLinkedObjectDescription.pas,v 1.2 2009/02/10 18:11:59 lulin Exp $ История: $Log: nsLinkedObjectDescription.pas,v $ Revision 1.2 2009/02/10 18:11:59 lulin - <K>: 133891247. Выделяем интерфейсы работы с документом. Revision 1.1 2007/07/11 10:05:35 oman - new: Показ информации о графическом объекте - передаем всю нужную информацию (cq24711) -----------------------------------------------------------------------------} interface uses l3Interfaces, l3Types, vcmBase, DocumentDomainInterfaces ; type TnsLinkedObjectDescription = class(TvcmBase, InsLinkedObjectDescription) protected // InsLinkedObjectDescription function InsLinkedObjectDescription.pm_GetName = Data_pm_GetName; function Data_pm_GetName: Il3CString; {-} function pm_GetShortName: Il3CString; function pm_GetID: Long; private f_Name: Il3CString; f_ShortName: Il3CString; f_ID: Long; protected procedure Cleanup; override; {-} public constructor Create(const aName: Il3CString; const aShortName: Il3CString; const aID: Long); reintroduce; {-} class function Make(const aName: Il3CString; const aShortName: Il3CString; const aID: Long): InsLinkedObjectDescription; reintroduce; {-} end; implementation { TnsLinkedObjectDescription } procedure TnsLinkedObjectDescription.Cleanup; begin f_Name := nil; f_ShortName := nil; f_ID := 0; inherited Cleanup; end; constructor TnsLinkedObjectDescription.Create(const aName, aShortName: Il3CString; const aID: Long); begin inherited Create; f_Name := aName; f_ShortName := aShortName; f_ID := aID; end; function TnsLinkedObjectDescription.Data_pm_GetName: Il3CString; begin Result := f_Name; end; class function TnsLinkedObjectDescription.Make(const aName, aShortName: Il3CString; const aID: Long): InsLinkedObjectDescription; var l_Instance: TnsLinkedObjectDescription; begin l_Instance := Create(aName, aShortName, aID); try Result := l_Instance; finally vcmFree(l_Instance); end; end; function TnsLinkedObjectDescription.pm_GetID: Long; begin Result := f_ID; end; function TnsLinkedObjectDescription.pm_GetShortName: Il3CString; begin Result := f_ShortName; end; end.
unit RSValueListEditor; { *********************************************************************** } { } { RSPak Copyright (c) Rozhenko Sergey } { http://sites.google.com/site/sergroj/ } { sergroj@mail.ru } { } { This file is a subject to any one of these licenses at your choice: } { BSD License, MIT License, Apache License, Mozilla Public License. } { } { *********************************************************************** } {$I RSPak.inc} interface uses Windows, Messages, SysUtils, Classes, Controls, Grids, ValEdit, RSCommon, RSSysUtils; { TODO : HotTrack in pseudoComboBox } {$I RSWinControlImport.inc} type TRSValueListEditor = class; TRSValueListEditorCreateEditEvent = procedure(Sender:TRSValueListEditor; var Editor:TInplaceEdit) of object; TRSValueListEditor = class(TValueListEditor) private FOnCreateParams: TRSCreateParamsEvent; FProps: TRSWinControlProps; FOnBeforeSetEditText: TGetEditEvent; FOnCreateEditor: TRSValueListEditorCreateEditEvent; protected FDeleting: boolean; procedure CreateParams(var Params:TCreateParams); override; procedure TranslateWndProc(var Msg:TMessage); procedure WndProc(var Msg:TMessage); override; procedure SetCell(ACol, ARow: integer; const Value: string); override; function SelectCell(ACol, ARow: integer): boolean; override; function CreateEditor: TInplaceEdit; override; procedure SetEditText(ACol, ARow: Longint; const Value: string); override; procedure WMCommand(var Msg: TWMCommand); message WM_COMMAND; public constructor Create(AOwner:TComponent); override; procedure DeleteRow(ARow: integer); override; published property OnBeforeSetEditText: TGetEditEvent read FOnBeforeSetEditText write FOnBeforeSetEditText; property OnCreateEditor: TRSValueListEditorCreateEditEvent read FOnCreateEditor write FOnCreateEditor; property BevelEdges; property BevelInner; property BevelKind default bkNone; property BevelOuter; property BevelWidth; property OnCanResize; property OnResize; {$I RSWinControlProps.inc} end; procedure register; implementation procedure register; begin RegisterComponents('RSPak', [TRSValueListEditor]); end; { ********************************** TRSValueListEditor *********************************** } constructor TRSValueListEditor.Create(AOwner:TComponent); begin inherited Create(AOwner); WindowProc:=TranslateWndProc; end; procedure TRSValueListEditor.CreateParams(var Params:TCreateParams); begin inherited CreateParams(Params); if Assigned(FOnCreateParams) then FOnCreateParams(Params); end; procedure TRSValueListEditor.TranslateWndProc(var Msg:TMessage); var b:boolean; begin if assigned(FProps.OnWndProc) then begin b:=false; FProps.OnWndProc(Self, Msg, b, WndProc); if b then exit; end; WndProc(Msg); end; procedure TRSValueListEditor.WndProc(var Msg:TMessage); begin RSProcessProps(self, Msg, FProps); inherited; end; // Gee. They failed to avoid "List index out of bounds". (see original SetCell) procedure TRSValueListEditor.SetCell(ACol, ARow: integer; const Value: string); var index: integer; Line: string; begin index:= ARow - FixedRows; if index >= Strings.Count then begin if ACol = 0 then Line:= Value + '=' else Line:= '=' + Value; Strings.Add(Line); end else begin if ACol = 0 then Line:= Value + '=' + Cells[1, ARow] else Line:= Cells[0, ARow] + '=' + Value; Strings[index]:= Line; end; end; // Another bug. OnSelectCell and OnValidate weren't called after deleting a row function TRSValueListEditor.SelectCell(ACol, ARow: integer): boolean; begin if (ARow <> Row) and (Strings.Count > 0) and IsEmptyRow and not FDeleting then begin result:= (ARow < Row); DeleteRow(Row); if not result then FocusCell(ACol, ARow - 1, True) else result:= inherited SelectCell(ACol, ARow); end else result:= inherited SelectCell(ACol, ARow); end; // In TValueListEditor class FDeleting field is stupidly made private procedure TRSValueListEditor.DeleteRow(ARow: integer); begin FDeleting:= true; try inherited; finally FDeleting:= false; end; end; function TRSValueListEditor.CreateEditor: TInplaceEdit; begin result:= inherited CreateEditor; // TInplaceEditList(InplaceEditor).PickList.ho if Assigned(OnCreateEditor) then OnCreateEditor(self, result); end; procedure TRSValueListEditor.SetEditText(ACol, ARow: Longint; const Value: string); var v:string; begin v:=Value; if Assigned(OnBeforeSetEditText) then OnBeforeSetEditText(self, ACol, ARow, v); inherited SetEditText(ACol, ARow, v); end; // A bug that prevented ComboBox dropped on grid from showing drop-down list procedure TRSValueListEditor.WMCommand(var Msg: TWMCommand); begin RSDispatchEx(self, TWinControl, Msg); inherited; end; end.
unit GetActivitiesResponseUnit; interface uses REST.Json.Types, GenericParametersUnit, NullableBasicTypesUnit, ActivityUnit, JSONNullableAttributeUnit; type TGetActivitiesResponse = class(TGenericParameters) private [JSONName('results')] FResults: TActivityArray; [JSONName('total')] [Nullable] FTotal: NullableInteger; public constructor Create; override; property Results: TActivityArray read FResults write FResults; property Total: NullableInteger read FTotal write FTotal; end; implementation constructor TGetActivitiesResponse.Create; begin inherited; SetLength(FResults, 0); end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, {$ifdef windows} Windows, {$endif} Menus, StdCtrls; type { TForm1 } TForm1 = class(TForm) bToggle: TButton; bShowMenu: TButton; MainMenu1: TMainMenu; MenuItem1: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; procedure bShowMenuClick(Sender: TObject); procedure bToggleClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure MenuItem3Click(Sender: TObject); procedure MenuItem4Click(Sender: TObject); procedure MenuItem5Click(Sender: TObject); private FShowMenu: boolean; procedure SetShowMenu(AValue: boolean); public property ShowMenu: boolean read FShowMenu write SetShowMenu; end; var Form1: TForm1; implementation {$R *.lfm} procedure MenuItem_Copy(ASrc, ADest: TMenuItem); var mi: TMenuItem; i: integer; begin ADest.Clear; ADest.Action:= ASrc.Action; ADest.AutoCheck:= ASrc.AutoCheck; ADest.Caption:= ASrc.Caption; ADest.Checked:= ASrc.Checked; ADest.Default:= ASrc.Default; ADest.Enabled:= ASrc.Enabled; ADest.Bitmap:= ASrc.Bitmap; ADest.GroupIndex:= ASrc.GroupIndex; ADest.GlyphShowMode:= ASrc.GlyphShowMode; ADest.HelpContext:= ASrc.HelpContext; ADest.Hint:= ASrc.Hint; ADest.ImageIndex:= ASrc.ImageIndex; ADest.RadioItem:= ASrc.RadioItem; ADest.RightJustify:= ASrc.RightJustify; ADest.ShortCut:= ASrc.ShortCut; ADest.ShortCutKey2:= ASrc.ShortCutKey2; ADest.ShowAlwaysCheckable:= ASrc.ShowAlwaysCheckable; ADest.SubMenuImages:= ASrc.SubMenuImages; ADest.SubMenuImagesWidth:= ASrc.SubMenuImagesWidth; ADest.Visible:= ASrc.Visible; ADest.OnClick:= ASrc.OnClick; ADest.OnDrawItem:= ASrc.OnDrawItem; ADest.OnMeasureItem:= ASrc.OnMeasureItem; ADest.Tag:= ASrc.Tag; for i:= 0 to ASrc.Count-1 do begin mi:= TMenuItem.Create(ASrc.Owner); MenuItem_Copy(ASrc.Items[i], mi); ADest.Add(mi); end; end; procedure Menu_Copy(ASrc, ADest: TMenu); begin MenuItem_Copy(ASrc.Items, ADest.Items); end; { TForm1 } procedure TForm1.MenuItem3Click(Sender: TObject); begin Showmessage('dlg'); end; procedure TForm1.bToggleClick(Sender: TObject); begin ShowMenu:= not ShowMenu; end; procedure TForm1.FormCreate(Sender: TObject); begin FShowMenu:= true; end; procedure TForm1.bShowMenuClick(Sender: TObject); var P: TPopupMenu; begin P:= TPopupMenu.Create(Self); Menu_Copy(MainMenu1, P); P.PopUp(); P.Free; end; procedure TForm1.MenuItem4Click(Sender: TObject); begin //OpenDialog1.Execute; end; procedure TForm1.MenuItem5Click(Sender: TObject); begin //SaveDialog1.Execute; end; procedure TForm1.SetShowMenu(AValue: boolean); begin FShowMenu:= AValue; {$ifdef windows} if AValue then Windows.SetMenu(Handle, MainMenu1.Handle) else Windows.SetMenu(Handle, 0); {$else} if AValue then Menu:= MainMenu1 else Menu:= nil; {$endif} end; end.
unit cCadFuncao; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils; // LISTA DE UNITS type TFuncao = class private // VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE ConexaoDB: TFDConnection; F_cod_funcao: Integer; F_funcao: string; F_cod_departamento: Integer; F_nome_departamento: string; public constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA function Inserir: Boolean; function Atualizar: Boolean; function Apagar: Boolean; function Selecionar(id: Integer): Boolean; published // VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE // PARA FORNECER INFORMAÇÕESD EM RUMTIME property cod_funcao: Integer read F_cod_funcao write F_cod_funcao; property funcao: string read F_funcao write F_funcao; property cod_departamento: Integer read F_cod_departamento write F_cod_departamento; property nome_departamento: string read F_nome_departamento write F_nome_departamento; end; implementation {$REGION 'Constructor and Destructor'} constructor TFuncao.Create; begin ConexaoDB := aConexao; end; destructor TFuncao.Destroy; begin inherited; end; {$ENDREGION} {$REGION 'CRUD'} function TFuncao.Apagar: Boolean; var Qry: TFDQuery; begin if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' + IntToStr(F_cod_funcao) + #13 + 'Descrição: ' + F_funcao, mtConfirmation, [mbYes, mbNo], 0) = mrNO then begin Result := false; Abort; end; Try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('DELETE FROM igreja.tb_funcao WHERE cod_funcao=:cod_funcao'); Qry.ParamByName('cod_funcao').AsInteger := F_cod_funcao; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; Finally if Assigned(Qry) then FreeAndNil(Qry) End; end; function TFuncao.Atualizar: Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('UPDATE igreja.tb_funcao '+ ' SET funcao=:funcao, cod_departamento=:cod_departamento, nome_departamento=:nome_departamento '+ ' WHERE cod_funcao=:cod_funcao'); Qry.ParamByName('cod_funcao').AsInteger := F_cod_funcao ; Qry.ParamByName('funcao').AsString := F_funcao; Qry.ParamByName('cod_departamento').AsInteger := F_cod_departamento ; Qry.ParamByName('nome_departamento').AsString := F_nome_departamento; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TFuncao.Inserir: Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO tb_funcao '+ ' (funcao, cod_departamento, nome_departamento) '+ ' VALUES(:funcao, :cod_departamento, :nome_departamento)'); Qry.ParamByName('funcao').AsString := F_funcao; Qry.ParamByName('cod_departamento').AsInteger := F_cod_departamento ; Qry.ParamByName('nome_departamento').AsString := F_nome_departamento; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TFuncao.Selecionar(id: Integer): Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('SELECT cod_funcao, funcao, cod_departamento, nome_departamento '+ ' FROM tb_funcao where cod_funcao=:cod_funcao '); Qry.ParamByName('cod_funcao').AsInteger := id; try Qry.Open; Self.F_cod_funcao := Qry.FieldByName('cod_funcao').AsInteger; Self.F_funcao := Qry.FieldByName('funcao').AsString; Self.F_cod_departamento := Qry.FieldByName('cod_departamento').AsInteger; Self.F_nome_departamento := Qry.FieldByName('nome_departamento').AsString; Except Result := false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; {$ENDREGION} end.
unit MFichas.Model.Item.Metodos.GravarNoBanco; interface uses System.SysUtils, System.Generics.Collections, System.Bluetooth, MFichas.Model.Item.Interfaces, MFichas.Model.Conexao.Interfaces, MFichas.Model.Conexao.Factory, MFichas.Model.Entidade.VENDAITENS, MFichas.Model.Entidade.PRODUTO, ORMBR.Container.ObjectSet.Interfaces, ORMBR.Container.ObjectSet, MFichas.Controller.Types; type TModelItemMetodosGravarNoBanco = class(TInterfacedObject, iModelItemGravarNoBanco) private FConn : iModelConexaoSQL; FBluetooth: iModelConexaoBluetooth; FDAO : iContainerObjectSet<TVENDAITENS>; FProduto : TObjectList<TPRODUTO>; [weak] FParent : iModelItem; constructor Create(AParent: iModelItem); procedure DestruirListaProduto; procedure Imprimir; procedure Gravar; public destructor Destroy; override; class function New(AParent: iModelItem): iModelItemGravarNoBanco; function Executar: iModelItemGravarNoBanco; function &End : iModelItem; end; implementation { TModelItemMetodosGravarNoBanco } uses MFichas.Model.Produto, MFichas.Model.Empresa; function TModelItemMetodosGravarNoBanco.&End: iModelItem; begin Result := FParent; end; constructor TModelItemMetodosGravarNoBanco.Create(AParent: iModelItem); begin FParent := AParent; FConn := TModelConexaoFactory.New.ConexaoSQL; FBluetooth := TModelConexaoFactory.New.ConexaoBluetooth; FDAO := TContainerObjectSet<TVENDAITENS>.Create(FConn.Conn, 10); end; destructor TModelItemMetodosGravarNoBanco.Destroy; begin DestruirListaProduto; inherited; end; procedure TModelItemMetodosGravarNoBanco.DestruirListaProduto; begin {$IFDEF MSWINDOWS} if Assigned(FProduto) then FreeAndNil(FProduto); {$ELSE} if Assigned(FProduto) then begin FProduto.Free; FProduto.DisposeOf; end; {$ENDIF} end; function TModelItemMetodosGravarNoBanco.Executar: iModelItemGravarNoBanco; var LItem : iModelItem; I : Integer; LSocket: TBluetoothSocket; begin Result := Self; Imprimir; Gravar; FParent.Iterator.ClearIterator; end; procedure TModelItemMetodosGravarNoBanco.Gravar; var LItem: iModelItem; begin while FParent.Iterator.hasNext do begin LItem := FParent.Iterator.Next; FDAO.Insert(LItem.Entidade); end; end; procedure TModelItemMetodosGravarNoBanco.Imprimir; var LItem : iModelItem; LSocket: TBluetoothSocket; I : Integer; begin FBluetooth.ConectarDispositivo(LSocket); while FParent.Iterator.hasNext do begin LItem := FParent.Iterator.Next; if LItem.Entidade.TIPO = Integer(tvVenda) then begin FProduto := TModelProduto.New.Metodos.BuscarModel.BuscarPorCodigo(LItem.Entidade.PRODUTO); if LItem.Entidade.QUANTIDADE > 1 then begin for I := 0 to Pred(Trunc(LItem.Entidade.QUANTIDADE)) do begin try LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(0))); LSocket.SendData(TEncoding.UTF8.GetBytes(TModelEmpresa.New.Metodos.BuscarModel.NomeDaEmpresa + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(1))); LSocket.SendData(TEncoding.UTF8.GetBytes(DateTimeToStr(Now) + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(1))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(48))); LSocket.SendData(TEncoding.UTF8.GetBytes(FProduto.Items[0].DESCRICAO + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(0))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(97) + chr(48))); LSocket.SendData(TEncoding.UTF8.GetBytes('R$' + LItem.Entidade.PRECO.ToString + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(1))); LSocket.SendData(TEncoding.UTF8.GetBytes('------------------------' + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(10))); except raise Exception.Create( 'Falha na impressão.' + sLineBreak + 'A comunicação com a impressora foi perdida. Tente novamente ou chame o suporte.' ); DestruirListaProduto; end; end; end else begin try LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(0))); LSocket.SendData(TEncoding.UTF8.GetBytes(TModelEmpresa.New.Metodos.BuscarModel.NomeDaEmpresa + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(1))); LSocket.SendData(TEncoding.UTF8.GetBytes(DateTimeToStr(Now) + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(1))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(48))); LSocket.SendData(TEncoding.UTF8.GetBytes(FProduto.Items[0].DESCRICAO + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(0))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(97) + chr(48))); LSocket.SendData(TEncoding.UTF8.GetBytes('R$' + LItem.Entidade.PRECO.ToString + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(1))); LSocket.SendData(TEncoding.UTF8.GetBytes('------------------------' + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(10))); except raise Exception.Create( 'Falha na impressão.' + sLineBreak + 'A comunicação com a impressora foi perdida. Tente novamente ou chame o suporte.' ); DestruirListaProduto; end; end; DestruirListaProduto; end; end; end; class function TModelItemMetodosGravarNoBanco.New(AParent: iModelItem): iModelItemGravarNoBanco; begin Result := Self.Create(AParent); end; end.
unit Sample.Platform.Android; {$INCLUDE 'Sample.inc'} interface uses Androidapi.Egl, Androidapi.AppGlue, Androidapi.Input, Androidapi.Rect, Androidapi.NativeActivity, Sample.Platform; type { Implements Android-specific functionality. } TPlatformAndroid = class(TPlatformBase) {$REGION 'Internal Declarations'} private class var FAndroidApp: Pandroid_app; FDisplay: EGLDisplay; FSurface: EGLSurface; FContext: EGLContext; FConfig: EGLConfig; FWidth: Integer; FHeight: Integer; FInvScreenScale: Single; FSizeChanged: Boolean; private class procedure Setup; static; class procedure SetupScreenScale; static; class procedure SetupInput; static; class procedure RunLoop; static; class procedure Shutdown; static; private class procedure CreateContext; static; private class procedure HandleAppCmd(var App: TAndroid_app; Cmd: Int32); cdecl; static; class function HandleInputEvent(var App: TAndroid_app; Event: PAInputEvent): Int32; cdecl; static; class procedure HandleContentRectChanged(Activity: PANativeActivity; Rect: PARect); cdecl; static; {$ENDREGION 'Internal Declarations'} protected class procedure DoRun; override; end; implementation uses System.Classes, System.UITypes, System.SysUtils, Androidapi.Helpers, Androidapi.Looper, Androidapi.NativeWindow, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Util, Neslib.Ooogles; const { Missing Delphi declarations } AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT = 8; AMOTION_EVENT_ACTION_POINTER_INDEX_MASK = $ff00; { As long as this window is visible to the user, keep the device's screen turned on and bright. } AWINDOW_FLAG_KEEP_SCREEN_ON = $00000080; { Hide all screen decorations (such as the status bar) while this window is displayed. This allows the window to use the entire display space for itself – the status bar will be hidden when an app window with this flag set is on the top layer. A fullscreen window will ignore a value of AWINDOW_SOFT_INPUT_ADJUST_RESIZE; the window will stay fullscreen and will not resize. } AWINDOW_FLAG_FULLSCREEN = $00000400; { TPlatformAndroid } class procedure TPlatformAndroid.CreateContext; const SURFACE_ATTRIBS: array [0..0] of EGLint = ( EGL_NONE); CONTEXT_ATTRIBS: array [0..2] of EGLint = ( EGL_CONTEXT_CLIENT_VERSION, 2, // OpenGL-ES 2 EGL_NONE); var NumConfigs, Format: EGLint; ConfigAttribs: TArray<EGLint>; begin { TODO: Handle context loss? } FDisplay := eglGetDisplay(EGL_DEFAULT_DISPLAY); if (FDisplay = EGL_NO_DISPLAY) then raise Exception.Create('Unable to get default EGL display'); if (eglInitialize(FDisplay, nil, nil) = EGL_FALSE) then raise Exception.Create('Unable to initialize EGL'); ConfigAttribs := TArray<EGLint>.Create( EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 16); if (TPlatformAndroid.App.NeedStencilBuffer) then ConfigAttribs := ConfigAttribs + [EGL_STENCIL_SIZE, 8]; ConfigAttribs := ConfigAttribs + [ EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_NONE]; if (eglChooseConfig(FDisplay, @ConfigAttribs[0], @FConfig, 1, @NumConfigs) = EGL_FALSE) then raise Exception.Create('Unable to create EGL configuration'); eglGetConfigAttrib(FDisplay, FConfig, EGL_NATIVE_VISUAL_ID, @Format); ANativeWindow_setBuffersGeometry(FAndroidApp.window, 0, 0, Format); FSurface := eglCreateWindowSurface(FDisplay, FConfig, FAndroidApp.window, @SURFACE_ATTRIBS[0]); if (FSurface = EGL_NO_SURFACE) then raise Exception.Create('Unable to get create EGL window surface'); FContext := eglCreateContext(FDisplay, FConfig, EGL_NO_CONTEXT, @CONTEXT_ATTRIBS[0]); if (FContext = EGL_NO_CONTEXT) then raise Exception.Create('Unable to get create EGL context'); eglMakeCurrent(FDisplay, FSurface, FSurface, FContext); InitOoogles; end; class procedure TPlatformAndroid.DoRun; begin { Although calling this routine is not really necessary, but it is a way to ensure that "Androidapi.AppGlue.pas" is kept in uses list, in order to export ANativeActivity_onCreate callback. } app_dummy; Setup; SetupScreenScale; SetupInput; RunLoop; App.Shutdown; Shutdown; end; class procedure TPlatformAndroid.HandleAppCmd(var App: TAndroid_app; Cmd: Int32); begin { This method gets called for Android NDK commands. For commands we are interested in, we convert these to cross-platform events. } case Cmd of APP_CMD_INIT_WINDOW: begin CreateContext; FWidth := ANativeWindow_getWidth(App.window); FHeight := ANativeWindow_getHeight(App.window); TPlatformAndroid.App.Initialize; TPlatformAndroid.App.Resize(FWidth, FHeight); end; APP_CMD_GAINED_FOCUS: { TODO }; APP_CMD_LOST_FOCUS: { TODO }; APP_CMD_RESUME: { TODO }; APP_CMD_PAUSE: { TODO }; APP_CMD_DESTROY: FAndroidApp.destroyRequested := 1; end; end; class procedure TPlatformAndroid.HandleContentRectChanged( Activity: PANativeActivity; Rect: PARect); var Width, Height: Integer; begin { Is called by the native activity when the content bounds have changed, usually as a result of the user rotating the device. } Width := Rect.right - Rect.left; Height := Rect.bottom - Rect.top; if (Width <> FWidth) or (Height <> FHeight) then begin { Resize the render surface to match the new dimensions } FWidth := Width; FHeight := Height; { This method is called from the Java UI thread. So we cannot call TApplication.Resize here since it may access the OpenGL state, which needs to be synchronized with the OpenGL context of the main thread. So we just set a flag and call Resize from the render loop. } FSizeChanged := True; end; end; class function TPlatformAndroid.HandleInputEvent(var App: TAndroid_app; Event: PAInputEvent): Int32; var Kind, Source, ActionBits, Count, Action, Index: Integer; X, Y: Single; Shift: TShiftState; begin { This method gets called for Android NDK input events. For events we are interested in, we convert these to cross-platform events } Kind := AInputEvent_getType(Event); Source := AInputEvent_getSource(Event); ActionBits := AMotionEvent_getAction(Event); case Kind of AINPUT_EVENT_TYPE_MOTION: begin if (Source = AINPUT_SOURCE_TOUCHSCREEN) then Shift := [ssTouch] else if (Source = AINPUT_SOURCE_MOUSE) then Shift := [] else Exit(0); X := AMotionEvent_getX(Event, 0) * FInvScreenScale; Y := AMotionEvent_getY(Event, 0) * FInvScreenScale; Count := AMotionEvent_getPointerCount(Event); Action := ActionBits and AMOTION_EVENT_ACTION_MASK; Index := (ActionBits and AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) shr AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; if (Count < 2) then begin { Simulate left mouse click with 1st touch and right mouse click with 2nd touch. Ignore other touches. } case Action of AMOTION_EVENT_ACTION_DOWN: TPlatformAndroid.App.MouseDown(TMouseButton.mbLeft, Shift, X, Y); AMOTION_EVENT_ACTION_POINTER_DOWN: TPlatformAndroid.App.MouseDown(TMouseButton.mbRight, Shift, X, Y); AMOTION_EVENT_ACTION_UP: TPlatformAndroid.App.MouseUp(TMouseButton.mbLeft, Shift, X, Y); AMOTION_EVENT_ACTION_POINTER_UP: TPlatformAndroid.App.MouseUp(TMouseButton.mbRight, Shift, X, Y); end; end; case Action of AMOTION_EVENT_ACTION_MOVE: if (Index = 0) then TPlatformAndroid.App.MouseMove(Shift, X, Y); end; end; end; Result := 0; end; class procedure TPlatformAndroid.RunLoop; var NumEvents: Integer; Source: Pandroid_poll_source; begin { Run the Android looper and handle its events. } StartClock; while (FAndroidApp.destroyRequested = 0) do begin while (FAndroidApp.destroyRequested = 0) do begin ALooper_pollAll(0, nil, @NumEvents, @Source); if (Source = nil) then Break; { This can call the HandleAppCmd and HandleInputEvent methods } Source.process(FAndroidApp, Source); end; if (FAndroidApp.destroyRequested = 0) and (FContext <> EGL_NO_CONTEXT) then begin if (FSizeChanged) then begin TPlatformAndroid.App.Resize(FWidth, FHeight); FSizeChanged := False; end; { Update app and render frame to back buffer } Update; { Swap backbuffer to front to display it } eglSwapBuffers(FDisplay, FSurface); end; end; end; class procedure TPlatformAndroid.Setup; var Activity: PANativeActivity; begin Activity := DelphiActivity; { Intercept the onAppCmd and onInputEvent methods of the Android app and forward them to our implementations } FAndroidApp := Activity.instance; FAndroidApp.onAppCmd := @HandleAppCmd; FAndroidApp.onInputEvent := @HandleInputEvent; { Intercept the onContentRectChanged callback from the Android native activity and forward it to our implementation } Activity.callbacks.onContentRectChanged := @HandleContentRectChanged; { Set the behavior of the main window } ANativeActivity_setWindowFlags(Activity, AWINDOW_FLAG_FULLSCREEN or AWINDOW_FLAG_KEEP_SCREEN_ON, 0); end; class procedure TPlatformAndroid.SetupInput; begin { TODO } end; class procedure TPlatformAndroid.SetupScreenScale; var Metrics: JDisplayMetrics; begin Metrics := TAndroidHelper.DisplayMetrics; if Assigned(Metrics) then TPlatformAndroid.ScreenScale := Metrics.density; FInvScreenScale := 1 / TPlatformAndroid.ScreenScale; end; class procedure TPlatformAndroid.Shutdown; begin if (FContext <> EGL_NO_CONTEXT) then begin eglMakeCurrent(FDisplay, FSurface, FSurface, FContext); eglDestroyContext(FDisplay, FContext); FContext := EGL_NO_CONTEXT; end; if (FSurface <> EGL_NO_SURFACE) then begin eglMakeCurrent(FDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroySurface(FDisplay, FSurface); FSurface := EGL_NO_SURFACE; end; if (FDisplay <> EGL_NO_DISPLAY) then begin eglTerminate(FDisplay); FDisplay := EGL_NO_DISPLAY; end; end; end.
unit StepParam; interface uses StepParamIntf; type TStepParam = class(TInterfacedObject, IStepParam) private FName: string; FValue: string; function GetName: string; function GetValue: string; procedure SetName(const Value: string); procedure SetValue(const Value: string); public property Name: string read GetName write SetName; property Value: string read GetValue write SetValue; end; implementation function TStepParam.GetName: string; begin Result := FName; end; function TStepParam.GetValue: string; begin Result := FValue; end; procedure TStepParam.SetName(const Value: string); begin FName := Value; end; procedure TStepParam.SetValue(const Value: string); begin FValue := Value; end; end.
unit uBaseData; interface uses SysUtils, Classes, DB, DBAccess, Uni, UniDacVcl, uMultiCastEvent; type TBaseData = class(TDataModule) conMain: TUniConnection; cdlgMain: TUniConnectDialog; procedure conMainAfterConnect(Sender: TObject); procedure conMainAfterDisconnect(Sender: TObject); procedure conMainBeforeConnect(Sender: TObject); procedure conMainBeforeDisconnect(Sender: TObject); procedure DataModuleCreate(Sender: TObject); private FAfterConnect: IMultiCastEvent; FAfterDisconnect: IMultiCastEvent; FBeforeConnect: IMultiCastEvent; FBeforeDisconnect: IMultiCastEvent; public function ReadConnectString(AConnection: TUniConnection): string; procedure WriteConnectString(AConnection: TUniConnection); property AfterConnect: IMultiCastEvent read FAfterConnect; property AfterDisconnect: IMultiCastEvent read FAfterDisconnect; property BeforeConnect: IMultiCastEvent read FBeforeConnect; property BeforeDisconnect: IMultiCastEvent read FBeforeDisconnect; end; implementation uses uServices, uUniSqlService, inifiles, uMultiCastEventImpl, Dialogs; resourcestring SConnectionStrings = 'Connection strings'; {$R *.dfm} procedure TBaseData.conMainAfterConnect(Sender: TObject); begin FAfterConnect.Broadcast(Sender); end; procedure TBaseData.conMainAfterDisconnect(Sender: TObject); var SecurityService: ISecurityService; begin FAfterDisconnect.Broadcast(Sender); if Services.TryGetService(ISecurityService, SecurityService) then begin SecurityService.Logout; end; end; procedure TBaseData.conMainBeforeConnect(Sender: TObject); begin FBeforeConnect.Broadcast(Sender); end; procedure TBaseData.conMainBeforeDisconnect(Sender: TObject); begin FBeforeDisconnect.Broadcast(Sender); end; procedure TBaseData.DataModuleCreate(Sender: TObject); begin FAfterConnect := CreateMultiCastEvent(); FAfterDisconnect := CreateMultiCastEvent(); FBeforeConnect := CreateMultiCastEvent(); FBeforeDisconnect := CreateMultiCastEvent(); Services.RegisterService(ISqlService, TUniSqlService.Create(conMain)); try conMain.LoginPrompt := False; conMain.ConnectString := ReadConnectString(conMain); conMain.Connect(); // WriteConnectString(conMain); except on E: Exception do MessageDlg(Format('Ошибка подключения к БД: %s', [E.Message]), mtError, [mbOk], 0); end; end; function TBaseData.ReadConnectString(AConnection: TUniConnection): string; var FileName: string; IniFile: TIniFile; begin Result := AConnection.ConnectString; FileName := ParamStr(0) + '.ini'; if FileExists(FileName) then begin IniFile := TIniFile.Create(FileName); if IniFile.SectionExists(SConnectionStrings) then begin if IniFile.ValueExists(SConnectionStrings, AConnection.Name) then begin Result := IniFile.ReadString(SConnectionStrings, AConnection.Name, AConnection.ConnectString); end; end; IniFile.Free; end; end; procedure TBaseData.WriteConnectString(AConnection: TUniConnection); var FileName: string; IniFile: TIniFile; begin FileName := ParamStr(0) + '.ini'; IniFile := TIniFile.Create(FileName); IniFile.WriteString(SConnectionStrings, AConnection.Name, AConnection.ConnectString); IniFile.Free; end; end.
unit SceneManager; interface uses Scene; type TSceneManager = class(TScene) private FScene: TScene; procedure SetScene(const Value: TScene); public procedure Clear; procedure Render(); override; procedure Update(); override; property Scene: TScene read FScene write SetScene; end; implementation uses Engine; { TSceneManager } procedure TSceneManager.Clear; begin Scene := nil end; procedure TSceneManager.Render; begin if (Scene <> nil) then Scene.Render; end; procedure TSceneManager.SetScene(const Value: TScene); begin FScene := Value; pEngineCore.WriteToLog(PAnsiChar(AnsiString('[HoD] Scene Manager set current scene ' + Value.ClassName + '.'))); end; procedure TSceneManager.Update; begin if (Scene <> nil) then Scene.Update; end; end.
unit pooyan_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,rom_engine,pal_engine, konami_snd,sound_engine; function iniciar_pooyan:boolean; implementation const pooyan_rom:array[0..3] of tipo_roms=( (n:'1.4a';l:$2000;p:0;crc:$bb319c63),(n:'2.5a';l:$2000;p:$2000;crc:$a1463d98), (n:'3.6a';l:$2000;p:$4000;crc:$fe1a9e08),(n:'4.7a';l:$2000;p:$6000;crc:$9e0f9bcc)); pooyan_pal:array[0..2] of tipo_roms=( (n:'pooyan.pr1';l:$20;p:0;crc:$a06a6d0e),(n:'pooyan.pr2';l:$100;p:$20;crc:$82748c0b), (n:'pooyan.pr3';l:$100;p:$120;crc:$8cd4cd60)); pooyan_char:array[0..1] of tipo_roms=( (n:'8.10g';l:$1000;p:0;crc:$931b29eb),(n:'7.9g';l:$1000;p:$1000;crc:$bbe6d6e4)); pooyan_sound:array[0..1] of tipo_roms=( (n:'xx.7a';l:$1000;p:0;crc:$fbe2b368),(n:'xx.8a';l:$1000;p:$1000;crc:$e1795b3d)); pooyan_sprites:array[0..1] of tipo_roms=( (n:'6.9a';l:$1000;p:0;crc:$b2d8c121),(n:'5.8a';l:$1000;p:$1000;crc:$1097c2b6)); //Dip pooyan_dip_a:array [0..2] of def_dip=( (mask:$0f;name:'Coin A';number:16;dip:((dip_val:$2;dip_name:'4C 1C'),(dip_val:$5;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$4;dip_name:'3C 2C'),(dip_val:$1;dip_name:'4C 3C'),(dip_val:$f;dip_name:'1C 1C'),(dip_val:$3;dip_name:'3C 4C'),(dip_val:$7;dip_name:'2C 3C'),(dip_val:$e;dip_name:'1C 2C'),(dip_val:$6;dip_name:'2C 5C'),(dip_val:$d;dip_name:'1C 3C'),(dip_val:$c;dip_name:'1C 4C'),(dip_val:$b;dip_name:'1C 5C'),(dip_val:$a;dip_name:'1C 6C'),(dip_val:$9;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Free Play'))), (mask:$f0;name:'Coin B';number:16;dip:((dip_val:$20;dip_name:'4C 1C'),(dip_val:$50;dip_name:'3C 1C'),(dip_val:$80;dip_name:'2C 1C'),(dip_val:$40;dip_name:'3C 2C'),(dip_val:$10;dip_name:'4C 3C'),(dip_val:$f0;dip_name:'1C 1C'),(dip_val:$30;dip_name:'3C 4C'),(dip_val:$70;dip_name:'2C 3C'),(dip_val:$e0;dip_name:'1C 2C'),(dip_val:$60;dip_name:'2C 5C'),(dip_val:$d0;dip_name:'1C 3C'),(dip_val:$c0;dip_name:'1C 4C'),(dip_val:$b0;dip_name:'1C 5C'),(dip_val:$a0;dip_name:'1C 6C'),(dip_val:$90;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Invalid'))),()); pooyan_dip_b:array [0..5] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'3'),(dip_val:$2;dip_name:'4'),(dip_val:$1;dip_name:'5'),(dip_val:$0;dip_name:'255'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$4;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8;name:'Bonus Life';number:2;dip:((dip_val:$8;dip_name:'50K 80K+'),(dip_val:$0;dip_name:'30K 70K+'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$70;name:'Difficulty';number:8;dip:((dip_val:$70;dip_name:'1 (Easy)'),(dip_val:$60;dip_name:'2'),(dip_val:$50;dip_name:'3'),(dip_val:$40;dip_name:'4'),(dip_val:$30;dip_name:'5'),(dip_val:$20;dip_name:'6'),(dip_val:$10;dip_name:'7'),(dip_val:$0;dip_name:'8 (Hard)'),(),(),(),(),(),(),(),())), (mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var nmi_vblank:boolean; last:byte; procedure update_video_pooyan; var f:word; x,y,color,nchar,atrib:byte; flipx,flipy:boolean; begin for f:=$0 to $3ff do begin if gfx[0].buffer[f] then begin x:=31-(f div 32); y:=f mod 32; atrib:=memoria[$8000+f]; color:=(atrib and $f) shl 4; nchar:=memoria[$8400+f]+8*(atrib and $20); put_gfx_flip(x*8,y*8,nchar,color,1,0,(atrib and $80)<>0,(atrib and $40)<>0); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,256,256,1,0,0,256,256,2); for f:=0 to $17 do begin atrib:=memoria[$9410+(f*2)]; nchar:=memoria[$9011+(f*2)] and $3f; color:=(atrib and $f) shl 4; x:=memoria[$9411+(f*2)]; y:=memoria[$9010+(f*2)]; flipx:=(atrib and $80)<>0; flipy:=(atrib and $40)=0; if main_screen.flip_main_screen then begin x:=240-x; y:=240-y; flipx:=not(flipx); flipy:=not(flipy); end; put_gfx_sprite(nchar,color,flipx,flipy,1); actualiza_gfx_sprite(x,y,2,1); end; actualiza_trozo_final(16,0,224,256,2); end; procedure eventos_pooyan; begin if event.arcade then begin //P1 if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $F7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); //P2 if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4); if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $F7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); //system if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); end; end; procedure pooyan_principal; var frame_m:single; f:byte; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //Main CPU z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //SND CPU konamisnd_0.run; if f=239 then begin if nmi_vblank then z80_0.change_nmi(ASSERT_LINE); update_video_pooyan; end; end; eventos_pooyan; video_sync; end; end; function pooyan_getbyte(direccion:word):byte; begin case direccion of 0..$8fff:pooyan_getbyte:=memoria[direccion]; $9000..$9fff:case (direccion and $7ff) of 0..$3ff:pooyan_getbyte:=memoria[$9000+(direccion and $ff)]; $400..$7ff:pooyan_getbyte:=memoria[$9400+(direccion and $ff)]; end; $a000..$bfff:case (direccion and $3ff) of 0..$7f,$200..$27f:pooyan_getbyte:=marcade.dswb; //dsw1 $80..$9f,$280..$29f:pooyan_getbyte:=marcade.in0; $a0..$bf,$2a0..$2bf:pooyan_getbyte:=marcade.in1; $c0..$df,$2c0..$2df:pooyan_getbyte:=marcade.in2; $e0..$ff,$2e0..$2ff:pooyan_getbyte:=marcade.dswa; //dsw0 end; end; end; procedure pooyan_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; $8000..$87ff:begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $8800..$8fff:memoria[direccion]:=valor; $9000..$9fff:case (direccion and $7ff) of 0..$3ff:memoria[$9000+(direccion and $ff)]:=valor; $400..$7ff:memoria[$9400+(direccion and $ff)]:=valor; end; $a000..$bfff:case (direccion and $3ff) of $0..$7f,$200..$27f:; //WatchDog $100..$17f,$300..$37f:konamisnd_0.sound_latch:=valor; $180,$380:begin nmi_vblank:=valor<>0; if not(nmi_vblank) then z80_0.change_nmi(CLEAR_LINE); end; $181,$381:begin if ((last=0) and (valor<>0)) then konamisnd_0.pedir_irq:=HOLD_LINE; last:=valor; end; $187,$387:main_screen.flip_main_screen:=(valor and 1)=0; end; end; end; //Main procedure reset_pooyan; begin z80_0.reset; reset_audio; konamisnd_0.reset; nmi_vblank:=false; last:=0; marcade.in0:=$FF; marcade.in1:=$FF; marcade.in2:=$FF; end; function iniciar_pooyan:boolean; var colores:tpaleta; f:word; ctemp1:byte; memoria_temp:array[0..$1fff] of byte; const ps_x:array[0..15] of dword=(0, 1, 2, 3, 8*8+0, 8*8+1, 8*8+2, 8*8+3, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 24*8+0, 24*8+1, 24*8+2, 24*8+3); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 32*8, 33*8, 34*8, 35*8, 36*8, 37*8, 38*8, 39*8); begin llamadas_maquina.bucle_general:=pooyan_principal; llamadas_maquina.reset:=reset_pooyan; iniciar_pooyan:=false; iniciar_audio(false); screen_init(1,256,256); screen_init(2,256,256,false,true); iniciar_video(224,256); //Main CPU z80_0:=cpu_z80.create(3072000,256); z80_0.change_ram_calls(pooyan_getbyte,pooyan_putbyte); //Sound Chip konamisnd_0:=konamisnd_chip.create(4,TIPO_TIMEPLT,1789772,256); if not(roms_load(@konamisnd_0.memoria,pooyan_sound)) then exit; //cargar roms if not(roms_load(@memoria,pooyan_rom)) then exit; //convertir chars if not(roms_load(@memoria_temp,pooyan_char)) then exit; init_gfx(0,8,8,256); gfx_set_desc_data(4,0,16*8,$1000*8+4,$1000*8+0,4,0); convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,true,false); //convertir sprites if not(roms_load(@memoria_temp,pooyan_sprites)) then exit; init_gfx(1,16,16,64); gfx[1].trans[0]:=true; gfx_set_desc_data(4,0,64*8,$1000*8+4,$1000*8+0,4,0); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,true,false); //poner la paleta if not(roms_load(@memoria_temp,pooyan_pal)) then exit; for f:=0 to 31 do begin ctemp1:=memoria_temp[f]; colores[f].r:=$21*(ctemp1 and 1)+$47*((ctemp1 shr 1) and 1)+$97*((ctemp1 shr 2) and 1); colores[f].g:=$21*((ctemp1 shr 3) and 1)+$47*((ctemp1 shr 4) and 1)+$97*((ctemp1 shr 5) and 1); colores[f].b:=0+$47*((ctemp1 shr 6) and 1)+$97*((ctemp1 shr 7) and 1); end; set_pal(colores,32); for f:=0 to $ff do begin gfx[1].colores[f]:=memoria_temp[$20+f] and $f; gfx[0].colores[f]:=(memoria_temp[$120+f] and $f)+$10; end; //DIP marcade.dswa:=$ff; marcade.dswb:=$7b; marcade.dswa_val:=@pooyan_dip_a; marcade.dswb_val:=@pooyan_dip_b; //final reset_pooyan; iniciar_pooyan:=true; end; end.
unit nsMainMenu2011Node; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Common$Lib" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Common/nsMainMenu2011Node.pas" // Начат: 16.09.2011 12:38 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Core::Common::Common$Lib::MainMenu::TnsMainMenu2011Node // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses l3Interfaces, l3Tree_TLB, nsNewCachableNode, MainMenuUnit, l3TreeInterfaces, l3IID ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type TnsMainMenu2011Node = class(TnsNewCachableNode) private // private fields f_SectionItem : ISectionItem; f_Caption : Il3CString; protected // overridden protected methods function GetAsPCharLen: Tl3WString; override; function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {* Реализация запроса интерфейса } procedure ClearFields; override; public // public methods constructor Create(const aSectionItem: ISectionItem); reintroduce; class function Make(const aSectionItem: ISectionItem): Il3Node; reintroduce; {* Сигнатура фабрики TnsMainMenu2011Node.Make } end;//TnsMainMenu2011Node {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses l3Base, SysUtils, l3String, nsTypes, IOUnit ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // start class TnsMainMenu2011Node constructor TnsMainMenu2011Node.Create(const aSectionItem: ISectionItem); //#UC START# *4E730CD20352_4E730AE6014C_var* //#UC END# *4E730CD20352_4E730AE6014C_var* begin //#UC START# *4E730CD20352_4E730AE6014C_impl* inherited Create(nil); Assert(aSectionItem <> nil); f_SectionItem := aSectionItem; //#UC END# *4E730CD20352_4E730AE6014C_impl* end;//TnsMainMenu2011Node.Create class function TnsMainMenu2011Node.Make(const aSectionItem: ISectionItem): Il3Node; var l_Inst : TnsMainMenu2011Node; begin l_Inst := Create(aSectionItem); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TnsMainMenu2011Node.GetAsPCharLen: Tl3WString; //#UC START# *47A869BB02DE_4E730AE6014C_var* var l_S : IString; //#UC END# *47A869BB02DE_4E730AE6014C_var* begin //#UC START# *47A869BB02DE_4E730AE6014C_impl* if (f_Caption = nil) then begin f_SectionItem.GetCaption(l_S); if (l_S = nil) then f_Caption := l3CStr('') else f_Caption := nsCStr(l_S); end;//f_Caption = nil Result := l3PCharLen(f_Caption); //#UC END# *47A869BB02DE_4E730AE6014C_impl* end;//TnsMainMenu2011Node.GetAsPCharLen function TnsMainMenu2011Node.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; //#UC START# *4A60B23E00C3_4E730AE6014C_var* //#UC END# *4A60B23E00C3_4E730AE6014C_var* begin //#UC START# *4A60B23E00C3_4E730AE6014C_impl* Result.SetOk; if IID.EQ(ISectionItem) then ISectionItem(Obj) := f_SectionItem else Result := inherited COMQueryInterface(IID, Obj); //#UC END# *4A60B23E00C3_4E730AE6014C_impl* end;//TnsMainMenu2011Node.COMQueryInterface procedure TnsMainMenu2011Node.ClearFields; {-} begin f_SectionItem := nil; f_Caption := nil; inherited; end;//TnsMainMenu2011Node.ClearFields {$IfEnd} //not Admin AND not Monitorings end.
{******************************************************************************} { } { Delphi FB4D Library } { Copyright (c) 2018-2022 Christoph Schneider } { Schneider Infosystems AG, Switzerland } { https://github.com/SchneiderInfosystems/FB4D } { } {******************************************************************************} { } { 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 FB4D.VisionMLDefinition; interface uses System.Classes, System.Types, System.SysUtils, System.JSON, System.Generics.Collections; type TErrorStatus = record ErrorFound: boolean; ErrorCode: integer; // See https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto ErrorMessage: string; Details: TStringDynArray; procedure Init; procedure SetFromJSON(Item: TJSONObject); function AsStr: string; end; TVertex = record x: integer; y: integer; procedure Init; procedure SetFromJSON(Vertex: TJSONObject); function AsStr: string; end; TNormalizedVertex = record x: double; y: double; procedure Init; procedure SetFromJSON(Vertex: TJSONObject); function AsStr: string; end; TBoundingPoly = record Vertices: array of TVertex; NormalizedVertices: array of TNormalizedVertex; procedure Init; procedure SetFromJSON(BoundingPoly: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TLocationInfo = record Latitude, Longitude: Extended; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TProperty = record Name, Value: string; uInt64Value: UInt64; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TEntityAnnotation = record Id: string; Locale: string; Description: string; Score, Topicality, Confidence: double; BoundingBox: TBoundingPoly; Locations: array of TLocationInfo; Properties: array of TProperty; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TAnnotationList = array of TEntityAnnotation; TFaceLandmarkType = (flmUnkown, flmLeftEye, flmRightEye, flmLeftOfLeftEyeBrow, flmRightOfLeftEyeBrow, flmLeftOfRightEyeBrow, flmRightOfRightEyeBrow, flmMidpointBetweenEyes, flmNoseTip, flmUpperLip, flmLowerLip, flmMouthLeft, flmMouthRight, flmMouthCenter, flmNoseBottomRight, flmNoseBottomLeft, flmNoseBottomCenter, flmLeftEyeTopBoundary, flmLeftEyeRightCorner, flmLeftEyeBottomBoundary, flmLeftEyeLeftCorner, flmRightEyeTopBoundary, flmRightEyeRightCorner, flmRightEyeBottomBoundary, flmRightEyeLeftCorner, flmLeftEyebrowUpperMidpoint, flmRightEyebrowUpperMidpoint, flmLeftEarTragion, flmRightEarTragion, flmLeftEyePupil, flmRightEyePupil, flmForeheadGlabella, flmChinGnathion, flmChinLeftGonion, flmChinRightGonion, flmLeftCheekCenter, flmRightCheekCenter); TFacePosition = record x, y, z: double; procedure Init; procedure SetFromJSON(Item: TJSONObject); function AsStr: string; end; TFaceLandmark = record FaceLandmarkType: TFaceLandmarkType; Position: TFacePosition; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TLikelihood = (lhUnknown, lhVeryUnlikely, lhUnlikely, lhPossible, lhLikely, lhVeryLikely); TFaceAnnotation = record BoundingPoly: TBoundingPoly; FaceDetectionBP: TBoundingPoly; FaceLandmarks: array of TFaceLandmark; RollAngle: double; // -180..180 PanAngle: double; // -180..180 TiltAngle: double; // -180..180 DetectionConfidence: double; // 0..1 LandmarkingConfidence: double; // 0..1 JoyLikelihood: TLikelihood; SorrowLikelihood: TLikelihood; AngerLikelihood: TLikelihood; SurpriseLikelihood: TLikelihood; UnderExposedLikelihood: TLikelihood; BlurredLikelihood: TLikelihood; HeadwearLikelihood: TLikelihood; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TFaceAnnotationList = array of TFaceAnnotation; TLocalizedObjectAnnotation = record Id: string; LanguageCode: string; Name: string; Score: double; BoundingPoly: TBoundingPoly; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TLocalizedObjectList = array of TLocalizedObjectAnnotation; TDetectedLanguage = record LanguageCode: string; Confidence: double; procedure Init; procedure SetFromJSON(Item: TJSONObject); function AsStr: string; end; TDetectedBreakType = (dbtUnknown, dbtSpace, dbtSureSpace, dbtEOLSureSpace, dtbHyphen, dbtLineBreak); TTextProperty = record DetectedLanguages: array of TDetectedLanguage; DetectedBreakType: TDetectedBreakType; DetectedBreakIsPrefix: boolean; procedure Init; procedure SetFromJSON(TextProperty: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); function AsStr: string; end; TSymbols = record TextProperty: TTextProperty; BoundingBox: TBoundingPoly; Text: string; Confidence: double; procedure Init; procedure SetFromJSON(Symbol: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); function AsStr(Short: boolean = false): string; end; TWord = record TextProperty: TTextProperty; BoundingBox: TBoundingPoly; Symbols: array of TSymbols; Confidence: double; procedure Init; procedure SetFromJSON(Word: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); function AsStr(Short: boolean = false): string; end; TParagraph = record TextProperty: TTextProperty; BoundingBox: TBoundingPoly; Words: array of TWord; Confidence: double; procedure Init; procedure SetFromJSON(Paragraph: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); function AsStr: string; function GetText(MinConfidence: double): string; end; TBlockType = (btUnkown, btText, btTable, btPicture, btRuler, btBarcode); TBlock = record TextProperty: TTextProperty; BoundingBox: TBoundingPoly; Paragraphs: array of TParagraph; BlockType: TBlockType; Confidence: double; procedure Init; procedure SetFromJSON(Block: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); function GetText(MinConfidence: double): string; end; TTextPages = record TextProperty: TTextProperty; Width, Height: integer; Blocks: array of TBlock; Confidence: double; procedure Init; procedure SetFromJSON(Page: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); function GetText(MinConfidence: double): string; end; TTextAnnotation = record Text: string; EncodedText: string; TextPages: array of TTextPages; procedure Init; procedure SetFromJSON(FullText: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); function GetText(MinConfidence: double): string; end; TColorInfo = record Red, Green, Blue, Alpha: integer; Score, PixelFraction: double; procedure Init; procedure SetFromJSON(Item: TJSONObject); function AsStr: string; end; TImagePropertiesAnnotation = record DominantColors: array of TColorInfo; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TCropHint = record BoundingPoly: TBoundingPoly; Confidence: double; ImportanceFraction: double; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TCropHintsAnnotation = record CropHints: array of TCropHint; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TWebEntity = record EntityId: string; Description: string; Score: Double; procedure Init; procedure SetFromJSON(Item: TJSONObject); function AsStr: string; end; TWebImage = record URL: string; Score: Double; procedure Init; procedure SetFromJSON(Item: TJSONObject); function AsStr: string; end; TWebPage = record URL: string; Score: Double; PageTitle: string; FullMatchingImages: array of TWebImage; PartialMatchingImages: array of TWebImage; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TWebLabel = record LabelText: string; LanguageCode: string; procedure Init; procedure SetFromJSON(Item: TJSONObject); function AsStr: string; end; TWebDetection = record WebEntities: array of TWebEntity; FullMatchingImages: array of TWebImage; PartialMatchingImages: array of TWebImage; PagesWithMatchingImages: array of TWebPage; VisuallySimilarImages: array of TWebImage; BestGuessLabels: array of TWebLabel; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TSafeSearchAnnotation = record AdultContent: TLikelihood; Spoof: TLikelihood; MedicalImage: TLikelihood; ViolentContent: TLikelihood; RacyContent: TLikelihood; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TKeyValue = record Key: string; Value: string; procedure Init; procedure SetFromJSON(Item: TJSONObject); function AsStr: string; end; TProduct = record Name: string; DisplayName: string; Description: string; ProductCategory: string; ProductLabels: array of TKeyValue; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TProductResult = record Product: TProduct; Score: double; Image: string; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TObjectAnnotation = record Id: string; LanguageCode: string; Name: string; Score: double; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TGroupedProductResult = record BoundingPoly: TBoundingPoly; ProductResults: array of TProductResult; ObjectAnnotations: array of TObjectAnnotation; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TProductSearchAnnotation = record IndexTime: TDateTime; ProductResults: array of TProductResult; GroupedProductResults: array of TGroupedProductResult; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; TImageAnnotationContext = record URI: string; PageNumber: integer; procedure Init; procedure SetFromJSON(Item: TJSONObject); procedure AddStrings(s: TStrings; Indent: integer); end; implementation uses System.TypInfo, FB4D.Helpers; { TEntityAnnotation } procedure TEntityAnnotation.Init; begin Id := ''; Locale := ''; Description := ''; Score := 0; Topicality := 0; Confidence := 0; BoundingBox.Init; SetLength(Locations, 0); SetLength(Properties, 0); end; procedure TEntityAnnotation.SetFromJSON(Item: TJSONObject); var O: TJSONObject; A: TJSONArray; c: integer; begin if not Item.TryGetValue<string>('mid', Id) then Id := ''; if not Item.TryGetValue<string>('locale', Locale) then Locale := ''; if not Item.TryGetValue<string>('description', Description) then Description := ''; if not Item.TryGetValue<Double>('score', Score) then Score := 0; if not Item.TryGetValue<Double>('topicality', Topicality) then Topicality := 0; if not Item.TryGetValue<Double>('confidence', Confidence) then Confidence := 0; if Item.TryGetValue<TJSONObject>('boundingPoly', O) then BoundingBox.SetFromJSON(O) else BoundingBox.Init; if Item.TryGetValue<TJSONArray>('locations', A) then begin SetLength(Locations, A.Count); for c := 0 to A.Count - 1 do Locations[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(Locations, 0); if Item.TryGetValue<TJSONArray>('properties', A) then begin SetLength(Properties, A.Count); for c := 0 to A.Count - 1 do Properties[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(Properties, 0); end; procedure TEntityAnnotation.AddStrings(s: TStrings; Indent: integer); var Line, Ind: string; c: integer; begin Ind := StringOfChar(' ', Indent); Line := Ind + '"' + Description + '"'; if Score > 0 then Line := Line + Format(' score %3.1f%%', [Score * 100]); if (Topicality > 0) and (abs(Score - Topicality) > 0.01) then Line := Line + Format(' topicality %3.1f%%', [Topicality * 100]); if not Locale.IsEmpty then Line := Line + ' locale ' + Locale; if not Id.IsEmpty then Line := Line + ' (mid ' + Id + ')'; s.Add(Line); BoundingBox.AddStrings(s, Indent); for c := 0 to length(Locations) - 1 do begin s.Add(Format('%sLocation %d of %d', [Ind, c + 1, length(Locations)])); Locations[c].AddStrings(s, Indent + 2); end; for c := 0 to length(Properties) - 1 do begin s.Add(Format('%sProperty %d of %d', [Ind, c + 1, length(Properties)])); Properties[c].AddStrings(s, Indent + 2); end; end; { TDetectedLanguage } procedure TDetectedLanguage.Init; begin LanguageCode := ''; Confidence := 0; end; procedure TDetectedLanguage.SetFromJSON(Item: TJSONObject); begin if not Item.TryGetValue<string>('languageCode', LanguageCode) then LanguageCode := ''; if not Item.TryGetValue<double>('confidence', Confidence) then Confidence := 0; end; function TDetectedLanguage.AsStr: string; begin if Confidence > 0 then result := Format('"%s" confidence %3.1f%%', [TFirebaseHelpers.GetLanguageInEnglishFromCode(LanguageCode), Confidence * 100]) else result := Format('"%s"', [TFirebaseHelpers.GetLanguageInEnglishFromCode(LanguageCode)]); end; { TTextPages } procedure TTextPages.Init; begin TextProperty.Init; SetLength(Blocks, 0); Width := 0; Height := 0; Confidence := 0; end; procedure TTextPages.SetFromJSON(Page: TJSONObject); var P: TJSONObject; B: TJSONArray; c: integer; begin if Page.TryGetValue<TJSONObject>('property', P) then TextProperty.SetFromJSON(P); Page.TryGetValue<integer>('width', Width); Page.TryGetValue<integer>('height', Height); Page.TryGetValue<double>('confidence', Confidence); if Page.TryGetValue<TJSONArray>('blocks', B) then begin SetLength(Blocks, B.Count); for c := 0 to B.Count - 1 do Blocks[c].SetFromJSON(B.Items[c] as TJSONObject); end; end; procedure TTextPages.AddStrings(s: TStrings; Indent: integer); var Line: string; c: integer; begin Line := StringOfChar(' ', Indent); if Width > 0 then Line := Line + 'width ' + Width.ToString + ' '; if Height > 0 then Line := Line + 'height ' + Height.ToString + ' '; if Confidence > 0 then Line := Line + 'confidence ' + Format('%3.1f%% ', [Confidence * 100]); if not trim(Line).IsEmpty then s.Add(Line); TextProperty.AddStrings(s, Indent + 2); for c := 0 to length(Blocks) - 1 do Blocks[c].AddStrings(s, Indent + 2); end; function TTextPages.GetText(MinConfidence: double): string; var c: integer; sl: TStringList; s: string; begin sl := TStringList.Create; try for c := 0 to length(Blocks) - 1 do begin s := Blocks[c].GetText(MinConfidence); if not s.IsEmpty then sl.Add(s); end; result := trim(sl.Text); finally sl.Free; end; end; { TTextAnnotation } procedure TTextAnnotation.Init; begin Text := ''; EncodedText := ''; SetLength(TextPages, 0); end; procedure TTextAnnotation.SetFromJSON(FullText: TJSONObject); var Str: TJSONString; Pages: TJSONArray; c: integer; begin if FullText.TryGetValue<TJSONString>('text', Str) then begin EncodedText := Str.ToJSON; Text := Str.Value; end else begin Text := ''; EncodedText := ''; end; if FullText.TryGetValue<TJSONArray>('pages', Pages) then begin SetLength(TextPages, Pages.Count); for c := 0 to Pages.Count - 1 do TextPages[c].SetFromJSON(Pages.Items[c] as TJSONObject); end else SetLength(TextPages, 0); end; procedure TTextAnnotation.AddStrings(s: TStrings; Indent: integer); var Ind: string; TextPage: integer; begin Ind := StringOfChar(' ', Indent); for TextPage := 0 to length(TextPages) - 1 do begin s.Add(Format('%sText page %d of %d', [Ind, TextPage + 1, length(TextPages)])); TextPages[TextPage].AddStrings(s, Indent + 2); end; if not EncodedText.IsEmpty then s.Add(Format('%sEncoded text: %s', [Ind, EncodedText])) else if not Text.IsEmpty then s.Add(Format('%sText: %s', [Ind, Text])) else s.Add(Format('%sNo text found', [Ind])); end; function TTextAnnotation.GetText(MinConfidence: double): string; var c: integer; sl: TStringList; s: string; begin sl := TStringList.Create; try for c := 0 to length(TextPages) - 1 do begin s := TextPages[c].GetText(MinConfidence); if not s.IsEmpty then sl.Add(s); end; result := trim(sl.Text); finally sl.Free; end; end; { TTextProperty } procedure TTextProperty.Init; begin SetLength(DetectedLanguages, 0); DetectedBreakType := TDetectedBreakType.dbtUnknown; DetectedBreakIsPrefix := false; end; procedure TTextProperty.SetFromJSON(TextProperty: TJSONObject); var L: TJSONArray; O: TJSONObject; c: integer; t: string; begin if TextProperty.TryGetValue<TJSONArray>('detectedLanguages', L) then begin SetLength(DetectedLanguages, L.Count); for c := 0 to L.Count - 1 do DetectedLanguages[c].SetFromJSON(L.Items[c] as TJSONObject); end else SetLength(DetectedLanguages, 0); if TextProperty.TryGetValue<TJSONObject>('detectedBreak', O) then begin if O.TryGetValue<string>('type', t) then begin if SameText(t, 'SPACE') then DetectedBreakType := TDetectedBreakType.dbtSpace else if SameText(t, 'SURE_SPACE') then DetectedBreakType := TDetectedBreakType.dbtSureSpace else if SameText(t, 'EOL_SURE_SPACE') then DetectedBreakType := TDetectedBreakType.dbtEOLSureSpace else if SameText(t, 'HYPHEN') then DetectedBreakType := TDetectedBreakType.dtbHyphen else if SameText(t, 'LINE_BREAK') then DetectedBreakType := TDetectedBreakType.dbtLineBreak else DetectedBreakType := TDetectedBreakType.dbtUnknown; end; if not O.TryGetValue<boolean>('isPrefix', DetectedBreakIsPrefix) then DetectedBreakIsPrefix := false; end else begin DetectedBreakType := TDetectedBreakType.dbtUnknown; DetectedBreakIsPrefix := false; end; end; procedure TTextProperty.AddStrings(s: TStrings; Indent: integer); var Line: string; dl: TDetectedLanguage; begin Line := StringOfChar(' ', Indent); for dl in DetectedLanguages do s.Add(Line + dl.AsStr); if DetectedBreakType > TDetectedBreakType.dbtUnknown then begin if DetectedBreakIsPrefix then case DetectedBreakType of dbtSpace: s.Add(Line + 'Prepends break: regular space'); dbtSureSpace: s.Add(Line + 'Prepends break: wide space'); dbtEOLSureSpace: s.Add(Line + 'Prepends break: line-wrapping'); dtbHyphen: s.Add(Line + 'Prepends break: end line hyphen'); dbtLineBreak: s.Add(Line + 'Prepends break: end line break'); end else case DetectedBreakType of dbtSpace: s.Add(Line + 'Break: regular space'); dbtSureSpace: s.Add(Line + 'Break: wide space'); dbtEOLSureSpace: s.Add(Line + 'Break: line-wrapping'); dtbHyphen: s.Add(Line + 'Break: end line hyphen'); dbtLineBreak: s.Add(Line + 'Break: end line break'); end; end; end; function TTextProperty.AsStr: string; var dl: TDetectedLanguage; sl: TStringList; begin sl := TStringList.Create; try for dl in DetectedLanguages do sl.Add(dl.AsStr); if DetectedBreakType > TDetectedBreakType.dbtUnknown then begin if DetectedBreakIsPrefix then case DetectedBreakType of dbtSpace: sl.Add('Prepends break: regular space'); dbtSureSpace: sl.Add('Prepends break: wide space'); dbtEOLSureSpace: sl.Add('Prepends break: line-wrapping'); dtbHyphen: sl.Add('Prepends break: end line hyphen'); dbtLineBreak: sl.Add('Prepends break: end line break'); end else case DetectedBreakType of dbtSpace: sl.Add('Break: regular space'); dbtSureSpace: sl.Add('Break: wide space'); dbtEOLSureSpace: sl.Add('Break: line-wrapping'); dtbHyphen: sl.Add('Break: end line hyphen'); dbtLineBreak: sl.Add('Break: end line break'); end; end; sl.QuoteChar := #0; sl.Delimiter := ','; result := sl.DelimitedText; finally sl.Free; end; end; { TTextBlock } procedure TBlock.Init; begin TextProperty.Init; BoundingBox.Init; SetLength(Paragraphs, 0); BlockType := TBlockType.btUnkown; Confidence := 0; end; procedure TBlock.SetFromJSON(Block: TJSONObject); var Item: TJSONObject; Arr: TJSONArray; bType: string; c: integer; begin if Block.TryGetValue<TJSONObject>('property', Item) then TextProperty.SetFromJSON(Item) else TextProperty.Init; if Block.TryGetValue<TJSONObject>('boundingBox', Item) then BoundingBox.SetFromJSON(Item) else BoundingBox.Init; if Block.TryGetValue<TJSONArray>('paragraphs', Arr) then begin SetLength(Paragraphs, Arr.Count); for c := 0 to Arr.Count - 1 do Paragraphs[c].SetFromJSON(Arr.Items[c] as TJSONObject); end; if Block.TryGetValue<string>('blockType', bType) then begin if SameText(bType, 'TEXT') then BlockType := TBlockType.btText else if SameText(bType, 'TABLE') then BlockType := TBlockType.btTable else if SameText(bType, 'PICTURE') then BlockType := TBlockType.btPicture else if SameText(bType, 'RULER') then BlockType := TBlockType.btRuler else if SameText(bType, 'BARCODE') then BlockType := TBlockType.btBarcode else BlockType := TBlockType.btUnkown; end else BlockType := TBlockType.btUnkown; if not Block.TryGetValue<double>('confidence', Confidence) then Confidence := 0; end; procedure TBlock.AddStrings(s: TStrings; Indent: integer); var Line: string; c: integer; begin if BlockType > TBlockType.btUnkown then begin case BlockType of btText: Line := 'Text'; btTable: Line := 'Table'; btPicture: Line := 'Picture'; btRuler: Line := 'Ruler'; btBarcode: Line := 'Barcode'; end; Line := StringOfChar(' ', Indent) + 'Block type: ' + Line; if Confidence > 0 then Line := Format('%s confidence %3.1f%%', [Line, Confidence * 100]); s.Add(Line); end; TextProperty.AddStrings(s, Indent); BoundingBox.AddStrings(s, Indent); for c := 0 to Length(Paragraphs) - 1 do begin s.Add(Format('%sParagraph %d of %d: %s', [StringOfChar(' ', Indent), c + 1, Length(Paragraphs), Paragraphs[c].AsStr])); Paragraphs[c].AddStrings(s, Indent + 2); end; end; function TBlock.GetText(MinConfidence: double): string; var c: integer; sl: TStringList; s: string; begin sl := TStringList.Create; try for c := 0 to length(Paragraphs) - 1 do begin s := Paragraphs[c].GetText(MinConfidence); if not s.IsEmpty then sl.Add(s); end; result := trim(sl.Text); finally sl.Free; end; end; { TParagraph } procedure TParagraph.Init; begin TextProperty.Init; BoundingBox.Init; SetLength(Words, 0); Confidence := 0; end; procedure TParagraph.SetFromJSON(Paragraph: TJSONObject); var Item: TJSONObject; Arr: TJSONArray; c: integer; begin if Paragraph.TryGetValue<TJSONObject>('property', Item) then TextProperty.SetFromJSON(Item) else TextProperty.Init; if Paragraph.TryGetValue<TJSONObject>('boundingBox', Item) then BoundingBox.SetFromJSON(Item) else BoundingBox.Init; if Paragraph.TryGetValue<TJSONArray>('words', Arr) then begin SetLength(Words, Arr.Count); for c := 0 to Arr.Count - 1 do Words[c].SetFromJSON(Arr.Items[c] as TJSONObject); end; if not Paragraph.TryGetValue<double>('confidence', Confidence) then Confidence := 0; end; procedure TParagraph.AddStrings(s: TStrings; Indent: integer); var c: integer; begin BoundingBox.AddStrings(s, Indent); for c := 0 to Length(Words) - 1 do begin s.Add(Format('%sWord %d of %d: %s', [StringOfChar(' ', Indent), c + 1, Length(Words), Words[c].AsStr])); Words[c].AddStrings(s, Indent + 2); end; end; function TParagraph.AsStr: string; var c: integer; begin result := '"'; for c := 0 to Length(Words) - 1 do result := result + Words[c].AsStr(true) + ' '; result := trim(result) + '"'; if Confidence > 0 then result := result + Format(', %3.1f%% confidence', [Confidence * 100]); result := result + TextProperty.AsStr; end; function TParagraph.GetText(MinConfidence: double): string; var c: integer; s: string; begin if (Confidence = 0) or (Confidence > MinConfidence) then begin result := ''; for c := 0 to length(Words) - 1 do begin s := Words[c].AsStr(true); if not s.IsEmpty then begin if not result.IsEmpty and not result.EndsWith(' ') then result := result + ' ' + s else result := result + s; end; end; end else result := ''; end; { TWord } procedure TWord.Init; begin TextProperty.Init; BoundingBox.Init; SetLength(Symbols, 0); Confidence := 0; end; procedure TWord.SetFromJSON(Word: TJSONObject); var Item: TJSONObject; Arr: TJSONArray; c: integer; begin if Word.TryGetValue<TJSONObject>('property', Item) then TextProperty.SetFromJSON(Item) else TextProperty.Init; if Word.TryGetValue<TJSONObject>('boundingBox', Item) then BoundingBox.SetFromJSON(Item) else BoundingBox.Init; if Word.TryGetValue<TJSONArray>('symbols', Arr) then begin SetLength(Symbols, Arr.Count); for c := 0 to Arr.Count - 1 do Symbols[c].SetFromJSON(Arr.Items[c] as TJSONObject); end; if not Word.TryGetValue<double>('confidence', Confidence) then Confidence := 0; end; procedure TWord.AddStrings(s: TStrings; Indent: integer); var c: integer; begin BoundingBox.AddStrings(s, Indent); for c := 0 to Length(Symbols) - 1 do begin s.Add(Format('%sSymbols %d of %d: %s', [StringOfChar(' ', Indent), c + 1, Length(Symbols), Symbols[c].AsStr])); Symbols[c].AddStrings(s, Indent + 2); end; end; function TWord.AsStr(Short: boolean): string; var c: integer; begin result := ''; for c := 0 to Length(Symbols) - 1 do result := result + Symbols[c].AsStr(true); if not Short then begin result := '"' + result + '"'; if Confidence > 0 then result := result + Format(', confidence %3.1f%%', [Confidence * 100]); if not TextProperty.AsStr.IsEmpty then result := result + ', ' + TextProperty.AsStr; end; end; { TSymbols } procedure TSymbols.Init; begin TextProperty.Init; BoundingBox.Init; Text := ''; Confidence := 0; end; procedure TSymbols.SetFromJSON(Symbol: TJSONObject); var Item: TJSONObject; begin if Symbol.TryGetValue<TJSONObject>('property', Item) then TextProperty.SetFromJSON(Item) else TextProperty.Init; if Symbol.TryGetValue<TJSONObject>('boundingBox', Item) then BoundingBox.SetFromJSON(Item) else BoundingBox.Init; if not Symbol.TryGetValue<string>('text', Text) then Text := ''; if not Symbol.TryGetValue<double>('confidence', Confidence) then Confidence := 0; end; procedure TSymbols.AddStrings(s: TStrings; Indent: integer); begin BoundingBox.AddStrings(s, Indent); end; function TSymbols.AsStr(Short: boolean): string; begin if Short then result := Text else begin result := '"' + Text + '" '; if Confidence > 0 then result := result + Format(', %3.1f%% confidence', [Confidence * 100]); result := result + ' ' + TextProperty.AsStr; end; end; { TBoundingPoly } procedure TBoundingPoly.Init; begin SetLength(Vertices, 0); SetLength(NormalizedVertices, 0); end; procedure TBoundingPoly.SetFromJSON(BoundingPoly: TJSONObject); var Arr: TJSONArray; c: integer; begin if BoundingPoly.TryGetValue<TJSONArray>('vertices', Arr) then begin SetLength(Vertices, Arr.Count); for c := 0 to Arr.Count - 1 do Vertices[c].SetFromJSON(Arr.Items[c] as TJSONObject); end; if BoundingPoly.TryGetValue<TJSONArray>('normalizedVertices', Arr) then begin SetLength(NormalizedVertices, Arr.Count); for c := 0 to Arr.Count - 1 do NormalizedVertices[c].SetFromJSON(Arr.Items[c] as TJSONObject); end; end; procedure TBoundingPoly.AddStrings(s: TStrings; Indent: integer); var c: integer; Ind, Line: string; begin Ind := StringOfChar(' ', Indent); Line := ''; for c := 0 to length(Vertices) - 1 do Line := Line + Vertices[c].AsStr; if not Line.IsEmpty then s.Add(Ind + 'Vertices: ' + Line) else begin Line := ''; for c := 0 to length(NormalizedVertices) - 1 do Line := Line + NormalizedVertices[c].AsStr; if not Line.IsEmpty then s.Add(Ind + 'Normalized Vertices: ' + Line); end; end; { TVertex } procedure TVertex.Init; begin x := 0; y := 0; end; procedure TVertex.SetFromJSON(Vertex: TJSONObject); begin if not Vertex.TryGetValue<integer>('x', x) then x := 0; if not Vertex.TryGetValue<integer>('y', y) then y := 0; end; function TVertex.AsStr: string; begin result := '['; if x > 0 then result := result + 'x: ' + IntToStr(x); if y > 0 then begin if not result.EndsWith('[') then result := result + ','; result := result + 'y: ' + IntToStr(y); end; result := result + ']'; end; { TNormalizedVertex } procedure TNormalizedVertex.Init; begin x := 0; y := 0; end; procedure TNormalizedVertex.SetFromJSON(Vertex: TJSONObject); begin if not Vertex.TryGetValue<double>('x', x) then x := 0; if not Vertex.TryGetValue<double>('y', y) then y := 0; end; function TNormalizedVertex.AsStr: string; begin result := '['; if x > 0 then result := result + 'x: ' + FloatToStr(x); if y > 0 then begin if not result.EndsWith('[') then result := result + ','; result := result + 'y: ' + FloatToStr(y); end; result := result + ']'; end; { TLocationInfo } procedure TLocationInfo.Init; begin Latitude := 0; Longitude := 0; end; procedure TLocationInfo.SetFromJSON(Item: TJSONObject); var O: TJSONObject; begin if Item.TryGetValue<TJSONObject>('latLng', O) then begin if not O.TryGetValue<extended>('latitude', Latitude) then Latitude := 0; if not O.TryGetValue<extended>('longitude', Longitude) then Longitude := 0; end else Init; end; procedure TLocationInfo.AddStrings(s: TStrings; Indent: integer); begin s.Add(Format('%sLocation latitude %9.6f longitude %9.6f', [StringOfChar(' ', Indent), Latitude, Longitude])); end; { TProperty } procedure TProperty.Init; begin Name := ''; Value := ''; uInt64Value := 0; end; procedure TProperty.SetFromJSON(Item: TJSONObject); var Val: string; begin if not Item.TryGetValue<string>('name', Name) then Name := ''; if not Item.TryGetValue<string>('value', Value) then Value := ''; if Item.TryGetValue<string>('uint64Value', Val) then uInt64Value := StrToInt64Def(Val, 0) else uInt64Value := 0; end; procedure TProperty.AddStrings(s: TStrings; Indent: integer); var Val: string; begin if not Value.IsEmpty then begin Val := '"' + Value + '"'; if uInt64Value > 0 then Val := Val + ' (' + IntToStr(uInt64Value) + ')'; end else Val := IntToStr(uInt64Value); s.Add(Format('%sProperty "%s"=%s', [StringOfChar(' ', Indent), Name, Val])); end; { TErrorStatus } procedure TErrorStatus.Init; begin ErrorFound := false; ErrorCode := 0; ErrorMessage := ''; SetLength(Details, 0); end; procedure TErrorStatus.SetFromJSON(Item: TJSONObject); var A: TJSONArray; c: integer; begin ErrorFound := assigned(Item); if not ErrorFound then Init else begin if not Item.TryGetValue<integer>('code', ErrorCode) then ErrorCode := 0; if not Item.TryGetValue<string>('message', ErrorMessage) then ErrorMessage := ''; if Item.TryGetValue<TJSONArray>('details', A) then begin SetLength(Details, A.Count); for c := 0 to A.Count - 1 do Details[c] := A.Items[c].Value; end else SetLength(Details, 0); end; end; function TErrorStatus.AsStr: string; begin if ErrorFound then result := Format('Error "%s" (%d)', [ErrorMessage, ErrorCode]) else result := ''; end; { TLikelihood } function ConvertLikelihood(const s: string): TLikelihood; begin if SameText(s, 'VERY_UNLIKELY') then result := TLikelihood.lhVeryUnlikely else if SameText(s, 'UNLIKELY') then result := TLikelihood.lhUnlikely else if SameText(s, 'POSSIBLE') then result := TLikelihood.lhPossible else if SameText(s, 'LIKELY') then result := TLikelihood.lhLikely else if SameText(s, 'VERY_LIKELY') then result := TLikelihood.lhVeryLikely else result := TLikelihood.lhUnknown; end; function LikelihoodAsStr(l: TLikelihood): string; begin case l of lhVeryUnlikely: result := 'very unlikely'; lhUnlikely: result := 'unlikely'; lhPossible: result := 'possible'; lhLikely: result := 'likely'; lhVeryLikely: result := 'very likely'; else result := 'unknown likelihood'; end; end; { TColorInfo } procedure TColorInfo.Init; begin Red := 0; Green := 0; Blue := 0; Alpha := 1; Score := 0; PixelFraction := 0; end; procedure TColorInfo.SetFromJSON(Item: TJSONObject); var Col: TJSONObject; begin if Item.TryGetValue<TJSONObject>('color', Col) then begin if not Col.TryGetValue<integer>('red', Red) then Red := 0; if not Col.TryGetValue<integer>('green', Green) then Green := 0; if not Col.TryGetValue<integer>('blue', Blue) then Blue := 0; if not Col.TryGetValue<integer>('alpha', Alpha) then Alpha := 1; end else begin Red := 0; Green := 0; Blue := 0; Alpha := 0; end; if not Item.TryGetValue<double>('score', Score) then Score := 0; if not Item.TryGetValue<double>('pixelFraction', PixelFraction) then PixelFraction := 0; end; function TColorInfo.AsStr: string; begin result := Format('R%d G%d B%d A%d, score %3.1f%%, pixel fraction %3.1f%%', [Red, Green, Blue, Alpha, Score * 100, PixelFraction * 100]); end; { TImagePropertiesAnnotation } procedure TImagePropertiesAnnotation.Init; begin SetLength(DominantColors, 0); end; procedure TImagePropertiesAnnotation.SetFromJSON(Item: TJSONObject); var O: TJSONObject; A: TJSONArray; c: integer; begin Init; if Item.TryGetValue<TJSONObject>('dominantColors', O) and O.TryGetValue<TJSONArray>('colors', A) then begin SetLength(DominantColors, A.Count); for c := 0 to A.Count - 1 do DominantColors[c].SetFromJSON(A.Items[c] as TJSONObject); end; end; procedure TImagePropertiesAnnotation.AddStrings(s: TStrings; Indent: integer); var Ind: string; c: integer; begin Ind := StringOfChar(' ', Indent); if length(DominantColors) = 0 then s.Add(Ind + 'No dominante colors') else for c := 0 to length(DominantColors) - 1 do s.Add(Format('%sDominant color %d of %d: %s', [Ind, c + 1, length(DominantColors), DominantColors[c].AsStr])); end; { TCropHint } procedure TCropHint.Init; begin BoundingPoly.Init; Confidence := 0; ImportanceFraction := 0; end; procedure TCropHint.SetFromJSON(Item: TJSONObject); var O: TJSONObject; begin if Item.TryGetValue<TJSONObject>('boundingPoly', O) then BoundingPoly.SetFromJSON(O) else BoundingPoly.Init; if not Item.TryGetValue<double>('confidence', Confidence) then Confidence := 0; if not Item.TryGetValue<double>('importanceFraction', ImportanceFraction) then ImportanceFraction := 0; end; procedure TCropHint.AddStrings(s: TStrings; Indent: integer); var Ind: string; begin BoundingPoly.AddStrings(s, Indent); Ind := StringOfChar(' ', Indent); s.Add(Format('%sConfidence %3.1f%%, importance Fraction %3.1f%%', [Ind, Confidence * 100, ImportanceFraction * 100])); end; { TCropHintsAnnotation } procedure TCropHintsAnnotation.Init; begin SetLength(CropHints, 0); end; procedure TCropHintsAnnotation.SetFromJSON(Item: TJSONObject); var A: TJSONArray; c: integer; begin Init; if Item.TryGetValue<TJSONArray>('cropHints', A) then begin SetLength(CropHints, A.Count); for c := 0 to A.Count - 1 do CropHints[c].SetFromJSON(A.Items[c] as TJSONObject); end; end; procedure TCropHintsAnnotation.AddStrings(s: TStrings; Indent: integer); var Ind: string; c: integer; begin Ind := StringOfChar(' ', Indent); if length(CropHints) = 0 then s.Add(Ind + 'No crop hints') else begin for c := 0 to length(CropHints) - 1 do begin s.Add(Format('%sCrop hints %d of %d', [Ind, c + 1, length(CropHints)])); CropHints[c].AddStrings(s, Indent + 2); end; end; end; { TWebEntity } procedure TWebEntity.Init; begin EntityId := ''; Description := ''; Score := 0; end; procedure TWebEntity.SetFromJSON(Item: TJSONObject); begin if not Item.TryGetValue<string>('entityId', EntityId) then EntityId := ''; if not Item.TryGetValue<double>('score', Score) then Score := 0; if not Item.TryGetValue<string>('description', Description) then Description := ''; end; function TWebEntity.AsStr: string; begin if Score > 0 then result := Format('"%s" (Id %s) %3.1f%% score', [Description, EntityId, Score * 100]) else result := Format('"%s" (Id %s)', [Description, EntityId]); end; { TWebImage } procedure TWebImage.Init; begin URL := ''; Score := 0; end; procedure TWebImage.SetFromJSON(Item: TJSONObject); begin if not Item.TryGetValue<string>('url', URL) then URL := ''; if not Item.TryGetValue<double>('score', Score) then Score := 0; end; function TWebImage.AsStr: string; begin if URL.IsEmpty then result := 'No URL found' else if Score > 0 then result := Format('URL: %s score %3.1f%%', [URL, Score * 100]) else result := Format('URL: %s', [URL]); end; { TWebPage } procedure TWebPage.Init; begin URL := ''; Score := 0; PageTitle := ''; SetLength(FullMatchingImages, 0); SetLength(PartialMatchingImages, 0); end; procedure TWebPage.SetFromJSON(Item: TJSONObject); var A: TJSONArray; c: integer; begin if not Item.TryGetValue<string>('url', URL) then URL := ''; if not Item.TryGetValue<double>('score', Score) then Score := 0; if not Item.TryGetValue<string>('pageTitle', PageTitle) then PageTitle := ''; if Item.TryGetValue<TJSONArray>('fullMatchingImages', A) then begin SetLength(FullMatchingImages, A.Count); for c := 0 to A.Count - 1 do FullMatchingImages[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(FullMatchingImages, 0); if Item.TryGetValue<TJSONArray>('partialMatchingImages', A) then begin SetLength(PartialMatchingImages, A.Count); for c := 0 to A.Count - 1 do PartialMatchingImages[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(PartialMatchingImages, 0); end; procedure TWebPage.AddStrings(s: TStrings; Indent: integer); var Ind: string; c: integer; begin Ind := StringOfChar(' ', Indent); s.Add(Format('%s"%s" URL: %s score %3.1f%%', [Ind, PageTitle, URL, Score * 100])); for c := 0 to length(FullMatchingImages) - 1 do s.Add(Format('%sFull matching image %d of %d: %s', [Ind, c + 1, length(FullMatchingImages), FullMatchingImages[c].AsStr])); for c := 0 to length(PartialMatchingImages) - 1 do s.Add(Format('%sPartial matching image %d of %d: %s', [Ind, c + 1, length(PartialMatchingImages), PartialMatchingImages[c].AsStr])); end; { TWebLabel } procedure TWebLabel.Init; begin LabelText := ''; LanguageCode := ''; end; procedure TWebLabel.SetFromJSON(Item: TJSONObject); begin if not Item.TryGetValue<string>('label', LabelText) then LabelText := ''; if not Item.TryGetValue<string>('languageCode', LanguageCode) then LanguageCode := ''; end; function TWebLabel.AsStr: string; begin if LabelText.IsEmpty then result := 'No label found' else if LanguageCode.IsEmpty then result := '"' + LabelText + '"' else result := Format('"%s" language %s', [LabelText, TFirebaseHelpers.GetLanguageInEnglishFromCode(LanguageCode)]); end; { TWebDetection } procedure TWebDetection.Init; begin SetLength(WebEntities, 0); SetLength(FullMatchingImages, 0); SetLength(PartialMatchingImages, 0); SetLength(PagesWithMatchingImages, 0); SetLength(VisuallySimilarImages, 0); SetLength(BestGuessLabels, 0); end; procedure TWebDetection.SetFromJSON(Item: TJSONObject); var A: TJSONArray; c: integer; begin if Item.TryGetValue<TJSONArray>('webEntities', A) then begin SetLength(WebEntities, A.Count); for c := 0 to A.Count - 1 do WebEntities[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(WebEntities, 0); if Item.TryGetValue<TJSONArray>('fullMatchingImages', A) then begin SetLength(FullMatchingImages, A.Count); for c := 0 to A.Count - 1 do FullMatchingImages[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(FullMatchingImages, 0); if Item.TryGetValue<TJSONArray>('partialMatchingImages', A) then begin SetLength(PartialMatchingImages, A.Count); for c := 0 to A.Count - 1 do PartialMatchingImages[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(PartialMatchingImages, 0); if Item.TryGetValue<TJSONArray>('visuallySimilarImages', A) then begin SetLength(VisuallySimilarImages, A.Count); for c := 0 to A.Count - 1 do VisuallySimilarImages[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(VisuallySimilarImages, 0); if Item.TryGetValue<TJSONArray>('bestGuessLabels', A) then begin SetLength(BestGuessLabels, A.Count); for c := 0 to A.Count - 1 do BestGuessLabels[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(BestGuessLabels, 0); end; procedure TWebDetection.AddStrings(s: TStrings; Indent: integer); var Ind: string; c: integer; begin Ind := StringOfChar(' ', Indent); if length(WebEntities) = 0 then s.Add(Ind + 'No web entities found') else for c := 0 to length(WebEntities) - 1 do s.Add(Format('%sFull matching image %d of %d: %s', [Ind, c + 1, length(WebEntities), WebEntities[c].AsStr])); for c := 0 to length(FullMatchingImages) - 1 do s.Add(Format('%sFull matching image %d of %d: %s', [Ind, c + 1, length(FullMatchingImages), FullMatchingImages[c].AsStr])); for c := 0 to length(PartialMatchingImages) - 1 do s.Add(Format('%sPartial matching image %d of %d: %s', [Ind, c + 1, length(PartialMatchingImages), PartialMatchingImages[c].AsStr])); for c := 0 to length(VisuallySimilarImages) - 1 do s.Add(Format('%sVisually similar image %d of %d: %s', [Ind, c + 1, length(VisuallySimilarImages), VisuallySimilarImages[c].AsStr])); for c := 0 to length(BestGuessLabels) - 1 do s.Add(Format('%sBest guess labels %d of %d: %s', [Ind, c + 1, length(BestGuessLabels), BestGuessLabels[c].AsStr])); end; { TSafeSearchAnnotation } procedure TSafeSearchAnnotation.Init; begin AdultContent := TLikelihood.lhUnknown; Spoof := TLikelihood.lhUnknown; MedicalImage := TLikelihood.lhUnknown; ViolentContent := TLikelihood.lhUnknown; RacyContent := TLikelihood.lhUnknown; end; procedure TSafeSearchAnnotation.SetFromJSON(Item: TJSONObject); var s: string; begin if Item.TryGetValue<string>('adult', s) then AdultContent := ConvertLikelihood(s) else AdultContent := TLikelihood.lhUnknown; if Item.TryGetValue<string>('spoof', s) then Spoof := ConvertLikelihood(s) else Spoof := TLikelihood.lhUnknown; if Item.TryGetValue<string>('medical', s) then MedicalImage := ConvertLikelihood(s) else MedicalImage := TLikelihood.lhUnknown; if Item.TryGetValue<string>('violence', s) then ViolentContent := ConvertLikelihood(s) else ViolentContent := TLikelihood.lhUnknown; if Item.TryGetValue<string>('racy', s) then RacyContent := ConvertLikelihood(s) else RacyContent := TLikelihood.lhUnknown; end; procedure TSafeSearchAnnotation.AddStrings(s: TStrings; Indent: integer); var Ind: string; begin Ind := StringOfChar(' ', Indent); s.Add(Format('%sLikelihood for adult content: %s', [Ind, LikelihoodAsStr(AdultContent)])); s.Add(Format('%sLikelihood for spoofed (fake) content: %s', [Ind, LikelihoodAsStr(Spoof)])); s.Add(Format('%sLikelihood for medical image: %s', [Ind, LikelihoodAsStr(MedicalImage)])); s.Add(Format('%sLikelihood for violent content: %s', [Ind, LikelihoodAsStr(ViolentContent)])); s.Add(Format('%sLikelihood for racy content: %s', [Ind, LikelihoodAsStr(RacyContent)])); end; { TFacePosition } procedure TFacePosition.Init; begin x := 0; y := 0; z := 0; end; procedure TFacePosition.SetFromJSON(Item: TJSONObject); begin if not Item.TryGetValue<double>('x', x) then x := 0; if not Item.TryGetValue<double>('y', y) then y := 0; if not Item.TryGetValue<double>('z', z) then z := 0; end; function TFacePosition.AsStr: string; begin result := '['; if x > 0 then result := result + 'x: ' + FloatToStr(x); if y > 0 then begin if not result.EndsWith('[') then result := result + ','; result := result + 'y: ' + FloatToStr(y); end; if z > 0 then begin if not result.EndsWith('[') then result := result + ','; result := result + 'z: ' + FloatToStr(z); end; result := result + ']'; end; { TFaceLandmark } procedure TFaceLandmark.Init; begin FaceLandmarkType := TFaceLandmarkType.flmUnkown; Position.Init; end; procedure TFaceLandmark.SetFromJSON(Item: TJSONObject); var s: string; O: TJSONObject; begin if Item.TryGetValue<string>('type', s) then begin if SameText(s, 'LEFT_EYE') then FaceLandmarkType := TFaceLandmarkType.flmLeftEye else if SameText(s, 'RIGHT_EYE') then FaceLandmarkType := TFaceLandmarkType.flmRightEye else if SameText(s, 'LEFT_OF_LEFT_EYEBROW') then FaceLandmarkType := TFaceLandmarkType.flmLeftOfLeftEyeBrow else if SameText(s, 'RIGHT_OF_LEFT_EYEBROW') then FaceLandmarkType := TFaceLandmarkType.flmRightOfLeftEyeBrow else if SameText(s, 'LEFT_OF_RIGHT_EYEBROW') then FaceLandmarkType := TFaceLandmarkType.flmLeftOfRightEyeBrow else if SameText(s, 'RIGHT_OF_RIGHT_EYEBROW') then FaceLandmarkType := TFaceLandmarkType.flmRightOfRightEyeBrow else if SameText(s, 'MIDPOINT_BETWEEN_EYES') then FaceLandmarkType := TFaceLandmarkType.flmMidpointBetweenEyes else if SameText(s, 'NOSE_TIP') then FaceLandmarkType := TFaceLandmarkType.flmNoseTip else if SameText(s, 'UPPER_LIP') then FaceLandmarkType := TFaceLandmarkType.flmUpperLip else if SameText(s, 'LOWER_LIP') then FaceLandmarkType := TFaceLandmarkType.flmLowerLip else if SameText(s, 'MOUTH_LEFT') then FaceLandmarkType := TFaceLandmarkType.flmMouthLeft else if SameText(s, 'MOUTH_RIGHT') then FaceLandmarkType := TFaceLandmarkType.flmMouthRight else if SameText(s, 'MOUTH_CENTER') then FaceLandmarkType := TFaceLandmarkType.flmMouthCenter else if SameText(s, 'NOSE_BOTTOM_RIGHT') then FaceLandmarkType := TFaceLandmarkType.flmNoseBottomRight else if SameText(s, 'NOSE_BOTTOM_LEFT') then FaceLandmarkType := TFaceLandmarkType.flmNoseBottomLeft else if SameText(s, 'NOSE_BOTTOM_CENTER') then FaceLandmarkType := TFaceLandmarkType.flmNoseBottomCenter else if SameText(s, 'LEFT_EYE_TOP_BOUNDARY') then FaceLandmarkType := TFaceLandmarkType.flmLeftEyeTopBoundary else if SameText(s, 'LEFT_EYE_RIGHT_CORNER') then FaceLandmarkType := TFaceLandmarkType.flmLeftEyeRightCorner else if SameText(s, 'LEFT_EYE_BOTTOM_BOUNDARY') then FaceLandmarkType := TFaceLandmarkType.flmLeftEyeBottomBoundary else if SameText(s, 'LEFT_EYE_LEFT_CORNER') then FaceLandmarkType := TFaceLandmarkType.flmLeftEyeLeftCorner else if SameText(s, 'RIGHT_EYE_TOP_BOUNDARY') then FaceLandmarkType := TFaceLandmarkType.flmRightEyeTopBoundary else if SameText(s, 'RIGHT_EYE_RIGHT_CORNER') then FaceLandmarkType := TFaceLandmarkType.flmRightEyeRightCorner else if SameText(s, 'RIGHT_EYE_BOTTOM_BOUNDARY') then FaceLandmarkType := TFaceLandmarkType.flmRightEyeBottomBoundary else if SameText(s, 'RIGHT_EYE_LEFT_CORNER') then FaceLandmarkType := TFaceLandmarkType.flmRightEyeLeftCorner else if SameText(s, 'LEFT_EYEBROW_UPPER_MIDPOINT') then FaceLandmarkType := TFaceLandmarkType.flmLeftEyebrowUpperMidpoint else if SameText(s, 'RIGHT_EYEBROW_UPPER_MIDPOINT') then FaceLandmarkType := TFaceLandmarkType.flmRightEyebrowUpperMidpoint else if SameText(s, 'LEFT_EAR_TRAGION') then FaceLandmarkType := TFaceLandmarkType.flmLeftEarTragion else if SameText(s, 'RIGHT_EAR_TRAGION') then FaceLandmarkType := TFaceLandmarkType.flmRightEarTragion else if SameText(s, 'LEFT_EYE_PUPIL') then FaceLandmarkType := TFaceLandmarkType.flmLeftEyePupil else if SameText(s, 'RIGHT_EYE_PUPIL') then FaceLandmarkType := TFaceLandmarkType.flmRightEyePupil else if SameText(s, 'FOREHEAD_GLABELLA') then FaceLandmarkType := TFaceLandmarkType.flmForeheadGlabella else if SameText(s, 'CHIN_GNATHION') then FaceLandmarkType := TFaceLandmarkType.flmChinGnathion else if SameText(s, 'CHIN_LEFT_GONION') then FaceLandmarkType := TFaceLandmarkType.flmChinLeftGonion else if SameText(s, 'CHIN_RIGHT_GONION') then FaceLandmarkType := TFaceLandmarkType.flmChinRightGonion else if SameText(s, 'LEFT_CHEEK_CENTER') then FaceLandmarkType := TFaceLandmarkType.flmLeftCheekCenter else if SameText(s, 'RIGHT_CHEEK_CENTER') then FaceLandmarkType := TFaceLandmarkType.flmRightCheekCenter else FaceLandmarkType := TFaceLandmarkType.flmUnkown; end else FaceLandmarkType := TFaceLandmarkType.flmUnkown; if Item.TryGetValue<TJSONObject>('position', O) then Position.SetFromJSON(O) else Position.Init; end; procedure TFaceLandmark.AddStrings(s: TStrings; Indent: integer); var FacePart: string; Ind: string; begin Ind := StringOfChar(' ', Indent); FacePart := GetEnumName(TypeInfo(TFaceLandmarkType), ord(FaceLandmarkType)). Substring(3); s.Add(Format('%sFace landmark %s at %s', [Ind, FacePart, Position.AsStr])); end; { TFaceAnnotation } procedure TFaceAnnotation.Init; begin BoundingPoly.Init; FaceDetectionBP.Init; SetLength(FaceLandmarks, 0); RollAngle := 0; PanAngle := 0; TiltAngle := 0; DetectionConfidence := 0; LandmarkingConfidence := 0; JoyLikelihood := TLikelihood.lhUnknown; SorrowLikelihood := TLikelihood.lhUnknown; AngerLikelihood := TLikelihood.lhUnknown; SurpriseLikelihood := TLikelihood.lhUnknown; UnderExposedLikelihood := TLikelihood.lhUnknown; BlurredLikelihood := TLikelihood.lhUnknown; HeadwearLikelihood := TLikelihood.lhUnknown; end; procedure TFaceAnnotation.SetFromJSON(Item: TJSONObject); var s: string; O: TJSONObject; A: TJSONArray; c: integer; begin if Item.TryGetValue<TJSONObject>('boundingPoly', O) then BoundingPoly.SetFromJSON(O) else BoundingPoly.Init; if Item.TryGetValue<TJSONObject>('fdBoundingPoly', O) then FaceDetectionBP.SetFromJSON(O) else FaceDetectionBP.Init; if Item.TryGetValue<TJSONArray>('landmarks', A) then begin SetLength(FaceLandmarks, A.Count); for c := 0 to A.Count - 1 do FaceLandmarks[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(FaceLandmarks, 0); if not Item.TryGetValue<double>('rollAngle', RollAngle) then RollAngle := 0; if not Item.TryGetValue<double>('panAngle', PanAngle) then PanAngle := 0; if not Item.TryGetValue<double>('tiltAngle', TiltAngle) then TiltAngle := 0; if not Item.TryGetValue<double>('detectionConfidence', DetectionConfidence) then DetectionConfidence := 0; if not Item.TryGetValue<double>('landmarkingConfidence', LandmarkingConfidence) then LandmarkingConfidence := 0; if Item.TryGetValue<string>('joyLikelihood', s) then JoyLikelihood := ConvertLikelihood(s) else JoyLikelihood := TLikelihood.lhUnknown; if Item.TryGetValue<string>('sorrowLikelihood', s) then SorrowLikelihood := ConvertLikelihood(s) else SorrowLikelihood := TLikelihood.lhUnknown; if Item.TryGetValue<string>('angerLikelihood', s) then AngerLikelihood := ConvertLikelihood(s) else AngerLikelihood := TLikelihood.lhUnknown; if Item.TryGetValue<string>('surpriseLikelihood', s) then SurpriseLikelihood := ConvertLikelihood(s) else SurpriseLikelihood := TLikelihood.lhUnknown; if Item.TryGetValue<string>('underExposedLikelihood', s) then UnderExposedLikelihood := ConvertLikelihood(s) else UnderExposedLikelihood := TLikelihood.lhUnknown; if Item.TryGetValue<string>('blurredLikelihood', s) then BlurredLikelihood := ConvertLikelihood(s) else BlurredLikelihood := TLikelihood.lhUnknown; if Item.TryGetValue<string>('headwearLikelihood', s) then HeadwearLikelihood := ConvertLikelihood(s) else HeadwearLikelihood := TLikelihood.lhUnknown; end; procedure TFaceAnnotation.AddStrings(s: TStrings; Indent: integer); var Ind: string; c: integer; begin Ind := StringOfChar(' ', Indent); s.Add(Format('%sFace detection confidence %3.1f%%', [Ind, DetectionConfidence * 100])); s.Add(Format('%sFace angles roll %d° pan/yaw %d° tilt/pitch %d°', [Ind, round(RollAngle), round(PanAngle), round(TiltAngle)])); BoundingPoly.AddStrings(s, Indent + 2); FaceDetectionBP.AddStrings(s, Indent + 2); s.Add(Format('%sLandmarking confidence %3.1f%%', [Ind, LandmarkingConfidence * 100])); for c := 0 to length(FaceLandmarks) - 1 do FaceLandmarks[c].AddStrings(s, Indent + 2); s.Add(Format('%sEmotions: joy %s, sorrow %s, anger %s, surprise %s', [Ind, LikelihoodAsStr(JoyLikelihood), LikelihoodAsStr(SorrowLikelihood), LikelihoodAsStr(AngerLikelihood), LikelihoodAsStr(SurpriseLikelihood) ])); s.Add(Format( '%sFace detection details: under exposed %s, blurred %s, head wear %s', [Ind, LikelihoodAsStr(UnderExposedLikelihood), LikelihoodAsStr(BlurredLikelihood), LikelihoodAsStr(HeadwearLikelihood)])); end; { TLocalizedObjectAnnotation } procedure TLocalizedObjectAnnotation.Init; begin Id := ''; LanguageCode := ''; Name := ''; Score := 0; BoundingPoly.Init; end; procedure TLocalizedObjectAnnotation.SetFromJSON(Item: TJSONObject); var O: TJSONObject; begin if not Item.TryGetValue<string>('mid', Id) then Id := ''; if not Item.TryGetValue<string>('languageCode', LanguageCode) then LanguageCode := ''; if not Item.TryGetValue<string>('name', Name) then Name := ''; if not Item.TryGetValue<double>('score', Score) then Score := 0; if Item.TryGetValue<TJSONObject>('boundingPoly', O) then BoundingPoly.SetFromJSON(O) else BoundingPoly.Init; end; procedure TLocalizedObjectAnnotation.AddStrings(s: TStrings; Indent: integer); var v: string; begin v := StringOfChar(' ', Indent) + '"' + Name + '"'; if not LanguageCode.IsEmpty then v := v + ' language ' + TFirebaseHelpers.GetLanguageInEnglishFromCode(LanguageCode); if Score > 0 then v := Format('%s score %3.1f%%', [v, Score * 100]); if not Id.IsEmpty then v := Format('%s (mid: %s)', [v,Id]); s.Add(v); BoundingPoly.AddStrings(s, Indent + 2); end; { TKeyValue } procedure TKeyValue.Init; begin Key := ''; Value := ''; end; procedure TKeyValue.SetFromJSON(Item: TJSONObject); begin if not Item.TryGetValue<string>('key', Key) then Key := ''; if not Item.TryGetValue<string>('mid', Value) then Value := ''; end; function TKeyValue.AsStr: string; begin result := '"' + Key + '"= ' + Value; end; { TProduct } procedure TProduct.Init; begin Name := ''; DisplayName := ''; Description := ''; ProductCategory := ''; SetLength(ProductLabels, 0); end; procedure TProduct.SetFromJSON(Item: TJSONObject); var A: TJSONArray; c: integer; begin if not Item.TryGetValue<string>('name', Name) then Name := ''; if not Item.TryGetValue<string>('displayName', DisplayName) then DisplayName := ''; if not Item.TryGetValue<string>('description', Description) then Description := ''; if not Item.TryGetValue<string>('productCategory', ProductCategory) then ProductCategory := ''; if Item.TryGetValue<TJSONArray>('productLabels', A) then begin SetLength(ProductLabels, A.Count); for c := 0 to A.Count - 1 do ProductLabels[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(ProductLabels, 0); end; procedure TProduct.AddStrings(s: TStrings; Indent: integer); var Ind: string; c: integer; begin Ind := StringOfChar(' ', Indent); s.Add(Ind + 'Product "' + DisplayName + '"'); if not Name.IsEmpty then s.Add(Ind + 'Name: ' + Name); if not Description.IsEmpty then s.Add(Ind + 'Description: ' + Description); if not ProductCategory.IsEmpty then s.Add(Ind + 'Product category: ' + ProductCategory); for c := 0 to length(ProductLabels) - 1 do s.Add(Format('%sLabel %d of %d: %s', [Ind, c + 1, length(ProductLabels), ProductLabels[c].AsStr])); end; { TProductResult } procedure TProductResult.Init; begin Product.Init; Score := 0; Image := ''; end; procedure TProductResult.SetFromJSON(Item: TJSONObject); var O: TJSONObject; begin if Item.TryGetValue<TJSONObject>('product', O) then Product.SetFromJSON(O) else Product.Init; if not Item.TryGetValue<double>('score', Score) then Score := 0; if not Item.TryGetValue<string>('image', Image) then Image := ''; end; procedure TProductResult.AddStrings(s: TStrings; Indent: integer); var Ind: string; begin Ind := StringOfChar(' ', Indent); Product.AddStrings(s, Indent); if not Image.IsEmpty then s.Add(Format('%simage %s', [Ind, Image])); if Score > 0 then s.Add(Format('%sscore %3.1f%%', [Ind, Score * 100])); end; { TObjectAnnotation } procedure TObjectAnnotation.Init; begin Id := ''; LanguageCode := ''; Name := ''; Score := 0; end; procedure TObjectAnnotation.SetFromJSON(Item: TJSONObject); begin if not Item.TryGetValue<string>('mid', Id) then Id := ''; if not Item.TryGetValue<string>('languageCode', LanguageCode) then LanguageCode := ''; if not Item.TryGetValue<string>('name', Name) then Name := ''; if not Item.TryGetValue<double>('score', Score) then Score := 0; end; procedure TObjectAnnotation.AddStrings(s: TStrings; Indent: integer); var v: string; begin v := StringOfChar(' ', Indent) + '"' + Name + '"'; if not LanguageCode.IsEmpty then v := v + ' language ' + TFirebaseHelpers.GetLanguageInEnglishFromCode(LanguageCode); if Score > 0 then v := Format('%s score %3.1f%%', [v, Score * 100]); if not Id.IsEmpty then v := Format('%s (mid: %s)', [v,Id]); s.Add(v); end; { TGroupedProductResult } procedure TGroupedProductResult.Init; begin BoundingPoly.Init; SetLength(ProductResults, 0); SetLength(ObjectAnnotations, 0); end; procedure TGroupedProductResult.SetFromJSON(Item: TJSONObject); var O: TJSONObject; A: TJSONArray; c: integer; begin if Item.TryGetValue<TJSONObject>('boundingPoly', O) then BoundingPoly.SetFromJSON(O) else BoundingPoly.Init; if Item.TryGetValue<TJSONArray>('results', A) then begin SetLength(ProductResults, A.Count); for c := 0 to A.Count - 1 do ProductResults[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(ProductResults, 0); if Item.TryGetValue<TJSONArray>('objectAnnotations', A) then begin SetLength(ObjectAnnotations, A.Count); for c := 0 to A.Count - 1 do ObjectAnnotations[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(ObjectAnnotations, 0); end; procedure TGroupedProductResult.AddStrings(s: TStrings; Indent: integer); var c: integer; Ind: string; begin Ind := StringOfChar(' ', Indent); BoundingPoly.AddStrings(s, Indent); for c := 0 to length(ProductResults) - 1 do begin s.Add(Format('%sProduct %d of %d', [Ind, c + 1, length(ProductResults)])); ProductResults[c].AddStrings(s, Indent + 2); end; for c := 0 to length(ObjectAnnotations) - 1 do begin s.Add(Format('%sObject annotation %d of %d', [Ind, c + 1, length(ObjectAnnotations)])); ObjectAnnotations[c].AddStrings(s, Indent + 2); end; end; { TProductSearchAnnotation } procedure TProductSearchAnnotation.Init; begin IndexTime := 0; SetLength(ProductResults, 0); SetLength(GroupedProductResults, 0); end; procedure TProductSearchAnnotation.SetFromJSON(Item: TJSONObject); var s: string; A: TJSONArray; c: integer; begin if Item.TryGetValue<string>('indexTime', s) then IndexTime := TFirebaseHelpers.DecodeRFC3339DateTime(s) else IndexTime := 0; if Item.TryGetValue<TJSONArray>('results', A) then begin SetLength(ProductResults, A.Count); for c := 0 to A.Count - 1 do ProductResults[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(ProductResults, 0); if Item.TryGetValue<TJSONArray>('productGroupedResults', A) then begin SetLength(GroupedProductResults, A.Count); for c := 0 to A.Count - 1 do GroupedProductResults[c].SetFromJSON(A.Items[c] as TJSONObject); end else SetLength(GroupedProductResults, 0); end; procedure TProductSearchAnnotation.AddStrings(s: TStrings; Indent: integer); var c: integer; Ind: string; begin Ind := StringOfChar(' ', Indent); if (IndexTime = 0) and (length(ProductResults) = 0) and (length(GroupedProductResults) = 0) then s.Add(Ind + 'No products found') else begin if IndexTime > 0 then s.Add(Ind + 'Index time stamp ' + DateTimeToStr(IndexTime)); for c := 0 to length(ProductResults) - 1 do begin s.Add(Format('%sProduct %d of %d', [Ind, c + 1, length(ProductResults)])); ProductResults[c].AddStrings(s, Indent + 2); end; for c := 0 to length(GroupedProductResults) - 1 do begin s.Add(Format('%sGrouped product %d of %d', [Ind, c + 1, length(GroupedProductResults)])); GroupedProductResults[c].AddStrings(s, Indent + 2); end; end; end; { TImageAnnotationContext } procedure TImageAnnotationContext.Init; begin URI := ''; PageNumber := 0; end; procedure TImageAnnotationContext.SetFromJSON(Item: TJSONObject); begin if not Item.TryGetValue<string>('uri', URI) then URI := ''; PageNumber := Item.GetValue<integer>('pageNumber'); end; procedure TImageAnnotationContext.AddStrings(s: TStrings; Indent: integer); begin s.Add(StringOfChar(' ', Indent) + 'Page number: ' + PageNumber.ToString); if not URI.IsEmpty then s.Add(StringOfChar(' ', Indent) + 'URI: ' + URI); end; end.
(* * iocp 服务端各种套接字封装 *) unit iocp_sockets; interface {$I in_iocp.inc} // 模式设置 uses {$IFDEF DELPHI_XE7UP} Winapi.Windows, System.Classes, System.SysUtils, Datasnap.DBClient, Datasnap.Provider, System.Variants, System.DateUtils, {$ELSE} Windows, Classes, SysUtils, DBClient, Provider, Variants, DateUtils, {$ENDIF} iocp_base, iocp_zlib, iocp_api, iocp_Winsock2, iocp_wsExt, iocp_utils, iocp_baseObjs, iocp_objPools, iocp_senders, iocp_receivers, iocp_msgPacks, iocp_log, http_objects, iocp_WsJSON; type // ================== 基本套接字 类 ====================== TRawSocket = class(TObject) private FConnected: Boolean; // 是否连接 FErrorCode: Integer; // 异常代码 FPeerIP: AnsiString; // IP FPeerIPPort: AnsiString; // IP+Port FPeerPort: Integer; // Port FSocket: TSocket; // 套接字 procedure InternalClose; protected procedure IniSocket(AServer: TObject; ASocket: TSocket; AData: Pointer = nil); virtual; procedure SetPeerAddr(const Addr: PSockAddrIn); public constructor Create(AddSocket: Boolean); destructor Destroy; override; procedure Close; virtual; public property Connected: Boolean read FConnected; property ErrorCode: Integer read FErrorCode; property PeerIP: AnsiString read FPeerIP; property PeerPort: Integer read FPeerPort; property PeerIPPort: AnsiString read FPeerIPPort; property Socket: TSocket read FSocket; public class function GetPeerIP(const Addr: PSockAddrIn): AnsiString; end; // ================== 监听套接字 类 ====================== TListenSocket = class(TRawSocket) public function Bind(Port: Integer; const Addr: String = ''): Boolean; function StartListen: Boolean; end; // ================== AcceptEx 投放套接字 ====================== TAcceptSocket = class(TRawSocket) private FListenSocket: TSocket; // 监听套接字 FIOData: TPerIOData; // 内存块 FByteCount: Cardinal; // 投放用 public constructor Create(ListenSocket: TSocket); destructor Destroy; override; function AcceptEx: Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} procedure NewSocket; {$IFDEF USE_INLINE} inline; {$ENDIF} function SetOption: Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} end; // ================== 业务执行模块基类 ====================== TBaseSocket = class; TStreamSocket = class; TIOCPSocket = class; THttpSocket = class; TWebSocket = class; TBaseWorker = class(TObject) protected FServer: TObject; // TInIOCPServer 服务器 FGlobalLock: TThreadLock; // 全局锁 FThreadIdx: Integer; // 编号 protected procedure Execute(const ASocket: TIOCPSocket); virtual; abstract; procedure StreamExecute(const ASocket: TStreamSocket); virtual; abstract; procedure HttpExecute(const ASocket: THttpSocket); virtual; abstract; procedure WebSocketExecute(const ASocket: TWebSocket); virtual; abstract; public property GlobalLock: TThreadLock read FGlobalLock; // 可以在业务操时用 property ThreadIdx: Integer read FThreadIdx; end; // ================== Socket 基类 ====================== // FState 状态: // 1. 空闲 = 0,关闭 = 9 // 2. 占用 = 1,TransmitFile 时 +1,任何异常均 +1 // (正常值=1,2,其他值即为异常) // 3. 尝试关闭:空闲=0,TransmitFile=2(特殊的空闲),均可直接关闭 // 4. 加锁:空闲=0 -> 成功 TBaseSocket = class(TRawSocket) private FLinkNode: PLinkRec; // 对应客户端池的 PLinkRec,方便回收 FRecvBuf: PPerIOData; // 接收用的数据包 FSender: TBaseTaskSender; // 数据发送器(引用) FObjPool: TIOCPSocketPool; // 对象池 FServer: TObject; // TInIOCPServer 服务器 FWorker: TBaseWorker; // 业务执行者(引用) FRefCount: Integer; // 引用数 FState: Integer; // 状态(原子操作变量) FTickCount: Cardinal; // 客户端访问毫秒数 FUseTransObj: Boolean; // 使用 TTransmitObject 发送 FData: Pointer; // 额外的数据,由用户扩展 function CheckDelayed(ATickCount: Cardinal): Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} function GetActive: Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} function GetBufferPool: TIODataPool; {$IFDEF USE_INLINE} inline; {$ENDIF} function GetReference: Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} function GetSocketState: Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} procedure InternalRecv; procedure OnSendError(IOType: TIODataType; ErrorCode: Integer); protected FBackground: Boolean; // 后台执行状态 FByteCount: Cardinal; // 接收字节数 FLinkSocket: TBaseSocket; // 后台执行时关联的主程序对象 FCompleted: Boolean; // 接收完毕/触发业务 {$IFDEF TRANSMIT_FILE} // TransmitFile 发送模式 FTask: TTransmitObject; // 待发送数据描述 FTaskExists: Boolean; // 存在任务 procedure FreeTransmitRes; // 释放 TransmitFile 的资源 procedure InterTransmit; // 发送数据 procedure InterFreeRes; virtual; abstract; // 释放发送资源 {$ENDIF} procedure ClearResources; virtual; abstract; procedure Clone(Source: TBaseSocket); // 克隆(转移资源) procedure DoWork(AWorker: TBaseWorker; ASender: TBaseTaskSender); // 业务线程调用入口 procedure BackgroundExecute; virtual; // 后台执行 procedure ExecuteWork; virtual; abstract; // 调用入口 procedure IniSocket(AServer: TObject; ASocket: TSocket; AData: Pointer = nil); override; procedure InterCloseSocket(Sender: TObject); virtual; procedure InternalPush(AData: PPerIOData); // 推送入口 procedure MarkIODataBuf(AData: PPerIOData); virtual; procedure SocketError(IOType: TIODataType); virtual; // 保护以下方法,防止在应用层被误用 function CheckTimeOut(NowTickCount, TimeoutInteval: Cardinal): Boolean; // 超时检查 function Lock(PushMode: Boolean): Integer; // 工作前加锁 function GetObjectState(const Group: string; AdminType: Boolean): Boolean; virtual; // 取可推送状态 procedure CopyResources(AMaster: TBaseSocket); virtual; // 设后台资源 procedure PostRecv; virtual; // 投递接收 procedure PostEvent(IOKind: TIODataType); virtual; abstract; // 投放事件 procedure TryClose; // 尝试关闭 public constructor Create(AObjPool: TIOCPSocketPool; ALinkNode: PLinkRec); virtual; destructor Destroy; override; procedure Close; override; // 关闭 public property Active: Boolean read GetActive; property Background: Boolean read FBackground; // 后台执行模式 property BufferPool: TIODataPool read GetBufferPool; property ByteCount: Cardinal read FByteCount; property Completed: Boolean read FCompleted; property LinkNode: PLinkRec read FLinkNode; property ObjPool: TIOCPSocketPool read FObjPool; property RecvBuf: PPerIOData read FRecvBuf; property Reference: Boolean read GetReference; property Sender: TBaseTaskSender read FSender; property SocketState: Boolean read GetSocketState; property Worker: TBaseWorker read FWorker; public // 属性 Data,用户可以扩展 property Data: Pointer read FData write FData; end; TBaseSocketClass = class of TBaseSocket; // ================== 原始数据流 Socket ================== TStreamSocket = class(TBaseSocket) private FClientId: TNameString; // 客户端 id FRole: TClientRole; // 权限 protected function GetObjectState(const Group: string; AdminType: Boolean): Boolean; override; // 取可推送状态 {$IFDEF TRANSMIT_FILE} procedure InterFreeRes; override; {$ENDIF} procedure ClearResources; override; procedure ExecuteWork; override; procedure IniSocket(AServer: TObject; ASocket: TSocket; AData: Pointer = nil); override; procedure PostEvent(IOKind: TIODataType); override; public procedure SendData(const Data: PAnsiChar; Size: Cardinal); overload; procedure SendData(const Msg: String); overload; procedure SendData(Handle: THandle); overload; procedure SendData(Stream: TStream); overload; procedure SendDataVar(Data: Variant); public property ClientId: TNameString read FClientId write FClientId; property Role: TClientRole read FRole write FRole; // 角色/权限 end; // ================== C/S 模式业务处理 ================== // 1. 服务端接收到的数据 TReceiveParams = class(TReceivePack) private FSocket: TIOCPSocket; // 宿主 FMsgHead: PMsgHead; // 协议头位置 function GetLogName: string; protected procedure SetUniqueMsgId; public constructor Create(AOwner: TIOCPSocket); overload; procedure CreateAttachment(const ALocalPath: string); override; public property LogName: string read GetLogName; property MsgHead: PMsgHead read FMsgHead; property Socket: TIOCPSocket read FSocket; end; // 2. 反馈给客户端的数据 TReturnResult = class(TBaseMessage) private FSocket: TIOCPSocket; // 宿主 FSender: TBaseTaskSender; // 任务发送器 public constructor Create(AOwner: TIOCPSocket; AInitialize: Boolean = True); procedure LoadFromFile(const AFileName: String; ServerMode: Boolean = False); override; // 服务端公开两个过程 procedure LoadFromCDSVariant(const ACDSAry: array of TClientDataSet; const ATableNames: array of String); override; procedure LoadFromVariant(const AProviders: array of TDataSetProvider; const ATableNames: array of String); override; public property Socket: TIOCPSocket read FSocket; // 公开协议头属性 property Action: TActionType read FAction; property ActResult: TActionResult read FActResult write FActResult; property Offset: TFileSize read FOffset; property OffsetEnd: TFileSize read FOffsetEnd; end; TIOCPSocket = class(TBaseSocket) private FReceiver: TServerReceiver; // 数据接收器 FParams: TReceiveParams; // 接收到的消息(变量化) FResult: TReturnResult; // 返回的数据 FEnvir: PEnvironmentVar; // 工作环境信息 FAction: TActionType; // 内部事件 FSessionId: Cardinal; // 对话凭证 id function CheckMsgHead(InBuf: PAnsiChar): Boolean; function CreateSession: Cardinal; function GetRole: TClientRole; function GetLogName: string; function SessionValid(ASession: Cardinal): Boolean; function GetUserGroup: string; procedure CreateResources; procedure HandleDataPack; procedure ReturnHead(ActResult: TActionResult); procedure ReturnMessage(ActResult: TActionResult; const ErrMsg: String = ''); procedure ReturnResult; procedure SetLogoutState; protected // 取可推送状态 function GetObjectState(const Group: string; AdminType: Boolean): Boolean; override; {$IFDEF TRANSMIT_FILE} procedure InterFreeRes; override; {$ENDIF} procedure ClearResources; override; procedure CopyResources(AMaster: TBaseSocket); override; procedure BackgroundExecute; override; procedure ExecuteWork; override; // 调用入口 procedure IniSocket(AServer: TObject; ASocket: TSocket; AData: Pointer = nil); override; procedure InterCloseSocket(Sender: TObject); override; procedure PostEvent(IOKind: TIODataType); override; procedure SetLogState(AEnvir: PEnvironmentVar); // 业务模块调用 procedure SocketError(IOType: TIODataType); override; public destructor Destroy; override; public property Action: TActionType read FAction; property Envir: PEnvironmentVar read FEnvir; property LoginName: string read GetLogName; property Params: TReceiveParams read FParams; property Result: TReturnResult read FResult; property Role: TClientRole read GetRole; // 角色/权限 property SessionId: Cardinal read FSessionId; property UserGroup: string read GetUserGroup; end; // ================== Http 协议 Socket ================== TRequestObject = class(THttpRequest); TResponseObject = class(THttpResponse); THttpSocket = class(TBaseSocket) private FRequest: THttpRequest; // http 请求 FResponse: THttpResponse; // http 应答 FStream: TFileStream; // 接收文件的流 FKeepAlive: Boolean; // 保持连接 function GetSessionId: AnsiString; procedure UpgradeSocket(SocketPool: TIOCPSocketPool); procedure DecodeHttpRequest; protected {$IFDEF TRANSMIT_FILE} procedure InterFreeRes; override; {$ENDIF} procedure ClearResources; override; procedure ExecuteWork; override; procedure PostEvent(IOKind: TIODataType); override; // 投放事件 procedure SocketError(IOType: TIODataType); override; public destructor Destroy; override; // 文件流操作 procedure CreateStream(const FileName: String); procedure WriteStream(Data: PAnsiChar; DataLength: Integer); procedure CloseStream; public property Request: THttpRequest read FRequest; property Response: THttpResponse read FResponse; property SessionId: AnsiString read GetSessionId; end; // ================== WebSocket 类 ================== // . 收到的 JSON 消息 TReceiveJSON = class(TSendJSON) private FSocket: TWebSocket; public constructor Create(AOwner: TWebSocket); public property Socket: TWebSocket read FSocket; end; // . 待返回的 JSON 消息 TResultJSON = class(TSendJSON) private FSocket: TWebSocket; public constructor Create(AOwner: TWebSocket); public property Socket: TWebSocket read FSocket; end; TWebSocket = class(TBaseSocket) private FReceiver: TWSServerReceiver; // 数据接收器 FJSON: TReceiveJSON; // 收到的 JSON 数据 FResult: TResultJSON; // 要返回的 JSON 数据 FMsgType: TWSMsgType; // 数据类型 FOpCode: TWSOpCode; // WebSocket 操作类型 FRole: TClientRole; // 客户权限(预设) FUserGroup: TNameString; // 用户分组 FUserName: TNameString; // 用户名称(预设) protected FInData: PAnsiChar; // 本次收到的数据引用位置 FMsgSize: UInt64; // 当前消息收到的累计长度 FFrameSize: UInt64; // 当前帧长度 FFrameRecvSize: UInt64; // 本次收到的数据长度 procedure SetProps(AOpCode: TWSOpCode; AMsgType: TWSMsgType; AData: Pointer; AFrameSize: Int64; ARecvSize: Cardinal); protected function GetObjectState(const Group: string; AdminType: Boolean): Boolean; override; // 取可推送状态 procedure ClearOwnerMark; procedure ClearResources; override; procedure CopyResources(AMaster: TBaseSocket); override; procedure BackgroundExecute; override; procedure ExecuteWork; override; procedure InternalPong; procedure PostEvent(IOKind: TIODataType); override; public constructor Create(AObjPool: TIOCPSocketPool; ALinkNode: PLinkRec); override; destructor Destroy; override; procedure SendData(const Data: PAnsiChar; Size: Cardinal); overload; procedure SendData(const Msg: String); overload; procedure SendData(Handle: THandle); overload; procedure SendData(Stream: TStream); overload; procedure SendDataVar(Data: Variant); procedure SendResult(UTF8CharSet: Boolean = False); public property InData: PAnsiChar read FInData; // raw property FrameRecvSize: UInt64 read FFrameRecvSize; // raw property FrameSize: UInt64 read FFrameSize; // raw property MsgSize: UInt64 read FMsgSize; // raw property JSON: TReceiveJSON read FJSON; // JSON property Result: TResultJSON read FResult; // JSON public property MsgType: TWSMsgType read FMsgType; // 数据类型 property OpCode: TWSOpCode read FOpCode; // WebSocket 操作 public property Role: TClientRole read FRole write FRole; property UserGroup: TNameString read FUserGroup write FUserGroup; property UserName: TNameString read FUserName write FUserName; end; // ================== TSocketBroker 代理套接字 ================== TSocketBroker = class; TAcceptBroker = procedure(Sender: TSocketBroker; const Host: AnsiString; Port: Integer; var Accept: Boolean) of object; TBindIPEvent = procedure(Sender: TSocketBroker; const Data: PAnsiChar; DataSize: Cardinal) of object; TForwardDataEvent = procedure(Sender: TSocketBroker; const Data: PAnsiChar; DataSize: Cardinal; Direction: Integer) of object; TOuterPingEvent = TBindIPEvent; TSocketBroker = class(TBaseSocket) private FAction: Integer; // 初始化 FBroker: TObject; // 代理服务 FCmdConnect: Boolean; // HTTP 代理模式 FDualBuf: PPerIOData; // 关联套接字的接收内存块 FDualConnected: Boolean; // 关联套接字连接状态 FDualSocket: TSocket; // 关联的套接字 FRecvState: Integer; // 接收状态 FSocketType: TSocketBrokerType; // 类型 FTargetHost: AnsiString; // 关联的主机地址 FTargetPort: Integer; // 关联的服务器端口 FOnBind: TBindIPEvent; // 绑定事件 FOnBeforeForward: TForwardDataEvent; // 转发前事件 // 新的投放方法 procedure BrokerPostRecv(ASocket: TSocket; AData: PPerIOData; ACheckState: Boolean = True); // HTTP 协议的绑定 procedure HttpBindOuter(Connection: TSocketBroker; const Data: PAnsiChar; DataSize: Cardinal); protected FBrokerId: AnsiString; // 所属的反向代理 Id procedure ClearResources; override; procedure ExecuteWork; override; procedure IniSocket(AServer: TObject; ASocket: TSocket; AData: Pointer = nil); override; procedure InterCloseSocket(Sender: TObject); override; procedure MarkIODataBuf(AData: PPerIOData); override; procedure PostEvent(IOKind: TIODataType); override; // 投放事件:被删除、拒绝服务、超时 protected procedure AssociateInner(InnerBroker: TSocketBroker); procedure SendInnerFlag; procedure SetConnection(AServer: TObject; Connection: TSocket); public procedure CreateBroker(const AServer: AnsiString; APort: Integer); // 建连接中继 end; implementation uses iocp_server, http_base, http_utils, iocp_threads, iocp_managers; type THeadMessage = class(TBaseMessage); TIOCPBrokerRef = class(TInIOCPBroker); { TRawSocket } procedure TRawSocket.Close; begin if FConnected then InternalClose; // 关闭 end; constructor TRawSocket.Create(AddSocket: Boolean); begin inherited Create; if AddSocket then // 建一个 Socket IniSocket(nil, iocp_utils.CreateSocket); end; destructor TRawSocket.Destroy; begin if FConnected then InternalClose; // 关闭 inherited; end; class function TRawSocket.GetPeerIP(const Addr: PSockAddrIn): AnsiString; begin // 取IP Result := iocp_Winsock2.inet_ntoa(Addr^.sin_addr); end; procedure TRawSocket.IniSocket(AServer: TObject; ASocket: TSocket; AData: Pointer); begin // 设置 Socket FSocket := ASocket; FConnected := FSocket <> INVALID_SOCKET; end; procedure TRawSocket.InternalClose; begin // 关闭 Socket try if (FSocket > 0) then // 后台执行时为 0 begin iocp_Winsock2.Shutdown(FSocket, SD_BOTH); iocp_Winsock2.CloseSocket(FSocket); FSocket := INVALID_SOCKET; end; finally FConnected := False; end; end; procedure TRawSocket.SetPeerAddr(const Addr: PSockAddrIn); begin // 从地址信息取 IP、Port FPeerIP := iocp_Winsock2.inet_ntoa(Addr^.sin_addr); FPeerPort := iocp_Winsock2.htons(Addr^.sin_port); // 转换 FPeerIPPort := FPeerIP + ':' + IntToStr(FPeerPort); end; { TListenSocket } function TListenSocket.Bind(Port: Integer; const Addr: String): Boolean; var SockAddr: TSockAddrIn; begin // 绑定地址 // htonl(INADDR_ANY); 在任何地址(多块网卡)上监听 FillChar(SockAddr, SizeOf(TSockAddr), 0); SockAddr.sin_family := AF_INET; SockAddr.sin_port := htons(Port); SockAddr.sin_addr.S_addr := inet_addr(PAnsiChar(ResolveHostIP(Addr))); if (iocp_Winsock2.bind(FSocket, TSockAddr(SockAddr), SizeOf(TSockAddr)) <> 0) then begin Result := False; FErrorCode := WSAGetLastError; {$IFDEF DEBUG_MODE} iocp_log.WriteLog('TListenSocket.Bind->Error:' + IntToStr(FErrorCode)); {$ENDIF} end else begin Result := True; FErrorCode := 0; end; end; function TListenSocket.StartListen: Boolean; begin // 监听 if (iocp_Winsock2.listen(FSocket, MaxInt) <> 0) then begin Result := False; FErrorCode := WSAGetLastError; {$IFDEF DEBUG_MODE} iocp_log.WriteLog('TListenSocket.StartListen->Error:' + IntToStr(FErrorCode)); {$ENDIF} end else begin Result := True; FErrorCode := 0; end; end; { TAcceptSocket } function TAcceptSocket.AcceptEx: Boolean; begin // 投放 AcceptEx 请求 FillChar(FIOData.Overlapped, SizeOf(TOverlapped), 0); FIOData.Owner := Self; // 宿主 FIOData.IOType := ioAccept; // 再设置 FByteCount := 0; Result := gAcceptEx(FListenSocket, FSocket, Pointer(FIOData.Data.buf), 0, // 用 0,不等待第一包数据 ADDRESS_SIZE_16, ADDRESS_SIZE_16, FByteCount, @FIOData.Overlapped); if Result then FErrorCode := 0 else begin FErrorCode := WSAGetLastError; Result := FErrorCode = WSA_IO_PENDING; {$IFDEF DEBUG_MODE} if (Result = False) then iocp_log.WriteLog('TAcceptSocket.AcceptEx->Error:' + IntToStr(FErrorCode)); {$ENDIF} end; end; constructor TAcceptSocket.Create(ListenSocket: TSocket); begin inherited Create(True); // 新建 AcceptEx 用的 Socket FListenSocket := ListenSocket; GetMem(FIOData.Data.buf, ADDRESS_SIZE_16 * 2); // 申请一块内存 FIOData.Data.len := ADDRESS_SIZE_16 * 2; FIOData.Node := nil; // 无 end; destructor TAcceptSocket.Destroy; begin FreeMem(FIOData.Data.buf); // 释放内存块 inherited; end; procedure TAcceptSocket.NewSocket; begin // 新建 Socket FSocket := iocp_utils.CreateSocket; end; function TAcceptSocket.SetOption: Boolean; begin // 复制 FListenSocket 的属性到 FSocket Result := iocp_Winsock2.setsockopt(FSocket, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, PAnsiChar(@FListenSocket), SizeOf(TSocket)) <> SOCKET_ERROR; end; { TBaseSocket } constructor TBaseSocket.Create(AObjPool: TIOCPSocketPool; ALinkNode: PLinkRec); begin inherited Create(False); // FSocket 由客户端接入时分配 // 见:TInIOCPServer.AcceptClient // TIOCPSocketPool.CreateObjData FObjPool := AObjPool; FLinkNode := ALinkNode; FUseTransObj := True; end; procedure TBaseSocket.BackgroundExecute; begin // Empty end; function TBaseSocket.CheckDelayed(ATickCount: Cardinal): Boolean; begin // 取距最近活动时间的差 if (ATickCount >= FTickCount) then Result := ATickCount - FTickCount <= 3000 else Result := High(Cardinal) - ATickCount + FTickCount <= 3000; {$IFDEF TRANSMIT_FILE} if Assigned(FTask) then // TransmitFile 没有任务 Result := Result and (FTask.Exists = False); {$ENDIF} end; function TBaseSocket.CheckTimeOut(NowTickCount, TimeoutInteval: Cardinal): Boolean; function GetTickCountDiff: Boolean; begin if (NowTickCount >= FTickCount) then Result := NowTickCount - FTickCount >= TimeoutInteval else Result := High(Cardinal) - FTickCount + NowTickCount >= TimeoutInteval; end; begin // 超时检查 if (FTickCount = 0) then // 投放即断开,=0 begin Inc(FTickCount); Result := False; end else Result := GetTickCountDiff; end; procedure TBaseSocket.Clone(Source: TBaseSocket); begin // 对象变换:把 Source 的套接字等资源转移到新对象 // 由 TIOCPSocketPool 加锁调用,防止被检查为超时 // 转移 Source 的套接字、地址 IniSocket(Source.FServer, Source.FSocket, Source.FData); FPeerIP := Source.FPeerIP; FPeerPort := Source.FPeerPort; FPeerIPPort := Source.FPeerIPPort; // 清除 Source 的资源值 // Source.FServer 不变,释放时要检查:TBaseSocket.Destroy Source.FData := nil; Source.FPeerIP := ''; Source.FPeerPort := 0; Source.FPeerIPPort := ''; Source.FConnected := False; Source.FSocket := INVALID_SOCKET; // 未建 FTask end; procedure TBaseSocket.Close; begin // 关闭 ClearResources; // 只清空资源 inherited; end; procedure TBaseSocket.CopyResources(AMaster: TBaseSocket); begin FByteCount := 0; // 收到字节数 FLinkSocket := AMaster; // 关联对象 FState := 0; // 不繁忙 AMaster.FBackground := True; // 后台模式 // 转义:FPeerIP 保存登录名称,它对后台 Socket 没太大意义 // FPeerIP := AMaster.FPeerIP; FPeerIPPort := AMaster.FPeerIPPort; FPeerPort := AMaster.FPeerPort; end; destructor TBaseSocket.Destroy; begin {$IFDEF TRANSMIT_FILE} if Assigned(FTask) then FTask.Free; {$ENDIF} if TInIOCPServer(FServer).Active and Assigned(FRecvBuf) then begin BufferPool.Push(FRecvBuf^.Node); // 回收内存块 FRecvBuf := Nil; end; inherited; end; procedure TBaseSocket.DoWork(AWorker: TBaseWorker; ASender: TBaseTaskSender); begin // 初始化 // 任务结束后不设 FWorker、FSender 为 Nil if Assigned(FLinkSocket) then // 后台状态 begin FBackground := True; // 后台执行 FCompleted := True; // 接收完毕 FErrorCode := 0; // 无异常 FWorker := AWorker; // 执行者 FSender := nil; // 发送器 BackgroundExecute; // 后台执行 end else begin {$IFDEF TRANSMIT_FILE} if FUseTransObj then begin if (Assigned(FTask) = False) then begin FTask := TTransmitObject.Create(Self); // TransmitFile 对象 FTask.OnError := OnSendError; end; FTask.Socket := FSocket; FTaskExists := False; // 必须 end; {$ENDIF} FErrorCode := 0; // 无异常 FByteCount := FRecvBuf^.Overlapped.InternalHigh; // 收到字节数 FBackground := False; FWorker := AWorker; // 执行者 FSender := ASender; // 发送器 FSender.Owner := Self; FSender.Socket := FSocket; FSender.OnError := OnSendError; // 执行任务 ExecuteWork; end; end; {$IFDEF TRANSMIT_FILE} procedure TBaseSocket.FreeTransmitRes; begin // 工作线程调用:TransmitFile 发送完毕 if FTask.SendDone then // FState=2 -> 正常,否则异常 if (InterlockedDecrement(FState) = 1) then // FState=2 -> 正常,否则异常 InterFreeRes // 在子类实现,正式释放发送资源,判断是否继续投放 WSARecv! else InterCloseSocket(Self); end; {$ENDIF} function TBaseSocket.GetActive: Boolean; begin // 推送前取初始化状态(接收过数据) Result := (iocp_api.InterlockedCompareExchange(Integer(FByteCount), 0, 0) > 0); end; function TBaseSocket.GetBufferPool: TIODataPool; begin // 取内存池 Result := TInIOCPServer(FServer).IODataPool; end; function TBaseSocket.GetObjectState(const Group: string; AdminType: Boolean): Boolean; begin Result := False; // 不接受推送 end; function TBaseSocket.GetReference: Boolean; begin // 推送时引用(业务引用 FRecvBuf^.RefCount) Result := InterlockedIncrement(FRefCount) = 1; end; function TBaseSocket.GetSocketState: Boolean; begin // 取状态, FState = 1 说明正常 Result := iocp_api.InterlockedCompareExchange(FState, 1, 1) = 1; end; procedure TBaseSocket.InternalPush(AData: PPerIOData); var ByteCount, Flags: Cardinal; begin // 推送消息(推送线程调用) // AData:TPushMessage.FPushBuf // 清重叠结构 FillChar(AData^.Overlapped, SizeOf(TOverlapped), 0); FErrorCode := 0; FRefCount := 0; // AData:Socket = 1:n FTickCount := GetTickCount; // + ByteCount := 0; Flags := 0; if (InterlockedDecrement(FState) <> 0) then InterCloseSocket(Self) else if (iocp_Winsock2.WSASend(FSocket, @(AData^.Data), 1, ByteCount, Flags, LPWSAOVERLAPPED(@AData^.Overlapped), nil) = SOCKET_ERROR) then begin FErrorCode := WSAGetLastError; if (FErrorCode <> ERROR_IO_PENDING) then // 异常 begin SocketError(AData^.IOType); InterCloseSocket(Self); // 关闭 end else FErrorCode := 0; end; end; procedure TBaseSocket.InternalRecv; var ByteCount, Flags: DWORD; begin // 在任务结束或一个数据包接收后,提交接收的请求 // 清重叠结构 FillChar(FRecvBuf^.Overlapped, SizeOf(TOverlapped), 0); FRecvBuf^.Owner := Self; // 宿主 FRecvBuf^.IOType := ioReceive; // iocp_server 中判断用 FRecvBuf^.Data.len := IO_BUFFER_SIZE; // 恢复 ByteCount := 0; Flags := 0; // 正常时 FState=1,其他任何值都说明出现了异常, // FState-,FState <> 0 -> 异常改变了状态,关闭! if (InterlockedDecrement(FState) <> 0) then InterCloseSocket(Self) else // FRecvBuf^.Overlapped 与 TPerIOData 同地址 if (iocp_Winsock2.WSARecv(FSocket, @(FRecvBuf^.Data), 1, ByteCount, Flags, LPWSAOVERLAPPED(@FRecvBuf^.Overlapped), nil) = SOCKET_ERROR) then begin FErrorCode := WSAGetLastError; if (FErrorCode <> ERROR_IO_PENDING) then // 异常 begin SocketError(ioReceive); InterCloseSocket(Self); // 关闭 end else FErrorCode := 0; end; end; function TBaseSocket.Lock(PushMode: Boolean): Integer; const SOCKET_STATE_IDLE = 0; // 空闲 SOCKET_STATE_BUSY = 1; // 在用 SOCKET_STATE_TRANS = 2; // TransmitFile 在用 begin // 工作前加锁 // 状态 FState = 0 -> 1, 且上次任务完成 -> 成功! // 以后在 Socket 内部的任何异常都 FState+ case iocp_api.InterlockedCompareExchange(FState, 1, 0) of // 返回原值 SOCKET_STATE_IDLE: begin if PushMode then // 推送模式 begin if FCompleted then Result := SOCKET_LOCK_OK else Result := SOCKET_LOCK_FAIL; end else begin // 业务线程模式,见:TWorkThread.HandleIOData Result := SOCKET_LOCK_OK; // 总是运行 end; if (Result = SOCKET_LOCK_FAIL) then // 业务未完成,放弃! if (InterlockedDecrement(FState) <> 0) then InterCloseSocket(Self); end; SOCKET_STATE_BUSY: Result := SOCKET_LOCK_FAIL; // 在用 SOCKET_STATE_TRANS: if FUseTransObj then Result := SOCKET_LOCK_FAIL // 在用 else Result := SOCKET_LOCK_CLOSE; // 异常 else Result := SOCKET_LOCK_CLOSE; // 已关闭或工作中异常 end; end; procedure TBaseSocket.MarkIODataBuf(AData: PPerIOData); begin // 空 end; procedure TBaseSocket.IniSocket(AServer: TObject; ASocket: TSocket; AData: Pointer); begin inherited; FServer := AServer;// 服务器(在前) FData := AData; // 扩展数据 // 分配接收内存块(释放时回收) if (FRecvBuf = nil) then FRecvBuf := BufferPool.Pop^.Data; // 在 FServer 赋值后 FByteCount := 0; // 接收数据长度 FCompleted := True; // 等待接收 FErrorCode := 0; // 无异常 FState := 9; // 无效状态,投放 Recv 才算正式使用 FTickCount := 0; // 0,防止被监测为超时,见:TOptimizeThread end; procedure TBaseSocket.InterCloseSocket(Sender: TObject); begin // 内部关闭,提交到 FServer 的关闭线程处理 InterlockedExchange(Integer(FByteCount), 0); // 不接受推送了 InterlockedExchange(FState, 9); // 无效状态 TInIOCPServer(FServer).CloseSocket(Self); // 用关闭线程(允许重复关闭) end; {$IFDEF TRANSMIT_FILE} procedure TBaseSocket.InterTransmit; begin if FTask.Exists then begin FTaskExists := True; InterlockedIncrement(FState); // FState+,正常时=2 FTask.TransmitFile; end; end; {$ENDIF} procedure TBaseSocket.OnSendError(IOType: TIODataType; ErrorCode: Integer); begin // 任务发送异常的回调方法 // 见:TBaseSocket.DoWork、TBaseTaskObject.Send... FErrorCode := ErrorCode; InterlockedIncrement(FState); // FState+ SocketError(IOType); end; procedure TBaseSocket.PostRecv; begin // 投放接收缓存 // ACompleted: 是否准备完成,将接受推送消息 // 见:TInIOCPServer.AcceptClient、THttpSocket.ExecuteWork FState := 1; // 设繁忙 InternalRecv; // 投放时 FState- end; procedure TBaseSocket.SocketError(IOType: TIODataType); const PROCEDURE_NAMES: array[ioReceive..ioTimeOut] of string = ( 'Post WSARecv->', 'TransmitFile->', 'Post WSASend->', 'InternalPush->', 'InternalPush->', 'InternalPush->'); begin // 写异常日志 if Assigned(FWorker) then // 主动型代理投放,没有 FWorker iocp_log.WriteLog(PROCEDURE_NAMES[IOType] + PeerIPPort + ',Error:' + IntToStr(FErrorCode) + ',BusiThread:' + IntToStr(FWorker.ThreadIdx)); end; procedure TBaseSocket.TryClose; begin // 尝试关闭 // FState+, 原值: 0,2,3... <> 1 -> 关闭 if (InterlockedIncrement(FState) in [1, 3]) then // <> 2 InterCloseSocket(Self) else if (FState = 8) then InterCloseSocket(Self); end; { TStreamSocket } procedure TStreamSocket.ClearResources; begin FByteCount := 0; // 防止接入时被推送消息 {$IFDEF TRANSMIT_FILE} if Assigned(FTask) then FTask.FreeResources(True); {$ENDIF} end; procedure TStreamSocket.ExecuteWork; begin try FTickCount := GetTickCount; FWorker.StreamExecute(Self); // 新版用管理器执行 finally {$IFDEF TRANSMIT_FILE} if (FTaskExists = False) then {$ENDIF} InternalRecv; // 继续接收 end; end; function TStreamSocket.GetObjectState(const Group: string; AdminType: Boolean): Boolean; begin // 取状态,是否可以接受推送 // 1. 已经接收过数据; 2. 有管理员权限 Result := (FByteCount > 0) and ((AdminType = False) or (FRole >= crAdmin)); end; procedure TStreamSocket.IniSocket(AServer: TObject; ASocket: TSocket; AData: Pointer); begin inherited; FClientId := ''; FRole := crUnknown; end; procedure TStreamSocket.PostEvent(IOKind: TIODataType); begin // Empty end; {$IFDEF TRANSMIT_FILE} procedure TStreamSocket.InterFreeRes; begin // 释放 TransmitFile 的发送资源,继续投放接收! try ClearResources; finally InternalRecv; end; end; {$ENDIF} procedure TStreamSocket.SendData(const Data: PAnsiChar; Size: Cardinal); var Buf: PAnsiChar; begin // 发送内存块数据(复制 Data) if Assigned(Data) and (Size > 0) then begin GetMem(Buf, Size); System.Move(Data^, Buf^, Size); {$IFDEF TRANSMIT_FILE} FTask.SetTask(Buf, Size); InterTransmit; {$ELSE} FSender.Send(Buf, Size); {$ENDIF} end; end; procedure TStreamSocket.SendData(const Msg: String); begin // 发送文本 if (Msg <> '') then begin {$IFDEF TRANSMIT_FILE} FTask.SetTask(Msg); InterTransmit; {$ELSE} FSender.Send(Msg); {$ENDIF} end; end; procedure TStreamSocket.SendData(Handle: THandle); begin // 发送文件 handle(自动关闭) if (Handle > 0) and (Handle <> INVALID_HANDLE_VALUE) then begin {$IFDEF TRANSMIT_FILE} FTask.SetTask(Handle, GetFileSize64(Handle)); InterTransmit; {$ELSE} FSender.Send(Handle, GetFileSize64(Handle)); {$ENDIF} end; end; procedure TStreamSocket.SendData(Stream: TStream); begin // 发送流数据(自动释放) if Assigned(Stream) then begin {$IFDEF TRANSMIT_FILE} FTask.SetTask(Stream, Stream.Size); InterTransmit; {$ELSE} FSender.Send(Stream, Stream.Size, True); {$ENDIF} end; end; procedure TStreamSocket.SendDataVar(Data: Variant); begin // 发送可变类型数据 if (VarIsNull(Data) = False) then begin {$IFDEF TRANSMIT_FILE} FTask.SetTaskVar(Data); InterTransmit; {$ELSE} FSender.SendVar(Data); {$ENDIF} end; end; { TReceiveParams } constructor TReceiveParams.Create(AOwner: TIOCPSocket); begin inherited Create; FSocket := AOwner; end; procedure TReceiveParams.CreateAttachment(const ALocalPath: string); begin // 建文件流,接收附件 inherited; if Error then // 出现错误 begin FSocket.FResult.ActResult := arFail; FSocket.FResult.Msg := GetSysErrorMessage(); end else begin FSocket.FAction := atAfterReceive; // 结束时执行事件 FSocket.FResult.FActResult := arAccept; // 允许上传 FSocket.FReceiver.Completed := False; // 继续接收附件 // 续传,返回额外的文件信息 if (FAction in FILE_CHUNK_ACTIONS) then begin FSocket.FResult.FOffset := FOffset; // 可能要从新接收,FOffset 被修改 FSocket.FResult.SetFileName(ExtractFileName(Attachment.FileName)); // 文件同名时被改变 FSocket.FResult.SetDirectory(EncryptString(ExtractFilePath(Attachment.FileName))); // 加密服务端文件 FSocket.FResult.SetAttachFileName(GetAttachFileName); // 客户端的文件全名 end; // 发布 URL(路径应该可以公开) if Assigned(TInIOCPServer(FSocket.FServer).HttpDataProvider) then SetURL(ChangeSlash(Attachment.FileName)); end; end; function TReceiveParams.GetLogName: string; begin // 取登录时的名称 Result := FSocket.GetLogName; end; procedure TReceiveParams.SetUniqueMsgId; begin // 设置推送消息的 MsgId // 推送消息改用服务器的唯一 MsgId // 修改缓冲的 MsgId // 不要改 FResult.FMsgId,否则客户端把发送反馈当作推送消息处理 FMsgHead^.MsgId := TSystemGlobalLock.GetMsgId; end; { TReturnResult } constructor TReturnResult.Create(AOwner: TIOCPSocket; AInitialize: Boolean); begin inherited Create(nil); // Owner 用 nil FSocket := AOwner; PeerIPPort := FSocket.PeerIPPort; if AInitialize then begin FOwner := AOwner.Params.FOwner; // 对应客户端组件 SetHeadMsg(AOwner.Params.FMsgHead, True); end; end; procedure TReturnResult.LoadFromFile(const AFileName: String; ServerMode: Boolean); begin inherited; // 立刻打开文件,等待发送 if Error then begin FActResult := arFail; FOffset := 0; FOffsetEnd := 0; end else begin FActResult := arOK; if (FAction = atFileDownChunk) then // 断点下载 begin FOffset := FSocket.FParams.FOffset; // 请求位移 AdjustTransmitRange(FSocket.FParams.FOffsetEnd); // 期望长度, =客户端 FMaxChunkSize SetDirectory(EncryptString(ExtractFilePath(AFileName))); // 返回加密的路径 end; end; end; procedure TReturnResult.LoadFromCDSVariant( const ACDSAry: array of TClientDataSet; const ATableNames: array of String); begin inherited; // 直接调用 end; procedure TReturnResult.LoadFromVariant( const AProviders: array of TDataSetProvider; const ATableNames: array of String); begin inherited; // 直接调用 end; { TIOCPSocket } procedure TIOCPSocket.BackgroundExecute; begin // 直接进入应用层 // 后台线程只能执行任务、推送消息,无法返回数据 try FTickCount := GetTickCount; FWorker.Execute(Self); except {$IFDEF DEBUG_MODE} on E: Exception do iocp_log.WriteLog('TIOCPSocket.BackgroundExecute->' + E.Message); {$ENDIF} end; end; function TIOCPSocket.CheckMsgHead(InBuf: PAnsiChar): Boolean; function CheckLogState: TActionResult; begin // 检查登录状态 if (FParams.Action = atUserLogin) then Result := arOK // 通过 else if (FParams.SessionId = 0) then Result := arErrUser // 客户端缺少 SessionId, 当非法用户 else if (FParams.SessionId = FSessionId) then Result := arOK // 通过 else if SessionValid(FParams.SessionId) then Result := arOK // 通过 else Result := arOutDate; // 凭证过期 end; begin // 检查第一请求数据包的有效性、用户登录状态(类似于 http 协议) if (FByteCount < IOCP_SOCKET_SIZE) or // 长度太短 (MatchSocketType(InBuf, IOCP_SOCKET_FLAG) = False) then // C/S 标志错误 begin // 关闭返回 InterCloseSocket(Self); Result := False; end else begin Result := True; FAction := atUnknown; // 内部事件(用于附件传输) FResult.FSender := FSender; // 发送器 // 先更新协议头 FParams.FMsgHead := PMsgHead(InBuf + IOCP_SOCKET_FLEN); // 推送时用 FParams.SetHeadMsg(FParams.FMsgHead); FResult.SetHeadMsg(FParams.FMsgHead, True); if (FParams.Action = atUnknown) then // 1. 响应服务 FReceiver.Completed := True else begin // 2. 检查登录状态 if Assigned(TInIOCPServer(FServer).ClientManager) then FResult.ActResult := CheckLogState else begin // 免登录,也返回 SessionId FResult.ActResult := arOK; FSessionId := CreateSession; FResult.FSessionId := FSessionId; end; if (FResult.ActResult in [arOffline, arOutDate]) then FReceiver.Completed := True // 3. 接收完毕 else // 4. 准备接收 FReceiver.Prepare(InBuf, FByteCount); end; end; end; procedure TIOCPSocket.ClearResources; begin // 清除资源 if Assigned(FResult) then FReceiver.Clear; if Assigned(FParams) then FParams.Clear; if Assigned(FResult) then FResult.Clear; SetLogoutState; // 登出 {$IFDEF TRANSMIT_FILE} if Assigned(FTask) then FTask.FreeResources(False); // 已在 FResult.Clear 释放 {$ENDIF} end; procedure TIOCPSocket.CopyResources(AMaster: TBaseSocket); begin // 复制参数、结果数据,准备投入后台线程 inherited; CreateResources; // 新建资源 FParams.Initialize(TIOCPSocket(AMaster).FParams); // 复制字段 FResult.Initialize(TIOCPSocket(AMaster).FResult); // 复制字段 FPeerIP := TIOCPSocket(AMaster).LoginName; // 转义:唤醒时要用 end; procedure TIOCPSocket.CreateResources; begin // 建资源:接收、结果参数/变量表,数据接收器 if (FReceiver = nil) then begin FParams := TReceiveParams.Create(Self); // 在前 FResult := TReturnResult.Create(Self, False); FReceiver := TServerReceiver.Create(FParams); // 在后 end else if FReceiver.Completed then begin FParams.Clear; FResult.Clear; end; end; function TIOCPSocket.CreateSession: Cardinal; var NowTime: TDateTime; Certify: TCertifyNumber; LHour, LMinute, LSecond, LMilliSecond: Word; begin // 生成一个登录凭证,有效期为 SESSION_TIMEOUT 分钟 // 结构:(相对日序号 + 有效分钟) xor 年 NowTime := Now(); DecodeTime(NowTime, LHour, LMinute, LSecond, LMilliSecond); Certify.DayCount := Trunc(NowTime - 43000); // 相对日序号 Certify.Timeout := LHour * 60 + LMinute + SESSION_TIMEOUT; if (Certify.Timeout >= 1440) then // 超过一天的分钟数 begin Inc(Certify.DayCount); // 后一天 Dec(Certify.Timeout, 1440); end; Result := Certify.Session xor Cardinal($AB12); end; destructor TIOCPSocket.Destroy; begin // 释放资源 if Assigned(FReceiver) then begin FReceiver.Free; FReceiver := Nil; end; if Assigned(FParams) then begin FParams.Free; FParams := Nil; end; if Assigned(FResult) then begin FResult.Free; FResult := Nil; end; inherited; end; procedure TIOCPSocket.ExecuteWork; const IO_FIRST_PACKET = True; // 首数据包 IO_SUBSEQUENCE = False; // 后续数据包 begin // 接收数据块 FRecvBuf 的内容 {$IFNDEF DELPHI_7} {$REGION '+ 接收数据'} {$ENDIF} // 1 建资源 CreateResources; // 1.1 接收数据 FTickCount := GetTickCount; case FReceiver.Completed of IO_FIRST_PACKET: // 1.2 首数据包,检查有效性 和 用户登录状态 if (CheckMsgHead(FRecvBuf^.Data.buf) = False) then Exit; IO_SUBSEQUENCE: // 1.3 接收后续数据包 FReceiver.Receive(FRecvBuf^.Data.buf, FByteCount); end; // 1.4 主体或附件接收完毕均进入应用层 FCompleted := FReceiver.Completed and (FReceiver.Cancel = False); {$IFNDEF DELPHI_7} {$ENDREGION} {$REGION '+ 进入应用层'} {$ENDIF} // 2. 进入应用层 try if FCompleted then // 接收完毕、文件协议 if FReceiver.CheckPassed then // 校验成功 HandleDataPack // 2.1 触发业务 else ReturnMessage(arErrHash); // 2.2 校验错误,反馈! finally // 2.3 继续投放 WSARecv,接收数据! {$IFDEF TRANSMIT_FILE} // 可能发出成功后任务被清在前! if (FTaskExists = False) then {$ENDIF} InternalRecv; end; {$IFNDEF DELPHI_7} {$ENDREGION} {$ENDIF} end; function TIOCPSocket.GetObjectState(const Group: string; AdminType: Boolean): Boolean; begin // 取状态,是否可以接受推送 // 同分组、已经接收过数据,有管理员权限 Result := (FByteCount > 0) and (GetUserGroup = Group) and ((AdminType = False) or (GetRole >= crAdmin)); end; function TIOCPSocket.GetLogName: string; begin if Assigned(FEnvir) then Result := FEnvir^.BaseInf.Name else Result := ''; end; function TIOCPSocket.GetRole: TClientRole; begin if Assigned(FEnvir) then Result := Envir^.BaseInf.Role else Result := crUnknown; end; function TIOCPSocket.GetUserGroup: string; begin if Assigned(FEnvir) then Result := Envir^.BaseInf.Group else Result := '<NULL_GROUP>'; // 保留名称:无效分组 end; procedure TIOCPSocket.HandleDataPack; begin // 执行客户端请求 // 1. 响应 -> 直接反馈协议头 if (FParams.Action = atUnknown) then ReturnHead(arOK) else // 2. 未登录(服务端不关闭)、对话过期 -> 反馈协议头 if (FResult.ActResult in [arErrUser, arOutDate]) then ReturnMessage(FResult.ActResult) else // 3. 变量解析异常 if FParams.Error then ReturnMessage(arErrAnalyse) else begin // 4. 进入应用层执行任务 try FWorker.Execute(Self); except on E: Exception do // 4.1 异常 -> 反馈 begin ReturnMessage(arErrWork, E.Message); Exit; // 4.2 返回 end; end; try // 5. 主体+附件接收完毕 -> 清空 FReceiver.OwnerClear; // 6. 非法用户,发送完毕要关闭 if (FResult.ActResult = arErrUser) then InterlockedIncrement(FState); // FState+ // 7. 发送结果! ReturnResult; {$IFNDEF TRANSMIT_FILE} // 7.1 发送完成事件(附件未关闭) if Assigned(FResult.Attachment) then begin FAction := atAfterSend; FWorker.Execute(Self); end; {$ENDIF} finally {$IFNDEF TRANSMIT_FILE} if (FReceiver.Complete = False) then // 附件未接收完毕 FAction := atAfterReceive; // 恢复 if Assigned(FResult.Attachment) then FResult.Clear; {$ENDIF} end; end; end; procedure TIOCPSocket.IniSocket(AServer: TObject; ASocket: TSocket; AData: Pointer); begin inherited; FSessionId := 0; // 初始凭证 end; procedure TIOCPSocket.InterCloseSocket(Sender: TObject); begin // 加入用户操作、名称,方便 OnDisconnect 使用 if Assigned(FParams) then begin if (FParams.FAction <> atUserLogout) then FResult.FAction := atDisconnect; if Assigned(FEnvir) then FResult.UserName := FEnvir^.BaseInf.Name; end; inherited; end; {$IFDEF TRANSMIT_FILE} procedure TIOCPSocket.InterFreeRes; begin // 释放 TransmitFile 的发送资源 try try if Assigned(FResult.Attachment) then // 附件发送完毕 begin FAction := atAfterSend; FWorker.Execute(Self); end; finally if (FReceiver.Completed = False) then // 附件未接收完毕 FAction := atAfterReceive; // 恢复 FResult.NilStreams(True); // 释放发送资源 FTask.FreeResources(False); // False -> 不用再释放 end; finally // 继续投放 Recv InternalRecv; end; end; {$ENDIF} procedure TIOCPSocket.PostEvent(IOKind: TIODataType); var Msg: TPushMessage; begin // 投放事件:被删除、拒绝服务、超时 // 构造、推送一个协议头消息(给自己) // C/S 服务 IOKind 只有 ioDelete、ioRefuse、ioTimeOut, // 其他消息用:Push(ATarget: TBaseSocket; UseUniqueMsgId: Boolean); // 同时开启 HTTP 服务时,会在 THttpSocket 发出 arRefuse(未转换资源) // 3 秒内活动过,取消超时 if (IOKind = ioTimeOut) and CheckDelayed(GetTickCount) then Exit; Msg := TPushMessage.Create(Self, IOKind, IOCP_SOCKET_SIZE); case IOKind of ioDelete: THeadMessage.CreateHead(Msg.PushBuf^.Data.buf, arDeleted); ioRefuse: THeadMessage.CreateHead(Msg.PushBuf^.Data.buf, arRefuse); ioTimeOut: THeadMessage.CreateHead(Msg.PushBuf^.Data.buf, arTimeOut); end; // 加入推送列表,激活推送线程 TInIOCPServer(FServer).PushManager.AddWork(Msg); end; procedure TIOCPSocket.SetLogoutState; begin // 设置关闭、登出状态 FByteCount := 0; // 防止接入时被推送消息 FBackground := False; FLinkSocket := nil; FSessionId := 0; if Assigned(FEnvir) then if FEnvir^.ReuseSession then // 短连接断开,保留 FData 主要信息 begin FEnvir^.BaseInf.Socket := 0; FEnvir^.BaseInf.LogoutTime := Now(); end else try // 释放登录信息 TInIOCPServer(FServer).ClientManager.RemoveClient(FEnvir^.BaseInf.Name); finally FEnvir := Nil; end; end; procedure TIOCPSocket.ReturnHead(ActResult: TActionResult); begin // 反馈协议头给客户端(响应、其他消息) // 格式:IOCP_HEAD_FLAG + TMsgHead // 更新协议头信息 FResult.FDataSize := 0; FResult.FAttachSize := 0; FResult.FActResult := ActResult; if (FResult.FAction = atUnknown) then // 响应 FResult.FVarCount := FObjPool.UsedCount // 返回客户端数 else FResult.FVarCount := 0; // 直接写入 FSender 的发送缓存 FResult.LoadHead(FSender.Data); // 发送 FSender.SendBuffers; end; procedure TIOCPSocket.ReturnMessage(ActResult: TActionResult; const ErrMsg: String); begin // 反馈协议头给客户端 FParams.Clear; FResult.Clear; if (ErrMsg <> '') then begin FResult.Msg := ErrMsg; FResult.ActResult := ActResult; ReturnResult; end else ReturnHead(ActResult); case ActResult of arOffline: iocp_log.WriteLog(Self.ClassName + '->客户端未登录.'); arOutDate: iocp_log.WriteLog(Self.ClassName + '->凭证/认证过期.'); arErrAnalyse: iocp_log.WriteLog(Self.ClassName + '->变量解析异常.'); arErrHash: iocp_log.WriteLog(Self.ClassName + '->校验异常!'); arErrWork: iocp_log.WriteLog(Self.ClassName + '->执行异常, ' + ErrMsg); end; end; procedure TIOCPSocket.ReturnResult; procedure SendMsgHeader; begin // 发送协议头(描述) FResult.LoadHead(FSender.Data); FSender.SendBuffers; end; procedure SendMsgEntity; begin // 发送主体数据流 {$IFDEF TRANSMIT_FILE} // 设置主体数据流 FTask.SetTask(FResult.FMain, FResult.FDataSize); {$ELSE} FSender.Send(FResult.FMain, FResult.FDataSize, False); // 不关闭资源 {$ENDIF} end; procedure SendMsgAttachment; begin // 发送附件数据 {$IFDEF TRANSMIT_FILE} // 设置附件数据流 if (FResult.FAction = atFileDownChunk) then FTask.SetTask(FResult.FAttachment, FResult.FAttachSize, FResult.FOffset, FResult.FOffsetEnd) else FTask.SetTask(FResult.FAttachment, FResult.FAttachSize); {$ELSE} if (FResult.FAction = atFileDownChunk) then // 不关闭资源 FSender.Send(FResult.FAttachment, FResult.FAttachSize, FResult.FOffset, FResult.FOffsetEnd, False) else FSender.Send(FResult.FAttachment, FResult.FAttachSize, False); {$ENDIF} end; begin // 发送结果给客户端,不用请求,直接发送 // 附件流是 TIOCPDocument,还要用,不能释放 // 见:TIOCPSocket.HandleDataPack; TClientParams.InternalSend // FSender.Socket、Owner 已经设置 try // 1. 准备数据流 FResult.CreateStreams; if (FResult.Error = False) then begin // 2. 发协议头 SendMsgHeader; // 3. 主体数据(内存流) if (FResult.FDataSize > 0) then SendMsgEntity; // 4. 发送附件数据 if (FResult.FAttachSize > 0) then SendMsgAttachment; end; finally {$IFDEF TRANSMIT_FILE} InterTransmit; {$ELSE} FResult.NilStreams(False); // 5. 清空,暂不释放附件流 {$ENDIF} end; end; procedure TIOCPSocket.SocketError(IOType: TIODataType); begin // 处理收发异常 if (IOType in [ioDelete, ioPush, ioRefuse]) then // 推送 FResult.ActResult := arErrPush; inherited; end; procedure TIOCPSocket.SetLogState(AEnvir: PEnvironmentVar); begin // 设置登录/登出信息 if (AEnvir = nil) then // 登出 begin SetLogoutState; FResult.FSessionId := FSessionId; FResult.ActResult := arLogout; // 不是 arOffline if Assigned(FEnvir) then // 不关联到 Socket FEnvir := nil; end else begin FSessionId := CreateSession; // 重建对话期 FResult.FSessionId := FSessionId; FResult.ActResult := arOK; FEnvir := AEnvir; end; end; function TIOCPSocket.SessionValid(ASession: Cardinal): Boolean; var NowTime: TDateTime; Certify: TCertifyNumber; LHour, LMinute, LSecond, LMilliSecond: Word; begin // 检查凭证是否正确且没超时 // 结构:(相对日序号 + 有效分钟) xor 年 NowTime := Now(); DecodeTime(NowTime, LHour, LMinute, LSecond, LMilliSecond); LMinute := LHour * 60 + LMinute; // 临时存放 LSecond := Trunc(NowTime - 43000); // 临时存放 Certify.Session := ASession xor Cardinal($AB12); Result := (Certify.DayCount = LSecond) and (Certify.Timeout > LMinute) or (Certify.DayCount = LSecond + 1) and (Certify.Timeout > (1440 - LMinute)); if Result then FSessionId := Certify.Session; end; { THttpSocket } procedure THttpSocket.ClearResources; begin // 清除资源 CloseStream; if Assigned(FRequest) then FRequest.Clear; if Assigned(FResponse) then FResponse.Clear; {$IFDEF TRANSMIT_FILE} if Assigned(FTask) then FTask.FreeResources(False); // 已在 FResult.Clear 释放 {$ENDIF} end; procedure THttpSocket.CloseStream; begin if Assigned(FStream) then begin FStream.Free; FStream := Nil; end; end; procedure THttpSocket.CreateStream(const FileName: String); begin // 建文件流 FStream := TFileStream.Create(FileName, fmCreate or fmOpenWrite); end; procedure THttpSocket.DecodeHttpRequest; begin // 请求命令解码(单数据包) // 在业务线程建 FRequest、FResponse,加快接入速度 if (FRequest = nil) then FRequest := THttpRequest.Create(TInIOCPServer(FServer).HttpDataProvider, Self); // http 请求 if (FResponse = nil) then FResponse := THttpResponse.Create(TInIOCPServer(FServer).HttpDataProvider, Self); // http 应答 // 更新时间、HTTP 命令解码 FTickCount := GetTickCount; TRequestObject(FRequest).Decode(FSender, FResponse, FRecvBuf); end; destructor THttpSocket.Destroy; begin CloseStream; if Assigned(FRequest) then begin FRequest.Free; FRequest := Nil; end; if Assigned(FResponse) then begin FResponse.Free; FResponse := Nil; end; inherited; end; procedure THttpSocket.ExecuteWork; begin // 执行 Http 请求 try // 1. 使用 C/S 协议时,要转换为 TIOCPSocket if (FTickCount = 0) and (FByteCount = IOCP_SOCKET_FLEN) and MatchSocketType(FRecvBuf^.Data.Buf, IOCP_SOCKET_FLAG) then begin UpgradeSocket(TInIOCPServer(FServer).IOCPSocketPool); Exit; // 返回 end; // 2. 是否提供 HTTP 服务 if (Assigned(TInIOCPServer(FServer).HttpDataProvider) = False) then begin InterCloseSocket(Self); Exit; end; // 2. 命令解码 DecodeHttpRequest; // 3. 检查升级 WebSocket if (FRequest.UpgradeState > 0) then begin if FRequest.Accepted then // 升级为 WebSocket,不能返回 THttpSocket 了 begin TResponseObject(FResponse).Upgrade; UpgradeSocket(TInIOCPServer(FServer).WebSocketPool); end else // 不允许升级,关闭 InterCloseSocket(Self); Exit; // 返回 end; // 4. 执行业务 FCompleted := FRequest.Completed; // 是否接收完毕 FResponse.StatusCode := FRequest.StatusCode; if FCompleted and FRequest.Accepted and (FRequest.StatusCode < 400) then FWorker.HttpExecute(Self); // 5. 检查是否要保持连接 if not FRequest.Accepted or FRequest.Attacked then // 被攻击 FKeepAlive := False else if FCompleted or (FResponse.StatusCode >= 400) then // 接收完毕或异常 begin // 是否保存连接 FKeepAlive := FResponse.KeepAlive; // 6. 发送内容给客户端 TResponseObject(FResponse).SendWork; if {$IFNDEF TRANSMIT_FILE} FKeepAlive {$ELSE} (FTaskExists = False) {$ENDIF} then // 7. 清资源,准备下次请求 ClearResources; end else FKeepAlive := True; // 未完成,还不能关闭 // 8. 继续投放或关闭 if FKeepAlive and (FErrorCode = 0) then // 继续投放 begin {$IFDEF TRANSMIT_FILE} if (FTaskExists = False) then {$ENDIF} InternalRecv; end else InterCloseSocket(Self); // 关闭时清资源 except InterCloseSocket(Self); // 异常关闭 {$IFDEF DEBUG_MODE} iocp_log.WriteLog('THttpSocket.ExecuteHttpWork->' + GetSysErrorMessage); {$ENDIF} end; end; function THttpSocket.GetSessionId: AnsiString; begin if Assigned(FRequest) then Result := FRequest.SessionId; end; {$IFDEF TRANSMIT_FILE} procedure THttpSocket.InterFreeRes; begin // 发送完毕,释放 TransmitFile 的发送资源 try ClearResources; finally if FKeepAlive and (FErrorCode = 0) then // 继续投放 InternalRecv else InterCloseSocket(Self); end; end; {$ENDIF} procedure THttpSocket.PostEvent(IOKind: TIODataType); const REQUEST_NOT_ACCEPTABLE = HTTP_VER + ' 406 Not Acceptable'; REQUEST_TIME_OUT = HTTP_VER + ' 408 Request Time-out'; var Msg: TPushMessage; ResponseMsg: AnsiString; begin // 构造、推送一个消息头(给自己) // HTTP 服务只有 arRefuse、arTimeOut // TransmitFile 有任务或 3 秒内活动过,取消超时 if (IOKind = ioTimeOut) and CheckDelayed(GetTickCount) then Exit; if (IOKind = ioRefuse) then ResponseMsg := REQUEST_NOT_ACCEPTABLE + STR_CRLF + 'Server: ' + HTTP_SERVER_NAME + STR_CRLF + 'Date: ' + GetHttpGMTDateTime + STR_CRLF + 'Content-Length: 0' + STR_CRLF + 'Connection: Close' + STR_CRLF2 else ResponseMsg := REQUEST_TIME_OUT + STR_CRLF + 'Server: ' + HTTP_SERVER_NAME + STR_CRLF + 'Date: ' + GetHttpGMTDateTime + STR_CRLF + 'Content-Length: 0' + STR_CRLF + 'Connection: Close' + STR_CRLF2; Msg := TPushMessage.Create(Self, IOKind, Length(ResponseMsg)); System.Move(ResponseMsg[1], Msg.PushBuf^.Data.buf^, Msg.PushBuf^.Data.len); // 加入推送列表,激活线程 TInIOCPServer(FServer).PushManager.AddWork(Msg); end; procedure THttpSocket.SocketError(IOType: TIODataType); begin // 处理收发异常 if Assigned(FResponse) then // 接入时 = Nil FResponse.StatusCode := 500; // 500: Internal Server Error inherited; end; procedure THttpSocket.UpgradeSocket(SocketPool: TIOCPSocketPool); var oSocket: TBaseSocket; begin // 把 THttpSocket 转换为 TIOCPSocket 或 TWebSocket try oSocket := TBaseSocket(SocketPool.Clone(Self)); // 未建 FTask! oSocket.PostRecv; // 投放 finally InterCloseSocket(Self); // 关闭自身 end; end; procedure THttpSocket.WriteStream(Data: PAnsiChar; DataLength: Integer); begin // 保存数据到文件流 if Assigned(FStream) then FStream.Write(Data^, DataLength); end; { TReceiveJSON } constructor TReceiveJSON.Create(AOwner: TWebSocket); begin inherited Create(AOwner); FSocket := AOwner; end; { TResultJSON } constructor TResultJSON.Create(AOwner: TWebSocket); begin inherited Create(AOwner); FSocket := AOwner; end; { TWebSocket } procedure TWebSocket.BackgroundExecute; begin // 后台执行 try FTickCount := GetTickCount; FWorker.WebSocketExecute(Self); except {$IFDEF DEBUG_MODE} on E: Exception do iocp_log.WriteLog('TWebSocket.BackgroundExecute->' + E.Message); {$ENDIF} end; end; procedure TWebSocket.ClearOwnerMark; var p: PAnsiChar; begin // 清除掩码、设宿主=0 if Assigned(FInData) then // FBackground = False begin FReceiver.ClearMask(FInData, @FRecvBuf^.Overlapped); if (FMsgType = mtJSON) then // 清除 Owner, 设为 0(表示服务端) begin p := FInData; Inc(p, Length(INIOCP_JSON_FLAG)); if SearchInBuffer(p, FRecvBuf^.Overlapped.InternalHigh, '"__MSG_OWNER":') then // 区分大小写 while (p^ <> AnsiChar(',')) do begin p^ := AnsiChar('0'); Inc(p); end; end; end; end; procedure TWebSocket.ClearResources; begin FByteCount := 0; // 防止接入时被推送消息 FUserGroup := ''; FUserName := ''; FRole := crUnknown; FJSON.Clear; FResult.Clear; FReceiver.Clear; end; procedure TWebSocket.CopyResources(AMaster: TBaseSocket); var Master: TWebSocket; begin // 复制参数、结果数据,准备投入后台线程 inherited; Master := TWebSocket(AMaster); FMsgType := Master.FMsgType; FMsgSize := Master.FMsgSize; FOpCode := Master.FOpCode; FRole := Master.FRole; FPeerIP := Master.UserName; // 唤醒时要用,转义 FJSON.Initialize(Master.FJSON); // 复制字段 FResult.Initialize(Master.FResult); // 复制字段 end; constructor TWebSocket.Create(AObjPool: TIOCPSocketPool; ALinkNode: PLinkRec); begin inherited; FUserGroup := '<NULL_GROUP>'; // 无效分组 FUseTransObj := False; // 不用 TransmitFile FJSON := TReceiveJSON.Create(Self); FResult := TResultJSON.Create(Self); FResult.FServerMode := True; // 服务器模式 FReceiver := TWSServerReceiver.Create(Self, FJSON); end; destructor TWebSocket.Destroy; begin FJSON.Free; FResult.Free; FReceiver.Free; inherited; end; procedure TWebSocket.ExecuteWork; begin // 接收数据,执行任务 // 1. 接收数据 FTickCount := GetTickCount; if FReceiver.Completed then // 首数据包 begin // 分析、接收数据 // 可能改变 FMsgType,见 FReceiver.UnMarkData FMsgType := mtDefault; FReceiver.Prepare(FRecvBuf^.Data.buf, FByteCount); case FReceiver.OpCode of ocClose: begin InterCloseSocket(Self); // 关闭,返回 Exit; end; ocPing, ocPong: begin InternalRecv; // 投放,返回 Exit; end; end; end else begin // 接收后续数据包 FReceiver.Receive(FRecvBuf^.Data.buf, FByteCount); end; // 是否接收完成 FCompleted := FReceiver.Completed; // 2. 进入应用层 // 2.1 标准操作,每接收一次即进入 // 2.2 扩展的操作,是 JSON 消息,接收完毕才进入 try if (FMsgType = mtDefault) or FCompleted then begin if (FMsgType <> mtDefault) then FResult.Action := FJSON.Action; // 复制 Action FWorker.WebSocketExecute(Self); end; finally if FCompleted then // 接收完毕 begin case FMsgType of mtJSON: begin // 扩展的 JSON FJSON.Clear; // 不清 Attachment FResult.Clear; FReceiver.Clear; end; mtAttachment: begin // 扩展的附件流 FJSON.Close; // 关闭附件流 FResult.Clear; FReceiver.Clear; end; end; InternalPong; // pong 客户端 end; // 继续接收 InternalRecv; end; end; function TWebSocket.GetObjectState(const Group: string; AdminType: Boolean): Boolean; begin // 取状态,是否可以接受推送 // 同分组、已经接收过数据,有管理员权限 Result := (FByteCount > 0) and (FUserGroup = Group) and ((AdminType = False) or (FRole >= crAdmin)); end; procedure TWebSocket.InternalPong; begin // Ping 客户端,等新的信息缓存接收完成 if (FBackground = False) then begin MakeFrameHeader(FSender.Data, ocPong); FSender.SendBuffers; end; end; procedure TWebSocket.PostEvent(IOKind: TIODataType); begin // Empty end; procedure TWebSocket.SendData(const Msg: String); begin // 未封装:发送文本 if (FBackground = False) and (Msg <> '') then begin FSender.OpCode := ocText; FSender.Send(System.AnsiToUtf8(Msg)); end; end; procedure TWebSocket.SendData(const Data: PAnsiChar; Size: Cardinal); var Buf: PAnsiChar; begin // 未封装:发送内存块数据(复制 Data) if (FBackground = False) and Assigned(Data) and (Size > 0) then begin GetMem(Buf, Size); System.Move(Data^, Buf^, Size); FSender.OpCode := ocBiary; FSender.Send(Buf, Size); end; end; procedure TWebSocket.SendData(Handle: THandle); begin // 未封装:发送文件 handle(自动关闭) if (FBackground = False) and (Handle > 0) and (Handle <> INVALID_HANDLE_VALUE) then begin FSender.OpCode := ocBiary; FSender.Send(Handle, GetFileSize64(Handle)); end; end; procedure TWebSocket.SendData(Stream: TStream); begin // 未封装:发送流数据(自动释放) if (FBackground = False) and Assigned(Stream) then begin FSender.OpCode := ocBiary; FSender.Send(Stream, Stream.Size, True); end; end; procedure TWebSocket.SendDataVar(Data: Variant); begin // 未封装:发送可变类型数据 if (FBackground = False) and (VarIsNull(Data) = False) then begin FSender.OpCode := ocBiary; FSender.SendVar(Data); end; end; procedure TWebSocket.SendResult(UTF8CharSet: Boolean); begin // 发送 FResult 给客户端(InIOCP-JSON) if (FBackground = False) then begin FResult.FOwner := FJSON.FOwner; FResult.InternalSend(FSender, False); end; end; procedure TWebSocket.SetProps(AOpCode: TWSOpCode; AMsgType: TWSMsgType; AData: Pointer; AFrameSize: Int64; ARecvSize: Cardinal); begin // 更新,见:TWSServerReceiver.InitResources FMsgType := AMsgType; // 数据类型 FOpCode := AOpCode; // 操作 FMsgSize := 0; // 消息长度 FInData := AData; // 引用地址 FFrameSize := AFrameSize; // 帧长度 FFrameRecvSize := ARecvSize; // 收到帧长度 end; { TSocketBroker } procedure TSocketBroker.AssociateInner(InnerBroker: TSocketBroker); begin // 外部代理:和内部 Socket 关联起来(已经投放 WSARecv) try // 转移资源 FDualConnected := True; FDualSocket := InnerBroker.FSocket; FDualBuf := InnerBroker.FRecvBuf; FDualBuf^.Owner := Self; // 改宿主 {$IFDEF DEBUG_MODE} iocp_log.WriteLog('TSocketBroker.AssociateInner->套接字关联成功:' + FPeerIPPort + '<->' + InnerBroker.FPeerIPPort + '(内,代理)'); {$ENDIF} finally // 清除 InnerBroker 资源值,回收 InnerBroker.FRecvBuf := nil; InnerBroker.FConnected := False; InnerBroker.FDualConnected := False; InnerBroker.FSocket := INVALID_SOCKET; InnerBroker.InterCloseSocket(InnerBroker); end; end; procedure TSocketBroker.BrokerPostRecv(ASocket: TSocket; AData: PPerIOData; ACheckState: Boolean); var ByteCount, Flags: DWORD; begin // 投放 WSRecv: ASocket, AData // 正常时 FState=1,其他任何值都说明出现了异常, // FState = 1 -> 正常,否则改变了状态,关闭! if ACheckState and (InterlockedDecrement(FState) <> 0) then begin FErrorCode := 9; InterCloseSocket(Self); end else begin // 清重叠结构 FillChar(AData^.Overlapped, SizeOf(TOverlapped), 0); AData^.Owner := Self; // 宿主 AData^.IOType := ioReceive; // iocp_server 中判断用 AData^.Data.len := IO_BUFFER_SIZE; // 长度 ByteCount := 0; Flags := 0; if (iocp_Winsock2.WSARecv(ASocket, @(AData^.Data), 1, ByteCount, Flags, LPWSAOVERLAPPED(@AData^.Overlapped), nil) = SOCKET_ERROR) then begin FErrorCode := WSAGetLastError; if (FErrorCode <> ERROR_IO_PENDING) then // 异常 begin SocketError(ioReceive); InterCloseSocket(Self); // 关闭 end else FErrorCode := 0; end; end; end; procedure TSocketBroker.ClearResources; begin // 反向代理:未关联的连接被断开,向外补发连接 if TInIOCPBroker(FBroker).ReverseMode and (FSocketType = stOuterSocket) then TIOCPBrokerRef(FBroker).IncOuterConnection; if FDualConnected then // 尝试关闭 TryClose; end; procedure TSocketBroker.CreateBroker(const AServer: AnsiString; APort: Integer); begin // 新建一个内部代理(中继套接字),不能改变连接 if (FDualSocket <> INVALID_SOCKET) or (TInIOCPServer(FServer).ServerAddr = AServer) and // 不能连接到服务器自身 (TInIOCPServer(FServer).ServerPort = APort) then Exit; // 建套接字 FDualSocket := iocp_utils.CreateSocket; if (ConnectSocket(FDualSocket, AServer, APort) = False) then // 连接 begin FErrorCode := GetLastError; {$IFDEF DEBUG_MODE} iocp_log.WriteLog('TSocketBroker.CreateBroker->代理套接字连接失败:' + AServer + ':' + IntToStr(APort) + ',' + GetSysErrorMessage(FErrorCode)); {$ENDIF} end else if TInIOCPServer(FServer).IOCPEngine.BindIoCompletionPort(FDualSocket) then // 绑定 begin // 分配接收内存块 if (FDualBuf = nil) then FDualBuf := BufferPool.Pop^.Data; // 投放 FDualSocket BrokerPostRecv(FDualSocket, FDualBuf, False); if (FErrorCode = 0) then // 异常 begin FDualConnected := True; FTargetHost := AServer; FTargetPort := APort; if TInIOCPBroker(FBroker).ReverseMode then // 反向代理 begin FSocketType := stDefault; // 改变(关闭时不补充连接) TIOCPBrokerRef(FBroker).IncOuterConnection; // 向外补发连接 end; {$IFDEF DEBUG_MODE} iocp_log.WriteLog('TSocketBroker.CreateBroker->代理套接字关联成功:' + FPeerIPPort + '<->' + AServer + ':' + IntToStr(APort) + '(外,代理)'); {$ENDIF} end; end else begin FErrorCode := GetLastError; {$IFDEF DEBUG_MODE} iocp_log.WriteLog('TSocketBroker.CreateBroker->代理套接字关联失败:' + AServer + ':' + IntToStr(APort) + ',' + GetSysErrorMessage(FErrorCode)); {$ENDIF} end; end; procedure TSocketBroker.ExecuteWork; function CheckInnerSocket: Boolean; begin // ++外部代理模式,两种连接: // 1、外部客户端,数据不带 InIOCP_INNER_SOCKET // 2、内部的反向代理客户端,数据带 InIOCP_INNER_SOCKET:InnerBrokerId if (PInIOCPInnerSocket(FRecvBuf^.Data.buf)^ = InIOCP_INNER_SOCKET) then begin // 这是内部的反向代理连接,保存到列表,在 TInIOCPBroker.BindBroker 配对 SetString(FBrokerId, FRecvBuf^.Data.buf + Length(InIOCP_INNER_SOCKET) + 1, Integer(FByteCount) - Length(InIOCP_INNER_SOCKET) - 1); TIOCPBrokerRef(FBroker).AddConnection(Self, FBrokerId); Result := True; end else Result := False; // 这是外部的客户端连接 end; procedure ExecSocketAction; begin // 发送内部连接标志到外部代理 try if (TInIOCPBroker(FBroker).BrokerId = '') then // 用默认标志 FSender.Send(InIOCP_INNER_SOCKET + ':DEFAULT') else // 同时发送代理标志,方便外部代理区分 FSender.Send(InIOCP_INNER_SOCKET + ':' + UpperCase(TInIOCPBroker(FBroker).BrokerId)); finally FAction := 0; end; end; procedure CopyForwardData(ASocket, AToSocket: TSocket; AData: PPerIOData; MaskInt: Integer); begin // 不能简单互换数据块,否则大并发时 AData 被重复投放 -> 995 异常 try // 执行转发前事件:FRecvState = 1 正向,= 2 逆向 if Assigned(FOnBeforeForward) then FOnBeforeForward(Self, AData^.Data.buf, AData^.Data.len, FRecvState); FSender.Socket := AToSocket; // 发给 AToSocket FRecvState := FRecvState and MaskInt; // 去除状态 TServerTaskSender(FSender).CopySend(AData); // 发送数据 finally if (FErrorCode = 0) then BrokerPostRecv(ASocket, AData) // 继续投放 WSRecv else InterCloseSocket(Self); end; end; procedure ForwardData; begin if FCmdConnect then // 1. Http代理的 Connect 请求,响应:and (AProxyType <> ptOuter) begin FCmdConnect := False; FSender.Send(HTTP_PROXY_RESPONSE); BrokerPostRecv(FSocket, FRecvBuf); end else // 2. 转发数据 if (FRecvState and $0001 = 1) then CopyForwardData(FSocket, FDualSocket, FRecvBuf, 2) else CopyForwardData(FDualSocket, FSocket, FDualBuf, 1); end; begin // 执行: // 1、绑定、关联,发送外部数据到 FDualSocket // 2、已经关联时直接发送到 FDualSocket // 要合理设置 TInIOCPBroker.ProxyType FTickCount := GetTickCount; case TIOCPBrokerRef(FBroker).ProxyType of ptDefault: // 默认代理模式 if (FAction > 0) then // 反向代理, 见:SendInnerFlag begin ExecSocketAction; // 执行操作,返回 BrokerPostRecv(FSocket, FRecvBuf); // 投放 Exit; end; ptOuter: // 外部代理模式 if (FDualConnected = False) and CheckInnerSocket then // 是内部反向代理的连接 begin BrokerPostRecv(FSocket, FRecvBuf); // 先投放 Exit; end; end; // 开始时根据协议绑定一个方法,代理连接设置后再删除绑定 try try if Assigned(FOnBind) then // 开始时 FOnBind <> nil try FOnBind(Self, FRecvBuf^.Data.buf, FByteCount); // 绑定、关联 finally FOnBind := nil; // 删除绑定事件,以后不再绑定! end; finally if FDualConnected then // 存在代理连接设置 ForwardData // 转发数据 else InterCloseSocket(Self); end; except raise; end; end; procedure TSocketBroker.HttpBindOuter(Connection: TSocketBroker; const Data: PAnsiChar; DataSize: Cardinal); procedure GetConnectHost(var p: PAnsiChar); var pb: PAnsiChar; i: Integer; begin // 提取主机地址:CONNECT xxx:443 HTTP/1.1 Delete(FTargetHost, 1, Length(FTargetHost)); pb := nil; Inc(p, 7); // connect for i := 1 to FByteCount do begin if (p^ = #32) then if (pb = nil) then // 地址开始 pb := p else begin // 地址结束,简化判断版本 SetString(FTargetHost, pb, p - pb); FTargetHost := Trim(FTargetHost); Break; end; Inc(p); end; end; procedure GetHttpHost(var p: PAnsiChar); var pb: PAnsiChar; begin // 提取主机地址:HOST: pb := nil; Inc(p, 4); repeat case p^ of ':': if (pb = nil) then pb := p + 1; #13: begin SetString(FTargetHost, pb, p - pb); FTargetHost := Trim(FTargetHost); Exit; end; end; Inc(p); until (p^ = #10); end; procedure GetUpgradeType(var p: PAnsiChar); var S: AnsiString; pb: PAnsiChar; begin // 提取内容长度:UPGRADE: WebSocket pb := nil; Inc(p, 14); repeat case p^ of ':': pb := p + 1; #13: begin SetString(S, pb, p - pb); if (UpperCase(Trim(S)) = 'WEBSOCKET') then FSocketType := stWebSocket; Exit; end; end; Inc(p); until (p^ = #10); end; procedure ExtractHostPort; var i, j, k: Integer; begin // 分离 Host、Port 和 局域网标志 j := 0; k := 0; for i := 1 to Length(FTargetHost) do // 127.0.0.1:800@DEFAULT case FTargetHost[i] of ':': j := i; '@': // HTTP 反向代理扩展,后面为局域网/分公司标志 k := i; end; if (k > 0) then // 反向代理标志 begin if (TInIOCPBroker(FBroker).ProxyType = ptOuter) then // 外部代理才用 FBrokerId := Copy(FTargetHost, k + 1, 99); Delete(FTargetHost, k, 99); end; if (j > 0) then // 内部主机 begin TryStrToInt(Copy(FTargetHost, j + 1, 99), FTargetPort); Delete(FTargetHost, j, 99); end; end; procedure HttpRequestDecode; var iState: Integer; pE, pb, p: PAnsiChar; begin // Http 协议:提取请求信息:Host、Upgrade p := FRecvBuf^.Data.buf; // 开始位置 pE := PAnsiChar(p + FByteCount); // 结束位置 // 1、HTTP代理:Connect 命令,代理=443 if http_utils.CompareBuffer(p, 'CONNECT', True) then begin FCmdConnect := True; GetConnectHost(p); // p 改变 ExtractHostPort; Exit; end; // 2、其他 HTTP 命令 iState := 0; // 信息状态 FCmdConnect := False; FTargetPort := 80; // 默认端口,代理=443 pb := nil; Inc(p, 12); repeat case p^ of #10: // 分行符 pb := p + 1; #13: // 回车符 if (pb <> nil) then if (p = pb) then // 出现连续的回车换行,报头结束 begin Inc(p, 2); Break; end else if (p - pb >= 15) then begin if http_utils.CompareBuffer(pb, 'HOST', True) then begin Inc(iState); GetHttpHost(pb); ExtractHostPort; end else if http_utils.CompareBuffer(pb, 'UPGRADE', True) then // WebSocket begin Inc(iState, 2); GetUpgradeType(pb); end; end; end; Inc(p); until (p >= pE) or (iState = 3); end; procedure HttpConnectHost(const AServer: AnsiString; APort: Integer); begin // Http 协议:连接到请求的主机 HOST,没有时连接到参数指定的 if (FTargetHost <> '') and (FTargetPort > 0) then CreateBroker(FTargetHost, FTargetPort) else if (AServer <> '') and (APort > 0) then // 用参数指定的 CreateBroker(AServer, APort); end; var Accept: Boolean; begin // Http 协议:检查 Connect 命令和其他命令的 Host // 提取 Host 信息 HttpRequestDecode; // 不能连接到服务器自身 if (TInIOCPServer(FServer).ServerAddr = FTargetHost) and (TInIOCPServer(FServer).ServerPort = FTargetPort) then Exit; Accept := True; if Assigned(TInIOCPBroker(FBroker).OnAccept) then // 是否允许连接 TInIOCPBroker(FBroker).OnAccept(Self, FTargetHost, FTargetPort, Accept); if Accept then case TInIOCPBroker(FBroker).ProxyType of ptDefault: // 默认代理:新建连接,关联 HttpConnectHost(TInIOCPBroker(FBroker).InnerServer.ServerAddr, TInIOCPBroker(FBroker).InnerServer.ServerPort); ptOuter: // 内部代理:从内部连接池选取关联对象 TIOCPBrokerRef(FBroker).BindInnerBroker(Connection, Data, DataSize); end; end; procedure TSocketBroker.IniSocket(AServer: TObject; ASocket: TSocket; AData: Pointer); begin inherited; FRecvState := 0; FTargetHost := ''; FTargetPort := 0; FUseTransObj := False; // 不用 TransmitFile FCmdConnect := False; FDualConnected := False; // Dual 未连接 FDualSocket := INVALID_SOCKET; // 代理管理器 FBroker := TInIOCPServer(FServer).IOCPBroker; FOnBeforeForward := TInIOCPBroker(FBroker).OnBeforeForwardData; case TInIOCPBroker(FBroker).ProxyType of ptDefault: // 绑定设计界面的组件事件 if (TInIOCPBroker(FBroker).Protocol = tpHTTP) then FOnBind := HttpBindOuter else FOnBind := TInIOCPBroker(FBroker).OnBind; ptOuter: begin FBrokerId := 'DEFAULT'; // 默认的 FBrokerId FOnBind := TIOCPBrokerRef(FBroker).BindInnerBroker; // 直接配对,此时 FCmdConnect 恒为 False end; end; end; procedure TSocketBroker.InterCloseSocket(Sender: TObject); begin // 回收内存块、关闭 DualSocket if TInIOCPServer(FServer).Active and Assigned(FDualBuf) then begin BufferPool.Push(FDualBuf^.Node); FDualBuf := nil; end; if FDualConnected then try iocp_Winsock2.Shutdown(FDualSocket, SD_BOTH); iocp_Winsock2.CloseSocket(FDualSocket); finally FDualSocket := INVALID_SOCKET; FDualConnected := False; end; inherited; end; procedure TSocketBroker.MarkIODataBuf(AData: PPerIOData); begin // AData 的接收状态 if (AData = FRecvBuf) then FRecvState := FRecvState or $0001 // Windows.InterlockedIncrement(FRecvState) else FRecvState := FRecvState or $0002; // Windows.InterlockedExchangeAdd(FRecvState, 2); end; procedure TSocketBroker.PostEvent(IOKind: TIODataType); begin InterCloseSocket(Self); // 直接关闭,见 TInIOCPServer.AcceptClient end; procedure TSocketBroker.SendInnerFlag; begin // 反向代理:向外部代理发送连接标志,在 ExecSocketAction 执行 FAction := 1; // 自身操作 FState := 0; // 解锁 TInIOCPServer(FServer).BusiWorkMgr.AddWork(Self); end; procedure TSocketBroker.SetConnection(AServer: TObject; Connection: TSocket); begin // 反向代理:内部设置主动发起到外部的连接 IniSocket(AServer, Connection); FSocketType := stOuterSocket; // 连接到外部的 if (TInIOCPBroker(FBroker).Protocol = tpNone) then FOnBind := TInIOCPBroker(FBroker).OnBind; // 绑定关联事件 end; end.
unit AccidentImageViewerControl; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, GameTypes; type TAccidentImageViewerControl = class(TGraphicControl) public constructor Create(Owner : TComponent); override; destructor Destroy; override; private fVClass : integer; fBuffer : TCanvasImage; procedure SetGameImage(Img : TGameImage); private fOnClick : TNotifyEvent; protected procedure Paint; override; protected fMouseDownTicks : integer; procedure MouseDown(button: TMouseButton; shift: TShiftState; x, y: integer); override; procedure MouseUp(button: TMouseButton; shift: TShiftState; x, y: integer); override; procedure MouseClicked; published property Image : TGameImage write SetGameImage; property VClass : integer read fVClass write fVClass; published property OnClick : TNotifyEvent write fOnClick; end; implementation const cCanvasBitCount = 16; constructor TAccidentImageViewerControl.Create(Owner : TComponent); begin inherited Create(Owner); fBuffer := TCanvasImage.CreateSized(1, 1, cCanvasBitCount); end; destructor TAccidentImageViewerControl.Destroy; begin fBuffer.Free; inherited; end; procedure TAccidentImageViewerControl.SetGameImage(Img : TGameImage); begin if (fBuffer.Width <> Img.Width) or (fBuffer.Height <> Img.Width) then fBuffer.NewSize(Img.Width, Img.Height, cCanvasBitCount); Img.Draw(0, 0, 0, 0, Rect(0, 0, Img.Width, Img.Height), fBuffer, nil); end; procedure TAccidentImageViewerControl.Paint; begin inherited; if fBuffer <> nil then fBuffer.StretchDraw(Canvas, ClientRect); end; procedure TAccidentImageViewerControl.MouseDown(button: TMouseButton; shift: TShiftState; x, y: integer); begin inherited; if button = mbLeft then fMouseDownTicks := GetTickCount; end; procedure TAccidentImageViewerControl.MouseUp(button: TMouseButton; shift: TShiftState; x, y: integer); begin inherited; if (button = mbLeft) and (GetTickCount - fMouseDownTicks < 100) then MouseClicked; end; procedure TAccidentImageViewerControl.MouseClicked; begin if assigned(fOnClick) then fOnClick(Self); end; end.
unit VAT.Headers.Utils; //************************************************// // Support for VAT MTD // // VAT.Headers.Utils // // provided as is, no warranties // //************************************************// interface uses Winapi.Windows; type THMRCMTDUtils = Class class function ScreensInfo: string; class function getTimeZone: string; class function getOSUserName: string; class function getUserAgent: string; End; implementation uses FMX.Platform, System.SysUtils, FMX.Forms, System.DateUtils, System.StrUtils, System.TimeSpan, REST.Utils, uSMBIOS; { THMRCMTDUtils } Function GetDisplayBits: Integer; var ZeroDC: HDC; begin ZeroDC := GetDC(0); Try Result := GetDeviceCaps(ZeroDC,BITSPIXEL)*GetDeviceCaps(ZeroDC,PLANES); Finally ReleaseDC (0,ZeroDC); End; end; class function THMRCMTDUtils.getOSUserName: string; Var lSize: DWORD; Begin lSize := 1024; SetLength(Result, lSize); If winapi.Windows.GetUserName(PChar(Result), lSize) Then SetLength(Result, lSize - 1) Else RaiseLastOSError; end; class function THMRCMTDUtils.ScreensInfo: string; Resourcestring tpl = 'width=$W&height=$H&scaling-factor=$S&colour-depth=$C'; Var ScreenService: IFMXScreenService; lScale: Single; Begin Result := tpl.Replace('$W', Screen.Width.ToString).Replace('$H', Screen.Height.ToString) .Replace('$C', GetDisplayBits.ToString); If TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, IInterface(ScreenService)) Then Begin Result := Result.Replace('$S', ScreenService.GetScreenScale.ToString); ScreenService.GetScreenSize End Else Begin Result := Result.Replace('$S', '1'); End; end; class function THMRCMTDUtils.getTimeZone: string; Var retval: TTimeSpan; Begin retval := TTimeZone.Local.GetUtcOffset(Now); result := 'UTC' + ifThen(retval.Hours >= 0, '+') + FormatFloat('00', retval.Hours) + ':' + FormatFloat('00', retval.Minutes); End; Class Function THMRCMTDUtils.getUserAgent: String; Var i, p: Integer; ldata: TArray<String>; bios: TSMBios; Begin ldata := TOSVersion.ToString.Split(['(']); Result := ldata[0].Trim.Replace(' ', '/'); // wmic computersystem get model, manufacturer bios := TSMBios.Create(); Try Result := Result + ' (' + URIEncode(bios.SysInfo.ManufacturerStr) + '/' + URIEncode(bios.SysInfo.ProductNameStr) + ')'; Finally bios.Free; End; End; end.
unit evTreeStorable; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Everest" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/Everest/evTreeStorable.pas" // Начат: 16.12.2004 18:48 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::Everest::DataObjects::TevTreeStorable // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\Everest\evDefine.inc} interface uses nevBase, k2Const, nevTools, evStorable, evdInterfaces ; type TevTreeStorableData = record rTree : InevSimpleTree; rLevelTag : Integer; rFlag : Word; end;//TevTreeStorableData TevTreeStorable = class(TevStorable) private // private fields f_LevelTag : Integer; f_Flag : Word; f_LevelIndent : Integer; {* Поле для свойства LevelIndent} f_Data : InevSimpleTree; {* Поле для свойства Data} f_SubRoot : InevSimpleNode; {* Поле для свойства SubRoot} protected // realized methods procedure DoStore(const G: InevTagGenerator; aFlags: TevdStoreFlags); override; protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; protected // protected methods procedure DoStoreNode(const aNode: InevSimpleNode; const G: InevTagGenerator; aLevel: Integer); procedure DoIterateTree(const G: InevTagGenerator; aFlags: TevStoreFlags = evDefaultStoreFlags); virtual; public // public methods constructor Create(const aData: TevTreeStorableData; const aReader: InevTagReader; aLevelIndent: Integer; const aSubRoot: InevSimpleNode); reintroduce; class function Make(const aData: TevTreeStorableData; const aReader: InevTagReader = nil; aLevelIndent: Integer = 2; const aSubRoot: InevSimpleNode = nil): IevdDataObject; reintroduce; class function MakeStorable(const aData: TevTreeStorableData; const aReader: InevTagReader = nil; aLevelIndent: Integer = 2; const aSubRoot: InevSimpleNode = nil): InevStorable; reintroduce; protected // protected properties property Data: InevSimpleTree read f_Data; property SubRoot: InevSimpleNode read f_SubRoot; public // public properties property LevelIndent: Integer read f_LevelIndent write f_LevelIndent; end;//TevTreeStorable function TevTreeStorableData_C(const aTree: InevSimpleTree; aLevelTag: Integer = k2_tiVoid; aFlag: Word = 0): TevTreeStorableData; implementation uses l3Defaults, l3Base, nevPersistentDocumentContainer, k2Tags, SysUtils, l3TreeInterfaces, l3Nodes, TextPara_Const, Document_Const ; function TevTreeStorableData_C(const aTree: InevSimpleTree; aLevelTag: Integer = k2_tiVoid; aFlag: Word = 0): TevTreeStorableData; //#UC START# *48FC65A403CF_48FC655F025C_var* //#UC END# *48FC65A403CF_48FC655F025C_var* begin System.FillChar(Result, SizeOf(Result), 0); //#UC START# *48FC65A403CF_48FC655F025C_impl* Result.rTree := aTree; Result.rLevelTag := aLevelTag; Result.rFlag := aFlag; //#UC END# *48FC65A403CF_48FC655F025C_impl* end;//TevTreeStorableData.C // start class TevTreeStorable procedure TevTreeStorable.DoStoreNode(const aNode: InevSimpleNode; const G: InevTagGenerator; aLevel: Integer); //#UC START# *48F8A8CD00D9_48F8A8480224_var* const cIndentUnit = def_FirstIndent div 2; var l_LevelValueMultiplier : Integer; l_DataObj : IevTreeDataObject; //#UC END# *48F8A8CD00D9_48F8A8480224_var* begin //#UC START# *48F8A8CD00D9_48F8A8480224_impl* if aLevel > 0 then begin if (f_LevelTag in [k2_tiFirstIndent, k2_tiLeftIndent]) then l_LevelValueMultiplier := cIndentUnit * f_LevelIndent else l_LevelValueMultiplier := 1; if Supports(aNode, IevTreeDataObject, l_DataObj) then begin try l_DataObj.Store(G, f_LevelTag, (aLevel-1) * l_LevelValueMultiplier); finally l_DataObj := nil; end; {try..finally} end else begin G.StartChild(k2_idTextPara); try G.AddPCharLenAtom(k2_tiText, aNode.Text); G.AddIntegerAtom(f_LevelTag, (aLevel-1) * l_LevelValueMultiplier); if f_LevelTag = k2_tiLeftIndent then G.AddIntegerAtom(k2_tiFirstIndent, (aLevel-1) * l_LevelValueMultiplier); finally G.Finish; end;//try..finally end; {if..} end;//aLevel > 0 //#UC END# *48F8A8CD00D9_48F8A8480224_impl* end;//TevTreeStorable.DoStoreNode procedure TevTreeStorable.DoIterateTree(const G: InevTagGenerator; aFlags: TevStoreFlags = evDefaultStoreFlags); //#UC START# *48F8A8F501DD_48F8A8480224_var* function lpIterate(const aIntf : InevSimpleNode) : Boolean; begin//AddChildren Result := True; DoStoreNode(aIntf, G, aIntf.GetLevelFor(f_Data.RootNode)); end;//AddChildren var l_ETree : Il3ExpandedSimpleTree; //#UC END# *48F8A8F501DD_48F8A8480224_var* begin //#UC START# *48F8A8F501DD_48F8A8480224_impl* if (f_Flag <> 0) AND Supports(f_Data, Il3ExpandedSimpleTree, l_ETree) then try l_ETree.FlagIterateF(l3L2SNA(@lpIterate), f_Flag, 0, f_SubRoot); finally l_ETree := nil; end//try..finally else f_Data.SimpleIterateF(L3L2SNA(@lpIterate), 0, f_SubRoot); //#UC END# *48F8A8F501DD_48F8A8480224_impl* end;//TevTreeStorable.DoIterateTree constructor TevTreeStorable.Create(const aData: TevTreeStorableData; const aReader: InevTagReader; aLevelIndent: Integer; const aSubRoot: InevSimpleNode); //#UC START# *48F8A91F004B_48F8A8480224_var* var l_Reader : InevTagReader; //#UC END# *48F8A91F004B_48F8A8480224_var* begin //#UC START# *48F8A91F004B_48F8A8480224_impl* f_Data := aData.rTree; f_LevelTag := aData.rLevelTag; f_Flag := aData.rFlag; if (f_LevelTag = k2_tiVoid) then f_LevelTag := k2_tiFirstIndent; if (aReader = nil) then l_Reader := TnevPersistentDocumentContainer.Make.TagReader else l_Reader := aReader; inherited Create(l_Reader); f_LevelIndent := aLevelIndent; f_SubRoot := aSubRoot; //#UC END# *48F8A91F004B_48F8A8480224_impl* end;//TevTreeStorable.Create class function TevTreeStorable.Make(const aData: TevTreeStorableData; const aReader: InevTagReader = nil; aLevelIndent: Integer = 2; const aSubRoot: InevSimpleNode = nil): IevdDataObject; var l_Inst : TevTreeStorable; begin l_Inst := Create(aData, aReader, aLevelIndent, aSubRoot); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; class function TevTreeStorable.MakeStorable(const aData: TevTreeStorableData; const aReader: InevTagReader = nil; aLevelIndent: Integer = 2; const aSubRoot: InevSimpleNode = nil): InevStorable; var l_Inst : TevTreeStorable; begin l_Inst := Create(aData, aReader, aLevelIndent, aSubRoot); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; procedure TevTreeStorable.DoStore(const G: InevTagGenerator; aFlags: TevdStoreFlags); //#UC START# *48F48C6E02F4_48F8A8480224_var* //#UC END# *48F48C6E02F4_48F8A8480224_var* begin //#UC START# *48F48C6E02F4_48F8A8480224_impl* G.Start; try G.StartChild(k2_idDocument); try DoIterateTree(G, aFlags); finally G.Finish; end;//try..finally finally G.Finish; end;//try..finally //#UC END# *48F48C6E02F4_48F8A8480224_impl* end;//TevTreeStorable.DoStore procedure TevTreeStorable.Cleanup; //#UC START# *479731C50290_48F8A8480224_var* //#UC END# *479731C50290_48F8A8480224_var* begin //#UC START# *479731C50290_48F8A8480224_impl* f_Data := nil; f_SubRoot := nil; inherited; //#UC END# *479731C50290_48F8A8480224_impl* end;//TevTreeStorable.Cleanup procedure TevTreeStorable.ClearFields; {-} begin f_Data := nil; f_SubRoot := nil; inherited; end;//TevTreeStorable.ClearFields end.
namespace Sugar.Test; interface uses Sugar, Sugar.Cryptography, RemObjects.Elements.EUnit; type UtilsTest = public class (Test) public method ToHexString; method FromHexString; end; implementation method UtilsTest.ToHexString; begin var Data: array of Byte := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; Assert.AreEqual(Utils.ToHexString(Data), "000102030405060708090A0B0C0D0E0F"); Assert.AreEqual(Utils.ToHexString(Data, 5), "0001020304"); Assert.AreEqual(Utils.ToHexString(Data, 9, 3), "090A0B"); Assert.AreEqual(Utils.ToHexString(Data, 0), ""); Assert.AreEqual(Utils.ToHexString(MessageDigest.ComputeHash([], DigestAlgorithm.MD5)), "D41D8CD98F00B204E9800998ECF8427E"); Assert.AreEqual(Utils.ToHexString(MessageDigest.ComputeHash(Encoding.UTF8.GetBytes("Hello"), DigestAlgorithm.SHA1)), "F7FF9E8B7BB2E09B70935A5D785E0CC5D9D0ABF0"); Assert.Throws(->Utils.ToHexString(nil)); Assert.Throws(->Utils.ToHexString(Data, -1)); Assert.Throws(->Utils.ToHexString(Data, 55)); Assert.Throws(->Utils.ToHexString(Data, -1, 1)); Assert.Throws(->Utils.ToHexString(Data, 1, -1)); Assert.Throws(->Utils.ToHexString(Data, 54, 1)); Assert.Throws(->Utils.ToHexString(Data, 1, 54)); end; method UtilsTest.FromHexString; begin var Data: String := "000102030405060708090A0B0C0D0E0F"; Assert.AreEqual(Utils.FromHexString(Data), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); Assert.AreEqual(Utils.FromHexString("D41D8CD98F00B204E9800998ECF8427E"), MessageDigest.ComputeHash([], DigestAlgorithm.MD5)); Assert.AreEqual(Utils.FromHexString(""), []); Assert.Throws(->Utils.FromHexString(nil)); Assert.Throws(->Utils.FromHexString("FFF")); Assert.Throws(->Utils.FromHexString("FFFZ")); Assert.Throws(->Utils.FromHexString(#13#10)); end; end.
unit TTSUTLTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSUTLRecord = record PLenderNum: String[4]; PUtlNumber: String[20]; PModCount: Integer; PName1: String[40]; PName2: String[40]; PAddr1: String[40]; PAddr2: String[40]; PCity: String[25]; PState: String[2]; PZip: String[10]; PPropCity: String[25]; PPropState: String[2]; PPropZip: String[10]; PCategory: String[8]; PDescription: String[25]; PReference: String[25]; PExpireDate: String[10]; PAgentID: String[8]; PInceptionDate: String[10]; PUserName: String[10]; PDateStamp: String[17]; PCollLookup: String[15]; PValue1: Currency; PValue2: Currency; PDesc1: String[60]; PDesc2: String[60]; PDesc3: String[60]; PDesc4: String[60]; PLoanCifNumber: String[20]; PApplied: Boolean; PAppLoanNum: String[20]; PAppCollNum: Integer; PAppCategory: String[8]; PAppSubNum: Integer; PAppCifFlag: String[1]; PSpFlags: String[9]; PDocumentID: String[9]; PPayeeCode: String[8]; PPremAmt: Currency; PPremDueDate: String[10]; PCovAmt: Currency; End; TTTSUTLBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSUTLRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSUTL = (TTSUTLPrimaryKey, TTSUTLByName, TTSUTLByReference, TTSUTLByCategory, TTSUTLByCollLookup, TTSUTLByUTLNumber); TTTSUTLTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFUtlNumber: TStringField; FDFModCount: TIntegerField; FDFName1: TStringField; FDFName2: TStringField; FDFAddr1: TStringField; FDFAddr2: TStringField; FDFCity: TStringField; FDFState: TStringField; FDFZip: TStringField; FDFPropCity: TStringField; FDFPropState: TStringField; FDFPropZip: TStringField; FDFCategory: TStringField; FDFDescription: TStringField; FDFReference: TStringField; FDFExpireDate: TStringField; FDFAgentID: TStringField; FDFInceptionDate: TStringField; FDFUserName: TStringField; FDFDateStamp: TStringField; FDFCollLookup: TStringField; FDFValue1: TCurrencyField; FDFValue2: TCurrencyField; FDFDesc1: TStringField; FDFDesc2: TStringField; FDFDesc3: TStringField; FDFDesc4: TStringField; FDFLoanCifNumber: TStringField; FDFApplied: TBooleanField; FDFAppLoanNum: TStringField; FDFAppCollNum: TIntegerField; FDFAppCategory: TStringField; FDFAppSubNum: TIntegerField; FDFAppCifFlag: TStringField; FDFSpFlags: TStringField; FDFDocumentID: TStringField; FDFPayeeCode: TStringField; FDFPremAmt: TCurrencyField; FDFPremDueDate: TStringField; FDFCovAmt: TCurrencyField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPUtlNumber(const Value: String); function GetPUtlNumber:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetPName1(const Value: String); function GetPName1:String; procedure SetPName2(const Value: String); function GetPName2:String; procedure SetPAddr1(const Value: String); function GetPAddr1:String; procedure SetPAddr2(const Value: String); function GetPAddr2:String; procedure SetPCity(const Value: String); function GetPCity:String; procedure SetPState(const Value: String); function GetPState:String; procedure SetPZip(const Value: String); function GetPZip:String; procedure SetPPropCity(const Value: String); function GetPPropCity:String; procedure SetPPropState(const Value: String); function GetPPropState:String; procedure SetPPropZip(const Value: String); function GetPPropZip:String; procedure SetPCategory(const Value: String); function GetPCategory:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPReference(const Value: String); function GetPReference:String; procedure SetPExpireDate(const Value: String); function GetPExpireDate:String; procedure SetPAgentID(const Value: String); function GetPAgentID:String; procedure SetPInceptionDate(const Value: String); function GetPInceptionDate:String; procedure SetPUserName(const Value: String); function GetPUserName:String; procedure SetPDateStamp(const Value: String); function GetPDateStamp:String; procedure SetPCollLookup(const Value: String); function GetPCollLookup:String; procedure SetPValue1(const Value: Currency); function GetPValue1:Currency; procedure SetPValue2(const Value: Currency); function GetPValue2:Currency; procedure SetPDesc1(const Value: String); function GetPDesc1:String; procedure SetPDesc2(const Value: String); function GetPDesc2:String; procedure SetPDesc3(const Value: String); function GetPDesc3:String; procedure SetPDesc4(const Value: String); function GetPDesc4:String; procedure SetPLoanCifNumber(const Value: String); function GetPLoanCifNumber:String; procedure SetPApplied(const Value: Boolean); function GetPApplied:Boolean; procedure SetPAppLoanNum(const Value: String); function GetPAppLoanNum:String; procedure SetPAppCollNum(const Value: Integer); function GetPAppCollNum:Integer; procedure SetPAppCategory(const Value: String); function GetPAppCategory:String; procedure SetPAppSubNum(const Value: Integer); function GetPAppSubNum:Integer; procedure SetPAppCifFlag(const Value: String); function GetPAppCifFlag:String; procedure SetPSpFlags(const Value: String); function GetPSpFlags:String; procedure SetPDocumentID(const Value: String); function GetPDocumentID:String; procedure SetPPayeeCode(const Value: String); function GetPPayeeCode:String; procedure SetPPremAmt(const Value: Currency); function GetPPremAmt:Currency; procedure SetPPremDueDate(const Value: String); function GetPPremDueDate:String; procedure SetPCovAmt(const Value: Currency); function GetPCovAmt:Currency; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSUTL); function GetEnumIndex: TEITTSUTL; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; override; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSUTLRecord; procedure StoreDataBuffer(ABuffer:TTTSUTLRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFUtlNumber: TStringField read FDFUtlNumber; property DFModCount: TIntegerField read FDFModCount; property DFName1: TStringField read FDFName1; property DFName2: TStringField read FDFName2; property DFAddr1: TStringField read FDFAddr1; property DFAddr2: TStringField read FDFAddr2; property DFCity: TStringField read FDFCity; property DFState: TStringField read FDFState; property DFZip: TStringField read FDFZip; property DFPropCity: TStringField read FDFPropCity; property DFPropState: TStringField read FDFPropState; property DFPropZip: TStringField read FDFPropZip; property DFCategory: TStringField read FDFCategory; property DFDescription: TStringField read FDFDescription; property DFReference: TStringField read FDFReference; property DFExpireDate: TStringField read FDFExpireDate; property DFAgentID: TStringField read FDFAgentID; property DFInceptionDate: TStringField read FDFInceptionDate; property DFUserName: TStringField read FDFUserName; property DFDateStamp: TStringField read FDFDateStamp; property DFCollLookup: TStringField read FDFCollLookup; property DFValue1: TCurrencyField read FDFValue1; property DFValue2: TCurrencyField read FDFValue2; property DFDesc1: TStringField read FDFDesc1; property DFDesc2: TStringField read FDFDesc2; property DFDesc3: TStringField read FDFDesc3; property DFDesc4: TStringField read FDFDesc4; property DFLoanCifNumber: TStringField read FDFLoanCifNumber; property DFApplied: TBooleanField read FDFApplied; property DFAppLoanNum: TStringField read FDFAppLoanNum; property DFAppCollNum: TIntegerField read FDFAppCollNum; property DFAppCategory: TStringField read FDFAppCategory; property DFAppSubNum: TIntegerField read FDFAppSubNum; property DFAppCifFlag: TStringField read FDFAppCifFlag; property DFSpFlags: TStringField read FDFSpFlags; property DFDocumentID: TStringField read FDFDocumentID; property DFPayeeCode: TStringField read FDFPayeeCode; property DFPremAmt: TCurrencyField read FDFPremAmt; property DFPremDueDate: TStringField read FDFPremDueDate; property DFCovAmt: TCurrencyField read FDFCovAmt; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PUtlNumber: String read GetPUtlNumber write SetPUtlNumber; property PModCount: Integer read GetPModCount write SetPModCount; property PName1: String read GetPName1 write SetPName1; property PName2: String read GetPName2 write SetPName2; property PAddr1: String read GetPAddr1 write SetPAddr1; property PAddr2: String read GetPAddr2 write SetPAddr2; property PCity: String read GetPCity write SetPCity; property PState: String read GetPState write SetPState; property PZip: String read GetPZip write SetPZip; property PPropCity: String read GetPPropCity write SetPPropCity; property PPropState: String read GetPPropState write SetPPropState; property PPropZip: String read GetPPropZip write SetPPropZip; property PCategory: String read GetPCategory write SetPCategory; property PDescription: String read GetPDescription write SetPDescription; property PReference: String read GetPReference write SetPReference; property PExpireDate: String read GetPExpireDate write SetPExpireDate; property PAgentID: String read GetPAgentID write SetPAgentID; property PInceptionDate: String read GetPInceptionDate write SetPInceptionDate; property PUserName: String read GetPUserName write SetPUserName; property PDateStamp: String read GetPDateStamp write SetPDateStamp; property PCollLookup: String read GetPCollLookup write SetPCollLookup; property PValue1: Currency read GetPValue1 write SetPValue1; property PValue2: Currency read GetPValue2 write SetPValue2; property PDesc1: String read GetPDesc1 write SetPDesc1; property PDesc2: String read GetPDesc2 write SetPDesc2; property PDesc3: String read GetPDesc3 write SetPDesc3; property PDesc4: String read GetPDesc4 write SetPDesc4; property PLoanCifNumber: String read GetPLoanCifNumber write SetPLoanCifNumber; property PApplied: Boolean read GetPApplied write SetPApplied; property PAppLoanNum: String read GetPAppLoanNum write SetPAppLoanNum; property PAppCollNum: Integer read GetPAppCollNum write SetPAppCollNum; property PAppCategory: String read GetPAppCategory write SetPAppCategory; property PAppSubNum: Integer read GetPAppSubNum write SetPAppSubNum; property PAppCifFlag: String read GetPAppCifFlag write SetPAppCifFlag; property PSpFlags: String read GetPSpFlags write SetPSpFlags; property PDocumentID: String read GetPDocumentID write SetPDocumentID; property PPayeeCode: String read GetPPayeeCode write SetPPayeeCode; property PPremAmt: Currency read GetPPremAmt write SetPPremAmt; property PPremDueDate: String read GetPPremDueDate write SetPPremDueDate; property PCovAmt: Currency read GetPCovAmt write SetPCovAmt; published property Active write SetActive; property EnumIndex: TEITTSUTL read GetEnumIndex write SetEnumIndex; end; { TTTSUTLTable } procedure Register; implementation function TTTSUTLTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TTTSUTLTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TTTSUTLTable.GenerateNewFieldName } function TTTSUTLTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TTTSUTLTable.CreateField } procedure TTTSUTLTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFUtlNumber := CreateField( 'UtlNumber' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFName1 := CreateField( 'Name1' ) as TStringField; FDFName2 := CreateField( 'Name2' ) as TStringField; FDFAddr1 := CreateField( 'Addr1' ) as TStringField; FDFAddr2 := CreateField( 'Addr2' ) as TStringField; FDFCity := CreateField( 'City' ) as TStringField; FDFState := CreateField( 'State' ) as TStringField; FDFZip := CreateField( 'Zip' ) as TStringField; FDFPropCity := CreateField( 'PropCity' ) as TStringField; FDFPropState := CreateField( 'PropState' ) as TStringField; FDFPropZip := CreateField( 'PropZip' ) as TStringField; FDFCategory := CreateField( 'Category' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFReference := CreateField( 'Reference' ) as TStringField; FDFExpireDate := CreateField( 'ExpireDate' ) as TStringField; FDFAgentID := CreateField( 'AgentID' ) as TStringField; FDFInceptionDate := CreateField( 'InceptionDate' ) as TStringField; FDFUserName := CreateField( 'UserName' ) as TStringField; FDFDateStamp := CreateField( 'DateStamp' ) as TStringField; FDFCollLookup := CreateField( 'CollLookup' ) as TStringField; FDFValue1 := CreateField( 'Value1' ) as TCurrencyField; FDFValue2 := CreateField( 'Value2' ) as TCurrencyField; FDFDesc1 := CreateField( 'Desc1' ) as TStringField; FDFDesc2 := CreateField( 'Desc2' ) as TStringField; FDFDesc3 := CreateField( 'Desc3' ) as TStringField; FDFDesc4 := CreateField( 'Desc4' ) as TStringField; FDFLoanCifNumber := CreateField( 'LoanCifNumber' ) as TStringField; FDFApplied := CreateField( 'Applied' ) as TBooleanField; FDFAppLoanNum := CreateField( 'AppLoanNum' ) as TStringField; FDFAppCollNum := CreateField( 'AppCollNum' ) as TIntegerField; FDFAppCategory := CreateField( 'AppCategory' ) as TStringField; FDFAppSubNum := CreateField( 'AppSubNum' ) as TIntegerField; FDFAppCifFlag := CreateField( 'AppCifFlag' ) as TStringField; FDFSpFlags := CreateField( 'SpFlags' ) as TStringField; FDFDocumentID := CreateField( 'DocumentID' ) as TStringField; FDFPayeeCode := CreateField( 'PayeeCode' ) as TStringField; FDFPremAmt := CreateField( 'PremAmt' ) as TCurrencyField; FDFPremDueDate := CreateField( 'PremDueDate' ) as TStringField; FDFCovAmt := CreateField( 'CovAmt' ) as TCurrencyField; end; { TTTSUTLTable.CreateFields } procedure TTTSUTLTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSUTLTable.SetActive } procedure TTTSUTLTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSUTLTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSUTLTable.SetPUtlNumber(const Value: String); begin DFUtlNumber.Value := Value; end; function TTTSUTLTable.GetPUtlNumber:String; begin result := DFUtlNumber.Value; end; procedure TTTSUTLTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TTTSUTLTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TTTSUTLTable.SetPName1(const Value: String); begin DFName1.Value := Value; end; function TTTSUTLTable.GetPName1:String; begin result := DFName1.Value; end; procedure TTTSUTLTable.SetPName2(const Value: String); begin DFName2.Value := Value; end; function TTTSUTLTable.GetPName2:String; begin result := DFName2.Value; end; procedure TTTSUTLTable.SetPAddr1(const Value: String); begin DFAddr1.Value := Value; end; function TTTSUTLTable.GetPAddr1:String; begin result := DFAddr1.Value; end; procedure TTTSUTLTable.SetPAddr2(const Value: String); begin DFAddr2.Value := Value; end; function TTTSUTLTable.GetPAddr2:String; begin result := DFAddr2.Value; end; procedure TTTSUTLTable.SetPCity(const Value: String); begin DFCity.Value := Value; end; function TTTSUTLTable.GetPCity:String; begin result := DFCity.Value; end; procedure TTTSUTLTable.SetPState(const Value: String); begin DFState.Value := Value; end; function TTTSUTLTable.GetPState:String; begin result := DFState.Value; end; procedure TTTSUTLTable.SetPZip(const Value: String); begin DFZip.Value := Value; end; function TTTSUTLTable.GetPZip:String; begin result := DFZip.Value; end; procedure TTTSUTLTable.SetPPropCity(const Value: String); begin DFPropCity.Value := Value; end; function TTTSUTLTable.GetPPropCity:String; begin result := DFPropCity.Value; end; procedure TTTSUTLTable.SetPPropState(const Value: String); begin DFPropState.Value := Value; end; function TTTSUTLTable.GetPPropState:String; begin result := DFPropState.Value; end; procedure TTTSUTLTable.SetPPropZip(const Value: String); begin DFPropZip.Value := Value; end; function TTTSUTLTable.GetPPropZip:String; begin result := DFPropZip.Value; end; procedure TTTSUTLTable.SetPCategory(const Value: String); begin DFCategory.Value := Value; end; function TTTSUTLTable.GetPCategory:String; begin result := DFCategory.Value; end; procedure TTTSUTLTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TTTSUTLTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TTTSUTLTable.SetPReference(const Value: String); begin DFReference.Value := Value; end; function TTTSUTLTable.GetPReference:String; begin result := DFReference.Value; end; procedure TTTSUTLTable.SetPExpireDate(const Value: String); begin DFExpireDate.Value := Value; end; function TTTSUTLTable.GetPExpireDate:String; begin result := DFExpireDate.Value; end; procedure TTTSUTLTable.SetPAgentID(const Value: String); begin DFAgentID.Value := Value; end; function TTTSUTLTable.GetPAgentID:String; begin result := DFAgentID.Value; end; procedure TTTSUTLTable.SetPInceptionDate(const Value: String); begin DFInceptionDate.Value := Value; end; function TTTSUTLTable.GetPInceptionDate:String; begin result := DFInceptionDate.Value; end; procedure TTTSUTLTable.SetPUserName(const Value: String); begin DFUserName.Value := Value; end; function TTTSUTLTable.GetPUserName:String; begin result := DFUserName.Value; end; procedure TTTSUTLTable.SetPDateStamp(const Value: String); begin DFDateStamp.Value := Value; end; function TTTSUTLTable.GetPDateStamp:String; begin result := DFDateStamp.Value; end; procedure TTTSUTLTable.SetPCollLookup(const Value: String); begin DFCollLookup.Value := Value; end; function TTTSUTLTable.GetPCollLookup:String; begin result := DFCollLookup.Value; end; procedure TTTSUTLTable.SetPValue1(const Value: Currency); begin DFValue1.Value := Value; end; function TTTSUTLTable.GetPValue1:Currency; begin result := DFValue1.Value; end; procedure TTTSUTLTable.SetPValue2(const Value: Currency); begin DFValue2.Value := Value; end; function TTTSUTLTable.GetPValue2:Currency; begin result := DFValue2.Value; end; procedure TTTSUTLTable.SetPDesc1(const Value: String); begin DFDesc1.Value := Value; end; function TTTSUTLTable.GetPDesc1:String; begin result := DFDesc1.Value; end; procedure TTTSUTLTable.SetPDesc2(const Value: String); begin DFDesc2.Value := Value; end; function TTTSUTLTable.GetPDesc2:String; begin result := DFDesc2.Value; end; procedure TTTSUTLTable.SetPDesc3(const Value: String); begin DFDesc3.Value := Value; end; function TTTSUTLTable.GetPDesc3:String; begin result := DFDesc3.Value; end; procedure TTTSUTLTable.SetPDesc4(const Value: String); begin DFDesc4.Value := Value; end; function TTTSUTLTable.GetPDesc4:String; begin result := DFDesc4.Value; end; procedure TTTSUTLTable.SetPLoanCifNumber(const Value: String); begin DFLoanCifNumber.Value := Value; end; function TTTSUTLTable.GetPLoanCifNumber:String; begin result := DFLoanCifNumber.Value; end; procedure TTTSUTLTable.SetPApplied(const Value: Boolean); begin DFApplied.Value := Value; end; function TTTSUTLTable.GetPApplied:Boolean; begin result := DFApplied.Value; end; procedure TTTSUTLTable.SetPAppLoanNum(const Value: String); begin DFAppLoanNum.Value := Value; end; function TTTSUTLTable.GetPAppLoanNum:String; begin result := DFAppLoanNum.Value; end; procedure TTTSUTLTable.SetPAppCollNum(const Value: Integer); begin DFAppCollNum.Value := Value; end; function TTTSUTLTable.GetPAppCollNum:Integer; begin result := DFAppCollNum.Value; end; procedure TTTSUTLTable.SetPAppCategory(const Value: String); begin DFAppCategory.Value := Value; end; function TTTSUTLTable.GetPAppCategory:String; begin result := DFAppCategory.Value; end; procedure TTTSUTLTable.SetPAppSubNum(const Value: Integer); begin DFAppSubNum.Value := Value; end; function TTTSUTLTable.GetPAppSubNum:Integer; begin result := DFAppSubNum.Value; end; procedure TTTSUTLTable.SetPAppCifFlag(const Value: String); begin DFAppCifFlag.Value := Value; end; function TTTSUTLTable.GetPAppCifFlag:String; begin result := DFAppCifFlag.Value; end; procedure TTTSUTLTable.SetPSpFlags(const Value: String); begin DFSpFlags.Value := Value; end; function TTTSUTLTable.GetPSpFlags:String; begin result := DFSpFlags.Value; end; procedure TTTSUTLTable.SetPDocumentID(const Value: String); begin DFDocumentID.Value := Value; end; function TTTSUTLTable.GetPDocumentID:String; begin result := DFDocumentID.Value; end; procedure TTTSUTLTable.SetPPayeeCode(const Value: String); begin DFPayeeCode.Value := Value; end; function TTTSUTLTable.GetPPayeeCode:String; begin result := DFPayeeCode.Value; end; procedure TTTSUTLTable.SetPPremAmt(const Value: Currency); begin DFPremAmt.Value := Value; end; function TTTSUTLTable.GetPPremAmt:Currency; begin result := DFPremAmt.Value; end; procedure TTTSUTLTable.SetPPremDueDate(const Value: String); begin DFPremDueDate.Value := Value; end; function TTTSUTLTable.GetPPremDueDate:String; begin result := DFPremDueDate.Value; end; procedure TTTSUTLTable.SetPCovAmt(const Value: Currency); begin DFCovAmt.Value := Value; end; function TTTSUTLTable.GetPCovAmt:Currency; begin result := DFCovAmt.Value; end; procedure TTTSUTLTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('UtlNumber, String, 20, N'); Add('ModCount, Integer, 0, N'); Add('Name1, String, 40, N'); Add('Name2, String, 40, N'); Add('Addr1, String, 40, N'); Add('Addr2, String, 40, N'); Add('City, String, 25, N'); Add('State, String, 2, N'); Add('Zip, String, 10, N'); Add('PropCity, String, 25, N'); Add('PropState, String, 2, N'); Add('PropZip, String, 10, N'); Add('Category, String, 8, N'); Add('Description, String, 25, N'); Add('Reference, String, 25, N'); Add('ExpireDate, String, 10, N'); Add('AgentID, String, 8, N'); Add('InceptionDate, String, 10, N'); Add('UserName, String, 10, N'); Add('DateStamp, String, 17, N'); Add('CollLookup, String, 15, N'); Add('Value1, Currency, 0, N'); Add('Value2, Currency, 0, N'); Add('Desc1, String, 60, N'); Add('Desc2, String, 60, N'); Add('Desc3, String, 60, N'); Add('Desc4, String, 60, N'); Add('LoanCifNumber, String, 20, N'); Add('Applied, Boolean, 0, N'); Add('AppLoanNum, String, 20, N'); Add('AppCollNum, Integer, 0, N'); Add('AppCategory, String, 8, N'); Add('AppSubNum, Integer, 0, N'); Add('AppCifFlag, String, 1, N'); Add('SpFlags, String, 9, N'); Add('DocumentID, String, 9, N'); Add('PayeeCode, String, 8, N'); Add('PremAmt, Currency, 0, N'); Add('PremDueDate, String, 10, N'); Add('CovAmt, Currency, 0, N'); end; end; procedure TTTSUTLTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;UtlNumber, Y, Y, N, N'); Add('ByName, Applied;LenderNum;Name1, N, N, Y, N'); Add('ByReference, Applied;LenderNum;Reference, N, N, Y, N'); Add('ByCategory, Applied;LenderNum;Category;Reference, N, N, Y, N'); Add('ByCollLookup, Applied;LenderNum;CollLookup, N, N, Y, N'); Add('ByUTLNumber, UtlNumber, N, N, N, N'); end; end; procedure TTTSUTLTable.SetEnumIndex(Value: TEITTSUTL); begin case Value of TTSUTLPrimaryKey : IndexName := ''; TTSUTLByName : IndexName := 'ByName'; TTSUTLByReference : IndexName := 'ByReference'; TTSUTLByCategory : IndexName := 'ByCategory'; TTSUTLByCollLookup : IndexName := 'ByCollLookup'; TTSUTLByUTLNumber : IndexName := 'ByUTLNumber'; end; end; function TTTSUTLTable.GetDataBuffer:TTTSUTLRecord; var buf: TTTSUTLRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PUtlNumber := DFUtlNumber.Value; buf.PModCount := DFModCount.Value; buf.PName1 := DFName1.Value; buf.PName2 := DFName2.Value; buf.PAddr1 := DFAddr1.Value; buf.PAddr2 := DFAddr2.Value; buf.PCity := DFCity.Value; buf.PState := DFState.Value; buf.PZip := DFZip.Value; buf.PPropCity := DFPropCity.Value; buf.PPropState := DFPropState.Value; buf.PPropZip := DFPropZip.Value; buf.PCategory := DFCategory.Value; buf.PDescription := DFDescription.Value; buf.PReference := DFReference.Value; buf.PExpireDate := DFExpireDate.Value; buf.PAgentID := DFAgentID.Value; buf.PInceptionDate := DFInceptionDate.Value; buf.PUserName := DFUserName.Value; buf.PDateStamp := DFDateStamp.Value; buf.PCollLookup := DFCollLookup.Value; buf.PValue1 := DFValue1.Value; buf.PValue2 := DFValue2.Value; buf.PDesc1 := DFDesc1.Value; buf.PDesc2 := DFDesc2.Value; buf.PDesc3 := DFDesc3.Value; buf.PDesc4 := DFDesc4.Value; buf.PLoanCifNumber := DFLoanCifNumber.Value; buf.PApplied := DFApplied.Value; buf.PAppLoanNum := DFAppLoanNum.Value; buf.PAppCollNum := DFAppCollNum.Value; buf.PAppCategory := DFAppCategory.Value; buf.PAppSubNum := DFAppSubNum.Value; buf.PAppCifFlag := DFAppCifFlag.Value; buf.PSpFlags := DFSpFlags.Value; buf.PDocumentID := DFDocumentID.Value; buf.PPayeeCode := DFPayeeCode.Value; buf.PPremAmt := DFPremAmt.Value; buf.PPremDueDate := DFPremDueDate.Value; buf.PCovAmt := DFCovAmt.Value; result := buf; end; procedure TTTSUTLTable.StoreDataBuffer(ABuffer:TTTSUTLRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFUtlNumber.Value := ABuffer.PUtlNumber; DFModCount.Value := ABuffer.PModCount; DFName1.Value := ABuffer.PName1; DFName2.Value := ABuffer.PName2; DFAddr1.Value := ABuffer.PAddr1; DFAddr2.Value := ABuffer.PAddr2; DFCity.Value := ABuffer.PCity; DFState.Value := ABuffer.PState; DFZip.Value := ABuffer.PZip; DFPropCity.Value := ABuffer.PPropCity; DFPropState.Value := ABuffer.PPropState; DFPropZip.Value := ABuffer.PPropZip; DFCategory.Value := ABuffer.PCategory; DFDescription.Value := ABuffer.PDescription; DFReference.Value := ABuffer.PReference; DFExpireDate.Value := ABuffer.PExpireDate; DFAgentID.Value := ABuffer.PAgentID; DFInceptionDate.Value := ABuffer.PInceptionDate; DFUserName.Value := ABuffer.PUserName; DFDateStamp.Value := ABuffer.PDateStamp; DFCollLookup.Value := ABuffer.PCollLookup; DFValue1.Value := ABuffer.PValue1; DFValue2.Value := ABuffer.PValue2; DFDesc1.Value := ABuffer.PDesc1; DFDesc2.Value := ABuffer.PDesc2; DFDesc3.Value := ABuffer.PDesc3; DFDesc4.Value := ABuffer.PDesc4; DFLoanCifNumber.Value := ABuffer.PLoanCifNumber; DFApplied.Value := ABuffer.PApplied; DFAppLoanNum.Value := ABuffer.PAppLoanNum; DFAppCollNum.Value := ABuffer.PAppCollNum; DFAppCategory.Value := ABuffer.PAppCategory; DFAppSubNum.Value := ABuffer.PAppSubNum; DFAppCifFlag.Value := ABuffer.PAppCifFlag; DFSpFlags.Value := ABuffer.PSpFlags; DFDocumentID.Value := ABuffer.PDocumentID; DFPayeeCode.Value := ABuffer.PPayeeCode; DFPremAmt.Value := ABuffer.PPremAmt; DFPremDueDate.Value := ABuffer.PPremDueDate; DFCovAmt.Value := ABuffer.PCovAmt; end; function TTTSUTLTable.GetEnumIndex: TEITTSUTL; var iname : string; begin result := TTSUTLPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSUTLPrimaryKey; if iname = 'BYNAME' then result := TTSUTLByName; if iname = 'BYREFERENCE' then result := TTSUTLByReference; if iname = 'BYCATEGORY' then result := TTSUTLByCategory; if iname = 'BYCOLLLOOKUP' then result := TTSUTLByCollLookup; if iname = 'BYUTLNUMBER' then result := TTSUTLByUTLNumber; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSUTLTable, TTTSUTLBuffer ] ); end; { Register } function TTTSUTLBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..41] of string = ('LENDERNUM','UTLNUMBER','MODCOUNT','NAME1','NAME2','ADDR1' ,'ADDR2','CITY','STATE','ZIP','PROPCITY' ,'PROPSTATE','PROPZIP','CATEGORY','DESCRIPTION','REFERENCE' ,'EXPIREDATE','AGENTID','INCEPTIONDATE','USERNAME','DATESTAMP' ,'COLLLOOKUP','VALUE1','VALUE2','DESC1','DESC2' ,'DESC3','DESC4','LOANCIFNUMBER','APPLIED','APPLOANNUM' ,'APPCOLLNUM','APPCATEGORY','APPSUBNUM','APPCIFFLAG','SPFLAGS' ,'DOCUMENTID','PAYEECODE','PREMAMT','PREMDUEDATE','COVAMT' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 41) and (flist[x] <> s) do inc(x); if x <= 41 then result := x else result := 0; end; function TTTSUTLBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftInteger; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftString; 8 : result := ftString; 9 : result := ftString; 10 : result := ftString; 11 : result := ftString; 12 : result := ftString; 13 : result := ftString; 14 : result := ftString; 15 : result := ftString; 16 : result := ftString; 17 : result := ftString; 18 : result := ftString; 19 : result := ftString; 20 : result := ftString; 21 : result := ftString; 22 : result := ftString; 23 : result := ftCurrency; 24 : result := ftCurrency; 25 : result := ftString; 26 : result := ftString; 27 : result := ftString; 28 : result := ftString; 29 : result := ftString; 30 : result := ftBoolean; 31 : result := ftString; 32 : result := ftInteger; 33 : result := ftString; 34 : result := ftInteger; 35 : result := ftString; 36 : result := ftString; 37 : result := ftString; 38 : result := ftString; 39 : result := ftCurrency; 40 : result := ftString; 41 : result := ftCurrency; end; end; function TTTSUTLBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PUtlNumber; 3 : result := @Data.PModCount; 4 : result := @Data.PName1; 5 : result := @Data.PName2; 6 : result := @Data.PAddr1; 7 : result := @Data.PAddr2; 8 : result := @Data.PCity; 9 : result := @Data.PState; 10 : result := @Data.PZip; 11 : result := @Data.PPropCity; 12 : result := @Data.PPropState; 13 : result := @Data.PPropZip; 14 : result := @Data.PCategory; 15 : result := @Data.PDescription; 16 : result := @Data.PReference; 17 : result := @Data.PExpireDate; 18 : result := @Data.PAgentID; 19 : result := @Data.PInceptionDate; 20 : result := @Data.PUserName; 21 : result := @Data.PDateStamp; 22 : result := @Data.PCollLookup; 23 : result := @Data.PValue1; 24 : result := @Data.PValue2; 25 : result := @Data.PDesc1; 26 : result := @Data.PDesc2; 27 : result := @Data.PDesc3; 28 : result := @Data.PDesc4; 29 : result := @Data.PLoanCifNumber; 30 : result := @Data.PApplied; 31 : result := @Data.PAppLoanNum; 32 : result := @Data.PAppCollNum; 33 : result := @Data.PAppCategory; 34 : result := @Data.PAppSubNum; 35 : result := @Data.PAppCifFlag; 36 : result := @Data.PSpFlags; 37 : result := @Data.PDocumentID; 38 : result := @Data.PPayeeCode; 39 : result := @Data.PPremAmt; 40 : result := @Data.PPremDueDate; 41 : result := @Data.PCovAmt; end; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.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. * ********************************************************************************************************************** * TERRA_Debug * Implements debug utilities *********************************************************************************************************************** } Unit TERRA_Debug; {$I terra.inc} Interface Uses TERRA_String, TERRA_Callstack; //Procedure DebugStack(S:TERRAString); Procedure DebugOpenAL; Procedure PushCallstack(ClassType:TClass; S:TERRAString); Procedure PopCallstack(); Function GetCallstack:TERRAString; Implementation Uses {$IFDEF WINDOWS}Windows,{$ENDIF} {$IFDEF FPC}lineinfo, {$ENDIF} SysUtils, TERRA_Utils, TERRA_Application, TERRA_OS, TERRA_Stack, TERRA_CollectionObjects, TERRA_Log, {$IFDEF DEBUG_GL}TERRA_DebugGL{$ELSE}TERRA_OpenGL{$ENDIF}, TERRA_AL {$IFDEF ANDROID} android_log {$ENDIF}; Var _Callstack:Stack; Procedure PushCallstack(ClassType:TClass; S:TERRAString); Begin If (_Callstack = Nil) Then _Callstack := Stack.Create(); If (ClassType <> Nil) Then S := ClassType.ClassName + '.' + S; If Pos('(',S)>0 Then IntToString(2); _Callstack.Push(StringObject.Create(S)); End; Procedure PopCallstack(); Begin _Callstack.Pop(); End; {$IFDEF WINDOWS} Type PExceptionRecord = ^TExceptionRecord; TExceptionRecord = record ExceptionCode : LongWord; ExceptionFlags : LongWord; OuterException : PExceptionRecord; ExceptionAddress : Pointer; NumberParameters : Longint; case {IsOsException:} Boolean of True: (ExceptionInformation : array [0..14] of Longint); False: (ExceptAddr: Pointer; ExceptObject: Pointer); end; Var oldRTLUnwindProc: procedure; stdcall; writeToFile : boolean = false; (*procedure MyRtlUnwind; stdcall; var PER : PExceptionRecord; procedure DoIt; var // This is done in a sub-routine because string variable is used and we want it finalized E: Exception; S:TERRAString; begin s:='--------------------------------------------------------'#13#10; s:=s+'New exception:'#13#10; if PER^.ExceptionFlags and 1=1 then // This seems to be an indication of internal Delphi exception, begin // thus we can access 'Exception' class try E := Exception( PER^.ExceptObject); if (E is Exception) then s:=s+'Delphi exception, type '+E.ClassName+', message: '+E.Message+#13#10; except end; end; DebugStack(S); MemCheck.RaiseExceptionsOnEnd := False; End; begin asm mov eax, dword ptr [EBP+8+13*4] // magic numbers - works for Delphi 7 mov PER, eax end; DoIt; asm mov esp, ebp pop ebp jmp oldRTLUnwindProc end; End;*) Procedure TERRADump(S:TERRAString); Begin Raise Exception.Create(S); End; {$ELSE} Procedure DebugStack(S:TERRAString); Var i:Integer; Frames: PPointer; Begin Frames:=ExceptFrames; For I:=0 To Pred(ExceptFrameCount) Do S := S + BackTraceStrFunc(Frames) + crLf; Log(logError,'Callstack', S); End; Procedure TERRADump(S:TERRAString); Begin DebugStack(''); RaiseError(S); While (True) Do; End; {$ENDIF} Function GetCallstack:TERRAString; Var P:StringObject; Begin Result := ''; If (_Callstack = Nil) Then Exit; P := StringObject(_Callstack.First); While P<>Nil Do Begin Result := Result + P.Value + crLf; P := StringObject(P.Next); End; End; Procedure DebugOpenAL; Var ErrorCode:Cardinal; S:TERRAString; Begin ErrorCode := alGetError; If ErrorCode = GL_NO_ERROR Then Exit; Case ErrorCode Of AL_INVALID_NAME: S := 'Invalid Name paramater passed to AL call.'; AL_INVALID_ENUM: S := 'Invalid parameter passed to AL call.'; AL_INVALID_VALUE: S := 'Invalid enum parameter value.'; AL_INVALID_OPERATION: S:= 'Invalid operation'; Else S := 'Unknown AL error.'; End; S := 'OpenAL Error ['+S+']'; TERRADump(S); End; {$IFDEF WINDOWS} Procedure InitExceptionLogging; Begin oldRTLUnwindProc := RTLUnwindProc; // RTLUnwindProc := @MyRtlUnwind; End; Initialization InitExceptionLogging; {$ENDIF} End.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.1 1/21/2004 4:03:08 PM JPMugaas InitComponent Rev 1.0 11/13/2002 08:00:12 AM JPMugaas 5-20-2002 - Started this unit. } unit IdSASLAnonymous; interface {$i IdCompilerDefines.inc} uses IdSASL, IdTCPConnection; { Implements RFC 2245 Anonymous SASL Mechanism Oxymoron if you ask me :-). } type TIdSASLAnonymous = class(TIdSASL) protected FTraceInfo : String; procedure InitComponent; override; public function IsReadyToStart: Boolean; override; class function ServiceName: TIdSASLServiceName; override; function StartAuthenticate(const AChallenge, AHost, AProtocolName : String): String; override; published property TraceInfo : String read FTraceInfo write FTraceInfo; end; implementation { TIdSASLAnonymous } procedure TIdSASLAnonymous.InitComponent; begin inherited; FSecurityLevel := 0; //broadcast on the evening news and post to every // newsgroup for good measure end; function TIdSASLAnonymous.IsReadyToStart: Boolean; begin Result := (TraceInfo <> ''); end; class function TIdSASLAnonymous.ServiceName: TIdSASLServiceName; begin Result := 'ANONYMOUS'; {Do not translate} end; function TIdSASLAnonymous.StartAuthenticate(const AChallenge, AHost, AProtocolName: String): String; begin Result := TraceInfo; end; end.
unit Tools; {$mode objfpc}{$H+} interface uses Classes, SysUtils; function min ( a: integer; b: integer) : integer; function max ( a: integer; b: integer) : integer; function hexValue ( ch: char) : integer; function midstr2 ( str: string; start:integer ; count : integer; var StrOut: shortstring) : integer; implementation function min ( a: integer; b: integer) : integer; begin if a<b then Result:= a else Result:= b; end; function max ( a: integer; b: integer) : integer; begin if a>b then Result:= a else Result:= b; end; function hexValue ( ch: char) : integer; begin case ch of '0': Result:=0; '1': Result:=1; '2': Result:=2; '3': Result:=3; '4': Result:=4; '5': Result:=5; '6': Result:=6; '7': Result:=7; '8': Result:=8; '9': Result:=9; 'A','a': Result:=10; 'B','b': Result:=11; 'C','c': Result:=12; 'D','d': Result:=13; 'E','e': Result:=14; 'F','f': Result:=15; end; end; function midstr2 ( str: string; start:integer ; count : integer; var StrOut : shortstring) : integer; var i: integer; begin for i:= start to count do begin StrOut[i - start + 1]:=str[i] ; end; StrOut[0]:= chr(count); end; end.
program COSINE ( INPUT , OUTPUT ) ; //************************************************* // compute the cosine using the expansion: // cos(x) = 1 - x**2/(2*1) + x**4/(4*3*2*1) - ... //************************************************* const EPS = 1E-14 ; var X , SX , S , T : REAL ; I , K , N : INTEGER ; begin (* HAUPTPROGRAMM *) READLN ( N ) ; for I := 1 to N do begin READLN ( X ) ; T := 1 ; K := 0 ; S := 1 ; SX := SQR ( X ) ; while ABS ( T ) > EPS * ABS ( S ) do begin K := K + 2 ; T := - T * SX / ( K * ( K - 1 ) ) ; S := S + T end (* while *) ; WRITELN ( 'input = ' , X : 20 , ' cos = ' , S : 20 , ' iter = ' , K DIV 2 ) ; end (* for *) end (* HAUPTPROGRAMM *) .
unit fpcorm_codebuilder_types_test; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcorm_codebuilder_types; type { TCodeBuiderTestClass } TCodeBuiderTestClass = class(TObject) private public constructor Create(); destructor Destroy; override; function Test: String; end; implementation { TCodeBuiderTestClass } constructor TCodeBuiderTestClass.Create; begin inherited Create; end; destructor TCodeBuiderTestClass.Destroy; begin inherited Destroy; end; function TCodeBuiderTestClass.Test: String; var aUnit: TcbUnit; aTObjectClass: TcbExternalType; aSourceCode: TStringList; begin aUnit := TcbUnit.Create(nil, 'TestUnit'); try aTObjectClass := TcbExternalType.Create(aUnit, 'TObject'); try with aUnit do begin UnitTopCommentBlock.Add('This is just a test unit man!'); with aUnit.UnitSections.AddSection do begin AddClass('TTheTestClass', True, aTObjectClass); end; end; aSourceCode := aUnit.WriteSourceCode; try Result := aSourceCode.Text; finally // aSourceCode.Free; end; finally // aTObjectClass.Free; end; finally aUnit.Free; aTObjectClass.Free; end; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.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. * ********************************************************************************************************************** * TERRA_Skybox * Implements a skybox *********************************************************************************************************************** } Unit TERRA_Skybox; {$i terra.inc} Interface Uses {$IFDEF USEDEBUGUNIT}TERRA_Debug,{$ENDIF} TERRA_String, TERRA_Utils, TERRA_Math, TERRA_Texture, TERRA_Stream, TERRA_Vector3D, TERRA_Vector2D, TERRA_Color, TERRA_ShaderFactory, TERRA_Matrix4x4, TERRA_Renderer, TERRA_VertexFormat; Type { SkyboxVertex = Packed Record Position:Vector2D; Normal:Vector3D; End; SkyboxFixedVertex = Packed Record Position:Vector3D; TexCoord:Vector2D; End;} Skybox = Class(TERRAObject) Protected _Cubemap:CubemapInterface; // Skybox textures _Textures:Array[0..5] Of Texture; _Color:Color; // Skybox color _Rotation:Single; _Vertices:VertexData; {$IFDEF PC} Procedure RenderFixedPipeline(); {$ENDIF} Public Constructor Create(SkyTexture:TERRAString); Procedure Release; Override; Procedure Render(BlendMode:Integer = 0); // Renders the skybox Property Color:TERRA_Color.Color Read _Color Write _Color; //Property Texture:CubemapTexture Read _Cubemap; Property Rotation:Single Read _Rotation Write _Rotation; End; Implementation Uses TERRA_GraphicsManager, TERRA_ResourceManager, TERRA_Log, TERRA_OS, TERRA_Camera, TERRA_Image, TERRA_BoundingBox, TERRA_Viewport; Var _SkyboxShader:ShaderInterface = Nil; _SkyboxNormalShader:ShaderInterface = Nil; (*Function GetShader_Skybox:TERRAString; Var S:TERRAString; Procedure Line(S2:TERRAString); Begin S := S + S2 + crLf; End; Begin S := ''; Line('version { 110 }'); Line('vertex {'); Line(' uniform mat4 cameraMatrix;'); Line(' uniform mat4 modelMatrix;'); Line(' uniform mat4 projectionMatrix;'); Line(' attribute vec4 terra_position;'); Line(' attribute vec2 terra_UV0;'); Line(' varying vec4 local_position;'); Line(' varying vec4 world_position;'); Line('void main() {'); Line(' local_position = terra_position;'); Line(' world_position = modelMatrix * local_position;'); Line(' gl_Position = gl_ProjectionMatrix * cameraMatrix * world_position;'); Line(' gl_TexCoord[0].st = terra_UV0; }'); Line('}'); Line('fragment {'); Line(' uniform sampler2D texture;'); Line(' uniform vec4 skyColor;'); Line('void main(){'); Line(' vec4 color = texture2D(texture, gl_TexCoord[0].st);'); Line(' gl_FragColor = color * skyColor;}'); Line('}'); Result := S; End;*) Function GetShader_Skybox(OutputMode:Integer):TERRAString; Var S:TERRAString; Procedure Line(S2:TERRAString); Begin S := S + S2 + crLf; End; Begin S := ''; Line('vertex {'); Line('varying highp vec3 normal;'); Line(' uniform mat4 projectionMatrix;'); Line(' uniform mat4 rotationMatrix;'); Line(' uniform mat4 reflectionMatrix;'); Line(' attribute highp vec4 terra_position;'); Line(' attribute highp vec3 terra_normal;'); Line(' void main() {'); Line(' gl_Position = projectionMatrix * terra_position;'); Line(' highp vec4 n = reflectionMatrix * vec4(terra_normal, 1.0);'); Line(' normal = (rotationMatrix * n).xyz;}'); Line('}'); Line('fragment {'); Line('varying highp vec3 normal;'); Line('uniform samplerCube skyTexture;'); Line('uniform lowp vec4 skyColor;'); Line(' void main() {'); Line(' highp vec3 n = normalize(normal);'); If (OutputMode And shader_OutputNormal<>0) Then Begin Line(' n *= 0.5; n += vec3(0.5, 0.5, 0.5);'); Line(' gl_FragColor = vec4(n, 0.0);}'); End Else Begin Line(' lowp vec4 sky = textureCube(skyTexture, n) * skyColor; '); Line(' gl_FragColor = vec4(sky.rgb, 1.0);}'); //Line(' gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);}'); End; Line('}'); Result := S; End; { Skybox } Constructor SkyBox.Create(SkyTexture:TERRAString); Var I, N:Integer; W,H:Integer; S:TERRAString; Img:Image; Begin _Color := ColorWhite; _Vertices := VertexData.Create([vertexFormatPosition, vertexFormatNormal], 6); If (GraphicsManager.Instance.Renderer.Features.Shaders.Avaliable) Then Begin _Cubemap := GraphicsManager.Instance.Renderer.CreateCubeMap(); _Cubemap.LoadFromFile(SkyTexture); For I:=0 To 5 Do _Textures[I] := Nil; End Else Begin _Cubemap := Nil; // Assign if possible, all 6 sides For I:=0 To 5 Do _Textures[I] := TextureManager.Instance.GetTexture(SkyTexture+'_' + CubeFaceNames[I]); End; End; // Renders the skybox Procedure Skybox.Release; Begin ReleaseObject(_Vertices); ReleaseObject(_Cubemap); End; Procedure SkyBox.Render(BlendMode:Integer); Var I:Integer; CamVertices:BoundingBoxVertices; Projection:Matrix4x4; Camera:TERRA_Camera.Camera; MyShader:ShaderInterface; View:Viewport; Graphics:GraphicsManager; Function GetNormal(V:Vector3D):Vector3D; Begin Result := VectorSubtract(V, Camera.Position); Result.Normalize; End; Begin Graphics := GraphicsManager.Instance; Graphics.Renderer.SetBlendMode(BlendMode); {$IFDEF PC} If (Not Graphics.Renderer.Features.Shaders.Avaliable) Then Begin RenderFixedPipeline(); Exit; End; {$ENDIF} If (GraphicsManager.Instance.RenderStage=renderStageNormal) Then Begin If (_SkyboxNormalShader = Nil) Then Begin _SkyboxNormalShader := Graphics.Renderer.CreateShader(); _SkyboxNormalShader.Generate('skybox_normal', GetShader_Skybox(shader_OutputNormal)); End; MyShader := _SkyboxNormalShader; End Else Begin If (_SkyboxShader = Nil) Then Begin _SkyboxShader := Graphics.Renderer.CreateShader(); _SkyboxShader.Generate('skybox', GetShader_Skybox(0)); End; MyShader := _SkyboxShader; End; If Not MyShader.IsReady() Then Exit; View := GraphicsManager.Instance.ActiveViewport; If View = Nil Then Exit; Camera := View.Camera; If Camera = Nil Then Exit; CamVertices := Camera.Frustum.Vertices; _Vertices.SetVector3D(0, vertexNormal, GetNormal(CamVertices[5])); _Vertices.SetVector3D(0, vertexPosition, VectorCreate(1.0, 0.0, 0.0)); _Vertices.CopyVertex(0, 5); _Vertices.SetVector3D(1, vertexNormal, GetNormal(CamVertices[7])); _Vertices.SetVector3D(1, vertexPosition, VectorCreate(1.0, 1.0, 0.0)); _Vertices.SetVector3D(2, vertexNormal, GetNormal(CamVertices[8])); _Vertices.SetVector3D(2, vertexPosition, VectorCreate(0.0, 1.0, 0.0)); _Vertices.CopyVertex(2, 3); _Vertices.SetVector3D(4, vertexNormal, GetNormal(CamVertices[6])); _Vertices.SetVector3D(4, vertexPosition, VectorCreate(0.0, 0.0, 0.0)); Projection := Matrix4x4Ortho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); Graphics.Renderer.BindShader(MyShader); // We need to disable zbuffer, otherwise other geometry wont be GraphicsManager correctly Graphics.Renderer.SetDepthMask(False); //glDepthRange(0.99, 1.0); Graphics.Renderer.BindSurface(_Cubemap, 0); MyShader.SetIntegerUniform('skyTexture', 0); MyShader.SetColorUniform('skyColor', _Color); MyShader.SetMat4Uniform('rotationMatrix', Matrix4x4Rotation(0, _Rotation, 0)); MyShader.SetMat4Uniform('projectionMatrix', Projection); MyShader.SetMat4Uniform('reflectionMatrix', GraphicsManager.Instance.ReflectionMatrixSky); { Graphics.Renderer.SetSourceVertexSize(SizeOf(SkyboxVertex)); Graphics.Renderer.SetAttributeSource(TERRA_POSITION_ATTRIBUTE, typeVector3D, @(V[0].Position)); Graphics.Renderer.SetAttributeSource(TERRA_NORMAL_ATTRIBUTE, typeVector3D, @(V[0].Normal));} Graphics.Renderer.SetVertexSource(_Vertices); Graphics.Renderer.DrawSource(renderTriangles, 6); // Restore zwriting Graphics.Renderer.SetDepthMask(True); //glDepthRange(0.0, 1.0); End; {$IFDEF PC} {Var _SkyGeometry:Array[0..5] Of SkyboxFixedVertex;} Procedure Skybox.RenderFixedPipeline; Var I,J:Integer; Size:Single; M,M2:Matrix4x4; Cam:Camera; Ofs:Vector3D; Graphics:GraphicsManager; Begin (* Graphics := GraphicsManager.Instance; Graphics.Renderer.SetDepthMask(False); Graphics.Renderer.SetCullMode(cullNone); //glDisable(GL_LIGHTING); Cam := GraphicsManager.Instance.MainViewport.Camera; M := GraphicsManager.Instance.MainViewport.Camera.Projection; Graphics.Renderer.SetProjectionMatrix(M); M := Cam.Transform; M.V[12] := 0; M.V[13] := 0; M.V[14] := 0; Graphics.Renderer.SetModelMatrix(M); Graphics.Renderer.SetTextureMatrix(Matrix4x4Identity); {glColor4f(1.0, 1.0, 1.0, 1.0); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY);} Size := 100; Ofs := VectorScale(VectorUniform(Size), 0.5); // Draw all 6 skybox sides For I:=0 To 5 Do If Assigned(_Textures[I]) Then Begin _Textures[I].Bind(0); _SkyGeometry[0].Position := VectorCreate(0, Size, 0); _SkyGeometry[0].TexCoord := VectorCreate2D(0, 0); _SkyGeometry[1].Position := VectorCreate(Size, Size, 0); _SkyGeometry[1].TexCoord := VectorCreate2D(1, 0); _SkyGeometry[2].Position := VectorCreate(Size, 0, 0); _SkyGeometry[2].TexCoord := VectorCreate2D(1, 1); _SkyGeometry[4].Position := VectorCreate(0, 0, 0); _SkyGeometry[4].TexCoord := VectorCreate2D(0, 1); Case I Of 1: For J:=0 To 5 Do Begin _SkyGeometry[J].Position := VectorCreate(Size-_SkyGeometry[J].Position.X, _SkyGeometry[J].Position.Y, Size-_SkyGeometry[J].Position.Z); _SkyGeometry[J].TexCoord := VectorCreate2D(_SkyGeometry[J].TexCoord.X, _SkyGeometry[J].TexCoord.Y); End; 2: For J:=0 To 5 Do Begin _SkyGeometry[J].Position := VectorCreate(_SkyGeometry[J].Position.Y, Size-_SkyGeometry[J].Position.Z, _SkyGeometry[J].Position.X); _SkyGeometry[J].TexCoord := VectorCreate2D(1-_SkyGeometry[J].TexCoord.X, _SkyGeometry[J].TexCoord.Y); End; 3: For J:=0 To 5 Do Begin _SkyGeometry[J].Position := VectorCreate(_SkyGeometry[J].Position.Y, _SkyGeometry[J].Position.Z, _SkyGeometry[J].Position.X); _SkyGeometry[J].TexCoord := VectorCreate2D(1-_SkyGeometry[J].TexCoord.X, _SkyGeometry[J].TexCoord.Y); End; 4: For J:=0 To 5 Do Begin _SkyGeometry[J].Position := VectorCreate(_SkyGeometry[J].Position.Z, _SkyGeometry[J].Position.Y, _SkyGeometry[J].Position.X); _SkyGeometry[J].TexCoord := VectorCreate2D(1-_SkyGeometry[J].TexCoord.X, _SkyGeometry[J].TexCoord.Y); End; 5: For J:=0 To 5 Do Begin _SkyGeometry[J].Position := VectorCreate(Size-_SkyGeometry[J].Position.Z, _SkyGeometry[J].Position.Y, Size-_SkyGeometry[J].Position.X); _SkyGeometry[J].TexCoord := VectorCreate2D(1-_SkyGeometry[J].TexCoord.X, _SkyGeometry[J].TexCoord.Y); End; End; _SkyGeometry[3] := _SkyGeometry[2]; _SkyGeometry[5] := _SkyGeometry[0]; For J:=0 To 5 Do _SkyGeometry[J].Position.Subtract(Ofs); { glVertexPointer(3, GL_FLOAT, SizeOf(SkyboxFixedVertex), @(_SkyGeometry[0].Position)); glTexCoordPointer(2, GL_FLOAT, SizeOf(SkyboxFixedVertex), @(_SkyGeometry[0].TexCoord)); glDrawArrays(GL_TRIANGLES, 0, 6);} End; { GraphicsManager.Instance.Internal(0 , 12); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY);} // Restore zwriting Graphics.Renderer.SetDepthMask(True);*) End; {$ENDIF} End.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Description: TNntpCli is a client for the NNTP protocol (RFC-977) Creation: December 19, 1997 Version: 6.00 EMail: http://www.overbyte.be francois.piette@overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 1997-2006 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. Updates: Dec 30, 1997 V0.91 Bug: StatusCode was not updated for Connect Added PostingPermited property and ParseListLine procedure as suggested by J. Peter Mugaas <oma00215@mail.wvnet.edu> Dec 31, 1997 V0.92 Added XOVER, LIST OVERVIEW.FMT and DATE commands Jan 10, 1998 V0.93 Added OnStateChange event as suggested by J. Peter Mugaas <oma00215@mail.wvnet.edu> Jan 13, 1998 V0.94 Added readonly property State Feb 02, 1998 V0.95 Corrected a message in the Quit method. Added the NntpCliVersion constant. Feb 03, 1998 V0.96 Added Authenticate method, UserName and PassWord properties. Apr 13, 1998 V1.00 Added an intermediate message for OnRequestDone event Created the Handle property and related WndProc stuff Apr 21, 1998 V1.01 Corrected buffer overflow in the OnDataAvailable event. Thanks to Tim Skinner tim@palacecs.demon.co.uk who found that bug. Sep 29, 1998 V1.02 Checked length of FLastResponse before writing it to stream. Thanks to Michael Bartos <MBartos@ExpoMedia.de> for the hint. Feb 01, 1999 V1.03 Added nntpConnect to solve connection problem after an abort. Thanks to Eric Fortier <efortier@videotron.ca>. Feb 27, 1999 V1.04 Made Connect, Abort and Quit method virtual so that they can be overriden in descending components. Checked line length in ParseListLine. Mar 31, 1999 V1.05 Made all methods virtual. Aug 14, 1999 V1.06 Implemented MODE READER and XHDR Aug 20, 1999 V1.07 Revised conditional compilation, adapted for BCB4, set compile options same as TWSocket. Jun 18, 2001 V1.08 Use AllocateHWnd and DeallocateHWnd from wsocket. Renamed property WSocket to CtrlSocket (this require code change in user application too). Sep 28, 2002 V1.09 Arnaud SUBTIL <arnaud_courrier@yahoo.fr> changed WSocketDataAvailable so that it doesn't fail when a line is longer than the receive buffer. Oct 26, 2002 V1.10 Fixed double dot problem in GetArticleLineNext. Thanks to Steve Blinch <steve@blitzaffe.com> who found it. Use TWSocket LineMode to avoid line length limit. Introduced LineLimit to allow user to limit max line (accepting unlimited lines can result in a Denial Of Service security hole. Nov 02, 2002 V1.11 Added OnSendData event, OnRcvdData event, SendCount property and RcvdCount property to easy progress bar update. Nov 11, 2002 V1.12 Revised for Delphi 1 Nov 23, 2002 V1.13 Added a port property to allow use of something else than NNTP port. Nov 27, 2002 V1.14 Changed NntpCliVersion to an integer. Apr 22, 2003 V1.15 Christophe Thiaux <tophet@free.fr> added Port property. Jul 20, 2003 V1.16 arnaud.mesnews@free.fr added ListNewsgroups and made a few functions cirtuals so that inheritance is easier. Jan 11, 2004 V1.17 "Piotr Hellrayzer Dalek" <enigmatical@interia.pl> added XPAT and ListMOTD features. May 31, 2004 V1.18 Used ICSDEFS.INC Jul 24, 2004 V1.19 Arnaud.mesnews@free.fr added GroupName property and related code. Jan 01, 2005 V1.20 In WSocketDataAvailable, check for length > 0 before calling OnDisplay. By Stephan Klimek <Stephan.Klimek@gmx.de>. Mar 11, 2005 V1.21 Marco van de Voort <marcov@stack.nl> updated the component to be compatible with NOFORMS concept. He implemented NNTPCliAllocateHWnd and NNTPCliDeallocateHWnd based on TWSocket versions. Jun 13, 2005 V1.22 Use SSL Mar 24, 2006 V6.00 New version 6 started from V5 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsNntpCli; {.DEFINE DUMP} interface {$Q-} { Disable overflow checking } {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$I OverbyteIcsDefs.inc} {$IFDEF DELPHI6_UP} {$WARN SYMBOL_PLATFORM OFF} {$WARN SYMBOL_LIBRARY OFF} {$WARN SYMBOL_DEPRECATED OFF} {$ENDIF} {$IFNDEF VER80} { Not for Delphi 1 } {$H+} { Use long strings } {$J+} { Allow typed constant to be modified } {$ENDIF} {$IFDEF BCB3_UP} {$ObjExportAll On} {$ENDIF} uses Messages, {$IFDEF USEWINDOWS} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} SysUtils, Classes, {$IFNDEF NOFORMS} Forms, {$ENDIF} { You must define USE_SSL so that SSL code is included in the component. } { To be able to compile the component, you must have the SSL related files } { which are _NOT_ freeware. See http://www.overbyte.be for details. } {$IFDEF USE_SSL} IcsSSLEAY, IcsLIBEAY, {$ENDIF} OverbyteIcsMimeUtils, OverbyteIcsWndControl, OverbyteIcsWinSock, OverbyteIcsWSocket; const NntpCliVersion = 122; CopyRight : String = ' TNntpCli (c) 1997-2006 F. Piette V1.22 '; {$IFDEF VER80} { Delphi 1 has a 255 characters string limitation } NNTP_SND_BUF_SIZE = 255; {$ELSE} NNTP_SND_BUF_SIZE = 4096; {$ENDIF} type TNntpContentType = (nntpHtml, nntpPlainText); TNntpMimeState = (nntpMimeHeader, nntpMimeIntro, nntpMimePlainText, nntpMimeHtmlText, nntpMimeImages, nntpMimeDone); TNntpShareMode = (nntpShareCompat, nntpShareExclusive, nntpShareDenyWrite, nntpShareDenyRead, nntpShareDenyNone); TNntpDisplay = procedure(Sender : TObject; MsgBuf : Pointer; MsgLen : Integer) of object; TNntpState = (nntpNotConnected, nntpDnsLookup, nntpWaitingBanner, nntpReady, nntpWaitingResponse); TNntpRequest = (nntpGroup, nntpList, nntpConnect, nntpPost, nntpHelp, nntpNewGroups, nntpNewNews, nntpArticleByNumber, nntpArticleByID, nntpBodyByID, nntpBodyByNumber, nntpHeadByID, nntpHeadByNumber, nntpStatByID, nntpStatByNumber, nntpNext, nntpLast, nntpQuit, nntpAbort, nntpXOver, nntpListOverViewFmt, nntpDate, nntpAuthenticate, nntpModeReader, nntpXHdr, nntpListNewsgroups, {AS} nntpXPAT, nntpListMotd); {HLX} TRequestDone = procedure(Sender: TObject; RqType: TNntpRequest; ErrCode: Word) of object; NntpException = class(Exception); TNntpCli = class(TIcsWndControl) public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Connect; virtual; procedure Abort; virtual; procedure Quit; virtual; procedure Group(NewsGroupName : String); virtual; procedure ArticleByNumber(Number : Integer; DestStream : TStream); virtual; procedure ArticleByID(ID : String; DestStream : TStream); virtual; procedure HeadByNumber(Number : Integer; DestStream : TStream); virtual; procedure HeadByID(ID : String; DestStream : TStream); virtual; procedure BodyByNumber(Number : Integer; DestStream : TStream); virtual; procedure BodyByID(ID : String; DestStream : TStream); virtual; procedure StatByNumber(Number : Integer); virtual; procedure StatByID(ID : String); virtual; procedure Next; virtual; procedure Last; virtual; { It is really Prior, but RFC-977 call it Last !} procedure List(DestStream : TStream); virtual; procedure ListNewsgroups(DestStream : TStream; chFiltre : String); {AS} procedure Post(FromStream : TStream); virtual; procedure Help(DestStream : TStream); virtual; procedure Authenticate; virtual; procedure XOver(Articles : String; DestStream : TStream); virtual; procedure ListOverViewFmt(DestStream : TStream); virtual; procedure ListMotd(DestStream : TStream); virtual; {HLX} procedure Date; virtual; procedure ModeReader; virtual; procedure XHdr(DestStream : TStream; Header : String; Range : String); virtual; procedure XPat(DestStream : TStream; Header, Range, FindStr: String); virtual; {HLX} procedure NewGroups(When : TDateTime; GMTFLag : Boolean; Distributions : String; DestStream : TStream); virtual; procedure NewNews(When : TDateTime; GMTFLag : Boolean; NewsGroupName : String; Distributions : String; DestStream : TStream); virtual; protected {$IFDEF DUMP} FDumpStream : TFileStream; FDumpBuf : String; {$ENDIF} FHost : String; FPort : String; FState : TNntpState; FWSocket : TWSocket; FRequest : String; FRequestType : TNntpRequest; FRequestDoneFlag : Boolean; FSentFlag : Boolean; FStatusCode : Integer; FSendCount : Integer; { Count sent bytes } FRcvdCount : Integer; { Count received bytes } FSendBuffer : array [0..NNTP_SND_BUF_SIZE - 1] of Char; FLastResponse : String; FLastCmdResponse : String; FErrorMessage : String; FArticleEstimated : Integer; FArticleFirst : Integer; FArticleLast : Integer; FArticleNumber : Integer; FArticleID : String; FServerDate : TDateTime; FDataStream : TStream; FUserName : String; FPassWord : String; FLineLimit : Integer; FNext : procedure of object; FPostingPermited : Boolean; FMsg_WM_NNTP_REQUEST_DONE : UINT; FOnSessionConnected : TSessionConnected; FOnSessionClosed : TSessionClosed; FOnDataAvailable : TDataAvailable; FOnRequestDone : TRequestDone; FOnDisplay : TNntpDisplay; FOnMessageBegin : TNotifyEvent; FOnMessageEnd : TNotifyEvent; FOnMessageLine : TNotifyEvent; FOnXHdrBegin : TNotifyEvent; FOnXHdrEnd : TNotifyEvent; FOnXHdrLine : TNotifyEvent; FOnStateChange : TNotifyEvent; FOnSendData : TNotifyEvent; FOnRcvdData : TNotifyEvent; FGroupName : String; procedure CreateSocket; virtual; procedure SetLineLimit(NewValue : Integer); procedure AllocateMsgHandlers; override; procedure FreeMsgHandlers; override; function MsgHandlersCount: Integer; override; procedure WndProc(var MsgRec: TMessage); override; procedure HandleBackGroundException(E: Exception); override; procedure WMNntpRequestDone(var msg: TMessage); virtual; procedure WSocketDnsLookupDone(Sender: TObject; ErrCode: Word); procedure WSocketSessionConnected(Sender: TObject; ErrCode: Word); procedure WSocketDataAvailable(Sender: TObject; ErrCode: Word); procedure WSocketSessionClosed(Sender: TObject; ErrCode: Word); virtual; procedure WSocketDataSent(Sender: TObject; ErrCode: Word); procedure DelayedRequestDone(ErrCode: Word); virtual; procedure TriggerStateChange; virtual; procedure TriggerRequestDone(Request: TNntpRequest; ErrCode: Word); virtual; procedure StateChange(NewState : TNntpState); virtual; procedure SendRequest; virtual; procedure GroupNext; virtual; procedure QuitNext; virtual; procedure XHdrLineNext; virtual; procedure GetArticleNext; virtual; procedure GetArticleLineNext; virtual; procedure GetArticleByNumber(RqType: TNntpRequest; Number : Integer; DestStream : TStream); virtual; procedure GetArticleByID(RqType: TNntpRequest; ID : String; DestStream : TStream); virtual; procedure GetArticle(RqType: TNntpRequest; ID : String; DestStream : TStream); virtual; procedure PostNext; virtual; procedure PostDone; virtual; procedure PostBlock; virtual; procedure PostSendNext; virtual; procedure DateNext; virtual; procedure ModeReaderNext; virtual; procedure XHdrNext; virtual; procedure AuthenticateNext1; virtual; procedure AuthenticateNext2; virtual; procedure TriggerSendData; virtual; procedure TriggerRcvdData; virtual; property SendCount : Integer read FSendCount write FSendCount; property RcvdCount : Integer read FRcvdCount write FRcvdCount; procedure TriggerSessionConnected(ErrCode: Word); virtual; procedure TriggerMessageLine; virtual; published property CtrlSocket : TWSocket read FWSocket; property State : TNntpState read FState; property Host : String read FHost write FHost; property ErrorMessage : String read FErrorMessage; property LastResponse : String read FLastResponse; property StatusCode : Integer read FStatusCode; property PostingPermited : Boolean read FPostingPermited; property ArticleEstimated : Integer read FArticleEstimated; property ArticleFirst : Integer read FArticleFirst; property ArticleLast : Integer read FArticleLast; property ArticleNumber : Integer read FArticleNumber; property ArticleID : String read FArticleID; property ServerDate : TDateTime read FServerDate; property UserName : String read FUserName write FUserName; property PassWord : String read FPassWord write FPassWord; property Port : String read FPort write FPort; property LineLimit : Integer read FLineLimit write SetLineLimit; property GroupName : String read FGroupName; property OnSessionConnected : TSessionConnected read FOnSessionConnected write FOnSessionConnected; property OnSessionClosed : TSessionClosed read FOnSessionClosed write FOnSessionClosed; property OnDataAvailable : TDataAvailable read FOnDataAvailable write FOnDataAvailable; property OnRequestDone : TRequestDone read FOnRequestDone write FOnRequestDone; property OnDisplay : TNntpDisplay read FOnDisplay write FOnDisplay; property OnMessageBegin : TNotifyEvent read FOnMessageBegin write FOnMessageBegin; property OnMessageEnd : TNotifyEvent read FOnMessageEnd write FOnMessageEnd; property OnMessageLine : TNotifyEvent read FOnMessageLine write FOnMessageLine; property OnXHdrBegin : TNotifyEvent read FOnXHdrBegin write FOnXHdrBegin; property OnXHdrEnd : TNotifyEvent read FOnXHdrEnd write FOnXHdrEnd; property OnXHdrLine : TNotifyEvent read FOnXHdrLine write FOnXHdrLine; property OnStateChange : TNotifyEvent read FOnStateChange write FOnStateChange; { Event intended for progress bar update (send) } property OnSendData : TNotifyEvent read FOnSendData write FOnSendData; { Event intended for progress bar update (receive) } property OnRcvdData : TNotifyEvent read FOnRcvdData write FOnRcvdData; end; THtmlNntpCli = class(TNntpCli) protected FPlainText : TStrings; FHtmlText : TStrings; FAttachedFiles : TStrings; { File names for attachment } FOutsideBoundary : String; FInsideBoundary : String; FMimeState : TNntpMimeState; FHtmlCharSet : String; FLineNumber : Integer; FLineOffset : Integer; FImageNumber : Integer; FContentType : TNntpContentType; FContentTypeStr : String; FHdrSubject : String; FHdrFrom : String; FHdrGroup : String; FHeader : TStringList; FCharSet : String; FShareMode : Word; FStream : TStream; procedure SetPlainText(const newValue: TStrings); virtual; procedure SetHtmlText(const newValue: TStrings); virtual; procedure SetAttachedFiles(const newValue: TStrings); virtual; procedure SetContentType(newValue : TNntpContentType); virtual; function GetShareMode: TNntpShareMode; virtual; procedure SetShareMode(newValue: TNntpShareMode); virtual; procedure PostBlock; override; procedure BuildHeader; virtual; procedure GenerateBoundaries; virtual; procedure Display(const Msg: String); virtual; procedure SendLine(const MsgLine: String); virtual; procedure TriggerRequestDone(Request: TNntpRequest; ErrCode: Word); override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Post(FromStream : TStream); override; published property PlainText : TStrings read FPlainText write SetPlainText; property HtmlText : TStrings read FHtmlText write SetHtmlText; property AttachedFiles : TStrings read FAttachedFiles write SetAttachedFiles; property ContentType : TNntpContentType read FContentType write SetContentType; property HdrSubject : String read FHdrSubject write FHdrSubject; property HdrGroup : String read FHdrGroup write FHdrGroup; property HdrFrom : String read FHdrFrom write FHdrFrom; property CharSet : String read FCharSet write FCharSet; property ShareMode : TNntpShareMode read GetShareMode write SetShareMode; end; { You must define USE_SSL so that SSL code is included in the component. } { To be able to compile the component, you must have the SSL related files } { which are _NOT_ freeware. See http://www.overbyte.be for details. } {$IFDEF USE_SSL} {$I NntpCliIntfSsl.inc} {$ENDIF} procedure ParseListLine(const Line : String; var NewsGroupName : String; var LastArticle : Integer; var FirstArticle : Integer; var PostingFlag : Char); procedure Register; implementation {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF VER80} function TrimRight(Str : String) : String; var I : Integer; begin I := Length(Str); while (I > 0) and (Str[I] = ' ') do I := I - 1; Result := Copy(Str, 1, I); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TrimLeft(Str : String) : String; var I : Integer; begin if Str[1] <> ' ' then Result := Str else begin I := 1; while (I <= Length(Str)) and (Str[I] = ' ') do I := I + 1; Result := Copy(Str, I, Length(Str) - I + 1); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function Trim(Str : String) : String; begin Result := TrimLeft(TrimRight(Str)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure SetLength(var S: string; NewLength: Integer); begin S[0] := chr(NewLength); end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Step over blank spaces } function StpBlk(Data : PChar) : PChar; begin Result := Data; if Result <> nil then begin while (Result^ <> #0) and (Result^ in [' ', #9, #13, #10]) do Inc(Result); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetInteger(Data : PChar; var Number : Integer) : PChar; var bSign : Boolean; begin Number := 0; Result := StpBlk(Data); if (Result = nil) then Exit; { Remember the sign } if Result^ in ['-', '+'] then begin bSign := (Result^ = '-'); Inc(Result); end else bSign := FALSE; { Convert any number } while (Result^ <> #0) and (Result^ in ['0'..'9']) do begin Number := Number * 10 + ord(Result^) - ord('0'); Inc(Result); end; { Correct for sign } if bSign then Number := -Number; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetMessageID(Data : PChar; var ID : String) : PChar; begin ID := ''; Result := StpBlk(Data); if Data = nil then Exit; while not (Result^ in [#0, '<']) do Inc(Result); if Result^ = '<' then begin while Result^ <> #0 do begin Inc(Result); if Result^ = '>' then break; ID := ID + Result^; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetNewsGroupName(Data : PChar; var GroupName : String) : PChar; begin GroupName := ''; Result := StpBlk(Data); if Data = nil then Exit; { Copy until first white space } while (Result^ <> #0) and (not (Result^ in [' ', #9])) do begin GroupName := GroupName + Result^; Inc(Result); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetChar(Data : PChar; var Ch : Char) : PChar; begin Ch := #0; Result := StpBlk(Data); if Data = nil then Exit; Ch := Result^; if Ch <> #0 then Inc(Result); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function atoi(Data : String) : Integer; begin {$IFDEF VER80} { Nul terminate string for Delphi 1 } Data[Length(Data) + 1] := #0; {$ENDIF} GetInteger(@Data[1], Result); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure Register; begin RegisterComponents('FPiette', [TNntpCli, {$IFDEF USE_SSL} TSslNntpCli, {$ENDIF} THtmlNntpCli]); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TNntpCli.Create(AOwner: TComponent); begin inherited Create(AOwner); AllocateHWnd; {$IFDEF DUMP} FDumpStream := TFileStream.Create('c:\temp\nntpcli.log', fmCreate); FDumpBuf := '---- START -----' + #13 + #10; FDumpStream.WriteBuffer(FDumpBuf[1], Length(FDumpBuf)); {$ENDIF} FState := nntpNotConnected; FArticleNumber := -1; FArticleID := ''; FArticleFirst := -1; FArticleLast := -1; FArticleEstimated := -1; FStatusCode := 503; { program fault } {$IFDEF VER80} FLineLimit := 255; {$ELSE} FLineLimit := 65536; {$ENDIF} FPort := 'nntp'; CreateSocket; FWSocket.LineMode := TRUE; FWSocket.LineEnd := #13#10; FWSocket.LineLimit := FLineLimit; FWSocket.ComponentOptions := FWSocket.ComponentOptions + [wsoNoReceiveLoop]; FWSocket.OnSessionConnected := WSocketSessionConnected; FWSocket.OnDataAvailable := WSocketDataAvailable; FWSocket.OnSessionClosed := WSocketSessionClosed; FWSocket.OnDnsLookupDone := WSocketDnsLookupDone; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TNntpCli.Destroy; begin {$IFDEF DUMP} if Assigned(FDumpStream) then begin FDumpBuf := '---- STOP -----' + #13 + #10; FDumpStream.WriteBuffer(FDumpBuf[1], Length(FDumpBuf)); FDumpStream.Destroy; end; {$ENDIF} if Assigned(FWSocket) then FWSocket.Destroy; inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.CreateSocket; begin FWSocket := TWSocket.Create(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.SetLineLimit(NewValue: Integer); begin if FLineLimit <> NewValue then begin FLineLimit := NewValue; FWSocket.LineLimit := FLineLimit; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TNntpCli.MsgHandlersCount : Integer; begin Result := 1 + inherited MsgHandlersCount; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.AllocateMsgHandlers; begin inherited AllocateMsgHandlers; FMsg_WM_NNTP_REQUEST_DONE := FWndHandler.AllocateMsgHandler(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.FreeMsgHandlers; begin if Assigned(FWndHandler) then begin FWndHandler.UnregisterMessage(FMsg_WM_NNTP_REQUEST_DONE); end; inherited FreeMsgHandlers; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.WndProc(var MsgRec: TMessage); begin try with MsgRec do begin if Msg = FMsg_WM_NNTP_REQUEST_DONE then WMNntpRequestDone(MsgRec) else inherited WndProc(MsgRec); end; except on E:Exception do HandleBackGroundException(E); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { All exceptions *MUST* be handled. If an exception is not handled, the } { application will be shut down ! } procedure TNntpCli.HandleBackGroundException(E: Exception); var CanAbort : Boolean; begin CanAbort := TRUE; { First call the error event handler, if any } if Assigned(FOnBgException) then begin try FOnBgException(Self, E, CanAbort); except end; end; { Then abort the component } if CanAbort then begin try Abort; except end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.WMNntpRequestDone(var msg: TMessage); begin TriggerRequestDone(TNntpRequest(Msg.WParam), Msg.LParam); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.TriggerRequestDone( Request : TNntpRequest; ErrCode : Word); begin if Assigned(FOnRequestDone) then FOnRequestDone(Self, Request, ErrCode); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.StateChange(NewState : TNntpState); begin if FState <> NewState then begin FState := NewState; TriggerStateChange; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.SendRequest; begin FLastCmdResponse := ''; {$IFDEF DUMP} FDumpBuf := '<|'; FDumpStream.WriteBuffer(FDumpBuf[1], Length(FDumpBuf)); FDumpStream.WriteBuffer(FRequest[1], Length(FRequest)); FDumpBuf := '|' + #13#10; FDumpStream.WriteBuffer(FDumpBuf[1], Length(FDumpBuf)); {$ENDIF} FWSocket.SendStr(FRequest + #13 + #10); FSendCount := (FSendCount + Length(FRequest) + 2) and $7FFFFFF; TriggerSendData; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.Connect; begin if FState <> nntpNotConnected then raise NntpException.Create('Already connected'); FRequestType := nntpConnect; FRequestDoneFlag := FALSE; FRequest := ''; FArticleNumber := -1; FArticleID := ''; FArticleFirst := -1; FArticleLast := -1; FArticleEstimated := -1; StateChange(nntpDnsLookup); FWSocket.DnsLookup(FHost); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.Group(NewsGroupName : String); begin if FState <> nntpReady then raise NntpException.Create('Not ready for GROUP'); FRequestDoneFlag := FALSE; FRequestType := nntpGroup; FRequest := 'GROUP ' + Trim(NewsGroupName); FNext := GroupNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.GroupNext; var Data : PChar; ErrCode : Integer; begin Data := GetInteger(@FLastResponse[1], FStatusCode); Data := GetInteger(Data, FArticleEstimated); Data := GetInteger(Data, FArticleFirst); Data := GetInteger(Data, FArticleLast); GetNewsGroupName(Data, FGroupName); if FStatusCode = 211 then Errcode := 0 else ErrCode := FStatusCode; DelayedRequestDone(Errcode); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.ArticleByNumber(Number : Integer; DestStream : TStream); begin GetArticleByNumber(nntpArticleByNumber, Number, DestStream); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.ArticleByID(ID : String; DestStream : TStream); begin GetArticleByID(nntpArticleByID, ID, DestStream); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.BodyByNumber(Number : Integer; DestStream : TStream); begin GetArticleByNumber(nntpBodyByNumber, Number, DestStream); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.BodyByID(ID : String; DestStream : TStream); begin GetArticleByID(nntpBodyByID, ID, DestStream); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.HeadByNumber(Number : Integer; DestStream : TStream); begin GetArticleByNumber(nntpHeadByNumber, Number, DestStream); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.HeadByID(ID : String; DestStream : TStream); begin GetArticleByID(nntpHeadByID, ID, DestStream); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.StatByNumber(Number : Integer); begin GetArticleByNumber(nntpStatByNumber, Number, nil); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.StatByID(ID : String); begin GetArticleByID(nntpStatByID, ID, nil); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.GetArticleByID( RqType : TNntpRequest; ID : String; DestStream : TStream); begin GetArticle(RqType, ' <' + ID + '>', DestStream); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.GetArticleByNumber( RqType : TNntpRequest; Number : Integer; DestStream : TStream); begin if Number > 0 then GetArticle(RqType, ' ' + IntToStr(Number), DestStream) else GetArticle(RqType, '', DestStream); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.GetArticle( RqType : TNntpRequest; ID : String; DestStream : TStream); var Cmd : String; begin case RqType of nntpArticleByID, nntpArticleByNumber: Cmd := 'ARTICLE'; nntpBodyByID, nntpBodyByNumber: Cmd := 'BODY'; nntpHeadByID, nntpHeadByNumber: Cmd := 'HEAD'; nntpStatByID, nntpStatByNumber: Cmd := 'STAT'; else raise NntpException.Create('Internal error: Invalid Request Type'); end; if FState <> nntpReady then raise NntpException.Create('Not ready for ' + Cmd); FDataStream := DestStream; FRequestType := RqType; FRequestDoneFlag := FALSE; FArticleNumber := -1; FArticleID := ''; FRequest := Cmd + ID; FNext := GetArticleNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.GetArticleNext; var Data : PChar; begin Data := GetInteger(@FLastResponse[1], FStatusCode); if not (FStatusCode in [100, 215, 220, 221, 222, 223, 224, 231]) then begin DelayedRequestDone(FStatusCode); Exit; end; Data := GetInteger(Data, FArticleNumber); GetMessageID(Data, FArticleID); if FStatusCode in [223] then DelayedRequestDone(0) else begin FNext := GetArticleLineNext; FLastCmdResponse := FLastResponse;; StateChange(nntpWaitingResponse); if Assigned(FOnMessageBegin) then FOnMessageBegin(Self); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.GetArticleLineNext; const CrLf : String[2] = #13#10; begin if FLastResponse = '.' then begin if FLastCmdResponse <> '' then begin FLastResponse := FLastCmdResponse; FLastCmdResponse := ''; end; if Assigned(FOnMessageEnd) then FOnMessageEnd(Self); DelayedRequestDone(0); end else begin if (Length(FLastResponse) > 1) and { 26/10/02 } (FLastResponse[1] ='.') and (FLastResponse[2] ='.') then Delete(FLastResponse, 1, 1); if Assigned(FDataStream) then begin if Length(FLastResponse) > 0 then FDataStream.Write(FLastResponse[1], Length(FLastResponse)); FDataStream.Write(CrLf[1], Length(CrLf)); end; TriggerMessageLine; {AS} end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.Next; begin if FState <> nntpReady then raise NntpException.Create('Not ready for NEXT'); FRequestDoneFlag := FALSE; FRequestType := nntpNext; FArticleNumber := -1; FArticleID := ''; FRequest := 'NEXT'; FNext := GetArticleNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.Last; begin if FState <> nntpReady then raise NntpException.Create('Not ready for LAST'); FRequestDoneFlag := FALSE; FRequestType := nntpLast; FArticleNumber := -1; FArticleID := ''; FRequest := 'LAST'; FNext := GetArticleNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.List(DestStream : TStream); begin if FState <> nntpReady then raise NntpException.Create('Not ready for LIST'); FDataStream := DestStream; FRequestDoneFlag := FALSE; FRequestType := nntpList; FRequest := 'LIST'; FNext := GetArticleNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {AS} procedure TNntpCli.ListNewsgroups(DestStream : TStream; chFiltre : String); begin if FState <> nntpReady then raise NntpException.Create('Not ready for LIST NEWSGROUPS'); FDataStream := DestStream; FRequestDoneFlag := FALSE; FRequestType := nntpListNewsgroups; FRequest := 'LIST NEWSGROUPS'; if chFiltre<>'' then FRequest := FRequest + ' '+chFiltre; FNext := GetArticleNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.Help(DestStream : TStream); begin if FState <> nntpReady then raise NntpException.Create('Not ready for HELP'); FDataStream := DestStream; FRequestDoneFlag := FALSE; FRequestType := nntpHelp; FRequest := 'HELP'; FNext := GetArticleNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.Quit; begin if FState <> nntpReady then raise NntpException.Create('Not ready for QUIT'); FRequestDoneFlag := FALSE; FRequestType := nntpQuit; FRequest := 'QUIT'; FNext := QuitNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.QuitNext; begin GetInteger(@FLastResponse[1], FStatusCode); DelayedRequestDone(0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.Abort; begin FRequestType := nntpAbort; FWSocket.Close; FLastResponse := '205 Closing connection - goodbye'; FStatusCode := 205; FRequestDoneFlag := FALSE; DelayedRequestDone(0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.Post(FromStream : TStream); begin if FState <> nntpReady then raise NntpException.Create('Not ready for POST'); FDataStream := FromStream; FRequestDoneFlag := FALSE; FRequestType := nntpPost; FRequest := 'POST'; FSentFlag := FALSE; FNext := PostNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.PostNext; begin GetInteger(@FLastResponse[1], FStatusCode); if FStatusCode <> 340 then begin DelayedRequestDone(FStatusCode); Exit; end; FNext := PostSendNext; FWSocket.OnDataSent := WSocketDataSent; PostBlock; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.PostBlock; var Len : Integer; begin if FDataStream = nil then Len := 0 { No data to send } else Len := FDataStream.Read(FSendBuffer, SizeOf(FSendBuffer)); if Len <= 0 then begin if FSentFlag then Exit; FSentFlag := TRUE; StrCopy(@FSendBuffer, #13#10 + '.' + #13#10); Len := 5; end; FWSocket.Send(@FSendBuffer, Len); Inc(FSendCount, Len); TriggerSendData; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.PostSendNext; begin FWSocket.OnDataSent := nil; GetInteger(@FLastResponse[1], FStatusCode); if FStatusCode = 240 then DelayedRequestDone(0) else DelayedRequestDone(FStatusCode); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.PostDone; begin FLastResponse := '441 posting failed'; PostSendNext; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.NewGroups( When : TDateTime; GMTFLag : Boolean; Distributions : String; DestStream : TStream); begin if FState <> nntpReady then raise NntpException.Create('Not ready for NEWGROUPS'); FDataStream := DestStream; FRequestDoneFlag := FALSE; FRequestType := nntpNewGroups; if When = 0 then When := Now; FRequest := 'NEWGROUPS ' + FormatDateTime('yymmdd hhnnss', When); if GMTFlag then FRequest := FRequest + ' GMT'; if Length(Distributions) > 0 then FRequest := FRequest + ' <' + Distributions + '>'; FNext := GetArticleNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.NewNews( When : TDateTime; GMTFLag : Boolean; NewsGroupName : String; Distributions : String; DestStream : TStream); begin if FState <> nntpReady then raise NntpException.Create('Not ready for NEWNEWS'); FDataStream := DestStream; FRequestDoneFlag := FALSE; FRequestType := nntpNewNews; if When = 0 then When := Now; if NewsGroupName = '' then NewsGroupName := '*'; FRequest := 'NEWNEWS ' + NewsGroupName + ' ' + FormatDateTime('yymmdd hhnnss', When); if GMTFlag then FRequest := FRequest + ' GMT'; if Length(Distributions) > 0 then FRequest := FRequest + ' <' + Distributions + '>'; FNext := GetArticleNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Articles can be: a) a single (positive) article number } { b) an article number followed by a dash } { c) two article numbers separated by a dash } procedure TNntpCli.XOver( Articles : String; DestStream : TStream); begin if FState <> nntpReady then raise NntpException.Create('Not ready for XOVER'); FDataStream := DestStream; FRequestDoneFlag := FALSE; FRequestType := nntpXOver; FRequest := 'XOVER ' + Articles; FNext := GetArticleNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {HLX} procedure TNntpCli.XPat( DestStream : TStream; Header, Range, FindStr: String); begin if FState <> nntpReady then raise NntpException.Create('Not ready for XPAT'); FDataStream := DestStream; FRequestDoneFlag := FALSE; FRequestType := nntpXPAT; FRequest := 'XPAT '+Header+' '+Range+' '+FindStr; FNext := GetArticleNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.ListOverViewFmt(DestStream : TStream); begin if FState <> nntpReady then raise NntpException.Create('Not ready for LIST OVERVIEW.FMT'); FDataStream := DestStream; FRequestDoneFlag := FALSE; FRequestType := nntpListOverViewFmt; FRequest := 'LIST OVERVIEW.FMT'; FNext := GetArticleNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.ListMotd(DestStream : TStream); {HLX} begin if FState <> nntpReady then raise NntpException.Create('Not ready for LIST MOTD'); FDataStream := DestStream; FRequestDoneFlag := FALSE; FRequestType := nntpListMotd; FRequest := 'LIST MOTD'; FNext := GetArticleNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.DateNext; var Data : PChar; Buf : String; Year, Month, Day, Hour, Min, Sec : Word; begin Data := StpBlk(GetInteger(@FLastResponse[1], FStatusCode)); if FStatusCode <> 111 then begin DelayedRequestDone(FStatusCode); Exit; end; Buf := Trim(StrPas(Data)); if Length(Buf) = 14 then begin Year := atoi(Copy(Buf, 1, 4)); Month := atoi(Copy(Buf, 5, 2)); Day := atoi(Copy(Buf, 7, 2)); Hour := atoi(Copy(Buf, 9, 2)); Min := atoi(Copy(Buf, 11, 2)); Sec := atoi(Copy(Buf, 13, 2)); FServerDate := EncodeDate(Year, Month, Day) + EncodeTime(Hour, Min, Sec, 0); end; DelayedRequestDone(0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.Date; begin if FState <> nntpReady then raise NntpException.Create('Not ready for DATE'); FServerDate := 0; FDataStream := nil; FRequestDoneFlag := FALSE; FRequestType := nntpDate; FRequest := 'DATE'; FNext := DateNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.ModeReaderNext; begin GetInteger(@FLastResponse[1], FStatusCode); if FStatusCode in [200, 201] then DelayedRequestDone(0) else DelayedRequestDone(FStatusCode); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.ModeReader; begin if FState <> nntpReady then raise NntpException.Create('Not ready for ModeReader'); FServerDate := 0; FDataStream := nil; FRequestDoneFlag := FALSE; FRequestType := nntpModeReader; FRequest := 'MODE READER'; FNext := ModeReaderNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.XHdrLineNext; const CrLf : String[2] = #13#10; begin if FLastResponse = '.' then begin if FLastCmdResponse <> '' then begin FLastResponse := FLastCmdResponse; FLastCmdResponse := ''; end; if Assigned(FOnXHdrEnd) then FOnXHdrEnd(Self); DelayedRequestDone(0); end else begin if Assigned(FDataStream) then begin if Length(FLastResponse) > 0 then FDataStream.Write(FLastResponse[1], Length(FLastResponse)); FDataStream.Write(CrLf[1], Length(CrLf)); end; if Assigned(FOnXHdrLine) then FOnXHdrLine(Self); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.XHdrNext; begin GetInteger(@FLastResponse[1], FStatusCode); if FStatusCode <> 221 then begin DelayedRequestDone(FStatusCode); Exit; end; FNext := XHdrLineNext; FLastCmdResponse := FLastResponse;; StateChange(nntpWaitingResponse); if Assigned(FOnXHdrBegin) then FOnXHdrBegin(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Header is a header line such as "subject". } { Range is either: } { an article number } { an article number followed by a dash to indicate all following } { an article number followed by a dash followed by another article number } { Range can be replaced by a message id. } { If range is empty current article is used. } procedure TNntpCli.XHdr(DestStream : TStream; Header : String; Range : String); begin if FState <> nntpReady then raise NntpException.Create('Not ready for XHDR'); FDataStream := DestStream; FRequestDoneFlag := FALSE; FRequestType := nntpXHdr; FRequest := 'XHDR ' + Header; if Length(Range) > 0 then Frequest := FRequest + ' ' + Range; FNext := XHdrNext; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.AuthenticateNext1; begin StpBlk(GetInteger(@FLastResponse[1], FStatusCode)); if FStatusCode <> 381 then begin DelayedRequestDone(FStatusCode); Exit; end; FRequestDoneFlag := FALSE; FRequest := 'AUTHINFO PASS ' + FPassWord; FNext := AuthenticateNext2; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.AuthenticateNext2; begin StpBlk(GetInteger(@FLastResponse[1], FStatusCode)); if FStatusCode <> 281 then begin DelayedRequestDone(FStatusCode); Exit; end; DelayedRequestDone(0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.Authenticate; begin if FState <> nntpReady then raise NntpException.Create('Not ready for AUTHINFO'); FRequestDoneFlag := FALSE; FRequestType := nntpAuthenticate; FRequest := 'AUTHINFO USER ' + FUserName; FNext := AuthenticateNext1; StateChange(nntpWaitingResponse); SendRequest; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure ParseListLine( const Line : String; var NewsGroupName : String; var LastArticle : Integer; var FirstArticle : Integer; var PostingFlag : Char); var Data : PChar; begin if Length(Line) = 0 then Exit; Data := GetNewsGroupName(@Line[1], NewsGroupName); Data := GetInteger(Data, LastArticle); Data := GetInteger(Data, FirstArticle); GetChar(Data, PostingFlag); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.WSocketDataSent(Sender: TObject; ErrCode: Word); begin if ErrCode <> 0 then begin PostDone; Exit; end; PostBlock; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.WSocketDnsLookupDone(Sender: TObject; ErrCode: Word); begin if ErrCode <> 0 then DelayedRequestDone(ErrCode) else begin FWSocket.Addr := FWSocket.DnsResult; FWSocket.Proto := 'tcp'; FWSocket.Port := FPort; StateChange(nntpWaitingBanner); FWSocket.Connect; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.WSocketSessionConnected(Sender: TObject; ErrCode: Word); begin { Do not trigger the client SessionConnected from here. We must wait } { to have received the server banner. } if ErrCode <> 0 then begin DelayedRequestDone(ErrCode); FWSocket.Close end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.WSocketDataAvailable(Sender: TObject; ErrCode: Word); var Len : Integer; begin Len := FWSocket.RcvdCount; if Len < 0 then Exit; if Len = 0 then begin FWSocket.Close; Exit; end; { We use line mode, we will receive complete lines } FLastResponse := FWSocket.ReceiveStr; FRcvdCount := (FRcvdCount + Length(FLastResponse)) and $7FFFFFF; TriggerRcvdData; { Remove ending CR/LF, if any } if (Length(FLastResponse) >= 1) and (FLastResponse[Length(FLastResponse)] = #10) then SetLength(FLastResponse, Length(FLastResponse) - 1); if (Length(FLastResponse) >= 1) and (FLastResponse[Length(FLastResponse)] = #13) then SetLength(FLastResponse, Length(FLastResponse) - 1); if FRequestType = nntpAbort then Exit; if Assigned(FOnDisplay) and (Length(FLastResponse) > 0) then {01/01/05} FOnDisplay(Self, @FLastResponse[1], Length(FLastResponse)); {$IFDEF VER80} { Add a nul byte at the end of string for Delphi 1 } FLastResponse[Length(FLastResponse) + 1] := #0; {$ENDIF} if FState = nntpWaitingBanner then begin StateChange(nntpReady); GetInteger(@FLastResponse[1], FStatusCode); FPostingPermited := (FStatusCode = 200); TriggerSessionConnected(ErrCode); {AS} { PostMessage en plus par rapport à avant (?) } PostMessage(Handle, FMsg_WM_NNTP_REQUEST_DONE, WORD(FRequestType), ErrCode); end else if FState = nntpWaitingResponse then begin if Assigned(FNext) then FNext else StateChange(nntpReady); end else begin if Assigned(FOnDataAvailable) then FOnDataAvailable(Self, ErrCode); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.TriggerSessionConnected(ErrCode: Word); begin if Assigned(FOnSessionConnected) then FOnSessionConnected(Self, ErrCode); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.TriggerMessageLine; begin if Assigned(FOnMessageLine) then FOnMessageLine(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.WSocketSessionClosed(Sender: TObject; ErrCode: Word); begin if not (FRequestType in [nntpAbort]) then DelayedRequestDone(ErrCode); if Assigned(FOnSessionClosed) then OnSessionClosed(Self, ErrCode); StateChange(nntpNotConnected); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.TriggerStateChange; begin if Assigned(FOnStateChange) then FOnStateChange(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.DelayedRequestDone(ErrCode: Word); begin if FRequestDoneFlag = FALSE then PostMessage(Handle, FMsg_WM_NNTP_REQUEST_DONE, WORD(FRequestType), ErrCode); FRequestDoneFlag := TRUE; FNext := nil; if FWSocket.State = wsConnected then StateChange(nntpReady) else StateChange(nntpNotConnected); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.TriggerSendData; begin if Assigned(FOnSendData) then FOnSendData(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNntpCli.TriggerRcvdData; begin if Assigned(FOnRcvdData) then FOnRcvdData(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor THtmlNntpCli.Create(AOwner: TComponent); begin inherited Create(AOwner); FAttachedFiles := TStringList.Create; FPlainText := TStringList.Create; FHtmlText := TStringList.Create; FHtmlCharSet := 'iso-8859-1'; FCharSet := 'iso-8859-1'; SetContentType(nntpHtml); Randomize; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor THtmlNntpCli.Destroy; begin if Assigned(FHeader) then begin FHeader.Destroy; FHeader := nil; end; if Assigned(FAttachedFiles) then begin FAttachedFiles.Destroy; FAttachedFiles := nil; end; if Assigned(FPlainText) then begin FPlainText.Destroy; FPlainText := nil; end; if Assigned(FHtmlText) then begin FHtmlText.Destroy; FHtmlText := nil; end; if Assigned(FStream) then begin FStream.Destroy; FStream := nil; end; inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THtmlNntpCli.SetContentType(newValue: TNntpContentType); begin if FContentType = newValue then Exit; FContentType := newValue; if FContentType = nntpPlainText then FContentTypeStr := 'text/plain' else FContentTypeStr := 'text/html'; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THtmlNntpCli.SetHtmlText(const newValue: TStrings); var I : Integer; begin FHtmlText.Clear; if Assigned(newValue) then for I := 0 to newValue.Count - 1 do FHtmlText.Add(newValue.Strings[I]); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THtmlNntpCli.SetPlainText(const newValue: TStrings); var I : Integer; begin FPlainText.Clear; if Assigned(newValue) then for I := 0 to newValue.Count - 1 do FPlainText.Add(newValue.Strings[I]); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THtmlNntpCli.SetAttachedFiles(const newValue: TStrings); var I : Integer; begin FAttachedFiles.Clear; if Assigned(newValue) then for I := 0 to newValue.Count - 1 do FAttachedFiles.Add(newValue.Strings[I]); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THtmlNntpCli.SetShareMode(newValue: TNntpShareMode); begin {$IFNDEF VER80}{$WARNINGS OFF}{$ENDIF} case newValue of nntpShareCompat : FShareMode := fmShareCompat; nntpShareExclusive : FShareMode := fmShareExclusive; nntpShareDenyWrite : FShareMode := fmShareDenyWrite; nntpShareDenyRead : FShareMode := fmShareDenyRead; nntpShareDenyNone : FShareMode := fmShareDenyNone; else FShareMode := fmShareDenyWrite; end; {$IFNDEF VER80}{$WARNINGS ON}{$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function THtmlNntpCli.GetShareMode: TNntpShareMode; begin begin {$IFNDEF VER80}{$WARNINGS OFF}{$ENDIF} case FShareMode of fmShareCompat : Result := nntpShareCompat; fmShareExclusive : Result := nntpShareExclusive; fmShareDenyWrite : Result := nntpShareDenyWrite; fmShareDenyRead : Result := nntpShareDenyRead; fmShareDenyNone : Result := nntpShareDenyNone; else Result := nntpShareDenyWrite; end; {$IFNDEF VER80}{$WARNINGS ON}{$ENDIF} end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THtmlNntpCli.GenerateBoundaries; var TickPart : String; RandPart : String; begin TickPart := '----=_NextPart_000_' + IntToHex(LongInt(GetTickCount), 8); RandPart := IntToHex(Random(High(Integer)), 8); FOutsideBoundary := TickPart + '_0.' + RandPart; FInsideBoundary := TickPart + '_1.' + RandPart; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THtmlNntpCli.BuildHeader; begin if not Assigned(FHeader) then FHeader := TStringList.Create else FHeader.Clear; GenerateBoundaries; FHeader.Add('From: ' + FHdrFrom); FHeader.Add('Newsgroups: ' + FHdrGroup); FHeader.Add('Subject: ' + FHdrSubject); FHeader.Add('Organization: None'); FHeader.Add('X-Newsreader: ICS NNTP component (http://www.overbyte.be)'); FHeader.Add('MIME-Version: 1.0'); FHeader.Add('Content-Type: multipart/related; ' + 'type="multipart/alternative"; ' + 'boundary="' + FOutsideBoundary + '";'); FHeader.Add(''); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THtmlNntpCli.Post(FromStream: TStream); begin FMimeState := nntpMimeHeader; FSentFlag := FALSE; FLineNumber := 0; BuildHeader; inherited Post(FromStream); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THtmlNntpCli.Display(const Msg : String); const NulString : String = #0; begin if Assigned(FOnDisplay) then begin if Msg <> '' then FOnDisplay(Self, @Msg[1], Length(Msg)) else FOnDisplay(Self, @NulString[1], 0); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THtmlNntpCli.SendLine(const MsgLine : String); begin FWSocket.SendStr(MsgLine + #13#10); Display(MsgLine); Inc(FSendCount, Length(MsgLine) + 2); Inc(FLineNumber); TriggerSendData; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THtmlNntpCli.PostBlock; var FileName : String; LineBuf : String; More : Boolean; begin if FMimeState = nntpMimeHeader then begin if FLineNumber < FHeader.Count then SendLine(FHeader.Strings[FLineNumber]) else begin FMimeState := nntpMimeIntro; FLineNumber := 0; end; end; if FMimeState = nntpMimeHeader then Exit; if FMimeState = nntpMimeIntro then begin case FLineNumber of 0: SendLine('This is a multipart MIME formatted message.'); 1, 4, 8: SendLine(''); 2: SendLine('--' + FOutsideBoundary); 3: SendLine('Content-Type: multipart/alternative; ' + 'boundary="' + FInsideBoundary + '"'); 5: SendLine('--' + FInsideBoundary); 6: SendLine('Content-Type: text/plain; charset="' + FCharSet + '"'); 7: SendLine('Content-Transfer-Encoding: quoted-printable'); 9: begin FMimeState := nntpMimePlainText; FLineNumber := 0; end; end; end; if FMimeState = nntpMimeIntro then Exit; if FMimeState = nntpMimePlainText then begin if FLineNumber < FPlainText.Count then begin LineBuf := FPlainText[FLineNumber]; if LineBuf > '' then begin { Common optimisation } LineBuf := SplitQuotedPrintableString( EncodeQuotedPrintable(LineBuf)); DotEscape(LineBuf); end; SendLine(LineBuf); end else begin case FLineNumber - FPlainText.Count of 0: SendLine(''); 1: SendLine('--' + FInsideBoundary); 2: SendLine('Content-Type: text/html; charset="' + FHtmlCharSet + '"'); 3: SendLine('Content-Transfer-Encoding: quoted-printable'); 4: SendLine(''); else FMimeState := nntpMimeHtmlText; FLineNumber := 0; end; end; end; if FMimeState = nntpMimePlainText then Exit; if FMimeState = nntpMimeHtmlText then begin if FLineNumber < FHtmlText.Count then begin LineBuf := FHtmlText[FLineNumber]; if LineBuf > '' then begin { Common optimisation } LineBuf := SplitQuotedPrintableString( EncodeQuotedPrintable(LineBuf)); DotEscape(LineBuf); end; SendLine(LineBuf); end else begin case FLineNumber - FHtmlText.Count of 0: SendLine(''); 1: SendLine('--' + FInsideBoundary + '--'); 2: SendLine(''); else FMimeState := nntpMimeImages; FImageNumber := 1; FLineNumber := 0; end; end; end; if FMimeState = nntpMimeHtmlText then Exit; if FMimeState = nntpMimeImages then begin if FImageNumber > FAttachedFiles.Count then begin case FLineNumber of 0: SendLine('--' + FOutsideBoundary + '--'); else FMimeState := nntpMimeDone; end; end else begin case FLineNumber of 0: SendLine('--' + FOutsideBoundary); 1: begin FileName := ExtractFileName(FAttachedFiles[FImageNumber - 1]); SendLine('Content-Type: ' + FilenameToContentType(FileName) + '; name="' + FileName + '"'); end; 2: SendLine('Content-Transfer-Encoding: base64'); 3: SendLine('Content-Disposition: inline; filename="' + ExtractFileName(FAttachedFiles[FImageNumber - 1]) + '"'); 4: SendLine('Content-ID: <IMAGE' + IntToStr(FImageNumber) + '>'); 5: begin SendLine(''); if Assigned(FStream) then FStream.Destroy; FStream := InitFileEncBase64(FAttachedFiles[FImageNumber - 1], FShareMode); end; else if Assigned(FStream) then begin LineBuf := DoFileEncBase64(FStream, More); SendLine(LineBuf); if not More then begin { We hit the end-of-file } EndFileEncBase64(FStream); end; end else begin { We hit the end of image file } SendLine(''); FLineNumber := 0; FImageNumber := FImageNumber + 1; end end; end; end; if FMimeState = nntpMimeImages then Exit; if FSentFlag then Exit; FSentFlag := TRUE; SendLine('.'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure THtmlNntpCli.TriggerRequestDone( Request : TNntpRequest; ErrCode : Word); begin if Assigned(FStream) then begin FStream.Destroy; FStream := nil; end; inherited TriggerRequestDone(Request, ErrCode); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { You must define USE_SSL so that SSL code is included in the component. } { To be able to compile the component, you must have the SSL related files } { which are _NOT_ freeware. See http://www.overbyte.be for details. } {$IFDEF USE_SSL} {$I NntpCliImplSsl.inc} {$ENDIF} end.