text
stringlengths
14
6.51M
{ $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.7 12/2/2004 4:23:58 PM JPMugaas Adjusted for changes in Core. Rev 1.6 10/26/2004 10:49:20 PM JPMugaas Updated ref. Rev 1.5 2004.02.03 5:44:30 PM czhower Name changes Rev 1.4 1/21/2004 4:04:04 PM JPMugaas InitComponent Rev 1.3 2/24/2003 10:29:50 PM JPMugaas Rev 1.2 1/17/2003 07:10:58 PM JPMugaas Now compiles under new framework. Rev 1.1 1/8/2003 05:53:54 PM JPMugaas Switched stuff to IdContext. Rev 1.0 11/13/2002 08:02:28 AM JPMugaas } unit IdSystatServer; { Indy Systat Client TIdSystatServer Copyright (C) 2002 Winshoes Working Group Original author J. Peter Mugaas 2002-August-13 Based on RFC 866 Note that this protocol is officially called Active User } interface {$i IdCompilerDefines.inc} uses Classes, IdAssignedNumbers, IdContext, IdCustomTCPServer; type TIdSystatEvent = procedure (AThread: TIdContext; AResults : TStrings) of object; Type TIdSystatServer = class(TIdCustomTCPServer) protected FOnSystat : TIdSystatEvent; // function DoExecute(AThread: TIdContext): boolean; override; procedure InitComponent; override; published property OnSystat : TIdSystatEvent read FOnSystat write FOnSystat; property DefaultPort default IdPORT_SYSTAT; end; { Note that no result parsing is done because RFC 866 does not specify a syntax for a user list. Quoted from RFC 866: There is no specific syntax for the user list. It is recommended that it be limited to the ASCII printing characters, space, carriage return, and line feed. Each user should be listed on a separate line. } implementation uses IdGlobal, SysUtils; { TIdSystatServer } procedure TIdSystatServer.InitComponent; begin inherited; DefaultPort := IdPORT_SYSTAT; end; function TIdSystatServer.DoExecute(AThread: TIdContext): boolean; var s : TStrings; begin Result := True; if Assigned(FOnSystat) then begin s := TStringList.Create; try FOnSystat(AThread,s); AThread.Connection.IOHandler.Write(s.Text); finally FreeAndNil(s); end; AThread.Connection.Disconnect; end; end; end.
unit RemoveEmptyComment; {(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is RemoveEmptyComment, released Nov 2003. The Initial Developer of the Original Code is Anthony Steele. Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele. All Rights Reserved. Contributor(s): Anthony Steele. The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"). you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/NPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL") See http://www.gnu.org/licenses/gpl.html ------------------------------------------------------------------------------*) {*)} {$I JcfGlobal.inc} interface { AFS 9 Nov 2003 Remove empty comments } uses SwitchableVisitor; type TRemoveEmptyComment = class(TSwitchableVisitor) private protected function EnabledVisitSourceToken(const pcNode: TObject): Boolean; override; public constructor Create; override; function IsIncludedInSettings: boolean; override; end; implementation uses { system } SysUtils, { local } JcfStringUtils, FormatFlags, SourceToken, Tokens, TokenUtils, JcfSettings; constructor TRemoveEmptyComment.Create; begin inherited; FormatFlags := FormatFlags + [eRemoveComments]; end; function TRemoveEmptyComment.EnabledVisitSourceToken(const pcNode: TObject): Boolean; var lcSourceToken: TSourceToken; lsCommentText: string; begin Result := False; lcSourceToken := TSourceToken(pcNode); case lcSourceToken.CommentStyle of eDoubleSlash: begin if JcfFormatSettings.Comments.RemoveEmptyDoubleSlashComments then begin lsCommentText := StrAfter('//', lcSourceToken.SourceCode); lsCommentText := Trim(lsCommentText); if lsCommentText = '' then BlankToken(lcSourceToken); end; end; eCurlyBrace: begin if JcfFormatSettings.Comments.RemoveEmptyCurlyBraceComments then begin lsCommentText := StrAfter('{', lcSourceToken.SourceCode); lsCommentText := StrBefore('}', lsCommentText); lsCommentText := Trim(lsCommentText); if lsCommentText = '' then BlankToken(lcSourceToken); end; end; eBracketStar, eCompilerDirective: ; // always leave these eNotAComment: ; // this is not a comment else // should not be here Assert(False); end; end; function TRemoveEmptyComment.IsIncludedInSettings: boolean; begin Result := JcfFormatSettings.Comments.RemoveEmptyDoubleSlashComments or JcfFormatSettings.Comments.RemoveEmptyCurlyBraceComments; end; end.
//////////////////////////////////////////////////////////////////////////////// // // // FileName : SUISideChannel.pas // Creator : Shen Min // Date : 2002-5-13 V1-V3 // 2003-7-11 V4 // Comment : // // Copyright (c) 2002-2003 Sunisoft // http://www.sunisoft.com // Email: support@sunisoft.com // //////////////////////////////////////////////////////////////////////////////// unit SUISideChannel; interface {$I SUIPack.inc} uses Windows, Messages, SysUtils, Classes, Controls, ExtCtrls, Buttons, Graphics, Forms, Math, SUIThemes, SUIMgr; type TsuiSideChannelAlign = (suiLeft, suiRight); TsuiSideChannelPopupMode = (suiMouseOn, suiMouseClick); TsuiSideChannel = class(TCustomPanel) private m_PinBtn : TSpeedButton; m_UIStyle : TsuiUIStyle; m_FileTheme : TsuiFileTheme; m_BorderColor : TColor; m_TitleBitmap : TBitmap; m_HandleBitmap : TBitmap; m_SideColor : TColor; m_CaptionFontColor : TColor; m_Poped : Boolean; m_ShowButton : Boolean; m_FromTheme : Boolean; m_Timer : TTimer; m_nWidth : Integer; m_bMoving : Boolean; m_Align : TsuiSideChannelAlign; m_StayOn : Boolean; m_PopupMode : TsuiSideChannelPopupMode; m_QuickMove : Boolean; m_OnPop : TNotifyEvent; m_OnPush : TNotifyEvent; m_OnPin : TNotifyEvent; m_OnUnPin : TNotifyEvent; procedure OnPinClick(Sender: TObject); procedure OnTimerCheck(Sender: TObject); procedure SetWidth(NewValue : Integer); procedure SetSideColor(NewValue : TColor); function GetSideColor() : TColor; function GetSideWidth() : Integer; procedure SetAlign(const Value : TsuiSideChannelAlign); procedure SetStayOn(const Value : Boolean); procedure SetFileTheme(const Value: TsuiFileTheme); procedure SetUIStyle(const Value: TsuiUIStyle); procedure SetBorderColor(const Value: TColor); procedure SetCaptionFontColor(const Value: TColor); procedure SetSideWidth(const Value: Integer); procedure SetHandleBitmap(const Value: TBitmap); procedure SetTitleBitmap(const Value: TBitmap); procedure SetShowButton(const Value: Boolean); procedure WMERASEBKGND(var Msg : TMessage); message WM_ERASEBKGND; procedure CMTextChanged(var Msg : TMessage); message CM_TEXTCHANGED; protected procedure Paint(); override; procedure Resize(); override; function CanResize(var NewWidth, NewHeight: Integer): Boolean; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure AlignControls(AControl: TControl; var Rect: TRect); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public constructor Create(AOwner : TComponent); override; destructor Destroy(); override; procedure Pop(bQuick : Boolean = true); procedure Push(bQuick : Boolean = true); property HandleImage : TBitmap read m_HandleBitmap write SetHandleBitmap; property TitleImage : TBitmap read m_TitleBitmap write SetTitleBitmap; published property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme; property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle; property BorderColor : TColor read m_BorderColor write SetBorderColor; property CaptionFontColor : TColor read m_CaptionFontColor write SetCaptionFontColor; property ShowButton : Boolean read m_ShowButton write SetShowButton; property Popped : Boolean read m_Poped; property Anchors; property BiDiMode; property Width read m_nWidth write SetWidth; property SideBarColor : TColor read GetSideColor write SetSideColor; property Caption; property Font; property Alignment; property Align : TsuiSideChannelAlign read m_Align write SetAlign; property StayOn : Boolean read m_StayOn write SetStayOn; property Visible; property Color; property ParentColor; property ParentShowHint; property ParentBiDiMode; property ParentFont; property PopupMenu; property PopupMode : TsuiSideChannelPopupMode read m_PopupMode write m_PopupMode; property QuickMove : Boolean read m_QuickMove write m_QuickMove; property OnResize; property OnCanResize; property OnPush : TNotifyEvent read m_OnPush write m_OnPush; property OnPop : TNotifyEvent read m_OnPop write m_OnPop; property OnPin : TNotifyEvent read m_OnPin write m_OnPin; property OnUnPin : TNotifyEvent read m_OnUnPin write m_OnUnPin; property OnMouseDown; property OnMouseMove; property OnMouseUp; // no use, only for compatibility property SideBarWidth : Integer read GetSideWidth write SetSideWidth; end; implementation uses SUIResDef, SUIPublic; { TsuiSideChannel } constructor TsuiSideChannel.Create(AOwner: TComponent); begin inherited Create(AOwner); m_TitleBitmap := TBitmap.Create(); m_HandleBitmap := TBitmap.Create(); m_FromTheme := false; m_PinBtn := TSpeedButton.Create(self); m_PinBtn.Parent := self; m_PinBtn.Flat := true; m_PinBtn.Height := 16; m_PinBtn.Width := 20; m_PinBtn.GroupIndex := 1; m_PinBtn.AllowAllUp := true; m_PinBtn.Glyph.LoadFromResourceName(hInstance, 'SIDECHANNEL_BTN'); m_PinBtn.Top := 1; m_PinBtn.Left := Width - m_PinBtn.Width - 1; m_PinBtn.OnClick := OnPinClick; ShowButton := true; m_Timer := TTimer.Create(self); m_Timer.Interval := 1000; m_Timer.Enabled := false; m_Timer.OnTimer := OnTimerCheck; m_bMoving := false; BevelOuter := bvNone; Align := suiLeft; SideBarColor := clBtnFace; PopupMode := suiMouseOn; QuickMove := false; Font.Name := 'Tahoma'; m_Poped := false; UIStyle := GetSUIFormStyle(AOwner); if (csDesigning in ComponentState) then Exit; Push(true); end; destructor TsuiSideChannel.Destroy; begin m_Timer.Free(); m_PinBtn.Free(); m_HandleBitmap.Free(); m_TitleBitmap.Free(); inherited; end; procedure TsuiSideChannel.OnTimerCheck(Sender: TObject); var CurPos : TPoint; LeftTop : TPoint; RightBottum : TPoint; begin if m_bMoving then Exit; LeftTop.x := 0; LeftTop.y := 0; RightBottum.x := inherited Width; RightBottum.y := Height; GetCursorPos(CurPos); if Parent <> nil then begin LeftTop := ClientToScreen(LeftTop); RightBottum := ClientToScreen(RightBottum); end else Push(m_QuickMove); if ( (CurPos.x > LeftTop.x) and (CurPos.x < RightBottum.x) and (CurPos.y > LeftTop.y) and (CurPos.y < RightBottum.y) ) then Exit; // in // out Push(m_QuickMove); end; procedure TsuiSideChannel.Pop(bQuick : Boolean = true); begin m_bMoving := true; m_PinBtn.Visible := true; if not bQuick then begin while inherited Width + 15 < m_nWidth do begin inherited Width := inherited Width + 15; Refresh(); Application.ProcessMessages(); end; end; inherited Width := m_nWidth; Refresh(); m_Timer.Enabled := true; m_bMoving := false; m_Poped := true; Repaint(); if Assigned (m_OnPop) then m_OnPop(self); end; procedure TsuiSideChannel.Push(bQuick : Boolean = true); begin m_bMoving := true; m_Poped := false; m_Timer.Enabled := false; if not bQuick then begin while inherited Width - 15 > 10 do begin inherited Width := inherited Width - 15; Refresh(); Application.ProcessMessages(); end; end; inherited Width := 10; Refresh(); m_PinBtn.Visible := false; m_bMoving := false; Repaint(); if Assigned(m_OnPush) then m_OnPush(self); end; procedure TsuiSideChannel.SetWidth(NewValue: Integer); begin m_nWidth := NewValue; if (csDesigning in ComponentState) or m_Poped then inherited Width := m_nWidth; end; function TsuiSideChannel.GetSideColor: TColor; begin Result := m_SideColor; end; procedure TsuiSideChannel.SetSideColor(NewValue: TColor); begin m_SideColor := NewValue; Repaint(); end; procedure TsuiSideChannel.OnPinClick(Sender: TObject); begin m_Timer.Enabled := not m_PinBtn.Down; m_PinBtn.Glyph.LoadFromResourceName(hInstance, 'SIDECHANNEL_BTN'); if m_PinBtn.Down then RoundPicture3(m_PinBtn.Glyph); m_StayOn := m_PinBtn.Down; if m_StayOn then begin if Assigned(m_OnPin) then m_OnPin(self); end else begin if Assigned(m_OnUnPin) then m_OnUnPin(self); end; end; function TsuiSideChannel.GetSideWidth: Integer; begin Result := 10; end; procedure TsuiSideChannel.SetAlign(const Value: TsuiSideChannelAlign); begin m_Align := Value; if m_Align = suiLeft then inherited Align := alLeft else inherited Align := alRight; end; procedure TsuiSideChannel.SetStayOn(const Value: Boolean); begin m_StayOn := Value; if Value then begin if not (csDesigning in ComponentState) then Pop(m_QuickMove); m_PinBtn.Down := true; end else begin m_PinBtn.Down := false; if not (csDesigning in ComponentState) then Push(true); end; Resize(); if not (csDesigning in ComponentState) then m_PinBtn.Click(); end; procedure TsuiSideChannel.Paint; var Buf : TBitmap; R : TRect; Y : Integer; begin Buf := TBitmap.Create(); Buf.Width := inherited Width; Buf.Height := Height; Buf.Canvas.Brush.Color := Color; Buf.Canvas.Pen.Color := m_BorderColor; Buf.Canvas.Rectangle(ClientRect); R := Rect(1, 0, inherited Width - 1, m_TitleBitmap.Height); Buf.Canvas.StretchDraw(R, m_TitleBitmap); if m_Poped or (csDesigning in ComponentState) then begin R.Left := R.Left + m_PinBtn.Width; R.Right := R.Right - m_PinBtn.Width; Buf.Canvas.Font.Assign(Font); Buf.Canvas.Font.Color := m_CaptionFontColor; Buf.Canvas.Brush.Style := bsClear; case Alignment of taLeftJustify : DrawText(Buf.Canvas.Handle, PChar(Caption), -1, R, DT_LEFT or DT_SINGLELINE or DT_VCENTER); taCenter : DrawText(Buf.Canvas.Handle, PChar(Caption), -1, R, DT_CENTER or DT_SINGLELINE or DT_VCENTER); taRightJustify : DrawText(Buf.Canvas.Handle, PChar(Caption), -1, R, DT_RIGHT or DT_SINGLELINE or DT_VCENTER); end; end; R := Rect(1, m_TitleBitmap.Height, 9, Height - 1); Buf.Canvas.Brush.Color := m_SideColor; Buf.Canvas.FillRect(R); Buf.Canvas.Pen.Color := clGray; Buf.Canvas.MoveTo(9, m_TitleBitmap.Height); Buf.Canvas.LineTo(9, Height - 1); Y := (Height - m_HandleBitmap.Height) div 2; if Y < m_TitleBitmap.Height + 1 then Y := m_TitleBitmap.Height + 1; Buf.Canvas.Draw(1, Y, m_HandleBitmap); BitBlt(Canvas.Handle, 0, 0, Width, Height, Buf.Canvas.Handle, 0, 0, SRCCOPY); Buf.Free(); end; procedure TsuiSideChannel.Resize; begin inherited; if ( (not m_bMoving) and (inherited Width > 10) ) then begin m_nWidth := inherited Width; end; m_PinBtn.Left := Width - m_PinBtn.Width - 1; end; function TsuiSideChannel.CanResize(var NewWidth, NewHeight: Integer): Boolean; begin if ( (not m_bMoving) and (m_PinBtn.Visible) and (NewWidth < 50) ) then Result := false else Result := true; end; procedure TsuiSideChannel.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if ( (Operation = opRemove) and (AComponent = m_FileTheme) )then begin m_FileTheme := nil; ContainerApplyUIStyle(self, SUI_THEME_DEFAULT, nil); SetUIStyle(SUI_THEME_DEFAULT); end; end; procedure TsuiSideChannel.SetFileTheme(const Value: TsuiFileTheme); begin m_FileTheme := Value; m_FromTheme := true; SetUIStyle(m_UIStyle); m_FromTheme := false; end; procedure TsuiSideChannel.SetUIStyle(const Value: TsuiUIStyle); var OutUIStyle : TsuiUIStyle; begin m_UIStyle := Value; if m_FromTheme and (m_UIStyle <> FromThemeFile) then Exit; Color := clWhite; if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then begin m_SideColor := m_FileTheme.GetColor(SUI_THEME_FORM_BACKGROUND_COLOR); m_FileTheme.GetBitmap(SUI_THEME_SIDECHENNEL_HANDLE_IMAGE, m_HandleBitmap); m_FileTheme.GetBitmap(SUI_THEME_SIDECHENNEL_BAR_IMAGE, m_TitleBitmap); m_BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR); m_CaptionFontColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_FONT_COLOR); if ( (m_CaptionFontColor = 131072) or (m_CaptionFontColor = 262144) or (m_CaptionFontColor = 196608) or (m_CaptionFontColor = 327680) or (m_CaptionFontColor = 8016662) or (m_CaptionFontColor = 2253583) ) then m_CaptionFontColor := clBlack else m_CaptionFontColor := clWhite; end else begin m_SideColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_FORM_BACKGROUND_COLOR); GetInsideThemeBitmap(OutUIStyle, SUI_THEME_SIDECHENNEL_HANDLE_IMAGE, m_HandleBitmap); GetInsideThemeBitmap(OutUIStyle, SUI_THEME_SIDECHENNEL_BAR_IMAGE, m_TitleBitmap); m_BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR); {$IFDEF RES_MACOS} if OutUIStyle = MacOS then m_CaptionFontColor := clBlack else {$ENDIF} m_CaptionFontColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_SELECTED_FONT_COLOR); end; if m_ShowButton then m_PinBtn.Top := Min((m_TitleBitmap.Height - m_PinBtn.Height) div 2, 5) else begin m_PinBtn.Top := -50; StayOn := True; end; ContainerApplyUIStyle(self, OutUIStyle, m_FileTheme); Repaint(); end; procedure TsuiSideChannel.SetBorderColor(const Value: TColor); begin m_BorderColor := Value; Repaint(); end; procedure TsuiSideChannel.SetCaptionFontColor(const Value: TColor); begin m_CaptionFontColor := Value; Repaint(); end; procedure TsuiSideChannel.AlignControls(AControl: TControl; var Rect: TRect); begin Rect.Right := Rect.Right - 3; Rect.Bottom := Rect.Bottom - 3; Rect.Top := Rect.Top + m_TitleBitmap.Height + 3; Rect.Left := Rect.Left + 13; inherited AlignControls(AControl, Rect); end; procedure TsuiSideChannel.MouseMove(Shift: TShiftState; X, Y: Integer); var Form : TCustomForm; begin inherited; if m_bMoving then Exit; if ( m_Poped or (m_PopupMode <> suiMouseOn) ) then Exit; Form := GetParentForm(self); if Form = nil then Exit; if (not Form.Active) and ((Form as TForm).FormStyle <> fsMDIForm) then Exit; if not FormHasFocus(Form) then Exit; Pop(m_QuickMove); end; procedure TsuiSideChannel.SetSideWidth(const Value: Integer); begin // do nothing end; procedure TsuiSideChannel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if m_Poped or (m_PopupMode <> suiMouseClick) then Exit; Pop(m_QuickMove); end; procedure TsuiSideChannel.SetHandleBitmap(const Value: TBitmap); begin m_HandleBitmap.Assign(Value); Repaint(); end; procedure TsuiSideChannel.SetTitleBitmap(const Value: TBitmap); begin m_TitleBitmap.Assign(Value); Repaint(); end; procedure TsuiSideChannel.WMERASEBKGND(var Msg: TMessage); begin // do nothing end; procedure TsuiSideChannel.CMTextChanged(var Msg: TMessage); begin Repaint(); end; procedure TsuiSideChannel.SetShowButton(const Value: Boolean); begin m_ShowButton := Value; if Value then begin m_PinBtn.Top := 1; end else begin m_PinBtn.Top := -50; StayOn := True; end; end; end.
unit TableWithProgress; interface uses FireDAC.Comp.Client, ProgressInfo, NotifyEvents, System.Classes, ProcRefUnit; type TTableWithProgress = class(TFDMemTable, IHandling) private FOnProgress: TNotifyEventsEx; FPI: TProgressInfo; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CallOnProcessEvent; procedure Process(AProcRef: TProcRef; ANotifyEventRef: TNotifyEventRef); overload; property OnProgress: TNotifyEventsEx read FOnProgress; end; implementation uses System.SysUtils, ProgressBarForm; constructor TTableWithProgress.Create(AOwner: TComponent); begin inherited; FPI := TProgressInfo.Create; FOnProgress := TNotifyEventsEx.Create(Self); end; destructor TTableWithProgress.Destroy; begin FreeAndNil(FOnProgress); FreeAndNil(FPI); inherited; end; procedure TTableWithProgress.CallOnProcessEvent; begin Assert(Active); Assert(FPI <> nil); FPI.TotalRecords := RecordCount; FPI.ProcessRecords := RecNo; OnProgress.CallEventHandlers(FPI) end; procedure TTableWithProgress.Process(AProcRef: TProcRef; ANotifyEventRef: TNotifyEventRef); var ne: TNotifyEventR; begin Assert(Assigned(AProcRef)); // Подписываем кого-то на событие ne := TNotifyEventR.Create(OnProgress, ANotifyEventRef); try // Вызываем метод, обрабатывающий нашу таблицу AProcRef(Self); finally // Отписываем кого-то от события FreeAndNil(ne); end; end; end.
unit AccountTypeList; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseGridDetail, Data.DB, RzButton, Vcl.StdCtrls, Vcl.Mask, RzEdit, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzLabel, Vcl.ExtCtrls, RzPanel, RzDBEdit, Vcl.DBCtrls; type TfrmAccountTypeList = class(TfrmBaseGridDetail) edTypeName: TRzDBEdit; RzDBMemo1: TRzDBMemo; Label2: TLabel; Label3: TLabel; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } protected function EntryIsValid: boolean; override; function NewIsAllowed: boolean; override; function EditIsAllowed: boolean; override; procedure SearchList; override; procedure BindToObject; override; end; var frmAccountTypeList: TfrmAccountTypeList; implementation {$R *.dfm} uses LoansAuxData, IFinanceDialogs; procedure TfrmAccountTypeList.FormClose(Sender: TObject; var Action: TCloseAction); begin dmLoansAux.Free; inherited; end; procedure TfrmAccountTypeList.FormCreate(Sender: TObject); begin dmLoansAux := TdmLoansAux.Create(self); inherited; end; function TfrmAccountTypeList.NewIsAllowed: boolean; begin Result := true; end; procedure TfrmAccountTypeList.SearchList; begin grList.DataSource.DataSet.Locate('acct_type_name',edSearchKey.Text, [loPartialKey,loCaseInsensitive]); end; procedure TfrmAccountTypeList.BindToObject; begin inherited; end; function TfrmAccountTypeList.EditIsAllowed: boolean; begin Result := true; end; function TfrmAccountTypeList.EntryIsValid: boolean; var error: string; begin if Trim(edTypeName.Text) = '' then error := 'Please enter a type name.'; if error <> '' then ShowErrorBox(error); Result := error = ''; end; end.
{*************************************************************** * * Project : Demo * Unit Name: Main * Purpose : Tunnel demonstration * Version : 1.0 * Date : Wed 25 Apr 2001 - 01:41:00 * Author : Gregor Ibic * History : * Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com> * ****************************************************************} unit Main; interface uses {$IFDEF Linux} QGraphics, QControls, QForms, QDialogs, QExtCtrls, QStdCtrls, QButtons, {$ELSE} windows, messages, graphics, controls, forms, dialogs, extctrls, stdctrls, buttons, {$ENDIF} SysUtils, Classes, IdTunnelSlave, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdTunnelMaster, QTypes; type TfrmMain = class(TForm) Panel2: TPanel; lblSlaves: TLabel; Label3: TLabel; lblServices: TLabel; Label4: TLabel; Label1: TLabel; Panel3: TPanel; lblClients: TLabel; Label5: TLabel; Label2: TLabel; Panel1: TPanel; btnStart: TBitBtn; btnStop: TBitBtn; tmrRefresh: TTimer; procedure tmrRefreshTimer(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } public { Public declarations } Master: TIdTunnelMaster; Slave: TIdTunnelSlave; end; var frmMain: TfrmMain; implementation {$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF} uses IdGlobal; procedure TfrmMain.tmrRefreshTimer(Sender: TObject); begin if Slave.Active then begin lblClients.Caption := IntToStr(Slave.NumClients); end; if Master.Active then begin lblSlaves.Caption := IntToStr(Master.NumSlaves); lblServices.Caption := IntToStr(Master.NumServices); end; end; procedure TfrmMain.btnStartClick(Sender: TObject); begin btnStart.Enabled := False; btnStop.Enabled := True; Master.Active := True; sleep(100); Slave.Active := True; tmrRefresh.Enabled := True; end; procedure TfrmMain.btnStopClick(Sender: TObject); begin tmrRefresh.Enabled := False; btnStart.Enabled := True; btnStop.Enabled := False; Slave.Active := False; lblClients.Caption := '0'; sleep(100); // only for Master to realize that something happened // before printing to the screen. It is not needed in real // app if Master.Active then begin lblSlaves.Caption := IntToStr(Master.NumSlaves); lblServices.Caption := IntToStr(Master.NumServices); end; Master.Active := False; end; procedure TfrmMain.FormCreate(Sender: TObject); begin Master := TIdTunnelMaster.Create(self); Master.MappedHost := '127.0.0.1'; Master.MappedPort := 80; Master.LockDestinationHost := True; Master.LockDestinationPort := True; Master.DefaultPort := 9000; Master.Bindings.Add; Slave := TIdTunnelSlave.Create(self); Slave.MasterHost := '127.0.0.1'; Slave.MasterPort := 9000; Slave.Socks4 := False; Slave.DefaultPort := 8080; Slave.Bindings.Add; end; procedure TfrmMain.FormDestroy(Sender: TObject); begin Slave.Active := False; Master.Active := False; sleep(100); Slave.Destroy; Master.Destroy; end; end.
{ Default drawing engine based on LCL-only routines Copyright (C) 2019 Werner Pamler (user wpat Lazarus forum https://forum.lazarus.freepascal.org) License: modified LGPL with linking exception (like RTL, FCL and LCL) See the file COPYING.modifiedLGPL.txt, included in the Lazarus distribution, for details about the license. See also: https://wiki.lazarus.freepascal.org/FPC_modified_LGPL } unit mvDE_LCL; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, Types, IntfGraphics, mvDrawingEngine; type TMvLCLDrawingEngine = class(TMvCustomDrawingEngine) private FBuffer: TBitmap; protected function GetBrushColor: TColor; override; function GetBrushStyle: TBrushStyle; override; function GetFontColor: TColor; override; function GetFontName: String; override; function GetFontSize: Integer; override; function GetFontStyle: TFontStyles; override; function GetPenColor: TColor; override; function GetPenWidth: Integer; override; procedure SetBrushColor(AValue: TColor); override; procedure SetBrushStyle(AValue: TBrushStyle); override; procedure SetFontColor(AValue: TColor); override; procedure SetFontName(AValue: String); override; procedure SetFontSize(AValue: Integer); override; procedure SetFontStyle(AValue: TFontStyles); override; procedure SetPenColor(AValue: TColor); override; procedure SetPenWidth(AValue: Integer); override; public destructor Destroy; override; procedure CreateBuffer(AWidth, AHeight: Integer); override; procedure DrawBitmap(X, Y: Integer; ABitmap: TCustomBitmap; {%H-}UseAlphaChannel: Boolean); override; procedure DrawLazIntfImage(X, Y: Integer; AImg: TLazIntfImage); override; procedure Ellipse(X1, Y1, X2, Y2: Integer); override; procedure FillRect(X1, Y1, X2, Y2: Integer); override; procedure Line(X1, Y1, X2, Y2: Integer); override; procedure PaintToCanvas(ACanvas: TCanvas); override; procedure Rectangle(X1, Y1, X2, Y2: Integer); override; function SaveToImage(AClass: TRasterImageClass): TRasterImage; override; function TextExtent(const AText: String): TSize; override; procedure TextOut(X, Y: Integer; const AText: String); override; end; implementation uses LCLType; destructor TMvLCLDrawingEngine.Destroy; begin FBuffer.Free; inherited; end; procedure TMvLCLDrawingEngine.CreateBuffer(AWidth, AHeight: Integer); begin FBuffer.Free; FBuffer := TBitmap.Create; FBuffer.PixelFormat := pf32Bit; FBuffer.SetSize(AWidth, AHeight); end; procedure TMvLCLDrawingEngine.DrawBitmap(X, Y: Integer; ABitmap: TCustomBitmap; UseAlphaChannel: Boolean); begin FBuffer.Canvas.Draw(X, Y, ABitmap); end; procedure TMvLCLDrawingEngine.DrawLazIntfImage(X, Y: Integer; AImg: TLazIntfImage); var bmp: TBitmap; h, mh: HBITMAP; begin bmp := TBitmap.Create; try bmp.PixelFormat := pf32Bit; bmp.SetSize(AImg.Width, AImg.Height); AImg.CreateBitmaps(h, mh); bmp.Handle := h; bmp.MaskHandle := mh; FBuffer.Canvas.Draw(X, Y, bmp); finally bmp.Free; end; end; procedure TMvLCLDrawingEngine.Ellipse(X1, Y1, X2, Y2: Integer); begin FBuffer.Canvas.Ellipse(X1,Y1, X2, Y2); end; procedure TMvLCLDrawingEngine.FillRect(X1, Y1, X2, Y2: Integer); begin FBuffer.Canvas.FillRect(X1,Y1, X2, Y2); end; function TMvLCLDrawingEngine.GetBrushColor: TColor; begin Result := FBuffer.Canvas.Brush.Color; end; function TMvLCLDrawingEngine.GetBrushStyle: TBrushStyle; begin Result := FBuffer.Canvas.Brush.Style end; function TMvLCLDrawingEngine.GetFontColor: TColor; begin Result := FBuffer.Canvas.Font.Color end; function TMvLCLDrawingEngine.GetFontName: String; begin Result := FBuffer.Canvas.Font.Name; end; function TMvLCLDrawingEngine.GetFontSize: Integer; begin Result := FBuffer.Canvas.Font.Size; end; function TMvLCLDrawingEngine.GetFontStyle: TFontStyles; begin Result := FBuffer.Canvas.Font.Style; end; function TMvLCLDrawingEngine.GetPenColor: TColor; begin Result := FBuffer.Canvas.Pen.Color; end; function TMvLCLDrawingEngine.GetPenWidth: Integer; begin Result := FBuffer.Canvas.Pen.Width; end; procedure TMvLCLDrawingEngine.Line(X1, Y1, X2, Y2: Integer); begin FBuffer.Canvas.Line(X1, Y1, X2, Y2); end; procedure TMvLCLDrawingEngine.PaintToCanvas(ACanvas: TCanvas); begin ACanvas.Draw(0, 0, FBuffer); end; procedure TMvLCLDrawingEngine.Rectangle(X1, Y1, X2, Y2: Integer); begin FBuffer.Canvas.Rectangle(X1,Y1, X2, Y2); end; function TMvLCLDrawingEngine.SaveToImage(AClass: TRasterImageClass): TRasterImage; begin Result := AClass.Create; Result.Width := FBuffer.Width; Result.Height := FBuffer.Height; Result.Canvas.FillRect(0, 0, Result.Width, Result.Height); Result.Canvas.Draw(0, 0, FBuffer); end; procedure TMvLCLDrawingEngine.SetBrushColor(AValue: TColor); begin FBuffer.Canvas.Brush.Color := AValue; end; procedure TMvLCLDrawingEngine.SetBrushStyle(AValue: TBrushStyle); begin FBuffer.Canvas.Brush.Style := AValue; end; procedure TMvLCLDrawingEngine.SetFontColor(AValue: TColor); begin FBuffer.Canvas.Font.Color := AValue; end; procedure TMvLCLDrawingEngine.SetFontName(AValue: String); begin FBuffer.Canvas.Font.Name := AValue; end; procedure TMvLCLDrawingEngine.SetFontSize(AValue: Integer); begin FBuffer.Canvas.Font.Size := AValue; end; procedure TMvLCLDrawingEngine.SetFontStyle(AValue: TFontStyles); begin FBuffer.Canvas.Font.Style := AValue; end; procedure TMvLCLDrawingEngine.SetPenColor(AValue: TColor); begin FBuffer.Canvas.Pen.Color := AValue; end; procedure TMvLCLDrawingEngine.SetPenWidth(AValue: Integer); begin FBuffer.Canvas.Pen.Width := AValue; end; function TMvLCLDrawingEngine.TextExtent(const AText: String): TSize; begin Result := FBuffer.Canvas.TextExtent(AText) end; procedure TMvLCLDrawingEngine.TextOut(X, Y: Integer; const AText: String); begin if (AText <> '') then FBuffer.Canvas.TextOut(X, Y, AText); end; end.
(* MPC: MM, 2020-04-29 *) (* ---- *) (* MiniPascal compiler. *) (* ========================================================================= *) PROGRAM MPC; USES MPL, MPPC; VAR inputFilePath: STRING; BEGIN (* MPI *) IF (ParamCount = 1) THEN BEGIN inputFilePath := ParamStr(1); END ELSE BEGIN Write('MiniPascal source file > '); ReadLn(inputFilePath); END; (* IF *) InitLex(inputFilePath); S; IF (success) THEN BEGIN WriteLn('parsing completed: success'); END ELSE BEGIN WriteLn('parsing failed. ERROR at position (', syLineNr, ',', syColNr, ')'); END; (* IF *) END. (* MPI *)
{route certain lines from a file to a new file} PROGRAM extract; { usage: EXTRACT InFileName OutFileName } uses FileOps; {directOutput, Exist} CONST tag = '#'; VAR outname, Name : string; infile, outfile : TEXT; WriteDate, Skip : BOOLEAN; PROCEDURE ProcessText; CONST CutOff = 16; VAR line, header, date : STRING; SkipCount, day, err : INTEGER; BEGIN SkipCount := 0; WHILE NOT eof(infile) DO BEGIN readln(infile,line); IF pos(tag,line) = 1 THEN BEGIN { start of msg } readln(infile,date); val(copy(date,5,2),day,err); IF day < CutOff THEN BEGIN Skip := TRUE; inc(SkipCount); END ELSE BEGIN Skip := FALSE; WriteDate := TRUE; END; END; {write out each line} IF NOT Skip THEN writeln(outfile,line); IF WriteDate THEN BEGIN writeln(outfile,date); WriteDate := FALSE; END; END; Writeln(SkipCount,' Messages Skipped.'); END; PROCEDURE DoFile; BEGIN Skip := FALSE; WriteDate := FALSE; Name := paramstr(1); outname := paramstr(2); IF (Name = '') or not Exist(Name) THEN BEGIN writeln(Name,' not found. Quitting.'); EXIT; END; assign(infile,Name); reset(infile); IF outname = '' THEN DirectOutput(outfile) ELSE BEGIN assign(outfile,outName); rewrite(outfile); END; ProcessText; close(infile); close(outfile); END {Main}; BEGIN DoFile; END.
{ Extended checked controls (radiobutton, checkbox, radiogroup, checkgroup) Copyright (C) 2020 Lazarus team This library is free software; you can redistribute it and/or modify it under the same terms as the Lazarus Component Library (LCL) See the file COPYING.modifiedLGPL.txt, included in the Lazarus distribution, for details about the license. } unit ExCheckCtrls; {$mode objfpc}{$H+} interface uses LCLType, LCLIntf, LCLProc, LMessages, Graphics, Classes, SysUtils, Types, Themes, Controls, StdCtrls, ExtCtrls, ImgList; type TGetImageIndexEvent = procedure (Sender: TObject; AHover, APressed, AEnabled: Boolean; AState: TCheckboxState; var AImgIndex: Integer) of object; { TCustomCheckControlEx } TCustomCheckControlEx = class(TCustomControl) private type TCheckControlKind = (cckCheckbox, cckRadioButton); private FAlignment: TLeftRight; FAllowGrayed: Boolean; FThemedBtnSize: TSize; FBtnLayout: TTextLayout; FDistance: Integer; // between button and caption FDrawFocusRect: Boolean; FFocusBorder: Integer; FGroupLock: Integer; FHover: Boolean; FImages: TCustomImageList; FImagesWidth: Integer; FKind: TCheckControlKind; FPressed: Boolean; FReadOnly: Boolean; FState: TCheckBoxState; FTextLayout: TTextLayout; FThemedCaption: Boolean; // FTransparent: Boolean; FWordWrap: Boolean; FOnChange: TNotifyEvent; FOnGetImageIndex: TGetImageIndexEvent; function GetCaption: TCaption; function GetChecked: Boolean; procedure SetAlignment(const AValue: TLeftRight); procedure SetBtnLayout(const AValue: TTextLayout); procedure SetCaption(const AValue: TCaption); procedure SetChecked(const AValue: Boolean); procedure SetDrawFocusRect(const AValue: Boolean); procedure SetImages(const AValue: TCustomImageList); procedure SetImagesWidth(const AValue: Integer); procedure SetState(const AValue: TCheckBoxState); procedure SetTextLayout(const AValue: TTextLayout); procedure SetThemedCaption(const AValue: Boolean); //procedure SetTransparent(const AValue: Boolean); procedure SetWordWrap(const AValue: Boolean); protected procedure AfterSetState; virtual; procedure CalculatePreferredSize(var PreferredWidth, PreferredHeight: Integer; {%H-}WithThemeSpace: Boolean); override; procedure CMBiDiModeChanged(var {%H-}Message: TLMessage); message CM_BIDIMODECHANGED; procedure CreateHandle; override; procedure DoAutoAdjustLayout(const AMode: TLayoutAdjustmentPolicy; const AXProportion, AYProportion: Double); override; procedure DoClick; procedure DoEnter; override; procedure DoExit; override; procedure DrawBackground; procedure DrawButton(AHovered, APressed, AEnabled: Boolean; AState: TCheckboxState); procedure DrawButtonText(AHovered, APressed, AEnabled: Boolean; AState: TCheckboxState); function GetBtnSize: TSize; virtual; function GetDrawTextFlags: Cardinal; function GetTextExtent(const ACaption: String): TSize; function GetThemedButtonDetails(AHovered, APressed, AEnabled: Boolean; AState: TCheckboxState): TThemedElementDetails; virtual; abstract; // procedure InitBtnSize(Scaled: Boolean); procedure LockGroup; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseEnter; override; procedure MouseLeave; override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; procedure TextChanged; override; procedure UnlockGroup; procedure WMSize(var Message: TLMSize); message LM_SIZE; property Alignment: TLeftRight read FAlignment write SetAlignment default taRightJustify; property AllowGrayed: Boolean read FAllowGrayed write FAllowGrayed default False; property ButtonLayout: TTextLayout read FBtnLayout write SetBtnLayout default tlCenter; property Caption: TCaption read GetCaption write SetCaption; property Checked: Boolean read GetChecked write SetChecked default false; property DrawFocusRect: Boolean read FDrawFocusRect write SetDrawFocusRect default true; property Images: TCustomImageList read FImages write SetImages; property ImagesWidth: Integer read FImagesWidth write SetImagesWidth default 0; property ReadOnly: Boolean read FReadOnly write FReadOnly default false; property State: TCheckBoxState read FState write SetState default cbUnchecked; property TextLayout: TTextLayout read FTextLayout write SetTextLayout default tlCenter; property ThemedCaption: Boolean read FThemedCaption write SetThemedCaption default true; //property Transparent: Boolean read FTransparent write SetTransparent default true; property WordWrap: Boolean read FWordWrap write SetWordWrap default false; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnGetImageIndex: TGetImageIndexEvent read FOnGetImageIndex write FOnGetImageIndex; public constructor Create(AOwner: TComponent); override; end; { TCustomCheckboxEx } TCustomCheckboxEx = class(TCustomCheckControlEx) private protected function GetThemedButtonDetails(AHovered, APressed, AEnabled: Boolean; AState: TCheckboxState): TThemedElementDetails; override; public constructor Create(AOwner: TComponent); override; end; { TCheckBoxEx } TCheckBoxEx = class(TCustomCheckBoxEx) published //property Action; property Align; property Alignment; property AllowGrayed; property Anchors; property AutoSize default true; property BiDiMode; property BorderSpacing; property ButtonLayout; property Caption; property Checked; property Color; property Constraints; property Cursor; property DoubleBuffered; property DragCursor; property DragKind; property DragMode; property DrawFocusRect; property Enabled; property Font; property Height; property HelpContext; property HelpKeyword; property HelpType; property Hint; property Images; property ImagesWidth; property Left; property Name; property ParentBiDiMode; property ParentColor; property ParentDoubleBuffered; property ParentFont; property ParentShowHint; property ReadOnly; property ShowHint; property State; property TabOrder; property TabStop; property Tag; property TextLayout; property ThemedCaption; property Top; //property Transparent; property Visible; property Width; property WordWrap; property OnChange; property OnChangeBounds; property OnClick; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEditingDone; property OnEndDrag; property OnEnter; property OnExit; property OnGetImageIndex; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnResize; property OnStartDrag; property OnUTF8KeyPress; end; { TCustomRadioButtonEx } TCustomRadioButtonEx = class(TCustomCheckControlEx) protected procedure AfterSetState; override; function GetThemedButtonDetails(AHovered, APressed, AEnabled: Boolean; AState: TCheckboxState): TThemedElementDetails; override; public constructor Create(AOwner: TComponent); override; published end; { TRadioButtonEx } TRadioButtonEx = class(TCustomRadioButtonEx) published property Align; property Alignment; property Anchors; property AutoSize default true; property BiDiMode; property BorderSpacing; property ButtonLayout; property Caption; property Checked; property Color; property Constraints; property Cursor; property DoubleBuffered; property DragCursor; property DragKind; property DragMode; property DrawFocusRect; property Enabled; property Font; property Height; property HelpContext; property HelpKeyword; property HelpType; property Hint; property Images; property ImagesWidth; property Left; property Name; property ParentBiDiMode; property ParentColor; property ParentDoubleBuffered; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property State; property TabOrder; property TabStop; property Tag; property TextLayout; property ThemedCaption; //property Transparent; property Visible; property WordWrap; property Width; property OnChange; property OnChangeBounds; property OnClick; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnResize; property OnStartDrag; property OnGetImageIndex; end; { TCustomCheckControlGroupEx } TCustomCheckControlGroupEx = class(TCustomGroupBox) private FAutoFill: Boolean; FButtonList: TFPList; FColumnLayout: TColumnLayout; FColumns: integer; FImages: TCustomImageList; FImagesWidth: Integer; FItems: TStrings; FIgnoreClicks: boolean; FReadOnly: Boolean; FUpdatingItems: Boolean; FOnClick: TNotifyEvent; FOnGetImageIndex: TGetImageIndexEvent; FOnItemEnter: TNotifyEvent; FOnItemExit: TNotifyEvent; FOnSelectionChanged: TNotifyEvent; procedure ItemEnter(Sender: TObject); virtual; procedure ItemExit(Sender: TObject); virtual; procedure ItemKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); virtual; procedure ItemKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); virtual; procedure ItemKeyPress(Sender: TObject; var Key: Char); virtual; procedure ItemUTF8KeyPress(Sender: TObject; var UTF8Key: TUTF8Char); virtual; procedure SetAutoFill(const AValue: Boolean); procedure SetColumnLayout(const AValue: TColumnLayout); procedure SetColumns(const AValue: integer); procedure SetImages(const AValue: TCustomImageList); procedure SetImagesWidth(const AValue: Integer); procedure SetItems(const AValue: TStrings); procedure SetOnGetImageIndex(const AValue: TGetImageIndexEvent); procedure SetReadOnly(const AValue: Boolean); protected procedure UpdateAll; procedure UpdateControlsPerLine; procedure UpdateInternalObjectList; procedure UpdateItems; virtual; abstract; procedure UpdateTabStops; property AutoFill: Boolean read FAutoFill write SetAutoFill default true; property ColumnLayout: TColumnLayout read FColumnLayout write SetColumnLayout default clHorizontalThenVertical; property Columns: Integer read FColumns write SetColumns default 1; property Images: TCustomImageList read FImages write SetImages; property ImagesWidth: Integer read FImagesWidth write SetImagesWidth default 0; property Items: TStrings read FItems write SetItems; property ReadOnly: Boolean read FReadOnly write SetReadOnly default false; property OnClick: TNotifyEvent read FOnClick write FOnClick; property OnGetImageIndex: TGetImageIndexEvent read FOnGetImageIndex write SetOnGetImageIndex; property OnItemEnter: TNotifyEvent read FOnItemEnter write FOnItemEnter; property OnItemExit: TNotifyEvent read FOnItemExit write FOnItemExit; property OnSelectionChanged: TNotifyEvent read FOnSelectionChanged write FOnSelectionChanged; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function CanModify: boolean; virtual; procedure FlipChildren(AllLevels: Boolean); override; function Rows: integer; end; { TCustomRadioGroupEx } TCustomRadioGroupEx = class(TCustomCheckControlGroupEx) private FCreatingWnd: Boolean; FHiddenButton: TRadioButtonEx; FItemIndex: integer; FLastClickedItemIndex: Integer; FReading: Boolean; procedure Changed(Sender: TObject); procedure Clicked(Sender: TObject); function GetButtonCount: Integer; function GetButtons(AIndex: Integer): TRadioButtonEx; procedure SetItemIndex(const AValue: Integer); protected procedure CheckItemIndexChanged; virtual; procedure InitializeWnd; override; procedure ItemKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); override; procedure ReadState(AReader: TReader); override; procedure UpdateItems; override; procedure UpdateRadioButtonStates; virtual; property ItemIndex: Integer read FItemIndex write SetItemIndex default -1; public property ButtonCount: Integer read GetButtonCount; property Buttons[AIndex: Integer]: TRadioButtonEx read GetButtons; published constructor Create(AOwner: TComponent); override; end; { TRadioGroupEx } TRadioGroupEx = class(TCustomRadioGroupEx) published property Align; property Anchors; property AutoFill; property AutoSize; property BiDiMode; property BorderSpacing; property Caption; property ChildSizing; property Color; property ColumnLayout; property Columns; property Constraints; property Cursor; property DoubleBuffered; property DragCursor; property DragMode; property Enabled; property Font; property Height; property HelpContext; property HelpKeyword; property HelpType; property Hint; property Images; property ImagesWidth; property ItemIndex; property Items; property Left; property Name; property ParentBiDiMode; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Tag; property Top; property Visible; property Width; property OnChangeBounds; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnGetImageIndex; property OnItemEnter; property OnItemExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnResize; property OnSelectionChanged; property OnStartDrag; property OnUTF8KeyPress; end; TCustomCheckGroupEx = class(TCustomCheckControlGroupEx) private FOnItemClick: TCheckGroupClicked; procedure Clicked(Sender: TObject); procedure DoClick(AIndex: integer); function GetButtonCount: Integer; function GetButtons(AIndex: Integer): TCheckBoxEx; function GetChecked(AIndex: integer): boolean; function GetCheckEnabled(AIndex: integer): boolean; procedure RaiseIndexOutOfBounds(AIndex: integer); procedure SetChecked(AIndex: integer; const AValue: boolean); procedure SetCheckEnabled(AIndex: integer; const AValue: boolean); protected procedure DefineProperties(Filer: TFiler); override; procedure Loaded; override; procedure ReadData(Stream: TStream); procedure UpdateItems; override; procedure WriteData(Stream: TStream); // procedure DoOnResize; override; public constructor Create(AOwner: TComponent); override; property ButtonCount: Integer read GetButtonCount; property Buttons[AIndex: Integer]: TCheckBoxEx read GetButtons; public property Checked[Index: integer]: boolean read GetChecked write SetChecked; property CheckEnabled[Index: integer]: boolean read GetCheckEnabled write SetCheckEnabled; property OnItemClick: TCheckGroupClicked read FOnItemClick write FOnItemClick; end; { TCheckGroupEx } TCheckGroupEx = class(TCustomCheckGroupEx) published property Align; property Anchors; property AutoFill; property AutoSize; property BiDiMode; property BorderSpacing; property Caption; property ChildSizing; property ClientHeight; property ClientWidth; property Color; property ColumnLayout; property Columns; property Constraints; property DoubleBuffered; property DragCursor; property DragMode; property Enabled; property Font; property Images; property ImagesWidth; property Items; property ParentBiDiMode; property ParentFont; property ParentColor; property ParentDoubleBuffered; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Visible; property OnChangeBounds; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnGetImageIndex; property OnItemClick; property OnItemEnter; property OnItemExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnResize; property OnStartDrag; property OnUTF8KeyPress; end; implementation uses Math, LCLStrConsts, LResources; const cIndent = 5; FIRST_RADIOBUTTON_DETAIL = tbRadioButtonUncheckedNormal; FIRST_CHECKBOX_DETAIL = tbCheckBoxUncheckedNormal; HOT_OFFSET = 1; PRESSED_OFFSET = 2; DISABLED_OFFSET = 3; CHECKED_OFFSET = 4; MIXED_OFFSET = 8; procedure DrawParentImage(Control: TControl; Dest: TCanvas); var SaveIndex: integer; DC: HDC; Position: TPoint; begin with Control do begin if Parent = nil then Exit; DC := Dest.Handle; SaveIndex := SaveDC(DC); GetViewportOrgEx(DC, @Position); SetViewportOrgEx(DC, Position.X - Left, Position.Y - Top, nil); IntersectClipRect(DC, 0, 0, Parent.ClientWidth, Parent.ClientHeight); Parent.Perform(LM_ERASEBKGND, DC, 0); Parent.Perform(LM_PAINT, DC, 0); RestoreDC(DC, SaveIndex); end; end; function ProcessLineBreaks(const AString: string; ToC: Boolean): String; var idx: Integer; procedure AddChar(ch: Char); begin Result[idx] := ch; inc(idx); if idx > Length(Result) then SetLength(Result, Length(Result) + 100); end; var P, PEnd: PChar; begin if AString = '' then begin Result := ''; exit; end; SetLength(Result, Length(AString)); idx := 1; P := @AString[1]; PEnd := P + Length(AString); if ToC then // Replace line breaks by '\n' while P < PEnd do begin if (P^ = #13) then begin AddChar('\'); AddChar('n'); inc(P); if P^ <> #10 then dec(P); end else if P^ = #10 then begin AddChar('\'); AddChar('n'); end else if P^ = '\' then begin AddChar('\'); AddChar('\'); end else AddChar(P^); inc(P); end else // Replace '\n' by LineEnding while (P < PEnd) do begin if (P^ = '\') and (P < PEnd-1) then begin inc(P); if (P^ = 'n') or (P^ = 'N') then AddChar(#10) else AddChar(P^); end else AddChar(P^); inc(P); end; SetLength(Result, idx-1); end; { TCheckboxControlEx } constructor TCustomCheckControlEx.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csParentBackground, csReplicatable] - [csOpaque] - csMultiClicks - [csClickEvents, csNoStdEvents]; { inherited Click not used } FAlignment := taRightJustify; FBtnLayout := tlCenter; FDrawFocusRect := true; FKind := cckCheckbox; FDistance := cIndent; FFocusBorder := FDistance div 2; FTextLayout := tlCenter; FThemedCaption := true; // FTransparent := true; AutoSize := true; TabStop := true; end; // Is called after the State has changed in SetState. Will be overridden by // TCustomRadioButtonEx to uncheck all other iteme.s procedure TCustomCheckControlEx.AfterSetState; begin end; procedure TCustomCheckControlEx.CalculatePreferredSize(var PreferredWidth, PreferredHeight: Integer; WithThemeSpace: Boolean); var flags: Cardinal; textSize: TSize; R: TRect; captn: String; details: TThemedElementDetails; btnSize: TSize; begin captn := inherited Caption; if (captn = '') then begin btnSize := GetBtnSize; PreferredWidth := btnSize.CX; PreferredHeight := btnSize.CY; exit; end; Canvas.Font.Assign(Font); R := ClientRect; btnSize := GetBtnSize; dec(R.Right, btnSize.CX + FDistance); R.Bottom := MaxInt; // Max height possible flags := GetDrawTextFlags + DT_CALCRECT; // rectangle available for text if FThemedCaption then begin details := GetThemedButtonDetails(false, false, true, cbChecked); if FWordWrap then begin with ThemeServices.GetTextExtent(Canvas.Handle, details, captn, flags, @R) do begin textSize.CX := Right; textSize.CY := Bottom; end; end else with ThemeServices.GetTextExtent(Canvas.Handle, details, captn, flags, nil) do begin textSize.CX := Right; textSize.CY := Bottom; end; end else begin DrawText(Canvas.Handle, PChar(captn), Length(captn), R, flags); textSize.CX := R.Right - R.Left; textSize.CY := R.Bottom - R.Top; end; PreferredWidth := btnSize.CX + FDistance + textSize.CX + FFocusBorder; PreferredHeight := Max(btnSize.CY, textSize.CY + 2*FFocusBorder); end; procedure TCustomCheckControlEx.CMBiDiModeChanged(var Message: TLMessage); begin Invalidate; end; procedure TCustomCheckControlEx.CreateHandle; var w, h: Integer; begin inherited; if (Width = 0) or (Height = 0) then begin CalculatePreferredSize(w{%H-}, h{%H-}, false); if Width <> 0 then w := Width; if Height <> 0 then h := Height; SetBounds(Left, Top, w, h); end; end; procedure TCustomCheckControlEx.DoAutoAdjustLayout( const AMode: TLayoutAdjustmentPolicy; const AXProportion, AYProportion: Double); begin inherited; if AMode in [lapAutoAdjustWithoutHorizontalScrolling, lapAutoAdjustForDPI] then begin FDistance := Round(cIndent * AXProportion); FFocusBorder := FDistance div 2; end; end; procedure TCustomCheckControlEx.DoClick; begin if FReadOnly then exit; if AllowGrayed then begin case FState of cbUnchecked: SetState(cbGrayed); cbGrayed: SetState(cbChecked); cbChecked: SetState(cbUnchecked); end; end else Checked := not Checked; end; procedure TCustomCheckControlEx.DoEnter; begin inherited DoEnter; Invalidate; end; procedure TCustomCheckControlEx.DoExit; begin inherited DoExit; Invalidate; end; procedure TCustomCheckControlEx.DrawBackground; var R: TRect; begin R := Rect(0, 0, Width, Height); Canvas.Brush.Style := bsSolid; Canvas.Brush.Color := Color; Canvas.FillRect(R); end; procedure TCustomCheckControlEx.DrawButton(AHovered, APressed, AEnabled: Boolean; AState: TCheckboxState); var btnRect: TRect; btnPoint: TPoint = (X:0; Y:0); details: TThemedElementDetails; imgIndex: Integer; imgRes: TScaledImageListResolution; btnSize: TSize; begin // Checkbox/Radiobutton size and position btnSize := GetBtnSize; case FAlignment of taLeftJustify: if not IsRightToLeft then btnPoint.X := ClientWidth - btnSize.CX; taRightJustify: if IsRightToLeft then btnPoint.X := ClientWidth - btnSize.CX; end; case FBtnLayout of tlTop: btnPoint.Y := FFocusBorder; tlCenter: btnPoint.Y := (ClientHeight - btnSize.CY) div 2; tlBottom: btnPoint.Y := ClientHeight - btnSize.CY - FFocusBorder; end; btnRect := Rect(0, 0, btnSize.CX, btnSize.CY); OffsetRect(btnRect, btnPoint.X, btnPoint.Y); imgIndex := -1; if (FImages <> nil) and Assigned(FOnGetImageIndex) then FOnGetImageIndex(Self, AHovered, APressed, AEnabled, AState, imgIndex); if imgIndex > -1 then begin ImgRes := FImages.ResolutionForPPI[FImagesWidth, Font.PixelsPerInch, GetCanvasScaleFactor]; ImgRes.Draw(Canvas, btnRect.Left, btnRect.Top, imgIndex, AEnabled); end else begin // Drawing style of button details := GetThemedButtonDetails(AHovered, APressed, AEnabled, AState); // Draw button ThemeServices.DrawElement(Canvas.Handle, details, btnRect); end; end; procedure TCustomCheckControlEx.DrawButtonText(AHovered, APressed, AEnabled: Boolean; AState: TCheckboxState); var R: TRect; // textStyle: TTextStyle; delta: Integer; details: TThemedElementDetails; flags: Cardinal; textSize: TSize; captn: TCaption; btnSize: TSize; begin captn := inherited Caption; // internal string with line breaks if captn = '' then exit; // Determine text drawing parameters flags := GetDrawTextFlags; btnSize := GetBtnSize; delta := btnSize.CX + FDistance; R := ClientRect; dec(R.Right, delta); Canvas.Font.Assign(Font); if FThemedCaption then begin R.Bottom := MaxInt; // max height for word-wrap details := GetThemedButtonDetails(AHovered, APressed, AEnabled, AState); with ThemeServices.GetTextExtent(Canvas.Handle, details, captn, flags, @R) do begin textSize.CX := Right; textSize.CY := Bottom; end; end else begin if not AEnabled then Canvas.Font.Color := clGrayText; DrawText(Canvas.Handle, PChar(captn), Length(captn), R, flags + DT_CALCRECT); textSize.CX := R.Right - R.Left; textSize.CY := R.Bottom - R.Top; end; R := ClientRect; case FTextLayout of tlTop: R.Top := 0; tlCenter: R.Top := (R.Top + R.Bottom - textSize.CY) div 2; tlBottom: R.Top := R.Bottom - textSize.CY; end; R.Bottom := R.Top + textSize.CY; if (FAlignment = taRightJustify) and IsRightToLeft then begin dec(R.Right, delta); R.Left := R.Right - textSize.CX; end else begin inc(R.Left, delta); R.Right := R.Left + textSize.CX; end; // Draw text if FThemedCaption then begin ThemeServices.DrawText(Canvas, details, captn, R, flags, 0); end else begin Canvas.Brush.Style := bsClear; DrawText(Canvas.Handle, PChar(captn), Length(captn), R, flags); end; // Draw focus rect if Focused and FDrawFocusRect then begin InflateRect(R, FFocusBorder, 0); if R.Left + R.Width > ClientWidth then R.Width := ClientWidth - R.Left; if R.Left < 0 then R.Left := 0; //LCLIntf.SetBkColor(Canvas.Handle, ColorToRGB(clBtnFace)); Canvas.Font.Color := clBlack; LCLIntf.DrawFocusRect(Canvas.Handle, R); end; end; function TCustomCheckControlEx.GetBtnSize: TSize; var ImgRes: TScaledImageListResolution; begin if (FImages <> nil) then begin ImgRes := FImages.ResolutionForPPI[FImagesWidth, Font.PixelsPerInch, GetCanvasScaleFactor]; Result.CX := ImgRes.Width; Result.CY := ImgRes.Height; end else begin with ThemeServices do if FKind = cckCheckbox then Result := GetDetailSize(GetElementDetails(tbCheckBoxCheckedNormal)) else if FKind = cckRadioButton then Result := GetDetailSize(GetElementDetails(tbRadioButtonCheckedNormal)); //Result.CX := Scale96ToFont(Result.CX); //Result.CY := Scale96ToFont(Result.CY); end; end; // Replaces linebreaks in the inherited Caption by '\n' (and '\' by '\\') so // that line breaks can be entered at designtime. function TCustomCheckControlEx.GetCaption: TCaption; const TO_C = true; begin Result := ProcessLineBreaks(inherited Caption, TO_C); end; function TCustomCheckControlEx.GetChecked: Boolean; begin Result := (FState = cbChecked); end; // Determine text drawing parameters for the DrawText command function TCustomCheckControlEx.GetDrawTextFlags: Cardinal; begin Result := 0; case FTextLayout of tlTop: inc(Result, DT_TOP); tlCenter: inc(Result, DT_VCENTER); tlBottom: inc(Result, DT_BOTTOM); end; if (FAlignment = taRightJustify) and IsRightToLeft then inc(Result, DT_RIGHT) else inc(Result, DT_LEFT); if IsRightToLeft then inc(Result, DT_RTLREADING); if FWordWrap then inc(Result, DT_WORDBREAK); end; function TCustomCheckControlEx.GetTextExtent(const ACaption: String): TSize; var L: TStrings; s: String; begin Result := Size(0, 0); L := TStringList.Create; try L.Text := ACaption; for s in L do begin Result.CY := Result.CY + Canvas.TextHeight(s); Result.CX := Max(Result.CX, Canvas.TextWidth(s)); end; finally L.Free; end; end; (* procedure TCustomCheckControlEx.InitBtnSize(Scaled: Boolean); var ImgRes: TScaledImageListResolution; begin if (FImages <> nil) then begin if Scaled then begin ImgRes := FImages.ResolutionForPPI[FImagesWidth, Font.PixelsPerInch, GetCanvasScaleFactor]; FBtnSize.CX := ImgRes.Width; FBtnSize.CY := ImgRes.Height; end else begin FBtnSize.CX := FImages.Width; FBtnSize.CY := FImages.Height; end; end else begin with ThemeServices do if FKind = cckCheckbox then FBtnSize := GetDetailSize(GetElementDetails(tbCheckBoxCheckedNormal)) else if FKind = cckRadioButton then FBtnSize := GetDetailSize(GetElementDetails(tbRadioButtonCheckedNormal)); if Scaled then begin FBtnSize.CX := Scale96ToFont(FBtnSize.CX); FBtnSize.CY := Scale96ToFont(FBtnSize.CY); end; end; end; *) procedure TCustomCheckControlEx.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); if (Key in [VK_RETURN, VK_SPACE]) and not (ssCtrl in Shift) and (not FReadOnly) then begin FPressed := True; Invalidate; end; end; procedure TCustomCheckControlEx.KeyUp(var Key: Word; Shift: TShiftState); begin inherited KeyUp(Key, Shift); if (Key in [VK_RETURN, VK_SPACE]) and not (ssCtrl in Shift) then begin FPressed := False; DoClick; end; end; procedure TCustomCheckControlEx.LockGroup; begin inc(FGroupLock); end; procedure TCustomCheckControlEx.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); if (Button = mbLeft) and FHover and not FReadOnly then begin FPressed := True; Invalidate; end; SetFocus; end; procedure TCustomCheckControlEx.MouseEnter; begin FHover := true; Invalidate; inherited; end; procedure TCustomCheckControlEx.MouseLeave; begin FHover := false; Invalidate; inherited; end; procedure TCustomCheckControlEx.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); if Button = mbLeft then begin if PtInRect(ClientRect, Point(X, Y)) then DoClick; FPressed := False; end; end; procedure TCustomCheckControlEx.Paint; begin { if FTransparent then DrawParentImage(Self, Self.Canvas) else DrawBackground; } DrawButton(FHover, FPressed, IsEnabled, FState); DrawButtonText(FHover, FPressed, IsEnabled, FState); end; procedure TCustomCheckControlEx.SetAlignment(const AValue: TLeftRight); begin if AValue = FAlignment then exit; FAlignment := AValue; Invalidate; end; procedure TCustomCheckControlEx.SetBtnLayout(const AValue: TTextLayout); begin if AValue = FBtnLayout then exit; FBtnLayout := AValue; Invalidate; end; procedure TCustomCheckControlEx.SetCaption(const AValue: TCaption); const FROM_C = false; begin if AValue = GetCaption then exit; inherited Caption := ProcessLineBreaks(AValue, FROM_C); end; procedure TCustomCheckControlEx.SetChecked(const AValue: Boolean); begin if AValue then State := cbChecked else State := cbUnChecked; end; procedure TCustomCheckControlEx.SetDrawFocusRect(const AValue: Boolean); begin if AValue = FDrawFocusRect then exit; FDrawFocusRect := AValue; Invalidate; end; procedure TCustomCheckControlEx.SetImages(const AValue: TCustomImageList); begin if AValue = FImages then exit; FImages := AValue; // InitBtnSize(true); InvalidatePreferredSize; AdjustSize; end; procedure TCustomCheckControlEx.SetImagesWidth(const AValue: Integer); begin if AValue = FImagesWidth then exit; FImagesWidth := AValue; // InitBtnSize(true); InvalidatePreferredSize; AdjustSize; end; procedure TCustomCheckControlEx.SetTextLayout(const AValue: TTextLayout); begin if AValue = FTextLayout then exit; FTextLayout := AValue; Invalidate; end; procedure TCustomCheckControlEx.SetThemedCaption(const AValue: Boolean); begin if AValue = FThemedCaption then exit; FThemedCaption := AValue; Invalidate; end; procedure TCustomCheckControlEx.SetState(const AValue: TCheckboxState); begin if (FState = AValue) then exit; FState := AValue; if [csLoading, csDestroying, csDesigning] * ComponentState = [] then begin if Assigned(OnEditingDone) then OnEditingDone(self); if Assigned(OnChange) then OnChange(self); { // Execute only when Action.Checked is changed if not CheckFromAction then begin if Assigned(OnClick) then if not (Assigned(Action) and CompareMethods(TMethod(Action.OnExecute), TMethod(OnClick))) then OnClick(self); if (Action is TCustomAction) and (TCustomAction(Action).Checked <> (AValue = cbChecked)) then ActionLink.Execute(self); end; } AfterSetState; end; Invalidate; end; { procedure TCustomCheckControlEx.SetTransparent(const AValue: Boolean); begin if AValue = FTransparent then exit; FTransparent := AValue; Invalidate; end; } procedure TCustomCheckControlEx.SetWordWrap(const AValue: Boolean); begin if AValue = FWordWrap then exit; FWordWrap := AValue; Invalidate; end; procedure TCustomCheckControlEx.TextChanged; begin inherited TextChanged; Invalidate; end; procedure TCustomCheckControlEx.UnlockGroup; begin dec(FGroupLock); end; procedure TCustomCheckControlEx.WMSize(var Message: TLMSize); begin inherited WMSize(Message); Invalidate; end; { TCustomRadioButtonEx } constructor TCustomRadioButtonEx.Create(AOwner: TComponent); begin inherited; FKind := cckRadioButton; // InitBtnSize(false); end; { Is called by SetState and is supposed to uncheck all other radiobuttons in the same group, i.e. having the same parent. Provides a locking mechanism because uncheding another radiobutton would trigger AfterSetState again. } procedure TCustomRadioButtonEx.AfterSetState; var i: Integer; C: TControl; begin if (FGroupLock > 0) or (Parent = nil) then exit; for i := 0 to Parent.ControlCount-1 do begin C := Parent.Controls[i]; if (C is TCustomRadioButtonEx) and (C <> self) then with TCustomRadioButtonEx(C) do begin LockGroup; try State := cbUnChecked; finally UnlockGroup; end; end; end; // Parent.Invalidate; end; function TCustomRadioButtonEx.GetThemedButtonDetails( AHovered, APressed, AEnabled: Boolean; AState: TCheckboxState): TThemedElementDetails; var offset: Integer = 0; tb: TThemedButton; begin offset := ord(FIRST_RADIOBUTTON_DETAIL); if APressed then inc(offset, PRESSED_OFFSET) else if AHovered then inc(offset, HOT_OFFSET); if not AEnabled then inc(offset, DISABLED_OFFSET); if AState = cbChecked then inc(offset, CHECKED_OFFSET); tb := TThemedButton(offset); Result := ThemeServices.GetElementDetails(tb); end; (* offset := 0 const // hovered pressed state caEnabledDetails: array [False..True, False..True, cbUnChecked..cbChecked] of TThemedElementDetails = ( ( (tbRadioButtonUncheckedNormal, tbRadioButtonCheckedNormal), (tbRadioButtonUncheckedPressed, tbRadioButtonCheckedPressed) ), ( (tbRadioButtonUncheckedHot, tbRadioButtonCheckedHot), (tbRadioButtonUncheckedPressed, tbRadioButtonCheckedPressed) ) ); caDisabledDetails: array [cbUnchecked..cbChecked] of TThemedButton = (tbRadioButtonUncheckedDisabled, tbRadioButtonCheckedDisabled); begin if Enabled then Result := caEnabledDetails[AHovered, APressed, AState] else Result := caDisabledDetails[AState]; end; *) {==============================================================================} { TCustomCheckboxEx } {==============================================================================} constructor TCustomCheckboxEx.Create(AOwner: TComponent); begin inherited; FKind := cckCheckbox; // InitBtnSize(false); end; function TCustomCheckBoxEx.GetThemedButtonDetails( AHovered, APressed, AEnabled: Boolean; AState: TCheckboxState): TThemedElementDetails; var offset: Integer = 0; tb: TThemedButton; begin offset := ord(FIRST_CHECKBOX_DETAIL); if APressed then inc(offset, PRESSED_OFFSET) else if AHovered then inc(offset, HOT_OFFSET); if not AEnabled then inc(offset, DISABLED_OFFSET); case AState of cbChecked: inc(offset, CHECKED_OFFSET); cbGrayed: inc(offset, MIXED_OFFSET); end; tb := TThemedButton(offset); Result := ThemeServices.GetElementDetails(tb); end; (* const // hovered pressed state caEnabledDetails: array [False..True, False..True, cbUnchecked..cbGrayed] of TThemedButton = ( ( (tbCheckBoxUncheckedNormal, tbCheckBoxCheckedNormal, tbCheckBoxMixedNormal), (tbCheckBoxUncheckedPressed, tbCheckBoxCheckedPressed, tbCheckBoxMixedPressed) ), ( (tbCheckBoxUncheckedHot, tbCheckBoxCheckedHot, tbCheckBoxMixedHot), (tbCheckBoxUncheckedPressed, tbCheckBoxCheckedPressed, tbCheckBoxMixedPressed) ) ); caDisabledDetails: array [cbUnchecked..cbGrayed] of TThemedButton = (tbCheckBoxUncheckedDisabled, tbCheckBoxCheckedDisabled, tbCheckBoxMixedDisabled); var tb: TThemedButton; begin if Enabled then tb := caEnabledDetails[AHovered, APressed, AState] else tb := caDisabledDetails[AState]; Result := ThemeServices.GetElementDetails(tb); end; *) {==============================================================================} { TCustomCheckControlGroupEx } {==============================================================================} constructor TCustomCheckControlGroupEx.Create(AOwner: TComponent); begin inherited; FAutoFill := true; FButtonList := TFPList.Create; FColumns := 1; FColumnLayout := clHorizontalThenVertical; ChildSizing.Layout := cclLeftToRightThenTopToBottom; ChildSizing.ControlsPerLine := FColumns; ChildSizing.ShrinkHorizontal := crsScaleChilds; ChildSizing.ShrinkVertical := crsScaleChilds; ChildSizing.EnlargeHorizontal := crsHomogenousChildResize; ChildSizing.EnlargeVertical := crsHomogenousChildResize; ChildSizing.LeftRightSpacing := 6; ChildSizing.TopBottomSpacing := 0; end; destructor TCustomCheckControlGroupEx.Destroy; var i: Integer; begin for i:=0 to FButtonList.Count-1 do TCustomCheckControlEx(FButtonList[i]).Free; FButtonList.Free; FItems.Free; inherited; end; function TCustomCheckControlGroupEx.CanModify: Boolean; begin Result := not FReadOnly; end; procedure TCustomCheckControlgroupEx.FlipChildren(AllLevels: Boolean); begin // no flipping end; procedure TCustomCheckControlGroupEx.ItemEnter(Sender: TObject); begin if Assigned(FOnItemEnter) then FOnItemEnter(Sender); end; procedure TCustomCheckControlGroupEx.ItemExit(Sender: TObject); begin if Assigned(FOnItemExit) then FOnItemExit(Sender); end; procedure TCustomCheckControlGroupEx.ItemKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key <> 0 then KeyDown(Key, Shift); end; procedure TCustomCheckControlGroupEx.ItemKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key <> 0 then KeyUp(Key, Shift); end; procedure TCustomCheckControlGroupEx.ItemKeyPress(Sender: TObject; var Key: Char); begin if Key <> #0 then KeyPress(Key); end; procedure TCustomCheckControlGroupEx.ItemUTF8KeyPress(Sender: TObject; var UTF8Key: TUTF8Char); begin UTF8KeyPress(UTF8Key); end; function TCustomCheckControlGroupEx.Rows: integer; begin if FItems.Count > 0 then Result := ((FItems.Count-1) div Columns) + 1 else Result := 0; end; procedure TCustomCheckControlGroupEx.SetAutoFill(const AValue: Boolean); begin if FAutoFill = AValue then exit; FAutoFill := AValue; DisableAlign; try if FAutoFill then begin ChildSizing.EnlargeHorizontal := crsHomogenousChildResize; ChildSizing.EnlargeVertical := crsHomogenousChildResize; end else begin ChildSizing.EnlargeHorizontal := crsAnchorAligning; ChildSizing.EnlargeVertical := crsAnchorAligning; end; finally EnableAlign; end; end; procedure TCustomCheckControlGroupEx.SetColumnLayout(const AValue: TColumnLayout); begin if FColumnLayout = AValue then exit; FColumnLayout := AValue; if FColumnLayout = clHorizontalThenVertical then ChildSizing.Layout := cclLeftToRightThenTopToBottom else ChildSizing.Layout := cclTopToBottomThenLeftToRight; UpdateControlsPerLine; end; procedure TCustomCheckControlGroupEx.SetColumns(const AValue: integer); begin if AValue <> FColumns then begin if (AValue < 1) then raise Exception.Create('TCustomRadioGroup: Columns must be >= 1'); FColumns := AValue; UpdateControlsPerLine; end; end; procedure TCustomCheckControlGroupEx.SetOnGetImageIndex(const AValue: TGetImageIndexEvent); var i: Integer; begin FOnGetImageIndex := AValue; for i := 0 to FButtonList.Count - 1 do TCustomCheckControlEx(FButtonList[i]).OnGetImageIndex := AValue; end; procedure TCustomCheckControlGroupEx.SetImages(const AValue: TCustomImagelist); var i: Integer; begin if AValue = FImages then exit; FImages := AValue; for i:=0 to FButtonList.Count-1 do TCustomCheckControlEx(FButtonList[i]).Images := FImages; end; procedure TCustomCheckControlGroupEx.SetImagesWidth(const AValue: Integer); var i: Integer; begin if AValue = FImagesWidth then exit; FImagesWidth := AValue; for i := 0 to FButtonList.Count - 1 do TCustomCheckControlEx(FButtonList[i]).ImagesWidth := FImagesWidth; end; procedure TCustomCheckControlGroupEx.SetItems(const AValue: TStrings); begin if (AValue <> FItems) then begin FItems.Assign(AValue); UpdateItems; UpdateControlsPerLine; end; end; procedure TCustomCheckControlGroupEx.SetReadOnly(const AValue: Boolean); var i: Integer; begin if AValue = FReadOnly then exit; FReadOnly := AValue; for i := 0 to FButtonList.Count -1 do TCustomCheckControlEx(FButtonList[i]).ReadOnly := FReadOnly; end; procedure TCustomCheckControlGroupEx.UpdateAll; begin UpdateItems; UpdateControlsPerLine; OwnerFormDesignerModified(Self); end; procedure TCustomCheckControlGroupEx.UpdateControlsPerLine; var newControlsPerLine: LongInt; begin if ChildSizing.Layout = cclLeftToRightThenTopToBottom then newControlsPerLine := Max(1, FColumns) else newControlsPerLine := Max(1, Rows); ChildSizing.ControlsPerLine := NewControlsPerLine; end; procedure TCustomCheckControlGroupEx.UpdateInternalObjectList; begin UpdateItems; end; procedure TCustomCheckControlGroupEx.UpdateTabStops; var i: Integer; btn: TCustomCheckControlEx; begin for i := 0 to FButtonList.Count - 1 do begin btn := TCustomCheckControlEx(FButtonList[i]); btn.TabStop := btn.Checked; end; end; {==============================================================================} { TRadioGroupExStringList } {==============================================================================} type TRadioGroupExStringList = class(TStringList) private FRadioGroup: TCustomRadioGroupEx; protected procedure Changed; override; public constructor Create(ARadioGroup: TCustomRadioGroupEx); procedure Assign(Source: TPersistent); override; end; constructor TRadioGroupExStringList.Create(ARadioGroup: TCustomRadioGroupEx); begin inherited Create; FRadioGroup := ARadioGroup; end; procedure TRadioGroupExStringList.Assign(Source: TPersistent); var savedIndex: Integer; begin savedIndex := FRadioGroup.ItemIndex; inherited Assign(Source); if savedIndex < Count then FRadioGroup.ItemIndex := savedIndex; end; procedure TRadioGroupExStringList.Changed; begin inherited Changed; if (UpdateCount = 0) then FRadioGroup.UpdateAll else FRadioGroup.UpdateInternalObjectList; FRadioGroup.FLastClickedItemIndex := FRadioGroup.FItemIndex; end; {==============================================================================} { TCustomRadioGroupEx } {==============================================================================} constructor TCustomRadioGroupEx.Create(AOwner: TComponent); begin inherited; FItems := TRadioGroupExStringList.Create(Self); FItemIndex := -1; FLastClickedItemIndex := -1; end; procedure TCustomRadioGroupEx.Changed(Sender: TObject); begin CheckItemIndexChanged; end; procedure TCustomRadioGroupEx.CheckItemIndexChanged; begin if FCreatingWnd or FUpdatingItems then exit; if [csLoading,csDestroying]*ComponentState<>[] then exit; UpdateRadioButtonStates; if [csDesigning]*ComponentState<>[] then exit; if FLastClickedItemIndex=FItemIndex then exit; FLastClickedItemIndex:=FItemIndex; EditingDone; // for Delphi compatibility: OnClick should be invoked, whenever ItemIndex // has changed if Assigned (FOnClick) then FOnClick(Self); // And a better named LCL equivalent if Assigned (FOnSelectionChanged) then FOnSelectionChanged(Self); end; procedure TCustomRadioGroupEx.Clicked(Sender: TObject); begin if FIgnoreClicks then exit; CheckItemIndexChanged; end; function TCustomRadioGroupEx.GetButtonCount: Integer; var i: Integer; begin Result := 0; for i := 0 to ControlCount-1 do if (Controls[i] is TCustomRadioButtonEx) and (Controls[i] <> FHiddenButton) then inc(Result); end; function TCustomRadioGroupEx.GetButtons(AIndex: Integer): TRadioButtonEx; begin Result := Controls[AIndex] as TRadioButtonEx; end; procedure TCustomRadioGroupEx.InitializeWnd; procedure RealizeItemIndex; var i: Integer; begin if (FItemIndex <> -1) and (FItemIndex<FButtonList.Count) then TRadioButtonEx(FButtonList[FItemIndex]).Checked := true else if FHiddenButton<>nil then FHiddenButton.Checked := true; for i:=0 to FItems.Count-1 do begin TRadioButtonEx(FButtonList[i]).Checked := (FItemIndex = i); end; end; begin if FCreatingWnd then RaiseGDBException('TCustomRadioGroup.InitializeWnd'); FCreatingWnd := true; UpdateItems; inherited InitializeWnd; RealizeItemIndex; //debugln(['TCustomRadioGroup.InitializeWnd END']); FCreatingWnd := false; end; procedure TCustomRadioGroupEx.ItemKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure MoveSelection(HorzDiff, VertDiff: integer); var Count: integer; StepSize: integer; BlockSize : integer; NewIndex : integer; WrapOffset: integer; begin if FReadOnly then exit; Count := FButtonList.Count; if FColumnLayout = clHorizontalThenVertical then begin //add a row for ease wrapping BlockSize := Columns * (Rows+1); StepSize := HorzDiff + VertDiff * Columns; WrapOffSet := VertDiff; end else begin //add a column for ease wrapping BlockSize := (Columns+1) * Rows; StepSize := HorzDiff * Rows + VertDiff; WrapOffSet := HorzDiff; end; NewIndex := ItemIndex; repeat Inc(NewIndex, StepSize); if (NewIndex >= Count) or (NewIndex < 0) then begin NewIndex := (NewIndex + WrapOffSet + BlockSize) mod BlockSize; // Keep moving in the same direction until in valid range while NewIndex >= Count do NewIndex := (NewIndex + StepSize) mod BlockSize; end; until (NewIndex = ItemIndex) or TCustomCheckControlEx(FButtonList[NewIndex]).Enabled; ItemIndex := NewIndex; TCustomCheckControlEx(FButtonList[ItemIndex]).SetFocus; Key := 0; end; begin if Shift=[] then begin case Key of VK_LEFT: MoveSelection(-1,0); VK_RIGHT: MoveSelection(1,0); VK_UP: MoveSelection(0,-1); VK_DOWN: MoveSelection(0,1); end; end; if Key <> 0 then KeyDown(Key, Shift); end; procedure TCustomRadioGroupEx.ReadState(AReader: TReader); begin FReading := True; inherited ReadState(AReader); FReading := False; if (FItemIndex < -1) or (FItemIndex >= FItems.Count) then FItemIndex := -1; FLastClickedItemIndex := FItemIndex; end; procedure TCustomRadioGroupEx.SetItemIndex(const AValue: integer); var oldItemIndex: LongInt; oldIgnoreClicks: Boolean; begin if (AValue = FItemIndex) or FReadOnly then exit; // needed later if handle isn't allocated oldItemIndex := FItemIndex; if FReading then FItemIndex := AValue else begin if (AValue < -1) or (AValue >= FItems.Count) then raise Exception.CreateFmt(rsIndexOutOfBounds, [ClassName, AValue, FItems.Count-1]); if HandleAllocated then begin // the radiobuttons are grouped by the widget interface // and some does not allow to uncheck all buttons in a group // Therefore there is a hidden button FItemIndex := AValue; oldIgnoreClicks := FIgnoreClicks; FIgnoreClicks := true; try if (FItemIndex <> -1) then TCustomCheckControlEx(FButtonList[FItemIndex]).Checked := true else FHiddenButton.Checked := true; // uncheck old radiobutton if (OldItemIndex <> -1) then begin if (OldItemIndex >= 0) and (OldItemIndex < FButtonList.Count) then TCustomCheckControlEx(FButtonList[OldItemIndex]).Checked := false end else FHiddenButton.Checked := false; finally FIgnoreClicks := OldIgnoreClicks; end; // this has automatically unset the old button. But they do not recognize // it. Update the states. CheckItemIndexChanged; UpdateTabStops; OwnerFormDesignerModified(Self); end else begin FItemIndex := AValue; // maybe handle was recreated. issue #26714 FLastClickedItemIndex := -1; // trigger event to be delphi compat, even if handle isn't allocated. // issue #15989 if (AValue <> oldItemIndex) and not FCreatingWnd then begin if Assigned(FOnClick) then FOnClick(Self); if Assigned(FOnSelectionChanged) then FOnSelectionChanged(Self); FLastClickedItemIndex := FItemIndex; end; end; end; end; procedure TCustomRadioGroupEx.UpdateItems; var i: integer; button: TCustomCheckControlEx; begin if FUpdatingItems then exit; FUpdatingItems := true; try // destroy radiobuttons, if there are too many while FButtonList.Count > FItems.Count do begin TObject(FButtonList[FButtonList.Count-1]).Free; FButtonList.Delete(FButtonList.Count-1); end; // create as many TRadioButtons as needed while (FButtonList.Count < FItems.Count) do begin button := TRadioButtonEx.Create(Self); with TCustomCheckControlEx(button) do begin Name := 'RadioButtonEx' + IntToStr(FButtonList.Count); OnClick := @Self.Clicked; OnChange := @Self.Changed; OnEnter := @Self.ItemEnter; OnExit := @Self.ItemExit; OnKeyDown := @Self.ItemKeyDown; OnKeyUp := @Self.ItemKeyUp; OnKeyPress := @Self.ItemKeyPress; OnUTF8KeyPress := @Self.ItemUTF8KeyPress; ParentFont := True; ReadOnly := Self.ReadOnly; BorderSpacing.CellAlignHorizontal := ccaLeftTop; BorderSpacing.CellAlignVertical := ccaCenter; ControlStyle := ControlStyle + [csNoDesignSelectable]; end; FButtonList.Add(button); end; if FHiddenButton = nil then begin FHiddenButton := TRadioButtonEx.Create(nil); with FHiddenButton do begin Name := 'HiddenRadioButton'; Visible := False; ControlStyle := ControlStyle + [csNoDesignSelectable, csNoDesignVisible]; end; end; if (FItemIndex >= FItems.Count) and not (csLoading in ComponentState) then FItemIndex := FItems.Count-1; if FItems.Count > 0 then begin // to reduce overhead do it in several steps // assign Caption and then Parent for i:=0 to FItems.Count-1 do begin button := TCustomCheckControlEx(FButtonList[i]); button.Caption := FItems[i]; button.Parent := Self; end; FHiddenButton.Parent := Self; // the checked and unchecked states can be applied only after all other for i := 0 to FItems.Count-1 do begin button := TCustomCheckControlEx(FButtonList[i]); button.Checked := (i = FItemIndex); button.Visible := true; end; //FHiddenButton must remain the last item in Controls[], so that Controls[] is in sync with Items[] Self.RemoveControl(FHiddenButton); Self.InsertControl(FHiddenButton); if HandleAllocated then FHiddenButton.HandleNeeded; FHiddenButton.Checked := (FItemIndex = -1); UpdateTabStops; end; finally FUpdatingItems := false; end; end; procedure TCustomRadioGroupEx.UpdateRadioButtonStates; var i: Integer; begin if FReadOnly then exit; FItemIndex := -1; FHiddenButton.Checked; for i:=0 to FButtonList.Count-1 do if TCustomRadioButtonEx(FButtonList[i]).Checked then FItemIndex := i; UpdateTabStops; end; {==============================================================================} { TCheckGroupExStringList } {==============================================================================} type TCheckGroupExStringList = class(TStringList) private FCheckGroup: TCustomCheckGroupEx; procedure RestoreCheckStates(const AStates: TByteDynArray); procedure SaveCheckStates(out AStates: TByteDynArray); protected procedure Changed; override; public constructor Create(ACheckGroup: TCustomCheckGroupEx); procedure Delete(AIndex: Integer); override; end; constructor TCheckGroupExStringList.Create(ACheckGroup: TCustomCheckGroupEx); begin inherited Create; FCheckGroup := ACheckGroup; end; procedure TCheckGroupExStringList.Changed; begin inherited Changed; if UpdateCount = 0 then FCheckGroup.UpdateAll else FCheckGroup.UpdateInternalObjectList; end; procedure TCheckGroupExStringList.Delete(AIndex: Integer); // Deleting destroys the checked state of the items -> we must save and restore it // Issue https://bugs.freepascal.org/view.php?id=34327. var b: TByteDynArray; i: Integer; begin SaveCheckStates(b); inherited Delete(AIndex); for i:= AIndex to High(b)-1 do b[i] := b[i+1]; SetLength(b, Length(b)-1); RestoreCheckStates(b); end; procedure TCheckGroupExStringList.RestoreCheckStates(const AStates: TByteDynArray); var i: Integer; begin Assert(Length(AStates) = FCheckGroup.Items.Count); for i:=0 to FCheckgroup.Items.Count-1 do begin FCheckGroup.Checked[i] := AStates[i] and 1 <> 0; FCheckGroup.CheckEnabled[i] := AStates[i] and 2 <> 0; end; end; procedure TCheckGroupExStringList.SaveCheckStates(out AStates: TByteDynArray); var i: Integer; begin SetLength(AStates, FCheckgroup.Items.Count); for i:=0 to FCheckgroup.Items.Count-1 do begin AStates[i] := 0; if FCheckGroup.Checked[i] then inc(AStates[i]); if FCheckGroup.CheckEnabled[i] then inc(AStates[i], 2); end; end; {==============================================================================} { TCustomCheckGroupEx } {==============================================================================} constructor TCustomCheckGroupEx.Create(AOwner: TComponent); begin inherited; FItems := TCheckGroupExStringList.Create(Self); end; procedure TCustomCheckGroupEx.Clicked(Sender: TObject); var index: Integer; begin index := FButtonList.IndexOf(Sender); if index < 0 then exit; DoClick(index); end; procedure TCustomCheckGroupEx.DefineProperties(Filer: TFiler); begin inherited DefineProperties(Filer); Filer.DefineBinaryProperty('Data', @ReadData, @WriteData, FItems.Count > 0); end; procedure TCustomCheckGroupEx.DoClick(AIndex: integer); begin if [csLoading,csDestroying, csDesigning] * ComponentState <> [] then exit; EditingDone; if Assigned(FOnItemClick) then FOnItemClick(Self, AIndex); end; function TCustomCheckGroupEx.GetButtonCount: Integer; var i: Integer; begin Result := 0; for i := 0 to ControlCount-1 do if (Controls[i] is TCustomCheckBoxEx) then inc(Result); end; function TCustomCheckGroupEx.GetButtons(AIndex: Integer): TCheckBoxEx; begin Result := Controls[AIndex] as TCheckBoxEx; end; function TCustomCheckGroupEx.GetChecked(AIndex: Integer): Boolean; begin if (AIndex < -1) or (AIndex >= FItems.Count) then RaiseIndexOutOfBounds(AIndex); Result := TCustomCheckControlEx(FButtonList[AIndex]).Checked; end; function TCustomCheckGroupEx.GetCheckEnabled(AIndex: integer): boolean; begin if (AIndex < -1) or (AIndex >= FItems.Count) then RaiseIndexOutOfBounds(AIndex); Result := TCustomCheckControlEx(FButtonList[AIndex]).Enabled; end; procedure TCustomCheckGroupEx.Loaded; begin inherited Loaded; UpdateItems; end; procedure TCustomCheckGroupEx.RaiseIndexOutOfBounds(AIndex: integer); begin raise Exception.CreateFmt(rsIndexOutOfBounds, [ClassName, AIndex, FItems.Count - 1]); end; procedure TCustomCheckGroupEx.ReadData(Stream: TStream); var ChecksCount: integer; Checks: string; i: Integer; v: Integer; begin ChecksCount := ReadLRSInteger(Stream); if ChecksCount > 0 then begin SetLength(Checks, ChecksCount); Stream.ReadBuffer(Checks[1], ChecksCount); for i:=0 to ChecksCount-1 do begin v := ord(Checks[i+1]); Checked[i] := ((v and 1) > 0); CheckEnabled[i] := ((v and 2) > 0); end; end; end; procedure TCustomCheckGroupEx.SetChecked(AIndex: integer; const AValue: boolean); begin if (AIndex < -1) or (AIndex >= FItems.Count) then RaiseIndexOutOfBounds(AIndex); // disable OnClick TCheckBox(FButtonList[AIndex]).OnClick := nil; // set value TCheckBox(FButtonList[AIndex]).Checked := AValue; // enable OnClick TCheckBox(FButtonList[AIndex]).OnClick := @Clicked; end; procedure TCustomCheckGroupEx.SetCheckEnabled(AIndex: integer; const AValue: boolean); begin if (AIndex < -1) or (AIndex >= FItems.Count) then RaiseIndexOutOfBounds(AIndex); TCustomCheckControlEx(FButtonList[AIndex]).Enabled := AValue; end; procedure TCustomCheckGroupEx.UpdateItems; var i: integer; btn: TCustomCheckControlEx; begin if FUpdatingItems then exit; FUpdatingItems := true; try // destroy checkboxes, if there are too many while FButtonList.Count > FItems.Count do begin TObject(FButtonList[FButtonList.Count-1]).Free; FButtonList.Delete(FButtonList.Count-1); end; // create as many TCheckBoxes as needed while (FButtonList.Count < FItems.Count) do begin btn := TCheckBoxEx.Create(Self); with TCheckBoxEx(btn) do begin Name := 'CheckBoxEx' + IntToStr(FButtonList.Count); OnClick := @Self.Clicked; OnKeyDown := @Self.ItemKeyDown; OnKeyUp := @Self.ItemKeyUp; OnKeyPress := @Self.ItemKeyPress; OnUTF8KeyPress := @Self.ItemUTF8KeyPress; AutoSize := False; Parent := Self; ParentFont := true; ReadOnly := Self.ReadOnly; BorderSpacing.CellAlignHorizontal := ccaLeftTop; BorderSpacing.CellAlignVertical := ccaCenter; ControlStyle := ControlStyle + [csNoDesignSelectable]; end; FButtonList.Add(btn); end; for i:=0 to FItems.Count-1 do begin btn := TCustomCheckControlEx(FButtonList[i]); btn.Caption := FItems[i]; end; finally FUpdatingItems := false; end; end; procedure TCustomCheckGroupEx.WriteData(Stream: TStream); var ChecksCount: integer; Checks: string; i: Integer; v: Integer; begin ChecksCount := FItems.Count; WriteLRSInteger(Stream, ChecksCount); if ChecksCount > 0 then begin SetLength(Checks, ChecksCount); for i := 0 to ChecksCount-1 do begin v := 0; if Checked[i] then inc(v, 1); if CheckEnabled[i] then inc(v, 2); Checks[i+1] := chr(v); end; Stream.WriteBuffer(Checks[1], ChecksCount); end; end; end.
unit DelphiSettingEditor; interface uses Classes, Registry, SysUtils; type TStringArray = array of string; IDelphiSettingKeys = interface ['{B910A6AD-9BEB-4540-A17B-4D099E7B7AE9}'] function GetSettingPath : string; function GetCurrentPath : string; function GetOnCurrentKeyChanged : TNotifyEvent; procedure SetOnCurrentKeyChanged (const Value : TNotifyEvent); procedure SetCurrentPath (const APath : string); function GetParent (const APath : string) : string; procedure GetChild (const APath : string; out StringArray : TStringArray); procedure OpenSetting (const SettingPath : string); procedure RefreshCurrentKey (const Recursive : boolean = false); function DeleteCurrentKey : string; procedure AddKey (const APath : string); property SettingPath : string read GetSettingPath; property CurrentPath : string read GetcurrentPath write SetCurrentPath; property OnCurrentKeyChanged : TNotifyEvent read GetOnCurrentKeyChanged write SetOnCurrentKeyChanged; end; TDelphiSettingKeys = class (TInterfacedObject, IDelphiSettingKeys) private FSettingPath : string; FNodes : TStringList; FReg : TRegistry; FCurrentIndex : integer; FOnCurrentKeyChanged : TNotifyEvent; procedure BuildNodes; protected function GetNodeCount : integer; function GetSettingPath : string; function GetCurrentPath : string; function GetOnCurrentKeyChanged : TNotifyEvent; procedure SetOnCurrentKeyChanged (const Value : TNotifyEvent); procedure SetCurrentPath (const APath : string); function GetParent (const APath : string) : string; procedure GetChild (const APath : string; out StringArray : TStringArray); procedure OpenSetting (const SettingPath : string); procedure RefreshCurrentKey (const Recursive : boolean = false); function DeleteCurrentKey : string; procedure AddKey (const APath : string); public constructor Create (const APath : string); destructor Destroy; override; end; implementation uses Contnrs; const NO_CURRENT = -2; ROOT = -1; function GetLastDelimiterIndex (const AValue : string): integer; const DELIMITER = '\'; begin Result := LastDelimiter (DELIMITER, AValue); if Result > 1 then if AValue [Result - 1] = DELIMITER then Result := GetLastDelimiterIndex (Copy (AValue, 1, Result - 2)); end; function NameValueCompare(List: TStringList; Index1, Index2: Integer): Integer; begin Result := AnsiCompareText (List.Names[Index1], List.Names[Index2]); if Result = 0 then Result := AnsiCompareText (List.ValueFromIndex[Index1], List.ValueFromIndex[Index2]); end; { TDelphiSettingKeys } constructor TDelphiSettingKeys.Create(const APath: string); begin inherited Create; FNodes := TStringList.Create; FReg := TRegistry.Create; FCurrentIndex := NO_CURRENT; OpenSetting (APath); end; destructor TDelphiSettingKeys.Destroy; begin if Assigned (FNodes) then FNodes.Free; inherited; end; function TDelphiSettingKeys.GetNodeCount: integer; begin Result := FNodes.Count; if SameText (FSettingPath, EmptyStr) = false then Inc (Result); end; procedure TDelphiSettingKeys.SetOnCurrentKeyChanged( const Value: TNotifyEvent); begin FOnCurrentKeyChanged := Value; end; function TDelphiSettingKeys.GetSettingPath: string; begin Result := FSettingPath; end; function TDelphiSettingKeys.GetOnCurrentKeyChanged: TNotifyEvent; begin Result := self.FOnCurrentKeyChanged; end; procedure TDelphiSettingKeys.OpenSetting(const SettingPath: string); begin FSettingPath := ExcludeTrailingBackslash (SettingPath); //It is important to include backslash at the beginning. The path is always a //full path under HKCU. Without backslash in the beginning, Regedit.OpenKey //may try to open a sub key under the current key. if SameText (FSettingPath[1], '\') = false then FSettingPath := '\' + FSettingPath; if FReg.OpenKey(FSettingPath, false) = false then raise Exception.Create (FSettingPath + ' does not exist.'); if Assigned (FOnCurrentKeyChanged) then FOnCurrentKeyChanged (self); end; procedure TDelphiSettingKeys.RefreshCurrentKey ( const Recursive : boolean = false); const NODE_FORMAT = '%s\%s'; var KeyQueue, SubKeyList : TStringList; KeyToProcess : string; Loop : integer; begin KeyQueue := TStringList.Create; SubKeyList := TStringList.Create; FNodes.BeginUpdate; try Loop := self.FCurrentIndex + 1; while Pos (GetCurrentPath, FNodes [Loop]) = 1 do FNodes.Delete (Loop); KeyQueue.Add (GetCurrentPath); repeat KeyToProcess := KeyQueue[0]; KeyQueue.Delete (0); if FReg.OpenKeyReadOnly (KeyToProcess) = false then raise Exception.Create ('Failed opening ' + KeyToProcess); FReg.GetKeyNames (SubKeyList); for Loop := 0 to SubKeyList.Count - 1 do begin KeyQueue.Add (Format (NODE_FORMAT, [KeyToProcess, SubKeyList[Loop]])); FNodes.Add (Format (NODE_FORMAT, [KeyToProcess, SubKeyList[Loop]])); end until (KeyQueue.Count = 0) or (Recursive = false); finally FNodes.EndUpdate; KeyQueue.Free; SubKeyList.Free; end; end; procedure TDelphiSettingKeys.BuildNodes; begin end; function TDelphiSettingKeys.GetCurrentPath: string; begin Result := '\' + self.FReg.CurrentPath; end; procedure TDelphiSettingKeys.SetCurrentPath(const APath: string); var NodeIndex, LastDelimiterIndex : integer; str : string; begin if FReg.OpenKey (APath, false) = false then raise Exception.Create (APath + ' not found.'); if Assigned (self.FOnCurrentKeyChanged) then FOncurrentKeyChanged (self); end; procedure TDelphiSettingKeys.AddKey(const APath: string); var CorrectedPath : string; begin CorrectedPath := ExcludeTrailingBackslash (APath); if CorrectedPath[1] <> '\' then CorrectedPath := '\' + CorrectedPath; if FReg.KeyExists (CorrectedPath) = false then if FReg.CreateKey (CorrectedPath) = false then raise Exception.Create('Cannot Create ' + CorrectedPath); FReg.OpenKey (CorrectedPath, false); if Assigned (self.FOnCurrentKeyChanged) then FOncurrentKeyChanged (self); end; function TDelphiSettingKeys.DeleteCurrentKey : string; var ParentPath : string; IsRootPath : boolean; begin IsRootPath := SameText (GetCurrentPath, FSettingPath); if FReg.DeleteKey (GetCurrentPath) = false then raise Exception.Create ('Failed to delete ' + GetCurrentPath); ParentPath := self.GetParent (GetCurrentPath); self.SetCurrentPath (ParentPath); Result := self.GetCurrentPath; end; procedure TDelphiSettingKeys.GetChild(const APath: string; out StringArray: TStringArray); var CurrentPath : string; List : TStringList; Loop : integer; begin CurrentPath := self.GetCurrentPath; List := TStringList.Create; try if FReg.OpenKey (APath, false) = false then raise Exception.Create ('Error opening ' + APath); FReg.GetKeyNames(List); SetLength (StringArray, List.Count); for Loop := 0 to List.Count - 1 do StringArray[Loop] := List[Loop]; finally List.Free; end; end; function TDelphiSettingKeys.GetParent(const APath: string): string; begin Result := Copy (APath, 1, GetLastDelimiterIndex (APath)); end; end. procedure TForm1.Button1Click(Sender: TObject); var DSK : DelphiSettingEditor.IDelphiSettingKeys; Childs : TStringArray; List : TStringList; ParentNode : TTreeNode; ChildStr, str : string; begin DSK := TDelphiSettingKeys.Create('Software\Borland\CustomSettings\BDS3\Barebone\3.0\'); List := TStringList.Create; try ParentNode := self.TreeView1.Items.AddChild (nil, DSK.CurrentPath); List.AddObject(DSK.CurrentPath, ParentNode); while List.Count > 0 do begin str := List [0]; ParentNode := List.Objects[0] as TTreeNode; List.Delete (0); DSK.GetChild (str, Childs); for ChildStr in Childs do begin List.AddObject (str + '\' + ChildStr, TreeView1.Items.AddChild (ParentNode, ChildStr)); end; end; finally List.Free; end; end;
unit LoanListIntf; interface type TLoanFilterType = (lftAll,lftPending,lftAssessed,lftApproved,lftActive, lftCancelled,lftRejected,lftClosed); type ILoanListFilter = interface(IInterface) ['{50297F40-7CE9-4F35-AFC3-CEF0A9390904}'] procedure FilterList(const filterType: TLoanFilterType); end; implementation end.
unit MasterMind.Evaluator.Tests; {$IFDEF FPC}{$MODE DELPHI}{$ENDIF} interface uses Classes, SysUtils, fpcunit, testregistry, MasterMind.API; type TTestMasterMindGuessEvaluator = class(TTestCase) private FEvaluator: IGuessEvaluator; procedure CheckResultsEqual(const Expected, Actual: TGuessEvaluationResult); procedure CheckEvaluation(const LeftCode, RightCode: array of TMasterMindCodeColor; const ExpectedResult: array of TMasterMindHint); protected procedure Setup; override; published procedure TestExactMatch; procedure TestNoMatch; procedure TestAllColorsAtWrongPlace; procedure TestFirstColorAtWrongPlaceAndSecondColorCorrect; procedure TestDuplicateColorsInGuessAreRewaredOnlyOneTimeForEachColorInTheCodeToBeGuessed; end; implementation uses MasterMind.Evaluator, EnumHelper, MasterMind.TestHelper; procedure TTestMasterMindGuessEvaluator.Setup; begin FEvaluator := TMasterMindGuessEvaluator.Create; end; procedure TTestMasterMindGuessEvaluator.CheckResultsEqual(const Expected, Actual: TGuessEvaluationResult); begin TEnumHelper<TMasterMindHint>.CheckArraysEqual(Expected, Actual); end; procedure TTestMasterMindGuessEvaluator.CheckEvaluation(const LeftCode, RightCode: array of TMasterMindCodeColor; const ExpectedResult: array of TMasterMindHint); var Expected, Actual: TGuessEvaluationResult; begin Actual := FEvaluator.EvaluateGuess(MakeCode(LeftCode), MakeCode(RightCode)); Expected := MakeResult(ExpectedResult); CheckResultsEqual(Expected, Actual); end; procedure TTestMasterMindGuessEvaluator.TestExactMatch; begin CheckEvaluation( [mmcGreen, mmcGreen, mmcGreen, mmcGreen], [mmcGreen, mmcGreen, mmcGreen, mmcGreen], [mmhCorrect, mmhCorrect, mmhCorrect, mmhCorrect] ); end; procedure TTestMasterMindGuessEvaluator.TestNoMatch; begin CheckEvaluation( [mmcGreen, mmcGreen, mmcGreen, mmcGreen], [mmcRed, mmcRed, mmcRed, mmcRed], [mmhNoMatch, mmhNoMatch, mmhNoMatch, mmhNoMatch] ); end; procedure TTestMasterMindGuessEvaluator.TestAllColorsAtWrongPlace; begin CheckEvaluation( [mmcGreen, mmcYellow, mmcOrange, mmcRed], [mmcYellow, mmcOrange, mmcRed, mmcGreen], [mmhWrongPlace, mmhWrongPlace, mmhWrongPlace, mmhWrongPlace] ); end; procedure TTestMasterMindGuessEvaluator.TestFirstColorAtWrongPlaceAndSecondColorCorrect; begin CheckEvaluation( [mmcGreen, mmcYellow, mmcOrange, mmcRed], [mmcOrange, mmcYellow, mmcBrown, mmcBrown], [mmhCorrect, mmhWrongPlace, mmhNoMatch, mmhNoMatch] ); end; procedure TTestMasterMindGuessEvaluator.TestDuplicateColorsInGuessAreRewaredOnlyOneTimeForEachColorInTheCodeToBeGuessed; begin CheckEvaluation( [mmcGreen, mmcGreen, mmcRed, mmcRed], [mmcGreen, mmcGreen, mmcGreen, mmcRed], [mmhCorrect, mmhCorrect, mmhCorrect, mmhNoMatch] ); end; initialization RegisterTest(TTestMasterMindGuessEvaluator); end.
{ KOL MCK } // Do not remove this line! {$DEFINE KOL_MCK} unit AboutForm; interface {$IFDEF KOL_MCK} uses Windows, Messages, KOL {$IF Defined(KOL_MCK)}{$ELSE}, mirror, Classes, Controls, mckCtrls, mckObjs, Graphics {$IFEND (place your units here->)}; {$ELSE} {$I uses.inc} Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs; {$ENDIF} type {$IF Defined(KOL_MCK)} {$I MCKfakeClasses.inc} {$IFDEF KOLCLASSES} {$I TFormAboutclass.inc} {$ELSE OBJECTS} PFormAbout = ^TFormAbout; {$ENDIF CLASSES/OBJECTS} {$IFDEF KOLCLASSES}{$I TFormAbout.inc}{$ELSE} TFormAbout = object(TObj) {$ENDIF} Form: PControl; {$ELSE not_KOL_MCK} TFormAbout = class(TForm) {$IFEND KOL_MCK} KOLForm: TKOLForm; LogoPaintBox: TKOLPaintBox; NameLabel: TKOLLabelEffect; CopyrightLabel: TKOLLabel; procedure KOLFormKeyUp(Sender: PControl; var Key: Integer; Shift: Cardinal); function KOLFormMessage(var Msg: TMsg; var Rslt: Integer): Boolean; procedure KOLFormFormCreate(Sender: PObj); procedure LogoPaintBoxPaint(Sender: PControl; DC: HDC); private FLogo: PBitmap; public { Public declarations } end; var FormAbout {$IFDEF KOL_MCK} : PFormAbout {$ELSE} : TFormAbout {$ENDIF} ; {$IFDEF KOL_MCK} procedure NewFormAbout( var Result: PFormAbout; AParent: PControl ); {$ENDIF} implementation {$R About.res} function nrv2e_decompress(src: Pointer; src_len: Cardinal; dst: Pointer; var dst_len: Cardinal; wrkmem: Pointer): Integer; cdecl; asm pop EBP db 85,87,86,83,81,82,131,236,8,137,227,252,139,115,36,139 db 123,44,137,248,139,83,48,3,2,15,130,137,1,0,0,137 db 3,137,240,3,67,40,15,130,124,1,0,0,137,67,4,131 db 205,255,49,201,235,24,59,116,36,4,15,131,58,1,0,0 db 59,60,36,15,131,81,1,0,0,164,0,219,117,15,59,116 db 36,4,15,131,34,1,0,0,138,30,70,16,219,114,215,49 db 192,64,0,219,117,15,59,116,36,4,15,131,10,1,0,0 db 138,30,70,16,219,17,192,15,136,36,1,0,0,0,219,117 db 15,59,116,36,4,15,131,239,0,0,0,138,30,70,16,219 db 114,30,72,0,219,117,15,59,116,36,4,15,131,217,0,0 db 0,138,30,70,16,219,17,192,15,136,243,0,0,0,235,178 db 61,2,0,0,1,15,135,230,0,0,0,131,232,3,114,58 db 193,224,8,59,116,36,4,15,131,173,0,0,0,172,131,240 db 255,15,132,152,0,0,0,15,137,196,0,0,0,209,248,137 db 197,115,40,0,219,117,15,59,116,36,4,15,131,137,0,0 db 0,138,30,70,16,219,17,201,235,74,0,219,117,11,59,116 db 36,4,115,118,138,30,70,16,219,114,216,65,0,219,117,11 db 59,116,36,4,115,100,138,30,70,16,219,114,198,0,219,117 db 11,59,116,36,4,115,83,138,30,70,16,219,17,201,120,106 db 0,219,117,11,59,116,36,4,115,64,138,30,70,16,219,115 db 220,131,193,2,129,253,0,251,255,255,131,209,2,137,242,137 db 254,1,206,114,69,59,52,36,119,64,137,254,1,238,115,65 db 59,116,36,44,114,59,243,164,137,214,233,219,254,255,255,59 db 60,36,119,38,59,116,36,4,118,7,184,55,255,255,255,235 db 5,116,3,72,176,51,43,124,36,44,139,84,36,48,137,58 db 131,196,8,90,89,91,94,95,93,195,184,54,255,255,255,235 db 229,184,53,255,255,255,235,222,131,200,255,235,217,144,144,144 end; {$IF Defined(KOL_MCK)}{$ELSE}{$R *.DFM}{$IFEND} {$IFDEF KOL_MCK} {$I AboutForm_1.inc} {$ENDIF} procedure TFormAbout.KOLFormKeyUp(Sender: PControl; var Key: Integer; Shift: Cardinal); begin if (Key = VK_RETURN) or (Key = VK_ESCAPE) then Form.Close; end; function TFormAbout.KOLFormMessage(var Msg: TMsg; var Rslt: Integer): Boolean; begin Result := false; if Msg.message = WM_CLOSE then Form.Hide; end; procedure TFormAbout.KOLFormFormCreate(Sender: PObj); var Data: PStream; BufSize, DecSize: Cardinal; Buf, Val: Pointer; begin Form.Caption := Form.Caption + ' ' + Applet.Caption; BufSize := GetFileVersionInfoSize(PChar(ExePath), DecSize); if BufSize > 0 then begin GetMem(Buf, BufSize); try if not GetFileVersionInfo(PChar(ExePath), DecSize, BufSize, Buf) then Exit; if VerQueryValue(Buf, '\StringFileInfo\040904E4\LegalCopyright', Val, DecSize) then CopyrightLabel.Caption := PChar(Val); if VerQueryValue(Buf, '\StringFileInfo\040904E4\FileDescription', Val, DecSize) then NameLabel.Caption := PChar(Val); if VerQueryValue(Buf, '\', Val, DecSize) then with PVSFixedFileInfo(Val)^ do NameLabel.Caption := NameLabel.Caption + ' ' + Int2Str(HiWord(dwFileVersionMS)) + '.' + Int2Str(LoWord(dwFileVersionMS)); finally FreeMem(Buf); end; end; Data := NewMemoryStream; try Resource2Stream(Data, hInstance, 'TCCLOGO', RT_RCDATA); Data.Position := 0; Data.Read(DecSize, SizeOf(DecSize)); BufSize := Data.Size - Data.Position; GetMem(Buf, BufSize); try Data.Read(Buf^, BufSize); Data.Size := DecSize; if (nrv2e_decompress(Buf, BufSize, Data.Memory, DecSize, nil) <> 0) or (DecSize <> Data.Size) then Exit; finally FreeMem(Buf); end; FLogo := NewBitmap(0, 0); Data.Position := 0; FLogo.LoadFromStream(Data); LogoPaintBox.Invalidate; finally Free_And_Nil(Data); end; end; procedure TFormAbout.LogoPaintBoxPaint(Sender: PControl; DC: HDC); begin if Assigned(FLogo) then FLogo.Draw(LogoPaintBox.Canvas.Handle, 0, 0); end; end.
program AVAIL; { show remaining system memory } CONST I_USE = 20560; BEGIN Writeln(MemAvail + I_USE:10,' Total Bytes Available'); END.
unit uFrameListViewGroup; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Generics.Collections, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, UI.Frame, UI.Standard, UI.Base, UI.ListView; type TDataItem = record Name: string; Phone: string; Color: TAlphaColor; constructor Create(const Name, Phone: string; const Color: TAlphaColor); end; TCustomListDataAdapter = class(TCustomTreeListDataAdapter<TDataItem>) protected function GetNodeItemView(const Index: Integer; const ANode: TTreeListNode<TDataItem>; ConvertView: TViewBase; Parent: TViewGroup): TViewBase; override; function GetNodeText(const ANode: TTreeListNode<TDataItem>): string; override; end; type TFrameListViewGroup = class(TFrame) LinearLayout1: TLinearLayout; tvTitle: TTextView; ListView: TListViewEx; btnBack: TTextView; procedure btnBackClick(Sender: TObject); procedure ListViewItemClick(Sender: TObject; ItemIndex: Integer; const ItemView: TControl); private { Private declarations } FAdapter: TCustomListDataAdapter; protected procedure DoCreate(); override; procedure DoFree(); override; procedure DoShow(); override; public { Public declarations } end; implementation {$R *.fmx} uses ui_CustomListView_ListItem; procedure TFrameListViewGroup.btnBackClick(Sender: TObject); begin Finish(); end; procedure TFrameListViewGroup.DoCreate; begin inherited; FAdapter := TCustomListDataAdapter.Create(); FAdapter.Root.AddNode(TDataItem.Create('我是组1', '', TAlphaColorRec.Crimson)); FAdapter.Root.AddNode(TDataItem.Create('我是组2', '', TAlphaColorRec.Crimson)); FAdapter.Root.AddNode(TDataItem.Create('我是组3', '', TAlphaColorRec.Crimson)); FAdapter.Root.AddNode(TDataItem.Create('我是组4', '', TAlphaColorRec.Crimson)); FAdapter.Root.AddNode(TDataItem.Create('我是组5', '', TAlphaColorRec.Crimson)); FAdapter.Root.AddNode(TDataItem.Create('我是组1', '', TAlphaColorRec.Crimson)); FAdapter.Root.AddNode(TDataItem.Create('我是组2', '', TAlphaColorRec.Crimson)); FAdapter.Root.AddNode(TDataItem.Create('我是组3', '', TAlphaColorRec.Crimson)); FAdapter.Root.AddNode(TDataItem.Create('我是组4', '', TAlphaColorRec.Crimson)); FAdapter.Root.AddNode(TDataItem.Create('我是组5', '', TAlphaColorRec.Crimson)); FAdapter.Root.AddNode(TDataItem.Create('我是组1', '', TAlphaColorRec.Crimson)); FAdapter.Root.AddNode(TDataItem.Create('我是组2', '', TAlphaColorRec.Crimson)); FAdapter.Root.AddNode(TDataItem.Create('我是组3', '', TAlphaColorRec.Crimson)); FAdapter.Root.AddNode(TDataItem.Create('我是组4', '', TAlphaColorRec.Crimson)); FAdapter.Root.AddNode(TDataItem.Create('我是组5', '', TAlphaColorRec.Crimson)); FAdapter.Root.Nodes[0].AddNode(TDataItem.Create('我是节点1', '131 0000 0000', TAlphaColorRec.Crimson)); FAdapter.Root.Nodes[0].AddNode(TDataItem.Create('我是节点2', '131 0000 0000', TAlphaColorRec.Yellow)); FAdapter.Root.Nodes[0].AddNode(TDataItem.Create('我是节点3', '131 0000 0000', TAlphaColorRec.Crimson)); FAdapter.Root.Nodes[0].AddNode(TDataItem.Create('我是节点4', '131 0000 0000', TAlphaColorRec.Yellow)); FAdapter.Root.Nodes[1].AddNode(TDataItem.Create('我是节点1', '131 0000 0000', TAlphaColorRec.Crimson)); FAdapter.Root.Nodes[1].AddNode(TDataItem.Create('我是节点2', '131 0000 0000', TAlphaColorRec.Yellow)); FAdapter.Root.Nodes[1].AddNode(TDataItem.Create('我是节点3', '131 0000 0000', TAlphaColorRec.Crimson)); FAdapter.Root.Nodes[1].AddNode(TDataItem.Create('我是节点4', '131 0000 0000', TAlphaColorRec.Yellow)); FAdapter.Root.Nodes[2].AddNode(TDataItem.Create('我是节点1', '131 0000 0000', TAlphaColorRec.Crimson)); FAdapter.Root.Nodes[2].AddNode(TDataItem.Create('我是节点2', '131 0000 0000', TAlphaColorRec.Yellow)); FAdapter.Root.Nodes[2].AddNode(TDataItem.Create('我是节点3', '131 0000 0000', TAlphaColorRec.Crimson)); FAdapter.Root.Nodes[2].AddNode(TDataItem.Create('我是节点4', '131 0000 0000', TAlphaColorRec.Yellow)); FAdapter.Root.Nodes[3].AddNode(TDataItem.Create('我是节点1', '131 0000 0000', TAlphaColorRec.Crimson)); FAdapter.Root.Nodes[3].AddNode(TDataItem.Create('我是节点2', '131 0000 0000', TAlphaColorRec.Yellow)); FAdapter.Root.Nodes[3].AddNode(TDataItem.Create('我是节点3', '131 0000 0000', TAlphaColorRec.Crimson)); FAdapter.Root.Nodes[3].AddNode(TDataItem.Create('我是节点4', '131 0000 0000', TAlphaColorRec.Yellow)); FAdapter.Root.Nodes[4].AddNode(TDataItem.Create('我是节点1', '131 0000 0000', TAlphaColorRec.Crimson)); FAdapter.Root.Nodes[4].AddNode(TDataItem.Create('我是节点2', '131 0000 0000', TAlphaColorRec.Yellow)); FAdapter.Root.Nodes[4].AddNode(TDataItem.Create('我是节点3', '131 0000 0000', TAlphaColorRec.Crimson)); FAdapter.Root.Nodes[4].AddNode(TDataItem.Create('我是节点4', '131 0000 0000', TAlphaColorRec.Yellow)); FAdapter.Root.Nodes[2].AddNode(TDataItem.Create('我是节点1', '131 0000 0000', TAlphaColorRec.Crimson)); FAdapter.Root.Nodes[3].AddNode(TDataItem.Create('我是节点2', '131 0000 0000', TAlphaColorRec.Yellow)); FAdapter.Root.Nodes[4].AddNode(TDataItem.Create('我是节点3', '131 0000 0000', TAlphaColorRec.Crimson)); FAdapter.Root.Nodes[5].AddNode(TDataItem.Create('我是节点4', '131 0000 0000', TAlphaColorRec.Yellow)); FAdapter.InitList; ListView.Adapter := FAdapter; end; procedure TFrameListViewGroup.DoFree; begin inherited; ListView.Adapter := nil; FAdapter := nil; end; procedure TFrameListViewGroup.DoShow; begin inherited; tvTitle.Text := Title; end; procedure TFrameListViewGroup.ListViewItemClick(Sender: TObject; ItemIndex: Integer; const ItemView: TControl); begin with FAdapter.FList.Items[ItemIndex] do if ItemView is TCustomListView_ListItem then begin Hint(Format('点击了%d. Level:%d. Name:%s', [Index, Level, Data.Name])); Hint(TCustomListView_ListItem(ItemView).TextView1.Text); end else Hint(Format('点击了分组%d. Level:%d. Name:%s', [Index, Level, Data.Name])); end; { TDataItem } constructor TDataItem.Create(const Name, Phone: string; const Color: TAlphaColor); begin Self.Name := Name; Self.Phone := Phone; Self.Color := Color; end; { TCustomListDataAdapter } function TCustomListDataAdapter.GetNodeItemView(const Index: Integer; const ANode: TTreeListNode<TDataItem>; ConvertView: TViewBase; Parent: TViewGroup): TViewBase; var ViewItem: TCustomListView_ListItem; begin if (ConvertView = nil) or (not (ConvertView.ClassType = TCustomListView_ListItem)) then begin ViewItem := TCustomListView_ListItem.Create(Parent); ViewItem.Parent := Parent; ViewItem.Width := Parent.Width; ViewItem.CanFocus := False; end else ViewItem := TObject(ConvertView) as TCustomListView_ListItem; ViewItem.BeginUpdate; ViewItem.TextView1.Text := ANode.Data.Name; ViewItem.TextView2.Text := ANode.Data.Phone; ViewItem.View1.Background.ItemDefault.Color := ANode.Data.Color; ViewItem.BadgeView1.Value := Index + 1; ViewItem.EndUpdate; Result := TViewBase(ViewItem); end; function TCustomListDataAdapter.GetNodeText( const ANode: TTreeListNode<TDataItem>): string; begin Result := ANode.Data.Name; end; end.
{ *********************************************************************** } { } { Delphi Runtime Library } { } { Copyright (c) 1995-2001 Borland Software Corporation } { } { *********************************************************************** } {*******************************************************} { Standard conversions types } {*******************************************************} { *************************************************************************** Physical, Fluidic, Thermal, and Temporal conversion units The metric units and prefixes in this unit follow the various SI/NIST standards (http://physics.nist.gov/cuu/Units/index.html and http://www.bipm.fr/enus/3_SI). We have decided to use the Deca instead of Deka to represent 10 of something. Great conversion sites http://www.ex.ac.uk/cimt/dictunit/dictunit.htm !! GREAT SITE !! http://www.unc.edu/~rowlett/units/index.html !! GREAT SITE !! http://www.omnis.demon.co.uk/indexfrm.htm !! GREAT SITE !! http://www.sciencemadesimple.com/conversions.html http://www.numberexchange.net/Convert/Weight.html http://students.washington.edu/kyle/temp.html http://www.convertit.com *************************************************************************** References: [1] NIST: Mendenhall Order of 1893 [2] http://ds.dial.pipex.com/nib/metric.htm [3] http://www.omnis.demon.co.uk/conversn/oldenguk.htm [4] NIST (http://physics.nist.gov/cuu/Units/outside.html) [5] NIST (http://physics.nist.gov/cuu/Units/meter.html) [6] Accepted best guess, but nobody really knows [7] http://www.ex.ac.uk/cimt/dictunit/dictunit.htm } unit StdConvs; interface uses SysUtils, ConvUtils; var { ************************************************************************* } { Distance Conversion Units } { basic unit of measurement is meters } cbDistance: TConvFamily; duMicromicrons: TConvType; duAngstroms: TConvType; duMillimicrons: TConvType; duMicrons: TConvType; duMillimeters: TConvType; duCentimeters: TConvType; duDecimeters: TConvType; duMeters: TConvType; duDecameters: TConvType; duHectometers: TConvType; duKilometers: TConvType; duMegameters: TConvType; duGigameters: TConvType; duInches: TConvType; duFeet: TConvType; duYards: TConvType; duMiles: TConvType; duNauticalMiles: TConvType; duAstronomicalUnits: TConvType; duLightYears: TConvType; duParsecs: TConvType; duCubits: TConvType; duFathoms: TConvType; duFurlongs: TConvType; duHands: TConvType; duPaces: TConvType; duRods: TConvType; duChains: TConvType; duLinks: TConvType; duPicas: TConvType; duPoints: TConvType; { ************************************************************************* } { Area Conversion Units } { basic unit of measurement is square meters } cbArea: TConvFamily; auSquareMillimeters: TConvType; auSquareCentimeters: TConvType; auSquareDecimeters: TConvType; auSquareMeters: TConvType; auSquareDecameters: TConvType; auSquareHectometers: TConvType; auSquareKilometers: TConvType; auSquareInches: TConvType; auSquareFeet: TConvType; auSquareYards: TConvType; auSquareMiles: TConvType; auAcres: TConvType; auCentares: TConvType; auAres: TConvType; auHectares: TConvType; auSquareRods: TConvType; { ************************************************************************* } { Volume Conversion Units } { basic unit of measurement is cubic meters } cbVolume: TConvFamily; vuCubicMillimeters: TConvType; vuCubicCentimeters: TConvType; vuCubicDecimeters: TConvType; vuCubicMeters: TConvType; vuCubicDecameters: TConvType; vuCubicHectometers: TConvType; vuCubicKilometers: TConvType; vuCubicInches: TConvType; vuCubicFeet: TConvType; vuCubicYards: TConvType; vuCubicMiles: TConvType; vuMilliLiters: TConvType; vuCentiLiters: TConvType; vuDeciLiters: TConvType; vuLiters: TConvType; vuDecaLiters: TConvType; vuHectoLiters: TConvType; vuKiloLiters: TConvType; vuAcreFeet: TConvType; vuAcreInches: TConvType; vuCords: TConvType; vuCordFeet: TConvType; vuDecisteres: TConvType; vuSteres: TConvType; vuDecasteres: TConvType; vuFluidGallons: TConvType; { American Fluid Units } vuFluidQuarts: TConvType; vuFluidPints: TConvType; vuFluidCups: TConvType; vuFluidGills: TConvType; vuFluidOunces: TConvType; vuFluidTablespoons: TConvType; vuFluidTeaspoons: TConvType; vuDryGallons: TConvType; { American Dry Units } vuDryQuarts: TConvType; vuDryPints: TConvType; vuDryPecks: TConvType; vuDryBuckets: TConvType; vuDryBushels: TConvType; vuUKGallons: TConvType; { English Imperial Fluid/Dry Units } vuUKPottles: TConvType; vuUKQuarts: TConvType; vuUKPints: TConvType; vuUKGills: TConvType; vuUKOunces: TConvType; vuUKPecks: TConvType; vuUKBuckets: TConvType; vuUKBushels: TConvType; { ************************************************************************* } { Mass Conversion Units } { basic unit of measurement is grams } cbMass: TConvFamily; muNanograms: TConvType; muMicrograms: TConvType; muMilligrams: TConvType; muCentigrams: TConvType; muDecigrams: TConvType; muGrams: TConvType; muDecagrams: TConvType; muHectograms: TConvType; muKilograms: TConvType; muMetricTons: TConvType; muDrams: TConvType; // Avoirdupois Units muGrains: TConvType; muLongTons: TConvType; muTons: TConvType; muOunces: TConvType; muPounds: TConvType; muStones: TConvType; { ************************************************************************* } { Temperature Conversion Units } { basic unit of measurement is celsius } cbTemperature: TConvFamily; tuCelsius: TConvType; tuKelvin: TConvType; tuFahrenheit: TConvType; tuRankine: TConvType; tuReaumur: TConvType; { ************************************************************************* } { Time Conversion Units } { basic unit of measurement is days (which is also the same as TDateTime) } cbTime: TConvFamily; tuMilliSeconds: TConvType; tuSeconds: TConvType; tuMinutes: TConvType; tuHours: TConvType; tuDays: TConvType; tuWeeks: TConvType; tuFortnights: TConvType; tuMonths: TConvType; tuYears: TConvType; tuDecades: TConvType; tuCenturies: TConvType; tuMillennia: TConvType; tuDateTime: TConvType; tuJulianDate: TConvType; tuModifiedJulianDate: TConvType; { Constants (and their derivatives) used in this unit } const MetersPerInch = 0.0254; // [1] MetersPerFoot = MetersPerInch * 12; MetersPerYard = MetersPerFoot * 3; MetersPerMile = MetersPerFoot * 5280; MetersPerNauticalMiles = 1852; MetersPerAstronomicalUnit = 1.49598E11; // [4] MetersPerLightSecond = 2.99792458E8; // [5] MetersPerLightYear = MetersPerLightSecond * 31556925.9747; // [7] MetersPerParsec = MetersPerAstronomicalUnit * 206264.806247096; // 60 * 60 * (180 / Pi) MetersPerCubit = 0.4572; // [6][7] MetersPerFathom = MetersPerFoot * 6; MetersPerFurlong = MetersPerYard * 220; MetersPerHand = MetersPerInch * 4; MetersPerPace = MetersPerInch * 30; MetersPerRod = MetersPerFoot * 16.5; MetersPerChain = MetersPerRod * 4; MetersPerLink = MetersPerChain / 100; MetersPerPoint = MetersPerInch * 0.013837; // [7] MetersPerPica = MetersPerPoint * 12; SquareMetersPerSquareInch = MetersPerInch * MetersPerInch; SquareMetersPerSquareFoot = MetersPerFoot * MetersPerFoot; SquareMetersPerSquareYard = MetersPerYard * MetersPerYard; SquareMetersPerSquareMile = MetersPerMile * MetersPerMile; SquareMetersPerAcre = SquareMetersPerSquareYard * 4840; SquareMetersPerSquareRod = MetersPerRod * MetersPerRod; CubicMetersPerCubicInch = MetersPerInch * MetersPerInch * MetersPerInch; CubicMetersPerCubicFoot = MetersPerFoot * MetersPerFoot * MetersPerFoot; CubicMetersPerCubicYard = MetersPerYard * MetersPerYard * MetersPerYard; CubicMetersPerCubicMile = MetersPerMile * MetersPerMile * MetersPerMile; CubicMetersPerAcreFoot = SquareMetersPerAcre * MetersPerFoot; CubicMetersPerAcreInch = SquareMetersPerAcre * MetersPerInch; CubicMetersPerCord = CubicMetersPerCubicFoot * 128; CubicMetersPerCordFoot = CubicMetersPerCubicFoot * 16; CubicMetersPerUSFluidGallon = CubicMetersPerCubicInch * 231; // [2][3][7] CubicMetersPerUSFluidQuart = CubicMetersPerUSFluidGallon / 4; CubicMetersPerUSFluidPint = CubicMetersPerUSFluidQuart / 2; CubicMetersPerUSFluidCup = CubicMetersPerUSFluidPint / 2; CubicMetersPerUSFluidGill = CubicMetersPerUSFluidCup / 2; CubicMetersPerUSFluidOunce = CubicMetersPerUSFluidCup / 8; CubicMetersPerUSFluidTablespoon = CubicMetersPerUSFluidOunce / 2; CubicMetersPerUSFluidTeaspoon = CubicMetersPerUSFluidOunce / 6; CubicMetersPerUSDryGallon = CubicMetersPerCubicInch * 268.8025; // [7] CubicMetersPerUSDryQuart = CubicMetersPerUSDryGallon / 4; CubicMetersPerUSDryPint = CubicMetersPerUSDryQuart / 2; CubicMetersPerUSDryPeck = CubicMetersPerUSDryGallon * 2; CubicMetersPerUSDryBucket = CubicMetersPerUSDryPeck * 2; CubicMetersPerUSDryBushel = CubicMetersPerUSDryBucket * 2; CubicMetersPerUKGallon = 0.00454609; // [2][7] CubicMetersPerUKPottle = CubicMetersPerUKGallon / 2; CubicMetersPerUKQuart = CubicMetersPerUKPottle / 2; CubicMetersPerUKPint = CubicMetersPerUKQuart / 2; CubicMetersPerUKGill = CubicMetersPerUKPint / 4; CubicMetersPerUKOunce = CubicMetersPerUKPint / 20; CubicMetersPerUKPeck = CubicMetersPerUKGallon * 2; CubicMetersPerUKBucket = CubicMetersPerUKPeck * 2; CubicMetersPerUKBushel = CubicMetersPerUKBucket * 2; GramsPerPound = 453.59237; // [1][7] GramsPerDrams = GramsPerPound / 256; GramsPerGrains = GramsPerPound / 7000; GramsPerTons = GramsPerPound * 2000; GramsPerLongTons = GramsPerPound * 2240; GramsPerOunces = GramsPerPound / 16; GramsPerStones = GramsPerPound * 14; { simple temperature conversion } function FahrenheitToCelsius(const AValue: Double): Double; function CelsiusToFahrenheit(const AValue: Double): Double; { C++ clients should call this routine to ensure the unit is initialized } procedure InitStdConvs; implementation uses RTLConsts, DateUtils; function FahrenheitToCelsius(const AValue: Double): Double; begin Result := ((AValue - 32) * 5) / 9; end; function CelsiusToFahrenheit(const AValue: Double): Double; begin Result := ((AValue * 9) / 5) + 32; end; function KelvinToCelsius(const AValue: Double): Double; begin Result := AValue - 273.15; end; function CelsiusToKelvin(const AValue: Double): Double; begin Result := AValue + 273.15; end; function RankineToCelsius(const AValue: Double): Double; begin Result := FahrenheitToCelsius(AValue - 459.67); end; function CelsiusToRankine(const AValue: Double): Double; begin Result := CelsiusToFahrenheit(AValue) + 459.67; end; function ReaumurToCelsius(const AValue: Double): Double; begin Result := ((CelsiusToFahrenheit(AValue) - 32) * 4) / 9; end; function CelsiusToReaumur(const AValue: Double): Double; begin Result := FahrenheitToCelsius(((AValue * 9) / 4) + 32); end; function ConvDateTimeToJulianDate(const AValue: Double): Double; begin Result := DateTimeToJulianDate(AValue); end; function ConvJulianDateToDateTime(const AValue: Double): Double; begin Result := JulianDateToDateTime(AValue); end; function ConvDateTimeToModifiedJulianDate(const AValue: Double): Double; begin Result := DateTimeToModifiedJulianDate(AValue); end; function ConvModifiedJulianDateToDateTime(const AValue: Double): Double; begin Result := ModifiedJulianDateToDateTime(AValue); end; procedure InitStdConvs; begin { Nothing to do, the implementation will arrange to call 'initialization' } end; initialization { ************************************************************************* } { Distance's family type } cbDistance := RegisterConversionFamily(SDistanceDescription); { Distance's various conversion types } duMicromicrons := RegisterConversionType(cbDistance, SMicromicronsDescription, 1E-12); duAngstroms := RegisterConversionType(cbDistance, SAngstromsDescription, 1E-10); duMillimicrons := RegisterConversionType(cbDistance, SMillimicronsDescription, 1E-9); duMicrons := RegisterConversionType(cbDistance, SMicronsDescription, 1E-6); duMillimeters := RegisterConversionType(cbDistance, SMillimetersDescription, 0.001); duCentimeters := RegisterConversionType(cbDistance, SCentimetersDescription, 0.01); duDecimeters := RegisterConversionType(cbDistance, SDecimetersDescription, 0.1); duMeters := RegisterConversionType(cbDistance, SMetersDescription, 1); duDecameters := RegisterConversionType(cbDistance, SDecametersDescription, 10); duHectometers := RegisterConversionType(cbDistance, SHectometersDescription, 100); duKilometers := RegisterConversionType(cbDistance, SKilometersDescription, 1000); duMegameters := RegisterConversionType(cbDistance, SMegametersDescription, 1E+6); duGigameters := RegisterConversionType(cbDistance, SGigametersDescription, 1E+9); duInches := RegisterConversionType(cbDistance, SInchesDescription, MetersPerInch); duFeet := RegisterConversionType(cbDistance, SFeetDescription, MetersPerFoot); duYards := RegisterConversionType(cbDistance, SYardsDescription, MetersPerYard); duMiles := RegisterConversionType(cbDistance, SMilesDescription, MetersPerMile); duNauticalMiles := RegisterConversionType(cbDistance, SNauticalMilesDescription, MetersPerNauticalMiles); duAstronomicalUnits := RegisterConversionType(cbDistance, SAstronomicalUnitsDescription, MetersPerAstronomicalUnit); duLightYears := RegisterConversionType(cbDistance, SLightYearsDescription, MetersPerLightYear); duParsecs := RegisterConversionType(cbDistance, SParsecsDescription, MetersPerParsec); duCubits := RegisterConversionType(cbDistance, SCubitsDescription, MetersPerCubit); duFathoms := RegisterConversionType(cbDistance, SFathomsDescription, MetersPerFathom); duFurlongs := RegisterConversionType(cbDistance, SFurlongsDescription, MetersPerFurlong); duHands := RegisterConversionType(cbDistance, SHandsDescription, MetersPerHand); duPaces := RegisterConversionType(cbDistance, SPacesDescription, MetersPerPace); duRods := RegisterConversionType(cbDistance, SRodsDescription, MetersPerRod); duChains := RegisterConversionType(cbDistance, SChainsDescription, MetersPerChain); duLinks := RegisterConversionType(cbDistance, SLinksDescription, MetersPerLink); duPicas := RegisterConversionType(cbDistance, SPicasDescription, MetersPerPica); duPoints := RegisterConversionType(cbDistance, SPointsDescription, MetersPerPoint); { ************************************************************************* } { Area's family type } cbArea := RegisterConversionFamily(SAreaDescription); { Area's various conversion types } auSquareMillimeters := RegisterConversionType(cbArea, SSquareMillimetersDescription, 1E-6); auSquareCentimeters := RegisterConversionType(cbArea, SSquareCentimetersDescription, 0.0001); auSquareDecimeters := RegisterConversionType(cbArea, SSquareDecimetersDescription, 0.01); auSquareMeters := RegisterConversionType(cbArea, SSquareMetersDescription, 1); auSquareDecameters := RegisterConversionType(cbArea, SSquareDecametersDescription, 100); auSquareHectometers := RegisterConversionType(cbArea, SSquareHectometersDescription, 10000); auSquareKilometers := RegisterConversionType(cbArea, SSquareKilometersDescription, 1E+6); auSquareInches := RegisterConversionType(cbArea, SSquareInchesDescription, SquareMetersPerSquareInch); auSquareFeet := RegisterConversionType(cbArea, SSquareFeetDescription, SquareMetersPerSquareFoot); auSquareYards := RegisterConversionType(cbArea, SSquareYardsDescription, SquareMetersPerSquareYard); auSquareMiles := RegisterConversionType(cbArea, SSquareMilesDescription, SquareMetersPerSquareMile); auAcres := RegisterConversionType(cbArea, SAcresDescription, SquareMetersPerAcre); auCentares := RegisterConversionType(cbArea, SCentaresDescription, 1); auAres := RegisterConversionType(cbArea, SAresDescription, 100); auHectares := RegisterConversionType(cbArea, SHectaresDescription, 10000); auSquareRods := RegisterConversionType(cbArea, SSquareRodsDescription, SquareMetersPerSquareRod); { ************************************************************************* } { Volume's family type } cbVolume := RegisterConversionFamily(SVolumeDescription); { Volume's various conversion types } vuCubicMillimeters := RegisterConversionType(cbVolume, SCubicMillimetersDescription, 1E-9); vuCubicCentimeters := RegisterConversionType(cbVolume, SCubicCentimetersDescription, 1E-6); vuCubicDecimeters := RegisterConversionType(cbVolume, SCubicDecimetersDescription, 0.001); vuCubicMeters := RegisterConversionType(cbVolume, SCubicMetersDescription, 1); vuCubicDecameters := RegisterConversionType(cbVolume, SCubicDecametersDescription, 1000); vuCubicHectometers := RegisterConversionType(cbVolume, SCubicHectometersDescription, 1E+6); vuCubicKilometers := RegisterConversionType(cbVolume, SCubicKilometersDescription, 1E+9); vuCubicInches := RegisterConversionType(cbVolume, SCubicInchesDescription, CubicMetersPerCubicInch); vuCubicFeet := RegisterConversionType(cbVolume, SCubicFeetDescription, CubicMetersPerCubicFoot); vuCubicYards := RegisterConversionType(cbVolume, SCubicYardsDescription, CubicMetersPerCubicYard); vuCubicMiles := RegisterConversionType(cbVolume, SCubicMilesDescription, CubicMetersPerCubicMile); vuMilliLiters := RegisterConversionType(cbVolume, SMilliLitersDescription, 1E-6); vuCentiLiters := RegisterConversionType(cbVolume, SCentiLitersDescription, 1E-5); vuDeciLiters := RegisterConversionType(cbVolume, SDeciLitersDescription, 1E-4); vuLiters := RegisterConversionType(cbVolume, SLitersDescription, 0.001); vuDecaLiters := RegisterConversionType(cbVolume, SDecaLitersDescription, 0.01); vuHectoLiters := RegisterConversionType(cbVolume, SHectoLitersDescription, 0.1); vuKiloLiters := RegisterConversionType(cbVolume, SKiloLitersDescription, 1); vuAcreFeet := RegisterConversionType(cbVolume, SAcreFeetDescription, CubicMetersPerAcreFoot); vuAcreInches := RegisterConversionType(cbVolume, SAcreInchesDescription, CubicMetersPerAcreInch); vuCords := RegisterConversionType(cbVolume, SCordsDescription, CubicMetersPerCord); vuCordFeet := RegisterConversionType(cbVolume, SCordFeetDescription, CubicMetersPerCordFoot); vuDecisteres := RegisterConversionType(cbVolume, SDecisteresDescription, 0.1); vuSteres := RegisterConversionType(cbVolume, SSteresDescription, 1); vuDecasteres := RegisterConversionType(cbVolume, SDecasteresDescription, 10); { American Fluid Units } vuFluidGallons := RegisterConversionType(cbVolume, SFluidGallonsDescription, CubicMetersPerUSFluidGallon); vuFluidQuarts := RegisterConversionType(cbVolume, SFluidQuartsDescription, CubicMetersPerUSFluidQuart); vuFluidPints := RegisterConversionType(cbVolume, SFluidPintsDescription, CubicMetersPerUSFluidPint); vuFluidCups := RegisterConversionType(cbVolume, SFluidCupsDescription, CubicMetersPerUSFluidCup); vuFluidGills := RegisterConversionType(cbVolume, SFluidGillsDescription, CubicMetersPerUSFluidGill); vuFluidOunces := RegisterConversionType(cbVolume, SFluidOuncesDescription, CubicMetersPerUSFluidOunce); vuFluidTablespoons := RegisterConversionType(cbVolume, SFluidTablespoonsDescription, CubicMetersPerUSFluidTablespoon); vuFluidTeaspoons := RegisterConversionType(cbVolume, SFluidTeaspoonsDescription, CubicMetersPerUSFluidTeaspoon); { American Dry Units } vuDryGallons := RegisterConversionType(cbVolume, SDryGallonsDescription, CubicMetersPerUSDryGallon); vuDryQuarts := RegisterConversionType(cbVolume, SDryQuartsDescription, CubicMetersPerUSDryQuart); vuDryPints := RegisterConversionType(cbVolume, SDryPintsDescription, CubicMetersPerUSDryPint); vuDryPecks := RegisterConversionType(cbVolume, SDryPecksDescription, CubicMetersPerUSDryPeck); vuDryBuckets := RegisterConversionType(cbVolume, SDryBucketsDescription, CubicMetersPerUSDryBucket); vuDryBushels := RegisterConversionType(cbVolume, SDryBushelsDescription, CubicMetersPerUSDryBushel); { English Imperial Fluid/Dry Units } vuUKGallons := RegisterConversionType(cbVolume, SUKGallonsDescription, CubicMetersPerUKGallon); vuUKPottles := RegisterConversionType(cbVolume, SUKPottlesDescription, CubicMetersPerUKPottle); vuUKQuarts := RegisterConversionType(cbVolume, SUKQuartsDescription, CubicMetersPerUKQuart); vuUKPints := RegisterConversionType(cbVolume, SUKPintsDescription, CubicMetersPerUKPint); vuUKGills := RegisterConversionType(cbVolume, SUKGillsDescription, CubicMetersPerUKGill); vuUKOunces := RegisterConversionType(cbVolume, SUKOuncesDescription, CubicMetersPerUKOunce); vuUKPecks := RegisterConversionType(cbVolume, SUKPecksDescription, CubicMetersPerUKPeck); vuUKBuckets := RegisterConversionType(cbVolume, SUKBucketsDescription, CubicMetersPerUKBucket); vuUKBushels := RegisterConversionType(cbVolume, SUKBushelsDescription, CubicMetersPerUKBushel); { ************************************************************************* } { Mass's family type } cbMass := RegisterConversionFamily(SMassDescription); { Mass's various conversion types } muNanograms := RegisterConversionType(cbMass, SNanogramsDescription, 1E-9); muMicrograms := RegisterConversionType(cbMass, SMicrogramsDescription, 1E-6); muMilligrams := RegisterConversionType(cbMass, SMilligramsDescription, 0.001); muCentigrams := RegisterConversionType(cbMass, SCentigramsDescription, 0.01); muDecigrams := RegisterConversionType(cbMass, SDecigramsDescription, 0.1); muGrams := RegisterConversionType(cbMass, SGramsDescription, 1); muDecagrams := RegisterConversionType(cbMass, SDecagramsDescription, 10); muHectograms := RegisterConversionType(cbMass, SHectogramsDescription, 100); muKilograms := RegisterConversionType(cbMass, SKilogramsDescription, 1000); muMetricTons := RegisterConversionType(cbMass, SMetricTonsDescription, 1E+6); muDrams := RegisterConversionType(cbMass, SDramsDescription, GramsPerDrams); muGrains := RegisterConversionType(cbMass, SGrainsDescription, GramsPerGrains); muTons := RegisterConversionType(cbMass, STonsDescription, GramsPerTons); muLongTons := RegisterConversionType(cbMass, SLongTonsDescription, GramsPerLongTons); muOunces := RegisterConversionType(cbMass, SOuncesDescription, GramsPerOunces); muPounds := RegisterConversionType(cbMass, SPoundsDescription, GramsPerPound); muStones := RegisterConversionType(cbMass, SStonesDescription, GramsPerStones); { ************************************************************************* } { Temperature's family type } cbTemperature := RegisterConversionFamily(STemperatureDescription); { Temperature's various conversion types } tuCelsius := RegisterConversionType(cbTemperature, SCelsiusDescription, 1); tuKelvin := RegisterConversionType(cbTemperature, SKelvinDescription, KelvinToCelsius, CelsiusToKelvin); tuFahrenheit := RegisterConversionType(cbTemperature, SFahrenheitDescription, FahrenheitToCelsius, CelsiusToFahrenheit); tuRankine := RegisterConversionType(cbTemperature, SRankineDescription, RankineToCelsius, CelsiusToRankine); tuReaumur := RegisterConversionType(cbTemperature, SReaumurDescription, ReaumurToCelsius, CelsiusToReaumur); { ************************************************************************* } { Time's family type } cbTime := RegisterConversionFamily(STimeDescription); { Time's various conversion types } tuMilliSeconds := RegisterConversionType(cbTime, SMilliSecondsDescription, 1 / MSecsPerDay); tuSeconds := RegisterConversionType(cbTime, SSecondsDescription, 1 / SecsPerDay); tuMinutes := RegisterConversionType(cbTime, SMinutesDescription, 1 / MinsPerDay); tuHours := RegisterConversionType(cbTime, SHoursDescription, 1 / HoursPerDay); tuDays := RegisterConversionType(cbTime, SDaysDescription, 1); tuWeeks := RegisterConversionType(cbTime, SWeeksDescription, DaysPerWeek); tuFortnights := RegisterConversionType(cbTime, SFortnightsDescription, WeeksPerFortnight * DaysPerWeek); tuMonths := RegisterConversionType(cbTime, SMonthsDescription, ApproxDaysPerMonth); tuYears := RegisterConversionType(cbTime, SYearsDescription, ApproxDaysPerYear); tuDecades := RegisterConversionType(cbTime, SDecadesDescription, ApproxDaysPerYear * YearsPerDecade); tuCenturies := RegisterConversionType(cbTime, SCenturiesDescription, ApproxDaysPerYear * YearsPerCentury); tuMillennia := RegisterConversionType(cbTime, SMillenniaDescription, ApproxDaysPerYear * YearsPerMillennium); tuDateTime := RegisterConversionType(cbTime, SDateTimeDescription, 1); tuJulianDate := RegisterConversionType(cbTime, SJulianDateDescription, ConvJulianDateToDateTime, ConvDateTimeToJulianDate); tuModifiedJulianDate := RegisterConversionType(cbTime, SModifiedJulianDateDescription, ConvModifiedJulianDateToDateTime, ConvDateTimeToModifiedJulianDate); finalization { Unregister all the conversion types we are responsible for } UnregisterConversionFamily(cbDistance); UnregisterConversionFamily(cbArea); UnregisterConversionFamily(cbVolume); UnregisterConversionFamily(cbMass); UnregisterConversionFamily(cbTemperature); UnregisterConversionFamily(cbTime); end.
unit FIToolkit.Commons.FiniteStateMachine.FSM; interface uses System.SysUtils, System.Generics.Collections, System.Generics.Defaults; type TOnEnterStateMethod<TState, TCommand> = procedure (const PreviousState, CurrentState : TState; const UsedCommand : TCommand) of object; TOnEnterStateProc<TState, TCommand> = reference to procedure (const PreviousState, CurrentState : TState; const UsedCommand : TCommand); TOnExitStateMethod<TState, TCommand> = procedure (const CurrentState, NewState : TState; const UsedCommand : TCommand) of object; TOnExitStateProc<TState, TCommand> = reference to procedure (const CurrentState, NewState : TState; const UsedCommand : TCommand); IFiniteStateMachine<TState, TCommand; ErrorClass : Exception, constructor> = interface function AddTransition(const FromState, ToState : TState; const OnCommand : TCommand ) : IFiniteStateMachine<TState, TCommand, ErrorClass>; overload; function AddTransition(const FromState, ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateMethod<TState, TCommand>; const OnExit : TOnExitStateMethod<TState, TCommand> = nil ) : IFiniteStateMachine<TState, TCommand, ErrorClass>; overload; function AddTransition(const FromState, ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateProc<TState, TCommand>; const OnExit : TOnExitStateProc<TState, TCommand> = nil ) : IFiniteStateMachine<TState, TCommand, ErrorClass>; overload; function AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand ) : IFiniteStateMachine<TState, TCommand, ErrorClass>; overload; function AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateMethod<TState, TCommand>; const OnExit : TOnExitStateMethod<TState, TCommand> = nil ) : IFiniteStateMachine<TState, TCommand, ErrorClass>; overload; function AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateProc<TState, TCommand>; const OnExit : TOnExitStateProc<TState, TCommand> = nil ) : IFiniteStateMachine<TState, TCommand, ErrorClass>; overload; function Execute(const Command : TCommand) : IFiniteStateMachine<TState, TCommand, ErrorClass>; function GetCurrentState : TState; function GetPreviousState : TState; function GetReachableState(const FromState : TState; const OnCommand : TCommand) : TState; overload; function GetReachableState(const OnCommand : TCommand) : TState; overload; function HasTransition(const FromState : TState; const OnCommand : TCommand) : Boolean; overload; function HasTransition(const OnCommand : TCommand) : Boolean; overload; function RemoveAllTransitions : IFiniteStateMachine<TState, TCommand, ErrorClass>; function RemoveTransition(const FromState : TState; const OnCommand : TCommand ) : IFiniteStateMachine<TState, TCommand, ErrorClass>; property CurrentState : TState read GetCurrentState; property PreviousState : TState read GetPreviousState; end; TFiniteStateMachine<TState, TCommand; ErrorClass : Exception, constructor> = class abstract (TInterfacedObject, IFiniteStateMachine<TState, TCommand, ErrorClass>) private type ICommandComparer = IEqualityComparer<TCommand>; IFiniteStateMachine = IFiniteStateMachine<TState, TCommand, ErrorClass>; IStateComparer = IEqualityComparer<TState>; TOnEnterStateMethod = TOnEnterStateMethod<TState, TCommand>; TOnEnterStateProc = TOnEnterStateProc<TState, TCommand>; TOnExitStateMethod = TOnExitStateMethod<TState, TCommand>; TOnExitStateProc = TOnExitStateProc<TState, TCommand>; TTransition = class sealed strict private FFromState : TState; FOnCommand : TCommand; FCommandComparer : ICommandComparer; FStateComparer : IStateComparer; FOnEnterStateMethod : TOnEnterStateMethod; FOnEnterStateProc : TOnEnterStateProc; FOnExitStateMethod : TOnExitStateMethod; FOnExitStateProc : TOnExitStateProc; private function GetCombinedHashCode(const HashCodes : array of Integer) : Integer; public function Equals(Obj : TObject) : Boolean; override; final; function GetHashCode : Integer; override; final; public constructor Create(const AFromState : TState; const AOnCommand : TCommand; const StateComparer : IStateComparer; const CommandComparer : ICommandComparer); overload; constructor Create(const AFromState : TState; const AOnCommand : TCommand; const StateComparer : IStateComparer; const CommandComparer : ICommandComparer; const OnEnterState : TOnEnterStateMethod; const OnExitState : TOnExitStateMethod); overload; constructor Create(const AFromState : TState; const AOnCommand : TCommand; const StateComparer : IStateComparer; const CommandComparer : ICommandComparer; const OnEnterState : TOnEnterStateProc; const OnExitState : TOnExitStateProc); overload; procedure PerformEnterStateAction(const CurrentState : TState); procedure PerformExitStateAction(const NewState : TState); property FromState : TState read FFromState; property OnCommand : TCommand read FOnCommand; end; TTransitionTable = class (TObjectDictionary<TTransition, TState>); strict private FCommandComparer : ICommandComparer; FCurrentState : TState; FExecuting : Boolean; FPreviousState : TState; FStateComparer : IStateComparer; FTransitionTable : TTransitionTable; private function AddTransition(var Transition : TTransition; const ToState : TState) : IFiniteStateMachine; overload; function FindTransition(const FromState : TState; const OnCommand : TCommand) : TTransition; function GetReachableState(const FromState : TState; const OnCommand : TCommand; out Transition : TTransition) : TState; overload; function HasTransition(const FromState : TState; const OnCommand : TCommand; out Transition : TTransition) : Boolean; overload; function GetCurrentState : TState; function GetPreviousState : TState; strict protected procedure AfterExecute(const Command : TCommand); virtual; procedure BeforeExecute(const Command : TCommand); virtual; procedure RaiseOuterException(E : Exception); virtual; protected class function GetDefaultInitialState : TState; virtual; function CommandToStr(const Command : TCommand) : String; virtual; function StateToStr(const State : TState) : String; virtual; public constructor Create; overload; constructor Create(const InitialState : TState); overload; virtual; constructor Create(const InitialState : TState; const StateComparer : IStateComparer; const CommandComparer : ICommandComparer); overload; virtual; destructor Destroy; override; function AddTransition(const FromState, ToState : TState; const OnCommand : TCommand ) : IFiniteStateMachine; overload; function AddTransition(const FromState, ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateMethod; const OnExit : TOnExitStateMethod = nil ) : IFiniteStateMachine; overload; function AddTransition(const FromState, ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateProc; const OnExit : TOnExitStateProc = nil ) : IFiniteStateMachine; overload; function AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand ) : IFiniteStateMachine; overload; function AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateMethod; const OnExit : TOnExitStateMethod = nil ) : IFiniteStateMachine; overload; function AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateProc; const OnExit : TOnExitStateProc = nil ) : IFiniteStateMachine; overload; function Execute(const Command : TCommand) : IFiniteStateMachine; function GetReachableState(const FromState : TState; const OnCommand : TCommand) : TState; overload; function GetReachableState(const OnCommand : TCommand) : TState; overload; function HasTransition(const FromState : TState; const OnCommand : TCommand) : Boolean; overload; function HasTransition(const OnCommand : TCommand) : Boolean; overload; function RemoveAllTransitions : IFiniteStateMachine; function RemoveTransition(const FromState : TState; const OnCommand : TCommand) : IFiniteStateMachine; property CurrentState : TState read GetCurrentState; property PreviousState : TState read GetPreviousState; end; IThreadFiniteStateMachine<TState, TCommand; ErrorClass : Exception, constructor> = interface (IFiniteStateMachine<TState, TCommand, ErrorClass>) function Lock : IFiniteStateMachine<TState, TCommand, ErrorClass>; procedure Unlock; end; TThreadFiniteStateMachine<TState, TCommand; ErrorClass : Exception, constructor> = class (TInterfacedObject, IFiniteStateMachine<TState, TCommand, ErrorClass>, IThreadFiniteStateMachine<TState, TCommand, ErrorClass>) private type ICommandComparer = IEqualityComparer<TCommand>; IFiniteStateMachine = IFiniteStateMachine<TState, TCommand, ErrorClass>; IStateComparer = IEqualityComparer<TState>; TOnEnterStateMethod = TOnEnterStateMethod<TState, TCommand>; TOnEnterStateProc = TOnEnterStateProc<TState, TCommand>; TOnExitStateMethod = TOnExitStateMethod<TState, TCommand>; TOnExitStateProc = TOnExitStateProc<TState, TCommand>; strict private FFiniteStateMachine : IFiniteStateMachine; FLock : TObject; private procedure InternalLock; procedure InternalUnlock; function GetCurrentState : TState; function GetPreviousState : TState; public constructor Create; overload; constructor Create(const StateMachine : IFiniteStateMachine); overload; destructor Destroy; override; function AddTransition(const FromState, ToState : TState; const OnCommand : TCommand ) : IFiniteStateMachine; overload; function AddTransition(const FromState, ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateMethod; const OnExit : TOnExitStateMethod = nil ) : IFiniteStateMachine; overload; function AddTransition(const FromState, ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateProc; const OnExit : TOnExitStateProc = nil ) : IFiniteStateMachine; overload; function AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand ) : IFiniteStateMachine; overload; function AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateMethod; const OnExit : TOnExitStateMethod = nil ) : IFiniteStateMachine; overload; function AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateProc; const OnExit : TOnExitStateProc = nil ) : IFiniteStateMachine; overload; function Execute(const Command : TCommand) : IFiniteStateMachine; function GetReachableState(const FromState : TState; const OnCommand : TCommand) : TState; overload; function GetReachableState(const OnCommand : TCommand) : TState; overload; function HasTransition(const FromState : TState; const OnCommand : TCommand) : Boolean; overload; function HasTransition(const OnCommand : TCommand) : Boolean; overload; function Lock : IFiniteStateMachine; function RemoveAllTransitions : IFiniteStateMachine; function RemoveTransition(const FromState : TState; const OnCommand : TCommand) : IFiniteStateMachine; procedure Unlock; property CurrentState : TState read GetCurrentState; property PreviousState : TState read GetPreviousState; end; implementation uses System.Rtti, FIToolkit.Commons.FiniteStateMachine.Exceptions, FIToolkit.Commons.FiniteStateMachine.Consts; { TFiniteStateMachine<TState, TCommand, ErrorClass>.TTransition } constructor TFiniteStateMachine<TState, TCommand, ErrorClass>.TTransition.Create(const AFromState : TState; const AOnCommand : TCommand; const StateComparer : IStateComparer; const CommandComparer : ICommandComparer); begin inherited Create; FFromState := AFromState; FOnCommand := AOnCommand; if Assigned(StateComparer) then FStateComparer := StateComparer else FStateComparer := TEqualityComparer<TState>.Default; if Assigned(CommandComparer) then FCommandComparer := CommandComparer else FCommandComparer := TEqualityComparer<TCommand>.Default; end; constructor TFiniteStateMachine<TState, TCommand, ErrorClass>.TTransition.Create(const AFromState : TState; const AOnCommand : TCommand; const StateComparer : IStateComparer; const CommandComparer : ICommandComparer; const OnEnterState : TOnEnterStateMethod; const OnExitState : TOnExitStateMethod); begin Create(AFromState, AOnCommand, StateComparer, CommandComparer); FOnEnterStateMethod := OnEnterState; FOnExitStateMethod := OnExitState; end; constructor TFiniteStateMachine<TState, TCommand, ErrorClass>.TTransition.Create(const AFromState : TState; const AOnCommand : TCommand; const StateComparer : IStateComparer; const CommandComparer : ICommandComparer; const OnEnterState : TOnEnterStateProc; const OnExitState : TOnExitStateProc); begin Create(AFromState, AOnCommand, StateComparer, CommandComparer); FOnEnterStateProc := OnEnterState; FOnExitStateProc := OnExitState; end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.TTransition.Equals(Obj : TObject) : Boolean; begin Result := False; if Obj is TTransition then Result := FStateComparer.Equals(FFromState, TTransition(Obj).FromState) and FCommandComparer.Equals(FOnCommand, TTransition(Obj).OnCommand); end; {$IFOPT Q+} {$DEFINE OVERFLOW_CHECKS_ENABLED} {$Q-} {$ENDIF} function TFiniteStateMachine<TState, TCommand, ErrorClass>.TTransition.GetCombinedHashCode( const HashCodes : array of Integer) : Integer; var HashCode : Integer; begin Result := 17; for HashCode in HashCodes do Result := Result * 37 + HashCode; end; {$IFDEF OVERFLOW_CHECKS_ENABLED} {$Q+} {$UNDEF OVERFLOW_CHECKS_ENABLED} {$ENDIF} function TFiniteStateMachine<TState, TCommand, ErrorClass>.TTransition.GetHashCode : Integer; begin Result := GetCombinedHashCode([FStateComparer.GetHashCode(FFromState), FCommandComparer.GetHashCode(FOnCommand)]); end; procedure TFiniteStateMachine<TState, TCommand, ErrorClass>.TTransition.PerformEnterStateAction( const CurrentState : TState); begin if Assigned(FOnEnterStateMethod) then FOnEnterStateMethod(FFromState, CurrentState, FOnCommand); if Assigned(FOnEnterStateProc) then FOnEnterStateProc(FFromState, CurrentState, FOnCommand); end; procedure TFiniteStateMachine<TState, TCommand, ErrorClass>.TTransition.PerformExitStateAction(const NewState : TState); begin if Assigned(FOnExitStateMethod) then FOnExitStateMethod(FFromState, NewState, FOnCommand); if Assigned(FOnExitStateProc) then FOnExitStateProc(FFromState, NewState, FOnCommand); end; { TFiniteStateMachine<TState, TCommand, ErrorClass> } function TFiniteStateMachine<TState, TCommand, ErrorClass>.AddTransition(const FromState, ToState : TState; const OnCommand : TCommand) : IFiniteStateMachine; var T : TTransition; begin T := TTransition.Create(FromState, OnCommand, FStateComparer, FCommandComparer); Result := AddTransition(T, ToState); end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.AddTransition(const FromState, ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateMethod; const OnExit : TOnExitStateMethod) : IFiniteStateMachine; var T : TTransition; begin T := TTransition.Create(FromState, OnCommand, FStateComparer, FCommandComparer, OnEnter, OnExit); Result := AddTransition(T, ToState); end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.AddTransition(const FromState, ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateProc; const OnExit : TOnExitStateProc) : IFiniteStateMachine; var T : TTransition; begin T := TTransition.Create(FromState, OnCommand, FStateComparer, FCommandComparer, OnEnter, OnExit); Result := AddTransition(T, ToState); end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand) : IFiniteStateMachine; var State : TState; begin for State in FromStates do AddTransition(State, ToState, OnCommand); Result := Self; end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateMethod; const OnExit : TOnExitStateMethod) : IFiniteStateMachine; var State : TState; begin for State in FromStates do AddTransition(State, ToState, OnCommand, OnEnter, OnExit); Result := Self; end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateProc; const OnExit : TOnExitStateProc) : IFiniteStateMachine; var State : TState; begin for State in FromStates do AddTransition(State, ToState, OnCommand, OnEnter, OnExit); Result := Self; end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.AddTransition(var Transition : TTransition; const ToState : TState) : IFiniteStateMachine; begin try FTransitionTable.Add(Transition, ToState); except FreeAndNil(Transition); RaiseOuterException(nil); end; Result := Self; end; procedure TFiniteStateMachine<TState, TCommand, ErrorClass>.AfterExecute(const Command : TCommand); begin // for descendants end; procedure TFiniteStateMachine<TState, TCommand, ErrorClass>.BeforeExecute(const Command : TCommand); begin // for descendants end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.CommandToStr(const Command : TCommand) : String; begin with TValue.From<TCommand>(Command) do if TypeInfo.Kind = tkClass then Result := AsObject.ToString else Result := ToString; end; constructor TFiniteStateMachine<TState, TCommand, ErrorClass>.Create; begin Create(GetDefaultInitialState); end; constructor TFiniteStateMachine<TState, TCommand, ErrorClass>.Create(const InitialState : TState); begin Create(InitialState, nil, nil); end; constructor TFiniteStateMachine<TState, TCommand, ErrorClass>.Create(const InitialState : TState; const StateComparer : IStateComparer; const CommandComparer : ICommandComparer); begin inherited Create; FCurrentState := InitialState; FPreviousState := InitialState; FCommandComparer := CommandComparer; FStateComparer := StateComparer; FTransitionTable := TTransitionTable.Create([doOwnsKeys]); end; destructor TFiniteStateMachine<TState, TCommand, ErrorClass>.Destroy; begin FreeAndNil(FTransitionTable); inherited Destroy; end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.Execute(const Command : TCommand) : IFiniteStateMachine; var NewState : TState; Transition : TTransition; begin if FExecuting then RaiseOuterException(EExecutionInProgress.Create(RSExecutionInProgress)); NewState := GetReachableState(FCurrentState, Command, Transition); try FExecuting := True; try BeforeExecute(Command); Transition.PerformExitStateAction(NewState); FPreviousState := FCurrentState; FCurrentState := NewState; Transition.PerformEnterStateAction(NewState); AfterExecute(Command); finally FExecuting := False; end; except RaiseOuterException(nil); end; Result := Self; end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.FindTransition(const FromState : TState; const OnCommand : TCommand) : TTransition; var SearchKey, Key : TTransition; begin Result := nil; SearchKey := TTransition.Create(FromState, OnCommand, FStateComparer, FCommandComparer); try if FTransitionTable.ContainsKey(SearchKey) then for Key in FTransitionTable.Keys do if Key.Equals(SearchKey) then begin Result := Key; Break; end; finally SearchKey.Free; end; end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.GetCurrentState : TState; begin Result := FCurrentState; end; class function TFiniteStateMachine<TState, TCommand, ErrorClass>.GetDefaultInitialState : TState; begin Result := Default(TState); end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.GetPreviousState : TState; begin Result := FPreviousState; end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.GetReachableState(const FromState : TState; const OnCommand : TCommand) : TState; var T : TTransition; begin Result := GetReachableState(FromState, OnCommand, T); end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.GetReachableState(const FromState : TState; const OnCommand : TCommand; out Transition : TTransition) : TState; begin Result := Default(TState); if HasTransition(FromState, OnCommand, Transition) then Result := FTransitionTable[Transition] else RaiseOuterException(ETransitionNotFound.CreateFmt( RSTransitionNotFound, [StateToStr(FromState), CommandToStr(OnCommand)])); end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.GetReachableState(const OnCommand : TCommand) : TState; begin Result := GetReachableState(FCurrentState, OnCommand); end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.HasTransition(const FromState : TState; const OnCommand : TCommand) : Boolean; var T : TTransition; begin Result := HasTransition(FromState, OnCommand, T); end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.HasTransition(const FromState : TState; const OnCommand : TCommand; out Transition : TTransition) : Boolean; begin Transition := FindTransition(FromState, OnCommand); Result := Assigned(Transition); end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.HasTransition(const OnCommand : TCommand) : Boolean; begin Result := HasTransition(FCurrentState, OnCommand); end; procedure TFiniteStateMachine<TState, TCommand, ErrorClass>.RaiseOuterException(E : Exception); begin if not Assigned(E) then Exception.RaiseOuterException(ErrorClass.Create) else try raise E; except RaiseOuterException(nil); end; end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.RemoveAllTransitions : IFiniteStateMachine; begin FTransitionTable.Clear; Result := Self; end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.RemoveTransition(const FromState : TState; const OnCommand : TCommand) : IFiniteStateMachine; var T : TTransition; begin if HasTransition(FromState, OnCommand, T) then FTransitionTable.Remove(T); Result := Self; end; function TFiniteStateMachine<TState, TCommand, ErrorClass>.StateToStr(const State : TState) : String; begin with TValue.From<TState>(State) do if TypeInfo.Kind = tkClass then Result := AsObject.ToString else Result := ToString; end; { TThreadFiniteStateMachine<TState, TCommand, ErrorClass> } function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.AddTransition(const FromState, ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateProc; const OnExit : TOnExitStateProc) : IFiniteStateMachine; begin InternalLock; try FFiniteStateMachine.AddTransition(FromState, ToState, OnCommand, OnEnter, OnExit); finally InternalUnlock; end; Result := Self; end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand) : IFiniteStateMachine; begin InternalLock; try FFiniteStateMachine.AddTransitions(FromStates, ToState, OnCommand); finally InternalUnlock; end; Result := Self; end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateMethod; const OnExit : TOnExitStateMethod) : IFiniteStateMachine; begin InternalLock; try FFiniteStateMachine.AddTransitions(FromStates, ToState, OnCommand, OnEnter, OnExit); finally InternalUnlock; end; Result := Self; end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.AddTransitions(const FromStates : array of TState; const ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateProc; const OnExit : TOnExitStateProc) : IFiniteStateMachine; begin InternalLock; try FFiniteStateMachine.AddTransitions(FromStates, ToState, OnCommand, OnEnter, OnExit); finally InternalUnlock; end; Result := Self; end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.AddTransition(const FromState, ToState : TState; const OnCommand : TCommand; const OnEnter : TOnEnterStateMethod; const OnExit : TOnExitStateMethod) : IFiniteStateMachine; begin InternalLock; try FFiniteStateMachine.AddTransition(FromState, ToState, OnCommand, OnEnter, OnExit); finally InternalUnlock; end; Result := Self; end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.AddTransition(const FromState, ToState : TState; const OnCommand : TCommand) : IFiniteStateMachine; begin InternalLock; try FFiniteStateMachine.AddTransition(FromState, ToState, OnCommand); finally InternalUnlock; end; Result := Self; end; constructor TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.Create; begin inherited Create; FLock := TObject.Create; FFiniteStateMachine := TFiniteStateMachine<TState, TCommand, ErrorClass>.Create; end; constructor TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.Create(const StateMachine : IFiniteStateMachine); begin inherited Create; FLock := TObject.Create; FFiniteStateMachine := StateMachine; end; destructor TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.Destroy; begin InternalLock; try FFiniteStateMachine := nil; inherited Destroy; finally InternalUnlock; FreeAndNil(FLock); end; end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.Execute(const Command : TCommand) : IFiniteStateMachine; begin InternalLock; try FFiniteStateMachine.Execute(Command); finally InternalUnlock; end; Result := Self; end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.GetCurrentState : TState; begin InternalLock; try Result := FFiniteStateMachine.CurrentState; finally InternalUnlock; end; end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.GetPreviousState : TState; begin InternalLock; try Result := FFiniteStateMachine.PreviousState; finally InternalUnlock; end; end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.GetReachableState(const FromState : TState; const OnCommand : TCommand) : TState; begin InternalLock; try Result := FFiniteStateMachine.GetReachableState(FromState, OnCommand); finally InternalUnlock; end; end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.GetReachableState(const OnCommand : TCommand) : TState; begin InternalLock; try Result := FFiniteStateMachine.GetReachableState(OnCommand); finally InternalUnlock; end; end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.HasTransition(const OnCommand : TCommand) : Boolean; begin InternalLock; try Result := FFiniteStateMachine.HasTransition(OnCommand); finally InternalUnlock; end; end; procedure TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.InternalLock; begin TMonitor.Enter(FLock); end; procedure TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.InternalUnlock; begin TMonitor.Exit(FLock); end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.Lock : IFiniteStateMachine; begin InternalLock; Result := FFiniteStateMachine; end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.HasTransition(const FromState : TState; const OnCommand : TCommand) : Boolean; begin InternalLock; try Result := FFiniteStateMachine.HasTransition(FromState, OnCommand); finally InternalUnlock; end; end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.RemoveAllTransitions : IFiniteStateMachine; begin InternalLock; try FFiniteStateMachine.RemoveAllTransitions; finally InternalUnlock; end; Result := Self; end; function TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.RemoveTransition(const FromState : TState; const OnCommand : TCommand) : IFiniteStateMachine; begin InternalLock; try FFiniteStateMachine.RemoveTransition(FromState, OnCommand); finally InternalUnlock; end; Result := Self; end; procedure TThreadFiniteStateMachine<TState, TCommand, ErrorClass>.Unlock; begin InternalUnlock; end; end.
unit SIB; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ExtCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.ToolWin, Vcl.Menus,DateUtils, Vcl.Buttons, 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, FireDAC.Comp.Client,clipbrd; type TfrmSIB = class(TForm) StatusBar1: TStatusBar; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; CategoryPanelGroup1: TCategoryPanelGroup; CategoryPanel1: TCategoryPanel; CategoryPanel2: TCategoryPanel; Image1: TImage; Splitter1: TSplitter; dp_cumpleanos: TDateTimePicker; mnu_SIB: TMainMenu; ParametrosSistema1: TMenuItem; consultas1: TMenuItem; Administracion1: TMenuItem; Polizas1: TMenuItem; Renovaciones1: TMenuItem; Endosos1: TMenuItem; Reportes1: TMenuItem; Produccion1: TMenuItem; Renovaciones2: TMenuItem; tb_SIB: TToolBar; dts_cumpleanos: TDataSource; DBGrid2: TDBGrid; ToolButton3: TToolButton; sb_Sib_Salir: TSpeedButton; sb_Sib_Poliza: TSpeedButton; Mapa1: TMenuItem; ToolButton1: TToolButton; sb_sib_Mapa: TSpeedButton; Timer1: TTimer; Pendientes: TFDQuery; dts_Pendientes: TDataSource; PendientesidGestion: TFDAutoIncField; Pendientesfecha: TSQLTimeStampField; Pendientesusuario: TStringField; Pendientesasignado: TStringField; Pendientesestado: TIntegerField; PendientesfechaInicio: TSQLTimeStampField; PendientesfechaCierre: TSQLTimeStampField; Pendientespoliza: TStringField; Pendientesramo_Subramo: TIntegerField; Pendientesvigencia: TIntegerField; Pendientesid_cia: TIntegerField; Pendientesaseguradora: TIntegerField; Pendientesasegurado: TIntegerField; Pendientesnota: TMemoField; Pendientescorreos: TStringField; Pendientesusuario_anterior: TStringField; Pendientesusuario_reasignado: TStringField; Pendientestipo_gestion: TIntegerField; Pendientesfecha_aud: TSQLTimeStampField; Pendientesusuario_aud: TStringField; PendientestiempoGestion: TSQLTimeStampField; PendientesreAsignado: TBooleanField; Pendientesguid: TStringField; Panel4: TPanel; DBGrid1: TDBGrid; sb_CargarPendientes: TSpeedButton; Archivos1: TMenuItem; MantTipoGestion1: TMenuItem; mnu_Man_Areas: TMenuItem; procedure FormShow(Sender: TObject); procedure dp_cumpleanosChange(Sender: TObject); procedure sb_Sib_SalirClick(Sender: TObject); procedure Polizas1Click(Sender: TObject); procedure Mapa1Click(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure sb_CargarPendientesClick(Sender: TObject); Procedure CargarPendientes; procedure DBGrid1DblClick(Sender: TObject); procedure MantTipoGestion1Click(Sender: TObject); procedure mnu_Man_AreasClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmSIB: TfrmSIB; implementation {$R *.dfm} uses dm, Poliza, Mant_TipoGestion, Mant_Areas; procedure TfrmSIB.CargarPendientes; begin Pendientes.Close; Pendientes.Params [0].AsString := usuario.id; Pendientes.Open() end; procedure TfrmSIB.DBGrid1DblClick(Sender: TObject); begin usuario.caso := Pendientesguid.AsString ; // ShowMessage(usuario.caso); application.CreateForm(TfrmPoliza , frmPoliza); Clipboard.AsText := usuario.caso; frmPoliza.Show; end; procedure TfrmSIB.dp_cumpleanosChange(Sender: TObject); var d,m,a : word; hh,mm,ss,zz : word; begin decodeDateTime(dp_cumpleanos.Datetime,a,m,d,hh,mm,ss,zz); dm1.cumpleanos.Close; dm1.cumpleanos.params [0].asinteger := d; dm1.cumpleanos.params [1].asinteger := m; dm1.cumpleanos.Open(); end; procedure TfrmSIB.FormShow(Sender: TObject); begin frmSIB.Caption := frmSib.Caption + ' - ' + usuario.id; dp_cumpleanos.Datetime := now; dp_cumpleanosChange(sender); Pendientes.Close; Pendientes.Params [0].AsString := usuario.id; Pendientes.Open() end; procedure TfrmSIB.MantTipoGestion1Click(Sender: TObject); begin application.CreateForm(TfrmTipoGestion , frmTipoGestion); frmTipoGestion.Show; end; procedure TfrmSIB.Mapa1Click(Sender: TObject); begin // end; procedure TfrmSIB.mnu_Man_AreasClick(Sender: TObject); begin application.CreateForm(TfrmArea , frmArea); usuario.caso := ''; frmArea.Show; end; procedure TfrmSIB.Polizas1Click(Sender: TObject); begin application.CreateForm(TfrmPoliza , frmPoliza); usuario.caso := ''; frmPoliza.Show; end; procedure TfrmSIB.sb_Sib_SalirClick(Sender: TObject); begin case MessageDlg('Esta Seguro de SALIR del Sistema...?', mtConfirmation, [mbOK, mbCancel], 0,mbCancel) of mrOk: begin dm1.RegistroLog(usuario.id,'Salida del Sistema','Salida del sistema...'); Application.Terminate; end; mrCancel: exit; end; end; procedure TfrmSIB.sb_CargarPendientesClick(Sender: TObject); begin CargarPendientes; end; procedure TfrmSIB.Timer1Timer(Sender: TObject); begin CargarPendientes; end; end.
{------------------------------------------------------------------------------- ---------------------------------- ALPHA UTILS --------------------------------- -------------------------------------------------------------------------------} { AlphaUtils : Unité de gestion de la transparence des fenêtres (AlphaBlending) Auteur : Bacterius Utilisé dans l'exemple ci-joint pour la barre des tâches et pour la fiche principale Adaptable pour tout type de fenêtre possèdant un descripteur de fenêtre (HWND) ... ... si elle prend en charge la transparence, bien sûr :] (vous pouvez forcer la transparence mais ça ne marchera pas à tous les coups !) ==> www.delphifr.com Vous devrez, comme dans l'exemple, trouver un moyen de mémoriser l'ancien style de la fenêtre (renvoyé par PrepareLayering), pour pouvoir le passer en paramètre dans ReleaseLayering. Ceci est particulièrement utile pour certaines fenêtres (par exemple, la barre des tâches disparaît à l'affichage de la boîte de dialogue "Arrêter l'ordinateur" si l'on ne remet pas son style par défaut (sans WS_EX_LAYERED)). ATTENTION : ne pas passer une valeur nulle dans ReleaseLayering, vous pourriez le regretter. Si vous n'avez pas mémorisé l'ancien style, n'appellez tout simplement pas la fonction (et pensez à mémoriser la prochaine fois !). En général, il n'y aura pas besoin de mémoriser le style de sa propre fiche (sauf indications contraires non liées à cette unité). } {------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------} unit AlphaUtils; interface uses Windows; // Uniquement besoin de l'unité Windows:] {------------------------------------------------------------------------------- ----------------------------- CONSTANTES DIVERSES ------------------------------ -------------------------------------------------------------------------------} const // Quelques constantes ... WS_EX_LAYERED = $00080000; // Flag pour le style de transparence LWA_ALPHA = $00000002; // Flag pour définir la transparence Alpha TrayClassName='Shell_TrayWnd'; // Nom de classe de la fenêtre de la barre des tâches {------------------------------------------------------------------------------- --------------------------------- TYPES DIVERS --------------------------------- -------------------------------------------------------------------------------} {------------------------------------------------------------------------------- ------------------------------ ROUTINES DIVERSES ------------------------------- -------------------------------------------------------------------------------} function GetTrayHWnd: HWND; // Récupère le HWND (descripteur de fenêtre) de la barre des tâches (une fonction rien que pour elle !) pour l'utiliser dans les API function GetDesktopHWnd: HWND; // Récupère le HWND (descripteur de fenêtre) du bureau function GetHWndByWindowName(WindowName: String): HWND; // Récupère le HWND (descripteur de fenêtre) d'une fenêtre si on connaît son nom function GetHWndByWindowClassName(WindowClassName: String): HWND; // Récupère le HWND (descripteur de fenêtre) d'une fenêtre si on connaît son nom de classe {------------------------------------------------------------------------------- ------------------------- GESTION DE LA TRANSPARENCE --------------------------- -------------------------------------------------------------------------------} {----- FONCTIONS ALPHA UTILS -----} function PrepareLayering(Wnd: HWND; var Style: Integer; ForceLayering: Boolean=True): Boolean; // Prépare la fenêtre à devenir transparente function ReleaseLayering(Wnd: HWND; Style: Integer): Boolean; // Remet la fenêtre sans style de transparence function SupportsLayering(Wnd: HWND): Boolean; // Vérifie si la fenêtre supporte le layering function GetWindowAlpha(Wnd: HWND; var Value: Byte): Boolean; // Récupère la valeur alpha de la fenêtre function SetWindowAlpha(Wnd: HWND; var Value: Byte): Boolean; // Définit la valeur alpha de la fenêtre {----- API (ADVANCED PROGRAMMING INTERFACE) -----} function GetLayeredWindowAttributes(hWnd: HWND; var crKey: COLORREF; var bAlpha: BYTE; var dwFlags: DWORD): BOOL; stdcall; external 'user32.dll'; function SetLayeredWindowAttributes(hWnd: HWND; crKey: COLORREF; bAlpha: BYTE; dwFlags: DWORD): BOOL; stdcall; external 'user32.dll'; // Deux fonctions API externes, pour définir les "layered attributes", c'est-à-dire comment une fenêtre doit réagir avec une fenêtre située "derrière" elle {------------------------------------------------------------------------------- --------------------------------- IMPLEMENTATION ------------------------------- -------------------------------------------------------------------------------} implementation {------------------------------------------------------------------------------- ------------------------------ ROUTINES DIVERSES ------------------------------- -------------------------------------------------------------------------------} function GetTrayHWnd: HWND; // Récupère le descripteur de la fenêtre begin Result := FindWindow(TrayClassName, ''); // Récupère la fenêtre de la barre des tâches ... // ... à partir du nom de classe de la fenêtre de la barre des tâches ("Shell_TrayWnd") ... // ... déclarée comme constante plus haut dans l'unité. end; function GetDesktopHWnd: HWND; // Récupère le HWND (descripteur de fenêtre) du bureau begin Result := GetDesktopWindow; // On appelle GetDesktopWindow ! end; function GetHWndByWindowName(WindowName: String): HWND; // Récupère le HWND (descripteur de fenêtre) d'une fenêtre si on connaît son nom begin Result := FindWindow(nil, PChar(WindowName)); // Récupère selon le nom de la fenêtre // Quelques exemples : "Inspecteur d'objets", "Main.pas", "Gestionnaire des tâches de Windows" ^^ end; function GetHWndByWindowClassName(WindowClassName: String): HWND; // Récupère le HWND (descripteur de fenêtre) d'une fenêtre si on connaît son nom de classe begin Result := FindWindow(PChar(WindowClassName), nil); // Récupère selon le nom de classe de la fenêtre // Revient au même que GetTrayWnd si WindowClassName = TrayClassName (ou "Shell_TrayWnd") end; {------------------------------------------------------------------------------- ------------------------- GESTION DE LA TRANSPARENCE --------------------------- -------------------------------------------------------------------------------} function PrepareLayering(Wnd: HWND; var Style: Integer; ForceLayering: Boolean=True): Boolean; // Prépare la fenêtre à devenir transparente Var // Renvoie False si la préparation a échoué (inutile alors d'appeller SetTrayAlpha ou GetTrayAlpha) WindowStyle: Integer; // Variable qui contient le style de la fenêtre begin Result := False; // Par défaut, résultat négatif WindowStyle := GetWindowLong(Wnd, GWL_EXSTYLE); // On récupère le style de la fenêtre Style := WindowStyle; // On repasse en paramètre le style de la fenêtre, brut ! if (WindowStyle = 0) then Exit; // Si le style est nul, pfuit ! if (not ForceLayering) and (WindowStyle and WS_EX_LAYERED = 0) then Exit; // Si la fenêtre ne prend pas en charge la transparence (et si on ne force pas la transparence) if SetWindowLong(Wnd, GWL_EXSTYLE, WindowStyle or WS_EX_LAYERED) = 0 then Exit; // On essaye d'ajouter l'option "transparence" dans le style de la fenêtre Result := True; // Si aucune erreur, résultat positif ! end; function ReleaseLayering(Wnd: HWND; Style: Integer): Boolean; // Remet la fenêtre sans style de transparence Var WindowStyle: Integer; // Variable qui contient le style de la fenêtre begin Result := False; // Par défaut, résultat négatif WindowStyle := Style; // On donne à WindowStyle la valeur de Style if (WindowStyle = 0) then Exit; // Si le style est nul, on part. if SetWindowLong(Wnd, GWL_EXSTYLE, WindowStyle) = 0 then Exit; // On essaye d'ajouter l'option "transparence" dans le style de la fenêtre Result := True; // Si aucune erreur, résultat positif ! end; function SupportsLayering(Wnd: HWND): Boolean; // Vérifie si la fenêtre supporte le layering Var WindowStyle: Integer; // Style de la fenêtre définie par Wnd begin WindowStyle := GetWindowLong(Wnd, GWL_EXSTYLE); // On récupère le style de la fenêtre Result := (WindowStyle and WS_EX_LAYERED <> 0); // On vérifie si WS_EX_LAYERED est dedans end; function GetWindowAlpha(Wnd: HWND; var Value: Byte): Boolean; // Récupération de la transparence de la fenêtre (Result renvoie la réussite de la fonction) Var clrref: COLORREF; // Variable qui sert uniquement pour l'appel à l'API Alpha: Byte; // Valeur alpha (on n'utilise pas le paramètre de la fonction directement) Flags: DWord; // Variable qui sert uniquement pour l'appel à l'API begin Result := False; // Résultat négatif par défaut if not GetLayeredWindowAttributes(Wnd, clrref, Alpha, Flags) then Exit; // Si on n'arrive pas à récupérer la transparence, on s'en va Value := Alpha; // On donne à Value la valeur de Alpha (qui contient la transparence de la fenêtre) Result := True; // Résultat positif si aucune erreur ! end; function SetWindowAlpha(Wnd: HWND; var Value: Byte): Boolean; // Définition de la transparence de la fenêtre (Result renvoie la réussite de la fonction) Var Alpha: Byte; // Valeur alpha (on n'utilise pas le paramètre de la fonction directement) begin Result := False; // Résultat négatif par défaut Alpha := Value; // On donne à Alpha la valeur de Value (pour l'utiliser dans l'API) if not SetLayeredWindowAttributes(Wnd, rgb(0, 0, 0), Alpha, LWA_ALPHA) then Exit; // On appelle l'API pour définir la transparence - si erreur, on s'en va ! Result := True; // Résultat positif si aucune erreur ! end; end.
unit uFIBEditorForm; interface {$i ..\FIBPlus.inc} uses Classes,{$IFDEF D6+}Variants, {$ENDIF}{$IFDEF D_XE2}Vcl.Forms{$ELSE}Forms{$ENDIF}; type TFIBEditorCustomForm= class(TForm) protected procedure ReadState(Reader: TReader); override; procedure OnReadError(Reader: TReader; const Message: string; var Handled: Boolean); protected LastTop, LastLeft, LastWidth,LastHeight:integer; procedure ReadPositions; procedure SavePositions; public constructor Create(AOwner:TComponent);override; destructor Destroy; override; end; TFIBEditorCustomFrame= class(TFrame) protected procedure ReadState(Reader: TReader); override; procedure OnReadError(Reader: TReader; const Message: string; var Handled: Boolean); end; implementation uses RegistryUtils; { TFIBEditorCustomForm } constructor TFIBEditorCustomForm.Create(AOwner: TComponent); begin inherited; LastTop:=-1; ReadPositions; if LastTop<>-1 then begin Position:=poDesigned; Top :=LastTop; Left :=LastLeft; Width :=LastWidth; Height:=LastHeight; end; end; destructor TFIBEditorCustomForm.Destroy; begin LastTop :=Top; LastLeft :=Left; LastWidth :=Width; LastHeight:=Height; SavePositions; inherited; end; procedure TFIBEditorCustomForm.OnReadError(Reader: TReader; const Message: string; var Handled: Boolean); begin Handled:=True end; procedure TFIBEditorCustomForm.ReadPositions; {$IFNDEF NO_REGISTRY} var v:Variant; i:integer; {$ENDIF} begin {$IFNDEF NO_REGISTRY} v:= DefReadFromRegistry(['Software',RegFIBRoot,ClassName], ['Top', 'Left', 'Height', 'Width' ] ); if (VarType(v)<>varBoolean) then for i:=0 to 3 do if V[1,i] then case i of 0: LastTop :=V[0,i]; 1: LastLeft :=V[0,i]; 2: LastHeight:=V[0,i]; 3: LastWidth :=V[0,i] end; {$ENDIF} end; procedure TFIBEditorCustomForm.ReadState(Reader: TReader); begin Reader.OnError:=OnReadError; inherited ReadState(Reader) end; procedure TFIBEditorCustomForm.SavePositions; begin {$IFNDEF NO_REGISTRY} DefWriteToRegistry(['Software',RegFIBRoot,ClassName], ['Top', 'Left', 'Height', 'Width' ], [ LastTop, LastLeft, LastHeight, LastWidth ] ); {$ENDIF} end; { TFIBEditorCustomFrame } procedure TFIBEditorCustomFrame.OnReadError(Reader: TReader; const Message: string; var Handled: Boolean); begin Handled:=True end; procedure TFIBEditorCustomFrame.ReadState(Reader: TReader); begin Reader.OnError:=OnReadError; inherited ReadState(Reader) end; end.
unit Test.Devices.ADCPChannelMaster; interface uses Windows, TestFrameWork, GMGlobals, Test.Devices.Base.ReqCreator, GMConst, Test.Devices.Base.ReqParser; type TADCPChannelMasterReqCreatorTest = class(TDeviceReqCreatorTestBase) protected function GetDevType(): int; override; procedure DoCheckRequests(); override; end; TADCPChannelMasterParserTest = class(TDeviceReqParserTestBase) private protected function GetDevType(): int; override; function GetThreadClass(): TSQLWriteThreadForTestClass; override; published procedure String1; procedure StringWithEmpties; procedure RealData; end; implementation uses Threads.ResponceParser, Devices.ModbusBase, SysUtils; { TADCPChannelMasterReqCreatorTest } procedure TADCPChannelMasterReqCreatorTest.DoCheckRequests; begin CheckReqHexString(0, ''); end; function TADCPChannelMasterReqCreatorTest.GetDevType: int; begin Result := DEVTYPE_ADCP_CHANNEL_MASTER; end; { TADCPChannelMasterParserTest } function TADCPChannelMasterParserTest.GetDevType: int; begin Result := DEVTYPE_ADCP_CHANNEL_MASTER; end; type TLocalSQLWriteThreadForTest = class(TResponceParserThreadForTest); function TADCPChannelMasterParserTest.GetThreadClass: TSQLWriteThreadForTestClass; begin Result := TLocalSQLWriteThreadForTest; end; procedure TADCPChannelMasterParserTest.RealData; const ai_vals: array [1..4] of double = (31.55, 0.34, 3.13, 21); var i: int; begin gbv.ReqDetails.rqtp := rqtADCP_Channel_Master; gbv.gmTime := NowGM(); gbv.SetBufRec('PRDIQ,+196,+743201.31,+3.13,+31.55,+0.34,+91.87,+21.00,+0.00,+0.00,0'#13#10); TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_DevType := DEVTYPE_ADCP_CHANNEL_MASTER; TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_AI; for i := 1 to 4 do begin TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := i; Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, 'AI' + IntToStr(i)); Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, 'AI' + IntToStr(i)); Check(TLocalSQLWriteThreadForTest(thread).Values[0].Val = ai_vals[i], 'AI' + IntToStr(i)); Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, 'AI' + IntToStr(i)); end; i := 1; TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_CNT_MTR; TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := i; Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, 'MTR' + IntToStr(i)); Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, 'MTR' + IntToStr(i)); Check(CompareFloatRelative(TLocalSQLWriteThreadForTest(thread).Values[0].Val, 196743201.31), 'MTR' + IntToStr(i)); Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, 'MTR' + IntToStr(i)); end; procedure TADCPChannelMasterParserTest.String1; const ai_vals: array [1..4] of double = (234.45, 0.65, 2.45, 15.12); var i: int; begin gbv.ReqDetails.rqtp := rqtADCP_Channel_Master; gbv.gmTime := NowGM(); gbv.SetBufRec('PRDIQ, 12, 432456.123, 2.45, 234.45, 0.65, 345.33, 15.12, 2.56, -0.32, 0'#13#10); TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_DevType := DEVTYPE_ADCP_CHANNEL_MASTER; TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_AI; for i := 1 to 4 do begin TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := i; Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, 'AI' + IntToStr(i)); Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, 'AI' + IntToStr(i)); Check(TLocalSQLWriteThreadForTest(thread).Values[0].Val = ai_vals[i], 'AI' + IntToStr(i)); Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, 'AI' + IntToStr(i)); end; i := 1; TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_CNT_MTR; TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := i; Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, 'MTR' + IntToStr(i)); Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, 'MTR' + IntToStr(i)); Check(CompareFloatRelative(TLocalSQLWriteThreadForTest(thread).Values[0].Val, 12432456.123), 'MTR' + IntToStr(i)); Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, 'MTR' + IntToStr(i)); end; procedure TADCPChannelMasterParserTest.StringWithEmpties; var i: int; begin gbv.ReqDetails.rqtp := rqtADCP_Channel_Master; gbv.gmTime := NowGM(); gbv.SetBufRec('PRDIQ,-140674992,-0.000000001,,,,,+21.00,+0.00,+0.00,10'#13#10); TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_DevType := DEVTYPE_ADCP_CHANNEL_MASTER; TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_AI; for i := 1 to 3 do begin TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := i; Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresEmpty, 'AI' + IntToStr(i)); end; i := 4; TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := i; Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, 'AI' + IntToStr(i)); Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, 'AI' + IntToStr(i)); Check(CompareFloatRelative(TLocalSQLWriteThreadForTest(thread).Values[0].Val, 21), 'AI' + IntToStr(i)); Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, 'AI' + IntToStr(i)); i := 1; TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_CNT_MTR; TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := i; Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, 'MTR' + IntToStr(i)); Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, 'MTR' + IntToStr(i)); Check(CompareFloatRelative(TLocalSQLWriteThreadForTest(thread).Values[0].Val, -140674992e6 - 0.000000001), 'MTR' + IntToStr(i)); Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, 'MTR' + IntToStr(i)); end; initialization RegisterTest('GMIOPSrv/Devices/ADCP ChannelMaster', TADCPChannelMasterReqCreatorTest.Suite); RegisterTest('GMIOPSrv/Devices/ADCP ChannelMaster', TADCPChannelMasterParserTest.Suite); end.
{ Hello world } program Test1; begin writeln('Hello, world!'); end.
unit IdMessageCoder; interface uses Classes, IdComponent, IdGlobal, IdMessage; type TIdMessageCoderPartType = (mcptUnknown, mcptText, mcptAttachment); TIdMessageDecoder = class(TIdComponent) protected FFilename: string; // Dont use TIdHeaderList for FHeaders - we dont know that they will all be like MIME. FHeaders: TStrings; FPartType: TIdMessageCoderPartType; FSourceStream: TStream; public function ReadBody(ADestStream: TStream; var AMsgEnd: Boolean): TIdMessageDecoder; virtual; abstract; procedure ReadHeader; virtual; function ReadLn: string; constructor Create(AOwner: TComponent); override; destructor Destroy; override; // property Filename: string read FFilename; property SourceStream: TStream read FSourceStream write FSourceStream; property Headers: TStrings read FHeaders; property PartType: TIdMessageCoderPartType read FPartType; end; TIdMessageDecoderInfo = class(TObject) public function CheckForStart(ASender: TIdMessage; ALine: string): TIdMessageDecoder; virtual; abstract; constructor Create; virtual; end; TIdMessageDecoderList = class(TObject) protected FMessageCoders: TStringList; public class function ByName(const AName: string): TIdMessageDecoderInfo; class function CheckForStart(ASender: TIdMessage; const ALine: string): TIdMessageDecoder; constructor Create; destructor Destroy; override; class procedure RegisterDecoder(const AMessageCoderName: string; AMessageCoderInfo: TIdMessageDecoderInfo); end; TIdMessageEncoder = class(TIdComponent) protected FFilename: string; FPermissionCode: integer; public constructor Create(AOwner: TComponent); override; procedure Encode(const AFilename: string; ADest: TStream); overload; procedure Encode(ASrc: TStream; ADest: TStream); overload; virtual; abstract; published property Filename: string read FFilename write FFilename; property PermissionCode: integer read FPermissionCode write FPermissionCode; end; TIdMessageEncoderClass = class of TIdMessageEncoder; TIdMessageEncoderInfo = class(TObject) protected FMessageEncoderClass: TIdMessageEncoderClass; public constructor Create; virtual; procedure InitializeHeaders(AMsg: TIdMessage); virtual; // property MessageEncoderClass: TIdMessageEncoderClass read FMessageEncoderClass; end; TIdMessageEncoderList = class(TObject) protected FMessageCoders: TStringList; public class function ByName(const AName: string): TIdMessageEncoderInfo; constructor Create; destructor Destroy; override; class procedure RegisterEncoder(const AMessageEncoderName: string; AMessageEncoderInfo: TIdMessageEncoderInfo); end; implementation uses IdException, IdResourceStrings, IdStream, SysUtils; var GMessageDecoderList: TIdMessageDecoderList = nil; GMessageEncoderList: TIdMessageEncoderList = nil; { TIdMessageDecoderList } class function TIdMessageDecoderList.ByName(const AName: string): TIdMessageDecoderInfo; begin with GMessageDecoderList.FMessageCoders do begin Result := TIdMessageDecoderInfo(Objects[IndexOf(AName)]); end; if Result = nil then begin raise EIdException.Create(RSMessageDecoderNotFound + ': ' + AName); {Do not Localize} end; end; class function TIdMessageDecoderList.CheckForStart(ASender: TIdMessage; const ALine: string): TIdMessageDecoder; var i: integer; begin Result := nil; for i := 0 to GMessageDecoderList.FMessageCoders.Count - 1 do begin Result := TIdMessageDecoderInfo(GMessageDecoderList.FMessageCoders.Objects[i]).CheckForStart(ASender , ALine); if Result <> nil then begin Break; end; end; end; constructor TIdMessageDecoderList.Create; begin inherited; FMessageCoders := TStringList.Create; end; destructor TIdMessageDecoderList.Destroy; var i: integer; begin for i := 0 to FMessageCoders.Count - 1 do begin TIdMessageDecoderInfo(FMessageCoders.Objects[i]).Free; end; FreeAndNil(FMessageCoders); inherited; end; class procedure TIdMessageDecoderList.RegisterDecoder(const AMessageCoderName: string; AMessageCoderInfo: TIdMessageDecoderInfo); begin if GMessageDecoderList = nil then begin GMessageDecoderList := TIdMessageDecoderList.Create; end; GMessageDecoderList.FMessageCoders.AddObject(AMessageCoderName, AMessageCoderInfo); end; { TIdMessageDecoderInfo } constructor TIdMessageDecoderInfo.Create; begin // end; { TIdMessageDecoder } constructor TIdMessageDecoder.Create(AOwner: TComponent); begin inherited; FHeaders := TStringList.Create; end; destructor TIdMessageDecoder.Destroy; begin FreeAndNil(FHeaders); FreeAndNil(FSourceStream); inherited; end; procedure TIdMessageDecoder.ReadHeader; begin end; function TIdMessageDecoder.ReadLn: string; begin Result := TIdStream(SourceStream).ReadLn; end; { TIdMessageEncoderInfo } constructor TIdMessageEncoderInfo.Create; begin // end; procedure TIdMessageEncoderInfo.InitializeHeaders(AMsg: TIdMessage); begin // end; { TIdMessageEncoderList } class function TIdMessageEncoderList.ByName(const AName: string): TIdMessageEncoderInfo; begin with GMessageEncoderList.FMessageCoders do begin Result := TIdMessageEncoderInfo(Objects[IndexOf(AName)]); end; if Result = nil then begin raise EIdException.Create(RSMessageEncoderNotFound + ': ' + AName); {Do not Localize} end; end; constructor TIdMessageEncoderList.Create; begin inherited; FMessageCoders := TStringList.Create; end; destructor TIdMessageEncoderList.Destroy; var i: integer; begin for i := 0 to FMessageCoders.Count - 1 do begin TIdMessageEncoderInfo(FMessageCoders.Objects[i]).Free; end; FreeAndNil(FMessageCoders); inherited; end; class procedure TIdMessageEncoderList.RegisterEncoder(const AMessageEncoderName: string; AMessageEncoderInfo: TIdMessageEncoderInfo); begin if GMessageEncoderList = nil then begin GMessageEncoderList := TIdMessageEncoderList.Create; end; GMessageEncoderList.FMessageCoders.AddObject(AMessageEncoderName, AMessageEncoderInfo); end; { TIdMessageEncoder } procedure TIdMessageEncoder.Encode(const AFilename: string; ADest: TStream); var LSrcStream: TFileStream; begin LSrcStream := TFileStream.Create(AFileName, fmShareDenyNone); try Encode(LSrcStream, ADest); finally FreeAndNil(LSrcStream); end; end; constructor TIdMessageEncoder.Create(AOwner: TComponent); begin inherited; FPermissionCode := 660; end; initialization finalization FreeAndNil(GMessageDecoderList); FreeAndNil(GMessageEncoderList); end.
PROGRAM marks; VAR grade: REAL; BEGIN WRITE ('Input your grade : '); READ (grade); IF grade>=70 THEN WRITE ('EXCELLENT') ELSE IF grade>=60 THEN WRITE ('VERY GOOD') ELSE IF grade>=50 THEN WRITE ('GOOD') ELSE IF grade>=40 THEN WRITE ('PASS') ELSE WRITE ('FAIL') END.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Menus, Vcl.Samples.Spin, Vcl.ComCtrls, sfLog, org.utilities, org.algorithms.time, org.tcpip.tcp, org.tcpip.tcp.server, dm.tcpip.tcp.server; type TForm1 = class(TForm) Panel1: TPanel; Panel2: TPanel; Splitter1: TSplitter; Memo1: TMemo; btnStart: TButton; MainMenu1: TMainMenu; N1: TMenuItem; llFatal1: TMenuItem; llError1: TMenuItem; llWarnning1: TMenuItem; llNormal1: TMenuItem; llDebug1: TMenuItem; GroupBox1: TGroupBox; Label1: TLabel; SpinEdit1: TSpinEdit; Label2: TLabel; SpinEdit2: TSpinEdit; Label3: TLabel; SpinEdit3: TSpinEdit; StatusBar1: TStatusBar; N2: TMenuItem; Button1: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure llNormal1Click(Sender: TObject); procedure llDebug1Click(Sender: TObject); procedure SpinEdit1Change(Sender: TObject); procedure SpinEdit2Change(Sender: TObject); procedure llError1Click(Sender: TObject); procedure llFatal1Click(Sender: TObject); procedure llWarnning1Click(Sender: TObject); procedure N2Click(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } //TLogNotify = procedure (Sender: TObject; LogLevel: TLogLevel; LogContent: string) of object; //TTCPConnectedNotify = procedure (Sender: TObject; Context: TTCPIOContext) of object; //TTCPRecvedNotify = procedure (Sender: TObject; Context: TTCPIOContext) of object; //TTCPSentNotify = procedure (Sender: TObject; Context: TTCPIOContext) of object; //TTCPDisConnectingNotify = procedure (Sender: TObject; Context: TTCPIOContext) of object; FLog: TsfLog; FLogLevel: TLogLevel; FMaxPreAcceptCount: Integer; FMultiIOBufferCount: Integer; FTCPServer: TDMTCPServer; // 用于更新OnlineCount FTimeWheel: TTimeWheel<TForm1>; procedure OnLog(Sender: TObject; LogLevel: TLogLevel; LogContent: string); procedure OnConnected(Sender: TObject; Context: TTCPIOContext); procedure WriteToScreen(const Value: string); procedure RefreshOnlineCount(AForm: TForm1); protected procedure WndProc(var MsgRec: TMessage); override; public { Public declarations } procedure StartService; procedure StopService; end; var Form1: TForm1; const WM_WRITE_LOG_TO_SCREEN = WM_USER + 1; WM_REFRESH_ONLINE_COUNT = WM_USER + 2; WM_REFRESH_BUFFERS_IN_USED = WM_USER + 3; implementation {$R *.dfm} { TForm1 } procedure TForm1.btnStartClick(Sender: TObject); begin StartService(); end; procedure TForm1.Button1Click(Sender: TObject); //var // IOContext: TTCPIOContext; // Msg: string; begin // FTCPServer.OnlineIOContexts.GetValue() // for IOContext in FTCPServer.OnlineIOContexts.Values do begin // Msg := Format('[%d] Status=%s, IOStatus=%x', // [ IOContext.Socket, // IOContext.StatusString(), // IOContext.IOStatus]); // Memo1.Lines.Add(Msg); // end; end; procedure TForm1.FormCreate(Sender: TObject); var CurDir: string; LogFile: string; begin CurDir := ExtractFilePath(ParamStr(0)); ForceDirectories(CurDir + 'Log\'); LogFile := CurDir + 'Log\Log_' + FormatDateTime('YYYYMMDD', Now()) + '.txt'; FLog := TsfLog.Create(LogFile); FLog.AutoLogFileName := True; FLog.LogFilePrefix := 'Log_'; FLogLevel := llNormal; FTCPServer := TDMTCPServer.Create(); FTCPServer.HeadSize := Sizeof(TTCPSocketProtocolHead); FTimeWheel := TTimeWheel<TForm1>.Create(); end; procedure TForm1.FormDestroy(Sender: TObject); begin FTCPServer.Free(); end; procedure TForm1.llDebug1Click(Sender: TObject); begin FLogLevel := llDebug; FTCPServer.LogLevel := llDebug; end; procedure TForm1.llError1Click(Sender: TObject); begin FLogLevel := llError; FTCPServer.LogLevel := llError; end; procedure TForm1.llFatal1Click(Sender: TObject); begin FLogLevel := llFatal; FTCPServer.LogLevel := llFatal; end; procedure TForm1.llNormal1Click(Sender: TObject); begin FLogLevel := llNormal; FTCPServer.LogLevel := llNormal; end; procedure TForm1.llWarnning1Click(Sender: TObject); begin FLogLevel := llWarning; FTCPServer.LogLevel := llWarning; end; procedure TForm1.N2Click(Sender: TObject); begin // StatusBar1.Panels[1].Text := IntToStr(FTCPServer.OnlineIOContexts.Count); end; procedure TForm1.SpinEdit1Change(Sender: TObject); begin FMaxPreAcceptCount := SpinEdit1.Value; end; procedure TForm1.SpinEdit2Change(Sender: TObject); begin FMultiIOBufferCount := SpinEdit2.Value; end; procedure TForm1.StartService; var Msg: string; CurDir: string; begin //\\ 初始化 CurDir := ExtractFilePath(ParamStr(0)); FMaxPreAcceptCount := SpinEdit1.Value; FMultiIOBufferCount := SpinEdit2.Value; // FTCPServer.LocalIP := '127.0.0.1'; FTCPServer.LocalPort := SpinEdit3.Value; FTCPServer.LogLevel := FLogLevel; FTCPServer.MaxPreAcceptCount := FMaxPreAcceptCount; FTCPServer.MultiIOBufferCount := FMultiIOBufferCount; FTCPServer.TempDirectory := CurDir + 'Temp\'; ForceDirectories(FTCPServer.TempDirectory); FTCPServer.OnLog := OnLog; FTCPServer.OnConnected := OnConnected; FTCPServer.RegisterIOContextClass($00000000, TDMTCPServerClientSocket); //\\ 启动服务端 FTCPServer.Start(); FTimeWheel.Start(); SpinEdit1.Enabled := False; SpinEdit2.Enabled := False; SpinEdit3.Enabled := False; Msg := Format('基本配置:'#13#10'MaxPreAcceptCount: %d'#13#10'MultiIOBufferCount: %d'#13#10'BufferSize: %d', [ FMaxPreAcceptCount, FMultiIOBufferCount, FTCPServer.BufferSize]); Memo1.Lines.Add(Msg); FTimeWheel.StartTimer(Form1, 1 * 1000, RefreshOnlineCount); end; procedure TForm1.StopService; begin FTCPServer.Stop(); end; procedure TForm1.WndProc(var MsgRec: TMessage); var Msg: string; begin if MsgRec.Msg = WM_WRITE_LOG_TO_SCREEN then begin Msg := FormatDateTime('YYYY-MM-DD hh:mm:ss.zzz',Now) + ':' + string(MsgRec.WParam); Memo1.Lines.Add(Msg); end else if MsgRec.Msg = WM_REFRESH_ONLINE_COUNT then begin StatusBar1.Panels[1].Text := IntToStr(FTCPServer.OnlineCount); StatusBar1.Panels[3].Text := IntToStr(FTCPServer.BuffersInUsed); end else inherited; end; procedure TForm1.WriteToScreen(const Value: string); begin SendMessage(Application.MainForm.Handle, WM_WRITE_LOG_TO_SCREEN, WPARAM(Value), 0); end; procedure TForm1.OnConnected(Sender: TObject; Context: TTCPIOContext); var Msg: string; begin {$IfDef DEBUG} Msg := Format('[调试][%d][%d]<OnConnected> [%s:%d]', [ Context.Socket, GetCurrentThreadId(), Context.RemoteIP, Context.RemotePort]); OnLog(nil, llDebug, Msg); {$Endif} end; procedure TForm1.OnLog(Sender: TObject; LogLevel: TLogLevel; LogContent: string); begin if LogLevel <= FLogLevel then WriteToScreen(LogContent); FLog.WriteLog(LogContent); end; procedure TForm1.RefreshOnlineCount(AForm: TForm1); begin SendMessage(Application.MainForm.Handle, WM_REFRESH_ONLINE_COUNT, 0, 0); FTimeWheel.StartTimer(AForm, 1 * 1000, RefreshOnlineCount); end; end.
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit REST.Backend.MetaTypes; interface uses System.Generics.Collections, System.Classes, System.JSON; type IBackendMetaFactory = interface; IBackendMetaObject = interface; IBackendMetaClass = interface; TBackendEntityValue = record class var FEmpty: TBackendEntityValue; private FData: IBackendMetaObject; FFiller: Integer; function GetBackendClassName: string; function GetCreatedAt: TDateTime; function GetObjectID: string; function GetUpdatedAt: TDateTime; function GetAuthToken: string; function GetUserName: string; function GetGroupName: string; function GetDownloadURL: string; function GetExpiresAt: TDateTime; function GetFileName: string; function GetFileID: string; function GetIsEmpty: Boolean; public constructor Create(const Intf: IBackendMetaObject); function TryGetBackendClassName(out AValue: string): Boolean; function TryGetObjectID(out AValue: string): Boolean; function TryGetUpdatedAt(out AValue: TDateTime): Boolean; function TryGetCreatedAt(out AValue: TDateTime): Boolean; function TryGetExpiresAt(out AValue: TDateTime): Boolean; function TryGetUserName(out AValue: string): Boolean; function TryGetGroupName(out AValue: string): Boolean; function TryGetFileName(out AValue: string): Boolean; function TryGetDownloadURL(out AValue: string): Boolean; function TryGetAuthToken(out AValue: string): Boolean; function TryGetFileID(out AValue: string): Boolean; property BackendClassName: string read GetBackendClassName; property ObjectID: string read GetObjectID; property UpdatedAt: TDateTime read GetUpdatedAt; property CreatedAt: TDateTime read GetCreatedAt; property UserName: string read GetUserName; property GroupName: string read GetGroupName; property AuthToken: string read GetAuthToken; property DownloadURL: string read GetDownloadURL; property ExpiresAt: TDateTime read GetExpiresAt; property FileName: string read GetFileName; property FileID: string read GetFileID; property Data: IBackendMetaObject read FData; property IsEmpty: Boolean read GetIsEmpty; class property Empty: TBackendEntityValue read FEmpty; end; TBackendMetaObject = TBackendEntityValue; // Temporary TBackendClassValue = record private FData: IBackendMetaClass; function GetBackendClassName: string; function GetDataType: string; public constructor Create(const Intf: IBackendMetaClass); function TryGetBackendClassName(out AValue: string): Boolean; function TryGetDataType(out AValue: string): Boolean; property BackendClassName: string read GetBackendClassName; property BackendDataType: string read GetDataType; end; TBackendMetaClass = TBackendClassValue; // Temporary IBackendMetaObject = interface ['{95F29709-C995-4E69-A16E-3E9FA6D81ED6}'] end; IBackendClassName = interface(IBackendMetaObject) ['{A73AB14F-12C8-4121-AFB1-2E0C55F37BB6}'] function GetClassName: string; end; IBackendDataType = interface(IBackendMetaObject) ['{8E75565A-3A1B-44E0-B150-B74927F50F97}'] function GetDataType: string; end; IBackendObjectID = interface(IBackendMetaObject) ['{CD893599-279D-4000-B7E2-F94B944D6C63}'] function GetObjectID: string; end; IBackendUpdatedAt = interface(IBackendMetaObject) ['{16630E95-EE80-4328-8323-6F7FF67C0141}'] function GetUpdatedAt: TDateTime; end; IBackendCreatedAt = interface(IBackendMetaObject) ['{C3204A92-434F-4008-B356-E41896BC22CA}'] function GetCreatedAt: TDateTime; end; IBackendAuthToken = interface(IBackendMetaObject) ['{3C4FF6D8-11CA-48D8-8967-B3F1FC06C3EA}'] function GetAuthToken: string; end; IBackendUserName = interface(IBackendMetaObject) ['{B7022538-2C7D-4F93-A1C8-A7A96545E4BF}'] function GetUserName: string; end; IBackendGroupName = interface(IBackendMetaObject) ['{BEA0754A-0D59-4D62-96A4-3175A3E8E1EB}'] function GetGroupName: string; end; ///<summary> MetaObject Interface. Use this type to read the property Module Name.</summary> IBackendModuleName = interface(IBackendMetaObject) ['{BEA0754A-0D59-4D62-96A4-3175A3E8E1EB}'] ///<summary> Gets module name property.</summary> function GetModuleName: string; end; ///<summary> MetaObject Interface. Use this type to read the property Resource Name.</summary> IBackendModuleResourceName = interface(IBackendMetaObject) ['{BEA0754A-0D59-4D62-96A4-3175A3E8E1EB}'] ///<summary> Gets resource name property.</summary> function GetResourceName: string; end; IBackendDownloadURL = interface(IBackendMetaObject) ['{0403AF5D-AF5D-4463-97DD-2903DE03EBFD}'] function GetDownloadURL: string; end; IBackendFileName = interface(IBackendMetaObject) ['{59E96B63-92B9-4A1D-991E-1487FF26B0A3}'] function GetFileName: string; end; IBackendFileID = interface(IBackendMetaObject) ['{B58DA141-82E8-4BD6-920D-9C9E680BEC03}'] function GetFileID: string; end; IBackendExpiresAt = interface(IBackendMetaObject) ['{CAD0E4F8-AB04-4EB5-B13C-CD9B0188036C}'] function GetExpiresAt: TDateTime; end; IBackendMetaClass = interface ['{F80536B3-4F7F-4C52-9F53-A81CF608299C}'] end; IBackendMetaDataType = interface ['{64064A4C-09AC-4FDC-8A12-31C40AC9E2FC}'] end; IBackendMetaFactory = interface ['{B58EC9B1-060C-4B44-82E9-82F576AB3793}'] end; IBackendMetaClassFactory = interface(IBackendMetaFactory) ['{B27A40E6-5084-4093-BED3-A329DCC65E92}'] function CreateMetaClass(const AClassName: string): TBackendMetaClass; overload; end; IBackendMetaClassObjectFactory = interface(IBackendMetaFactory) ['{80E7B794-6088-4A85-A5A2-49ADA2112629}'] function CreateMetaClassObject(const AClassName, AObjectID: string): TBackendEntityValue; overload; end; IBackendMetaUserFactory = interface(IBackendMetaFactory) ['{5C1A367B-F06E-492F-BD64-D68CA268671F}'] function CreateMetaUserObject(const AObjectID: string): TBackendEntityValue; overload; end; IBackendMetaGroupFactory = interface(IBackendMetaFactory) ['{3CB88315-4399-4307-A5E5-CF60C919FF2D}'] function CreateMetaGroupObject(const AGroupName: string): TBackendEntityValue; overload; end; IBackendMetaFileFactory = interface(IBackendMetaFactory) ['{96C22B76-C711-4D7C-90C8-AEA565F622D5}'] function CreateMetaFileObject(const AObjectID: string): TBackendEntityValue; overload; end; IBackendMetaDataTypeFactory = interface(IBackendMetaFactory) ['{7FDED929-4F6D-4C41-8AF9-8AE20BFB2EF9}'] function CreateMetaDataType(const ADataType, ABackendClassName: string): TBackendMetaClass; overload; end; implementation uses System.SysUtils, REST.Backend.Consts, REST.Backend.Exception; { TBackendEntityValue } constructor TBackendEntityValue.Create(const Intf: IBackendMetaObject); begin FData := Intf; FFiller := 0; end; function TBackendEntityValue.GetAuthToken: string; begin if not TryGetAuthToken(Result) then raise EBackendServiceError.Create(sAuthTokenRequired); end; function TBackendEntityValue.GetBackendClassName: string; begin if not TryGetBackendClassName(Result) then raise EBackendServiceError.Create(sBackendClassNameRequired); end; function TBackendEntityValue.GetCreatedAt: TDateTime; begin if not TryGetCreatedAt(Result) then raise EBackendServiceError.Create(sCreateAtRequired); end; function TBackendEntityValue.GetDownloadURL: string; begin if not TryGetDownloadURL(Result) then raise EBackendServiceError.Create(sDownloadUrlRequired); end; function TBackendEntityValue.GetExpiresAt: TDateTime; begin if not TryGetExpiresAt(Result) then raise EBackendServiceError.Create(sExpiresAtRequired); end; function TBackendEntityValue.GetFileName: string; begin if not TryGetFileName(Result) then raise EBackendServiceError.Create(sFileNameRequired); end; function TBackendEntityValue.GetFileID: string; begin if not TryGetFileID(Result) then raise EBackendServiceError.Create(sFileIDRequired); end; function TBackendEntityValue.GetObjectID: string; begin if not TryGetObjectID(Result) then raise EBackendServiceError.Create(sObjectIDRequired); end; function TBackendEntityValue.GetUpdatedAt: TDateTime; begin if not TryGetUpdatedAt(Result) then raise EBackendServiceError.Create(sUpdatedAtRequired); end; function TBackendEntityValue.GetUserName: string; begin if not TryGetUserName(Result) then raise EBackendServiceError.Create(sUserNameRequired); end; function TBackendEntityValue.GetGroupName: string; begin if not TryGetGroupName(Result) then raise EBackendServiceError.Create(sGroupNameRequired); end; function TBackendEntityValue.GetIsEmpty: Boolean; begin Result := FData = nil; end; function TBackendEntityValue.TryGetAuthToken(out AValue: string): Boolean; var LIntf: IBackendAuthToken; begin Result := Supports(FData, IBackendAuthToken, LIntf); if Result then AValue := LIntf.GetAuthToken; end; function TBackendEntityValue.TryGetBackendClassName(out AValue: string): Boolean; var LIntf: IBackendClassName; begin Result := Supports(FData, IBackendClassName, LIntf); if Result then AValue := LIntf.GetClassName; end; function TBackendEntityValue.TryGetCreatedAt(out AValue: TDateTime): Boolean; var LIntf: IBackendCreatedAt; begin Result := Supports(FData, IBackendCreatedAt, LIntf); if Result then AValue := LIntf.GetCreatedAt; end; function TBackendEntityValue.TryGetDownloadURL(out AValue: string): Boolean; var LIntf: IBackendDownloadURL; begin Result := Supports(FData, IBackendDownloadURL, LIntf); if Result then AValue := LIntf.GetDownloadURL; end; function TBackendEntityValue.TryGetExpiresAt(out AValue: TDateTime): Boolean; var LIntf: IBackendExpiresAt; begin Result := Supports(FData, IBackendExpiresAt, LIntf); if Result then AValue := LIntf.GetExpiresAt; end; function TBackendEntityValue.TryGetFileName(out AValue: string): Boolean; var LIntf: IBackendFileName; begin Result := Supports(FData, IBackendFileName, LIntf); if Result then AValue := LIntf.GetFileName; end; function TBackendEntityValue.TryGetFileID(out AValue: string): Boolean; var LIntf: IBackendFileID; begin Result := Supports(FData, IBackendFileID, LIntf); if Result then AValue := LIntf.GetFileID; end; function TBackendEntityValue.TryGetObjectID(out AValue: string): Boolean; var LIntf: IBackendObjectID; begin Result := Supports(FData, IBackendObjectID, LIntf); if Result then AValue := LIntf.GetObjectID; end; function TBackendEntityValue.TryGetUpdatedAt(out AValue: TDateTime): Boolean; var LIntf: IBackendUpdatedAt; begin Result := Supports(FData, IBackendUpdatedAt, LIntf); if Result then AValue := LIntf.GetUpdatedAt; end; function TBackendEntityValue.TryGetUserName(out AValue: string): Boolean; var LIntf: IBackendUserName; begin Result := Supports(FData, IBackendUserName, LIntf); if Result then AValue := LIntf.GetUserName; end; function TBackendEntityValue.TryGetGroupName(out AValue: string): Boolean; var LIntf: IBackendGroupName; begin Result := Supports(FData, IBackendGroupName, LIntf); if Result then AValue := LIntf.GetGroupName; end; { TBackendClassValue } constructor TBackendClassValue.Create(const Intf: IBackendMetaClass); begin Assert(Supports(Intf, IBackendClassName)); FData := Intf; end; function TBackendClassValue.GetBackendClassName: string; begin if not TryGetBackendClassName(Result) then raise EBackendServiceError.Create(sBackendClassNameRequired); end; function TBackendClassValue.GetDataType: string; begin if not TryGetDataType(Result) then raise EBackendServiceError.Create(sDataTypeNameRequired); end; function TBackendClassValue.TryGetBackendClassName(out AValue: string): Boolean; var LIntf: IBackendClassName; begin Result := Supports(FData, IBackendClassName, LIntf); if Result then AValue := LIntf.GetClassName else Assert(False); // Expect this to work end; function TBackendClassValue.TryGetDataType(out AValue: string): Boolean; var LIntf: IBackendDataType; begin Result := Supports(FData, IBackendDataType, LIntf); if Result then AValue := LIntf.GetDataType else Assert(False); // Expect this to work end; end.
unit uMeetingsArray; interface uses uMeetingsClass, ADODB, DB, SysUtils, Classes, Dialogs; type TMeetingsArray = class private conn : TADOConnection; dbName : String; public constructor Create(db : String); function getAllMeetings: TStringList; function deleteMeeting(meetingID : integer): TStringList; procedure addMeeting(meeting : TMeetings); procedure updateMeeting(meeting : TMeetings); procedure closeDB; end; implementation { TMembersArray } {This procedure takes in a TMeetings object and uses its functions and procedures to construct an SQL query to add a new meeting to the meetings table in the database. It then creates and executes the query before closing the connection to the database.} procedure TMeetingsArray.addMeeting(meeting: TMeetings); var sqlQ : string; query :TADOQuery; begin sqlQ := 'INSERT INTO tblMeetings ' + '(MeetingID, MeetingDate, MeetingTime, Location,' + 'Programme, Attendance, Theme, Chairman, OpeningGrace,' + 'Toastmaster, ClosingGrace, Grammarian, TopicsMaster,' + 'SgtAtArms, OpeningComments, ClosingComments) VALUES ('; sqlQ := sqlQ + '''' +IntToStr(meeting.getID); sqlQ := sqlQ + ''', #' +meeting.getDate; sqlQ := sqlQ + '#, ''' +meeting.getTime; sqlQ := sqlQ + ''', ''' +meeting.getLocation; sqlQ := sqlQ + ''', ' +IntToStr(meeting.getProgramme); sqlQ := sqlQ + ', ' +IntToStr(meeting.getAttendance); sqlQ := sqlQ + ', ''' +meeting.getTheme; sqlQ := sqlQ + ''', ''' +meeting.getChairman; sqlQ := sqlQ + ''', ''' +meeting.getOpeningGrace; sqlQ := sqlQ + ''', ''' +meeting.getToastmaster; sqlQ := sqlQ + ''', ''' +meeting.getClosingGrace; sqlQ := sqlQ + ''', ''' +meeting.getGrammarian; sqlQ := sqlQ + ''', ''' +meeting.getTopicsMaster; sqlQ := sqlQ + ''', ''' +meeting.getSgtAtArms; sqlQ := sqlQ + ''', '''+meeting.getOpeningComments+''', '''+ meeting.getClosingComments+''')'; //InputBox(sqlQ, sqlQ, sqlQ); query := TADOQuery.Create(NIL); query.Connection := conn; query.Sql.Add(sqlQ); query.ExecSQL; query.Close; end; procedure TMeetingsArray.closeDB; begin conn.Close; end; {The array class is created and connects to the specified database.} constructor TMeetingsArray.Create(db: String); begin conn := TADOConnection.Create(NIL); conn.ConnectionString := 'Provider=MSDASQL.1;Persist Security Info=False;' + 'Extended Properties="DBQ=' + db + ';' + 'Driver={Driver do Microsoft Access (*.mdb)};' + 'DriverId=25;FIL=MS Access;FILEDSN=C:\Test.dsn;MaxBufferSize=2048;' + 'MaxScanRows=8;PageTimeout=5;SafeTransactions=0;Threads=3;UID=admin;'+ 'UserCommitSync=Yes;"'; end; {This function takes in a meeting ID and uses it to construct an SQL query to delete a meeting from the meetings table in the database. It then creates and executes the query before closing the connection to the database.} function TMeetingsArray.deleteMeeting(meetingID: integer): TStringList; var sqlQ : String; query :TADOQuery; begin sqlQ := 'DELETE * FROM tblMeetings WHERE MeetingID = ' + IntToStr(meetingID); //InputBox(sqlQ, sqlQ, sqlQ); query := TADOQuery.Create(NIL); query.Connection := conn; query.Sql.Add(sqlQ); query.ExecSQL; query.Close; end; {This function constructs and sends a query to the database which returns all the members in the database. A Stringlist is created. The details from the query are added to a series of new meetings objects which are inserted into the Stringlist. The details are then passed through a ToString function which returns a string of text representing the data. The connection to the database is then closed.} function TMeetingsArray.getAllMeetings: TStringList; var sqlQ : string; query : TADOQuery; m : TMeetings; sl : TStringList; begin sqlQ := 'SELECT * FROM tblMeetings'; query := TADOQuery.Create(NIL); query.Connection := conn; query.Sql.Add(sqlQ); query.Active := true; sl := TStringList.Create; while NOT query.EOF do begin m := TMeetings.Create(query.FieldValues['MeetingID'], query.FieldValues['MeetingDate'], query.FieldValues['MeetingTime'], query.FieldValues['Location'], query.FieldValues['Attendance'], query.FieldValues['Theme'], query.FieldValues['Chairman'], query.FieldValues['OpeningGrace'], query.FieldValues['Toastmaster'], query.FieldValues['ClosingGrace'], query.FieldValues['Grammarian'], query.FieldValues['TopicsMaster'], query.FieldValues['SgtAtArms'], query.FieldValues['OpeningComments'], query.FieldValues['ClosingComments'], query.FieldValues['Programme']); sl.AddObject(m.toString, m); query.Next; end; query.Active := false; query.Close; Result := sl; end; {This procedure take sin a Meetings class object and uses its functions to construct a query for updating a meeting in the meetings table of the database. The query is then executed and the connection to the database is closed.} procedure TMeetingsArray.updateMeeting(meeting: TMeetings); var sqlQ : string; query :TADOQuery; begin sqlQ := 'UPDATE tblMeetings SET '+ 'MeetingDate = #' + meeting.getDate + '#, '+ 'MeetingTime = ''' + meeting.getTime + ''', '+ 'Location = ''' + meeting.getLocation + ''', '+ 'Programme = ' + IntToStr(meeting.getProgramme) + ', '+ 'Attendance = ' + IntToStr(meeting.getAttendance) + ', '+ 'Theme = ''' + meeting.getTheme + ''', '+ 'Chairman = ' + meeting.getChairman + ', '+ 'OpeningGrace = ' + meeting.getOpeningGrace + ', '+ 'Toastmaster = ' + meeting.getToastmaster + ', '+ 'ClosingGrace = ' + meeting.getClosingGrace + ', '+ 'Grammarian = ' + meeting.getGrammarian + ', '+ 'TopicsMaster = ' + meeting.getTopicsMaster + ', '+ 'SgtAtArms = ' + meeting.getSgtAtArms + ', '+ 'OpeningComments = ' + meeting.getOpeningComments + ', '+ 'ClosingComments = ' + meeting.getClosingComments + ' WHERE MeetingID = ' + IntToStr(meeting.getID); //InputBox(sqlQ, sqlQ, sqlQ); query := TADOQuery.Create(NIL); query.Connection := conn; query.Sql.Clear; query.Sql.Text := sqlQ; query.ExecSQL; query.Close; end; end.
unit bSpartan; interface uses vEnv, vConst, bFile, system.SysUtils, system.StrUtils, firedac.comp.client, bDB, bFormatter, bHelper, types; type TSpartan = class private class procedure version(newLine: boolean = true); class procedure noteCaseInsensitive; class procedure createModel(model_name: string); class procedure createController(controller_name: string); class procedure createDAO(dao_name: string); public class procedure raiseArmy; class procedure raiseWeapons(dir: string); class procedure spartError(msg: string); end; implementation { TSpartan } class procedure TSpartan.raiseWeapons(dir: string); var projectName, confFile, defPort, defUser, defPass: string; begin projectName := THelper.getPathName(dir); writeln(format('Starting project %s ...', [projectName])); tfile.Create(dir); writeln(''); if not fileexists(dir + tconst.GITIGNORE_FILE) then begin tfile.Create(dir + tconst.GITIGNORE_FILE); tfile.writeInFile(dir + tconst.GITIGNORE_FILE, tconst.GITIGNORE_CONTENT); end; if (fileexists(dir + tconst.CONTROLLER_FILE) and THelper.readbolinput('Base Controller file already exists. Do you want to recriate it ?') ) or (not fileexists(dir + tconst.CONTROLLER_FILE)) then begin writeln(format('Creating Controller Weapons in %s%s ...', [dir, tconst.CONTROLLER_FILE])); tfile.Create(dir + tconst.CONTROLLER); tfile.Create(dir + tconst.CONTROLLER_FILE); writeln(''); end; if (fileexists(dir + tconst.MODEL_FILE) and THelper.readbolinput('Base Model file already exists. Do you want to recriate it ?')) or (not fileexists(dir + tconst.MODEL_FILE)) then begin writeln(format('Creating Model Weapons in %s%s ...', [dir, tconst.MODEL_FILE])); tfile.Create(dir + tconst.MODEL); tfile.Create(dir + tconst.MODEL_FILE); writeln(''); end; if (fileexists(dir + tconst.DAO_FILE) and THelper.readbolinput('Base DAO file already exists. Do you want to recriate it ?')) or (not fileexists(dir + tconst.DAO_FILE)) then begin writeln(format('Creating DAO Weapons in %s%s ...', [dir, tconst.DAO_FILE])); tfile.Create(dir + tconst.DAO); tfile.Create(dir + tconst.DAO_FILE); writeln(''); end; writeln(format('Creating View Weapons in %s%s ...', [dir, tconst.View])); writeln(''); tfile.Create(dir + tconst.View); confFile := dir + tconst.CONF_FILE; if (fileexists(confFile) and THelper.readbolinput(format('Configuration file "%s" already exists. Do you want to recriate it ?', [tconst.CONF_FILE, slinebreak]))) or (not fileexists(confFile)) then begin tfile.Create(confFile); writeln(''); writeln('Database configurations: '); writeln('-------------------------'); CONF_FULL_PATH := confFile; tenv.db.driver := THelper.readinput('Driver [ mysql | postgres | firebird ]', 'mysql'); defPass := ''; case ansiindexstr(tenv.db.driver, ['mysql', 'postgres', 'firebird']) of 0: { mysql } begin defPort := '3306'; defUser := 'root'; end; 1: { postgres } begin defPort := '5432'; defUser := 'postgres'; end; 2: { firebird } begin defPort := '3050'; defUser := 'sysdba'; defPass := 'masterkey'; end else begin spartError(format('Driver "%s" not supported.', [tenv.db.driver])); tenv.db.driver := ''; tenv.db.server := ''; tenv.db.Port := ''; tenv.db.database := ''; tenv.db.user := ''; tenv.db.password := ''; end; end; tenv.db.server := THelper.readinput('Server', 'localhost'); tenv.db.Port := THelper.readinput('Port', defPort); if tenv.db.driver = 'firebird' then begin tenv.db.database := '"' + THelper.selectfile(dir, '.fdb|.fdb2|.fdb3|.gdb') + '"'; if tenv.db.database = '' then tenv.db.database := 'no_database_selected'; writeln('Database: ', tenv.db.database); end else tenv.db.database := THelper.readinput('Database'); tenv.db.user := THelper.readinput('User', defUser); tenv.db.password := THelper.readinput('Password', defPass); writeln(''); writeln('-------------------------'); end; writeln(''); writeln(format('Weapon "%s" created successfully' + slinebreak + 'START YOUR BATTLE NOW !!!', [projectName])); end; class procedure TSpartan.spartError(msg: string); begin raise Exception.Create(msg); end; class procedure TSpartan.version(newLine: boolean = true); begin writeln(tconst.APP_NAME, ': ', tenv.system.version); if newLine then writeln(''); end; class procedure TSpartan.createController(controller_name: string); var selected_controller: string; begin writeln(''); if not fileexists(tconst.Project.MainController) then tfile.Copy(tconst.system.MainController, tconst.Project.MainController); selected_controller := tenv.system.currentPath + tconst.CONTROLLER + tformatter.parseController(controller_name) + tconst.pas; if (fileexists(selected_controller) and THelper.readBolInputWithAll('Controller "' + selected_controller + '" already exists!' + slinebreak + 'Do you want to recriate it ?')) or (not fileexists(selected_controller)) then begin tfile.Create(selected_controller); writeln('Controller ', tformatter.parseController(controller_name), ' created successfully !'); end; end; class procedure TSpartan.createDAO(dao_name: string); var selected_DAO: string; begin writeln(''); if not fileexists(tconst.Project.MainDao) then tfile.Copy(tconst.system.MainDao, tconst.Project.MainDao); selected_DAO := tenv.system.currentPath + tconst.DAO + tformatter.parseDAO(dao_name) + tconst.pas; if (fileexists(selected_DAO) and THelper.readBolInputWithAll('DAO "' + selected_DAO + '" already exists!' + slinebreak + 'Do you want to recriate it ?')) or (not fileexists(selected_DAO)) then begin tfile.Create(selected_DAO); writeln('DAO ', tformatter.parseDAO(dao_name), ' created successfully !'); end; end; class procedure TSpartan.createModel(model_name: string); var selected_model: string; begin writeln(''); writeln(tconst.system.MainModel, tconst.Project.MainModel); if not fileexists(tconst.Project.MainModel) then tfile.Copy(tconst.system.MainModel, tconst.Project.MainModel); selected_model := tenv.system.currentPath + tconst.MODEL + tformatter.parseModel(model_name) + tconst.pas; if (fileexists(selected_model) and THelper.readBolInputWithAll('Model "' + selected_model + '" already exists!' + slinebreak + 'Do you want to recriate it ?')) or (not fileexists(selected_model)) then begin tfile.Create(selected_model); writeln('Model ', tformatter.parseModel(model_name), ' created successfully !'); end; end; class procedure TSpartan.noteCaseInsensitive; begin writeln('Note: Types bellow are case sensitive!'); end; class procedure TSpartan.raiseArmy; var i: integer; aName, table: string; tables_list: TStringDynArray; begin case ParamCount of 0: begin writeln(''); writeln(tconst.APP_NAME, ' Framework | A Delphi MVC micro-framework to fast build applications and dinner in HELL.'); writeln('=================================================================================================='); writeln('Authors: Paulo Barros <paulo.alfredo.barros@gmail.com>, Junior de Paula <juniiordepaula@gmail.com>'); TSpartan.version(false); writeln('=================================================================================================='); writeln(''); writeln('Usage: ', lowercase(tconst.APP_NAME), ' [option] <param|params>'); writeln(''); writeln(''); writeln('Avaliable soldiers:'); for i := 0 to High(tconst.SOLDIERS) do writeln(' ', tconst.SOLDIERS[i], StringOfChar(' ', 20 - length(tconst.SOLDIERS[i])), tconst.soldiers_help[i]); end; 1: begin TSpartan.version; case ansiindexstr(ParamStr(1), tconst.SOLDIERS) of 0: { version already been promt } ; 1: { -c } begin writeln(tenv.system.getConfig); writeln('--------------------------------------------------------'); writeln(format('Configuration file must be located in "%s"', [tconst.getConfFile])); end; 2: { stare } begin spartError('A NAME to your new weapon must be informed.' + slinebreak + 'If you want to create new weapon in current folder, type "spartan stare ."'); end; 3: { push } begin spartError('You must choose one of the weapons bellow:' + slinebreak + ' model' + slinebreak + ' controller' + slinebreak + ' dao'); end else spartError(format('Soldier "%s" is not part of our army.', [ParamStr(1)])); end; end; 2: begin TSpartan.version; case ansiindexstr(ParamStr(1), tconst.SOLDIERS) of 2: { stare } begin if ParamStr(2) = '.' then TSpartan.raiseWeapons(tenv.system.currentPath) else begin if tfile.exists(tenv.system.currentPath + ParamStr(2)) then spartError(format('A project "%s" already exists.', [ParamStr(2)])) else TSpartan.raiseWeapons(tenv.system.currentPath + ParamStr(2) + '\'); end; end; 3: { push } begin case ansiindexstr(ParamStr(2), tconst.push_options) of 0: { model } begin tables_list := TDB.listTables; if length(tables_list) > 0 then begin writeln('Avaliable tables to became Model weapons: '); TSpartan.noteCaseInsensitive; writeln(''); for table in tables_list do begin aName := tformatter.modelFromTable(table); if THelper.existsInArray(tenv.system.currentPath + tconst.MODEL + Copy(aName, 2, length(aName)) + tconst.pas, tenv.system.Models) then writeln(' - ', aName, StringOfChar(' ', 40 - length(aName)), '( Created )') else writeln(' - ', aName, StringOfChar(' ', 40 - length(aName)), '( Not created )'); end; end; end; 1: { controller } begin tables_list := TDB.listTables; if length(tables_list) > 0 then begin writeln('Avaliable tables to became Controller weapons: '); TSpartan.noteCaseInsensitive; writeln(''); for table in tables_list do begin aName := tformatter.controllerFromTable(table); if THelper.existsInArray(tenv.system.currentPath + tconst.CONTROLLER + Copy(aName, 2, length(aName)) + tconst.pas, tenv.system.Controllers) then writeln(' - ', aName, StringOfChar(' ', 40 - length(aName)), '( Created )') else writeln(' - ', aName, StringOfChar(' ', 40 - length(aName)), '( Not created )'); end; end; end; 2: { DAO } begin tables_list := TDB.listTables; if length(tables_list) > 0 then begin writeln('Avaliable tables to became DAO weapons: '); TSpartan.noteCaseInsensitive; writeln(''); for table in tables_list do begin aName := tformatter.daoFromTable(table); if THelper.existsInArray(tenv.system.currentPath + tconst.DAO + Copy(aName, 2, length(aName)) + tconst.pas, tenv.system.DAOs) then writeln(' - ', aName, StringOfChar(' ', 40 - length(aName)), '( Created )') else writeln(' - ', aName, StringOfChar(' ', 40 - length(aName)), '( Not created )'); end; end; end else spartError(format('Weapon "%s" is not part of our arsenal.', [ParamStr(2)])); end; end; else spartError(format('Soldier "%s" is not part of our army.', [ParamStr(1)])); end; end; 3: begin TSpartan.version; case ansiindexstr(ParamStr(2), tconst.push_options) of 0: { model } begin if ParamStr(3) = '*' then begin tables_list := TDB.listTables; if length(tables_list) > 0 then begin for table in tables_list do TSpartan.createModel(tformatter.modelFromTable(table)); end; end else if ansimatchstr(tformatter.tableFromModel(ParamStr(3)), TDB.listTables) then TSpartan.createModel(ParamStr(3)) else writeln('Model ', ParamStr(3), ' not found !'); end; 1: { controller } begin if ParamStr(3) = '*' then begin tables_list := TDB.listTables; if length(tables_list) > 0 then begin for table in tables_list do TSpartan.createController(tformatter.controllerFromTable(table)); end; end else if ansimatchstr(tformatter.tableFromController(ParamStr(3)), TDB.listTables) then TSpartan.createController(ParamStr(3)) else writeln('Controller ', ParamStr(3), ' not found !'); end; 2: { dao } begin if ParamStr(3) = '*' then begin tables_list := TDB.listTables; if length(tables_list) > 0 then begin for table in tables_list do TSpartan.createDAO(tformatter.daoFromTable(table)); end; end else if ansimatchstr(tformatter.tablefromdao(ParamStr(3)), TDB.listTables) then TSpartan.createDAO(ParamStr(3)) else writeln('DAO ', ParamStr(3), ' not found !'); end; else spartError(format('Weapon "%s" is not part of our arsenal.', [ParamStr(2)])); end end; end; end; end.
unit PascalCoin.Frame.NewKey; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.ListBox, FMX.Edit, FMX.Controls.Presentation, FMX.Layouts, PascalCoin.Wallet.Interfaces; type TNewKeyFrame = class(TFrame) Layout1: TLayout; Layout2: TLayout; TitleLabel: TLabel; Name: TLabel; NameEdit: TEdit; KeyTypeLayout: TLayout; Label1: TLabel; KeyTypeCombo: TComboBox; CancelButton: TButton; CreateButton: TButton; Panel1: TPanel; procedure CancelButtonClick(Sender: TObject); procedure CreateButtonClick(Sender: TObject); private FKeyIndex: Integer; function CreateNewKey: boolean; { Private declarations } public { Public declarations } OnCancel: TProc; OnCreateKey: TProc<Integer>; constructor Create(AComponent: TComponent); override; property KeyIndex: Integer read FKeyIndex; end; implementation {$R *.fmx} uses PascalCoin.FMX.DataModule, System.Rtti, PascalCoin.Utils.Interfaces; { TNewKeyFrame } constructor TNewKeyFrame.Create(AComponent: TComponent); var lKeyType: TKeyType; lName: String; begin inherited; FKeyIndex := -1; for lKeyType := Low(TKeyType) to High(TKeyType) do begin lName := TRttiEnumerationType.GetName<TKeyType>(lKeyType); KeyTypeCombo.Items.Add(lName); end; KeyTypeCombo.ItemIndex := KeyTypeCombo.Items.IndexOf('SECP256K1'); KeyTypeLayout.Visible := MainDataModule.Settings.AdvancedOptions; if not KeyTypeLayout.Visible then Height := Height - KeyTypeLayout.Height; end; procedure TNewKeyFrame.CancelButtonClick(Sender: TObject); begin OnCancel; end; procedure TNewKeyFrame.CreateButtonClick(Sender: TObject); begin if CreateNewKey then OnCreateKey(FKeyIndex); end; function TNewKeyFrame.CreateNewKey: boolean; var lName: string; lKeyType: TKeyType; begin result := False; lName := NameEdit.Text.Trim; if lName = '' then begin ShowMessage('Please enter a name for this key'); Exit; end; lKeyType := TRttiEnumerationType.GetValue<TKeyType> (KeyTypeCombo.Selected.Text); FKeyIndex := MainDataModule.Wallet.CreateNewKey(lKeyType, lName); result := KeyIndex > -1; end; end.
unit u_xPL_Web_Listener; {============================================================================== UnitName = uxPLWebListener UnitDesc = xPL Listener with WebServer capabilities UnitCopyright = GPL by Clinique / xPL Project ============================================================================== 0.93 : Modifications made for modif 0.92 for uxPLConfig Configuration handling modified to allow restart of web server after config modification without the need to restart the app 0.94 : Changed to create ReplaceTag and ReplaceArrayedTag 0.95 : Changes made since move of schema from Body to Header 0.96 : Added /data path to web server } {$mode objfpc}{$H+} interface uses u_xPL_Listener , Classes , SysUtils , IdGlobal , u_xPL_Message , u_xpl_body , u_xpl_udp_socket , IdContext , IdCustomHTTPServer , superobject ; type TWebCommandGet = procedure(var aPageContent : widestring; ARequestInfo: TIdHTTPRequestInfo) of object; TWebCallReplaceTag = function(const aDevice : string; const aParam : string; aValue : string; const aVariable : string; out ReplaceString : string) : boolean of object; TWebCallReplaceArrayedTag= function(const aDevice : string; const aValue : string; const aVariable : string; ReturnList : TStringList) : boolean of object; { TWebServer =============================================================} TWebServer = class(TIdHTTPServer) public constructor Create(const aOwner : TComponent); end; { TxPLWebListener } TxPLWebListener = class(TxPLListener) protected private fWebServer : TWebServer; procedure InitWebServer; procedure DoCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); public OnCommandGet : TWebCommandGet; // read fOnCommandGet write fOnCommandGet; OnReplaceTag : TWebCallReplaceTag; OnReplaceArrayedTag : TWebCallReplaceArrayedTag; destructor destroy; override; procedure UpdateConfig; override; procedure FinalizeHBeat(const aBody : TxPLBody); procedure GetData(const aSuperObject : ISuperObject); dynamic; end; implementation { ==============================================================} uses IdStack //cRandom , fpjsonrtti , fpjson, uRegExpr, LResources, u_xpl_common, uxPLConst, u_xpl_header, u_xpl_config; // u_xpl_custom_listener; const // K_CONFIG_LIB_SERVER_ROOT = 'webroot'; K_HBEAT_ME_WEBPORT = 'webport'; // TWebServer ================================================================= constructor TWebServer.Create(const aOwner: TComponent); begin inherited Create(aOwner); with Bindings.Add do begin // Dynamically assign port IP:=K_IP_LOCALHOST; ClientPortMin := XPL_BASE_DYNAMIC_PORT; ClientPortMax := ClientPortMin + XPL_BASE_PORT_RANGE; Port := 0; end; //if TxPLApplication(Owner).Settings.ListenOnAddress<>K_IP_LOCALHOST then with Bindings.Add do begin // IP:=TxPLApplication(Owner).Settings.ListenOnAddress; // ClientPortMin := XPL_BASE_DYNAMIC_PORT; // ClientPortMax := ClientPortMin + XPL_BASE_PORT_RANGE; // Port := 0; // end; AutoStartSession := True; SessionTimeOut := 600000; SessionState := True; end; { Utility functions ============================================================} //function StringListToHtml(aSList : TStrings) : widestring; //begin // result := StrReplace(#13#10,'<br>',aSList.Text,false); //end; { TxPLWebListener ==============================================================} //constructor TxPLWebListener.Create(const aOwner : TComponent; const aDevice, aVendor, aVersion : string); ////const K_DEFAULT_PORT = '8080'; //begin // inherited; // //fDiscovered := TStringList.Create; // //fDiscovered.Duplicates := dupIgnore; // //Config.DefineItem(K_HBEAT_ME_WEB_PORT , u_xpl_config.config, 1,K_DEFAULT_PORT); // //Config.DefineItem(K_CONFIG_LIB_SERVER_ROOT , u_xpl_config.config, 1); // // //OnxPLHBeatApp := @HBeatApp; // //Log(etInfo,K_MSG_LISTENER_STARTED,[AppName,Version]); //end; destructor TxPLWebListener.destroy; begin if Assigned(fWebServer) then begin Log(etInfo,K_WEB_MSG_SRV_STOP); fWebServer.Active := false; FreeAndNil(fWebServer); end; // fDiscovered.Destroy; inherited destroy; end; procedure TxPLWebListener.InitWebServer; begin if Assigned(fWebServer) then fWebServer.Free; fWebServer := TWebServer.Create(self); OnxPLHBeatPrepare := @FinalizeHBeat; // with fWebServer.Bindings.Add do begin // IP:=K_IP_LOCALHOST; //// Port:=StrToIntDef(Config.GetItemValue(K_HBEAT_ME_WEB_PORT),K_IP_DEFAULT_WEB_PORT); // end; // // if Settings.ListenOnAddress<>K_IP_LOCALHOST then with fWebServer.Bindings.Add do begin // IP:=Settings.ListenOnAddress; // Port:=StrToIntDef(Config.GetItemValue(K_HBEAT_ME_WEB_PORT),K_IP_DEFAULT_WEB_PORT); // end; with fWebServer do try fWebServer.OnCommandGet:=@DoCommandGet; Active:=true; Log(etInfo,K_WEB_MSG_PORT,[fWebServer.Bindings[0].Port]); except on E : Exception do Log(etError,K_MSG_GENERIC_ERROR,[E.ClassName,E.Message]); end; // fHtmlDir := Config.GetItemValue(K_CONFIG_LIB_SERVER_ROOT); // Log(etInfo,K_WEB_MSG_ROOT_DIR,[fHtmlDir]); end; procedure TxPLWebListener.DoCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var LFilename: string; //LPathname: string; //s : widestring; //aParam,aValue : string; //RegExpr : TRegExpr; page : TMemoryStream; //st : TStringStream; //obj: ISuperObject; streamer : TJSonStreamer; //s : string; jso : TJsonObject; //function LoadAFile(aFileName : string) : widestring; //var sl : tstringlist; //begin // sl := tstringlist.create; // if not FileExists(aFileName) then result := '' // else begin // sl.LoadFromFile(aFileName); // result := sl.Text; // end; // sl.Destroy; //end; //procedure SearchIncludes(var aText : widestring); //var i : widestring; // bFound : boolean; //begin // RegExpr.Expression := K_WEB_RE_INCLUDE; // bFound := RegExpr.Exec(aText); // while bFound do with RegExpr do begin // i := LoadAFile(htmlDir + Match[3] + Match[4]); // Delete(aText,MatchPos[0],MatchLen[0]); // Insert(i,aText,MatchPos[0]); // bFound := RegExpr.Exec(aText); // end; //end; //procedure ReplaceVariables(var aText : widestring; aParam, aValue : string); // //function ReplaceTag(const aDevice : string; const aVariable : string; out ReplaceString : string) : boolean; //begin // if aDevice<>'xplweb' then exit; // ReplaceString := ''; // if aVariable = 'appname' then ReplaceString := AppName // else if aVariable = 'devicename' then ReplaceString := Adresse.Device // else if aVariable = 'appversion' then ReplaceString := Version // else if aVariable = 'hubstatus' then ReplaceString := ConnectionStatusAsStr // else if aVariable = 'configstatus' then ReplaceString := Format(K_MSG_CONFIGURED,[IfThen(Config.IsValid,'done','pending')]); // result := ReplaceString<>''; //end; // //var bLoop : boolean; // sReplace: string; // sDuplicate : widestring; // tag,device,variable : string; //begin // sDuplicate := aText; // RegExpr.Expression := K_WEB_RE_VARIABLE; // {%appli_variable%} // bLoop := RegExpr.Exec(sDuplicate); // while bLoop do with RegExpr do begin // tag := Match[0]; // device := AnsiLowerCase(Match[1]); // variable := AnsiLowercase(Match[2]); // if device='xplweb' then begin // if ReplaceTag(device,variable,sReplace) then aText := AnsiReplaceStr(aText,tag, sReplace); // end else // if Assigned(OnReplaceTag) then // if OnReplaceTag(device,aParam,aValue,variable,sReplace) then aText := AnsiReplaceStr(aText,tag, sReplace); // // bLoop := RegExpr.ExecNext; // end; //end; //procedure LoopOnTemplate(var aPageContent : widestring); // ////function ReplaceArrayedTag(const aDevice : string; const aVariable : string; ReturnList : TStringList) : boolean; ////var i,j : integer; //// menuName, menuAction, variable, optionlist, entryzone : string; //// valuelist : stringArray; //// bLoop : boolean; ////begin //// if aDevice<>'xplweb' then exit; //// //// ReturnList.Clear; //// if aVariable = 'webappurl' then for i:=0 to fDiscovered.Count-1 do ReturnList.Add(fDiscovered.ValueFromIndex[i]) //// else if aVariable = 'webappname' then for i:=0 to fDiscovered.Count-1 do ReturnList.Add(fDiscovered.Names[i]) //// else if aVariable = 'log' then ReturnList.LoadFromFile(LogFileName) //// else if aVariable = 'menuitem' then begin //// if Assigned(DeviceInVendorFile) then //// for i:=0 to DeviceInVendorFile.MenuItems.Count-1 do begin //// menuName := DeviceInVendorFile.MenuItems[i].Name; //// menuAction := DeviceInVendorFile.MenuItems[i].xPLMsg; //(menuName); //// with TRegExpr.Create do begin //// EntryZone := ''; //// Expression :=K_MNU_ITEM_RE_PARAMETER; // Search for parameters //// bLoop := Exec(menuAction); //// while bLoop do begin // Loop on every parameter found //// Variable := Match[1]; //// if AnsiPos(K_MNU_ITEM_OPTION_SEP,Variable) = 0 then //// EntryZone += Format(K_MNU_ITEM_INPUT_TEXT,[Match[1],Match[0]]) //// else begin //// valuelist := StrSplit(Variable+K_MNU_ITEM_OPTION_SEP,K_MNU_ITEM_OPTION_SEP); //// optionlist := ''; //// for j:=0 to high(valuelist)-1 do optionlist += Format(K_MNU_ITEM_OPTION_LIST,[valuelist[j],valuelist[j]]); //// EntryZone += Format(K_MNU_ITEM_SELECT_LIST,[Match[0],optionlist]); //// end; //// bLoop := ExecNext; //// end; //// Destroy; //// end; //// EntryZone += Format(K_MNU_ITEM_MSG_AND_SUBMIT,[menuAction,menuName]); //// returnlist.Add(Format(K_MNU_ITEM_ACTION_ZONE,[EntryZone])); //// end; //// end; //// result := (ReturnList.Count >0); ////end; // //var // Pattern : string; // Where : integer; // i : integer; // ReturnList,PatternList : TStringList; // bLoop : boolean; // tag,device,variable : string; // bFirstVariable : boolean; //begin // Pattern := StrBetween(aPageContent,K_WEB_TEMPLATE_BEGIN,K_WEB_TEMPLATE_END); // if length(Pattern) = 0 then exit; // bFirstVariable := True; // ReturnList := TStringList.Create; // PatternList := TStringList.Create; // // RegExpr.Expression := K_WEB_RE_VARIABLE; // {%appli_variable%} // bLoop := RegExpr.Exec(Pattern); // while bLoop do with RegExpr do begin // tag := Match[0]; // device := AnsiLowerCase(Match[1]); // variable := AnsiLowercase(Match[2]); // // if Device = 'xplweb' then begin // if ReplaceArrayedTag(device,variable,ReturnList) then // for i:=0 to ReturnList.Count-1 do begin // if bFirstVariable then PatternList.Add(Pattern); // PatternList[i] := StringReplace(PatternList[i],tag,ReturnList[i],[rfIgnoreCase, rfReplaceAll ]); // end; // end else // if Assigned(OnReplaceArrayedTag) then // if OnReplaceArrayedTag(device,aValue,variable,ReturnList) then // for i:=0 to ReturnList.Count-1 do begin // if bFirstVariable then PatternList.Add(Pattern); // PatternList[i] := StringReplace(PatternList[i],tag,ReturnList[i],[rfIgnoreCase, rfReplaceAll]); // end; // // if PatternList.Count>0 then bFirstVariable := False; // bLoop := ExecNext; // end; // // Where := AnsiPos(K_WEB_TEMPLATE_BEGIN, aPageContent); // Delete(aPageContent,Where,length(K_WEB_TEMPLATE_END + K_WEB_TEMPLATE_BEGIN +Pattern)); // Insert(PatternList.Text,aPageContent,Where); // PatternList.Destroy; // ReturnList.Destroy; //end; //procedure HandleMenuItem; //var commande, aPar : string; // schema : string; // i : integer; // st : TStringStream; //begin // commande := ARequestInfo.Params.Values['xplMsg']; // StrSplitAtChar(commande,#10,schema,commande); // for i := 0 to ARequestInfo.Params.Count-1 do begin // aPar := ARequestInfo.Params.Names[i]; // if AnsiPos('%',aPar) <> 0 then commande := AnsiReplaceStr(commande,aPar,ARequestInfo.Params.Values[aPar]); // end; // // SendMessage(cmnd,Adresse.RawxPL,schema,commande, true); //end; begin LFilename := ARequestInfo.Document; Page := TMemoryStream.Create; if LFileName = '/' then begin aResponseInfo.ContentText := 'Available commands' + #10 + ' /log' + #10 + ' /config' + #10 + ' /status' + #10 + ' /data'; end; if LFileName = '/log' then begin page.LoadFromFile(LogFileName); aResponseInfo.ContentText := StreamToString(Page); end; if LFileName = '/config' then begin WriteComponentAsTextToStream(Page,Self); aResponseInfo.ContentText := StreamToString(Page); end; if LFileName = '/status' then begin end; if LFileName = '/data' then begin streamer := TJSONStreamer.Create(self); jso := streamer.ObjectToJSON(self); // obj := SO; // GetData(obj); // obj.SaveTo(page); // aResponseInfo.ContentText := StreamToString(page); aResponseInfo.ContentText:= jso.AsJSON; streamer.free; jso.free; end; Page.Free; (* (* *) end else begin LPathname := HtmlDir + LFilename; if FileExists(LPathName) then begin if ExtractFileExt(LFileName)='.html' then begin aParam := ''; aValue := ''; if ARequestInfo.Params.Count>0 then begin aParam := ARequestInfo.Params.Names[0]; aValue := ARequestInfo.Params.Values[aParam]; end; if ARequestInfo.Params.Values['xPLWeb_menuItem']<>'' then HandleMenuItem; s := LoadAFile(LPathName); if length(s)>0 then begin RegExpr := TRegExpr.Create; SearchIncludes(s); if Assigned(OnCommandGet) then OnCommandGet(s,ARequestInfo); ReplaceVariables(s, aParam, aValue); LoopOnTemplate(s); AResponseInfo.ContentText := s; RegExpr.Destroy; end end else AResponseInfo.ContentStream := TFileStream.Create(LPathname, fmOpenRead + fmShareDenyWrite); end else begin AResponseInfo.ResponseNo := 404; AResponseInfo.ContentText := Format(K_WEB_ERR_404,[LPathName]); end; end; *) end; procedure TxPLWebListener.GetData(const aSuperObject : ISuperObject); begin aSuperObject.S['address'] := Adresse.RawxPL; aSuperObject.S['application'] := AppName; end; //procedure TxPLWebListener.HBeatApp(const axPLMsg: TxPLMessage); //const DiscString = '%s=http://%s:%s'; //var aPort : string; // anApp : string; //begin // aPort := axPLMsg.Body.GetValueByKey(K_HBEAT_ME_WEB_PORT); // if aPort = '' then exit; // // anApp := axPLMsg.Body.GetValueByKey(K_HBEAT_ME_APPNAME); //// if fDiscovered.IndexOfName(anApp)=-1 then fDiscovered.Add(Format(DiscString,[anApp, axPLMsg.Body.GetValueByKey(K_HBEAT_ME_REMOTEIP), aPort])); //end; procedure TxPLWebListener.UpdateConfig; begin if Config.IsValid then InitWebServer; inherited; end; procedure TxPLWebListener.FinalizeHBeat(const aBody : TxPLBody); begin if Assigned(fWebServer) then aBody.SetValueByKey(K_HBEAT_ME_WEBPORT,IntToStr(fWebServer.Bindings[0].Port)); end; end.
unit Delphi.Mocks.Tests.Utils; interface uses DUnitX.TestFramework, Rtti, Delphi.Mocks.Helpers; type //Testing TValue helper methods in TValueHelper {$M+} [TestFixture] TTestTValue = class published procedure Test_TValue_Equals_Interfaces; procedure Test_TValue_NotEquals_Interfaces; procedure Test_TValue_Equals_Strings; procedure Test_TValue_NotEquals_Strings; procedure Test_TValue_Equals_SameGuid_Instance; procedure Test_TValue_Equals_DifferentGuid_Instance; procedure Test_TValue_NotEquals_Guid; end; {$M-} implementation uses SysUtils; { TTestTValue } procedure TTestTValue.Test_TValue_Equals_Interfaces; var i1,i2 : IInterface; v1, v2 : TValue; begin i1 := TInterfacedObject.Create; i2 := i1; v1 := TValue.From<IInterface>(i1); v2 := TValue.From<IInterface>(i2); Assert.IsTrue(v1.Equals(v2)); end; procedure TTestTValue.Test_TValue_Equals_Strings; var s1,s2 : string; v1, v2 : TValue; begin s1 := 'hello'; s2 := 'hello'; v1 := s1; v2 := s2; Assert.IsTrue(v1.Equals(v2)); end; procedure TTestTValue.Test_TValue_Equals_SameGuid_Instance; var s1,s2 : TGUID; v1, v2 : TValue; begin s1 := StringToGUID( '{2933052C-79D0-48C9-86D3-8FF29416033C}' ); s2 := s1; v1 := TValue.From<TGUID>( s1 ); v2 := TValue.From<TGUID>( s2 ); Assert.IsTrue(v1.Equals(v2)); end; procedure TTestTValue.Test_TValue_Equals_DifferentGuid_Instance; var s1,s2 : TGUID; v1, v2 : TValue; begin s1 := StringToGUID( '{2933052C-79D0-48C9-86D3-8FF29416033C}' ); s2 := StringToGUID( '{2933052C-79D0-48C9-86D3-8FF29416033C}' ); v1 := TValue.From<TGUID>( s1 ); v2 := TValue.From<TGUID>( s2 ); Assert.IsTrue(v1.Equals(v2)); end; procedure TTestTValue.Test_TValue_NotEquals_Guid; var s1,s2 : TGUID; v1, v2 : TValue; begin s1 := StringToGUID( '{2933052C-79D0-48C9-86D3-8FF294160000}' ); s2 := StringToGUID( '{2933052C-79D0-48C9-86D3-8FF29416FFFF}' ); v1 := TValue.From<TGUID>( s1 ); v2 := TValue.From<TGUID>( s2 ); Assert.IsFalse(v1.Equals(v2)); end; procedure TTestTValue.Test_TValue_NotEquals_Interfaces; var i1,i2 : IInterface; v1, v2 : TValue; begin i1 := TInterfacedObject.Create; i2 := TInterfacedObject.Create; v1 := TValue.From<IInterface>(i1); v2 := TValue.From<IInterface>(i2); Assert.IsFalse(v1.Equals(v2)); end; procedure TTestTValue.Test_TValue_NotEquals_Strings; var s1,s2 : string; v1, v2 : TValue; begin s1 := 'hello'; s2 := 'goodbye'; v1 := s1; v2 := s2; Assert.IsFalse(v1.Equals(v2)); end; initialization TDUnitX.RegisterTestFixture(TTestTValue); end.
unit SofaFile; interface uses ECMA.TypedArray, HdfFile; type TVector3 = record X, Y, Z: Float; end; TSofaFile = class private FNumberOfMeasurements: Integer; FNumberOfDataSamples: Integer; FNumberOfEmitters: Integer; FNumberOfReceivers: Integer; FListenerPositions: array of TVector3; FReceiverPositions: array of TVector3; FSourcePositions: array of TVector3; FEmitterPositions: array of TVector3; FListenerUp: TVector3; FListenerView: TVector3; FSampleRate: array of Float; FImpulseResponses: array of array of JFloat64Array; FDelay: array of Float; FDateModified: String; FHistory: String; FComment: String; FLicense: String; FAPIVersion: String; FAPIName: String; FOrigin: String; FTitle: String; FDateCreated: String; FReferences: String; FDataType: String; FOrganization: String; FRoomLocation: String; FRoomType: String; FApplicationVersion: String; FApplicationName: String; FAuthorContact: String; FNumberOfSources: Integer; procedure ReadAttributes(DataObject: THdfDataObject); procedure ReadDataObject(DataObject: THdfDataObject); function GetEmitterPositions(Index: Integer): TVector3; function GetListenerPositions(Index: Integer): TVector3; function GetReceiverPositions(Index: Integer): TVector3; function GetSourcePositions(Index: Integer): TVector3; function GetSampleRate(Index: Integer): Float; function GetDelay(Index: Integer): Float; function GetDelayCount: Integer; function GetSampleRateCount: Integer; function GetImpulseResponse(MeasurementIndex, ReceiverIndex: Integer): JFloat64Array; public procedure LoadFromBuffer(Buffer: JArrayBuffer); procedure SaveToBuffer(Buffer: JArrayBuffer); property DataType: String read FDataType; property RoomType: String read FRoomType; property RoomLocation: String read FRoomLocation; property Title: String read FTitle; property DateCreated: String read FDateCreated; property DateModified: String read FDateModified; property APIName: String read FAPIName; property APIVersion: String read FAPIVersion; property AuthorContact: String read FAuthorContact; property Organization: String read FOrganization; property License: String read FLicense; property ApplicationName: String read FApplicationName; property ApplicationVersion: String read FApplicationVersion; property Comment: String read FComment; property History: String read FHistory; property References: String read FReferences; property Origin: String read FOrigin; property NumberOfMeasurements: Integer read FNumberOfMeasurements; property NumberOfReceivers: Integer read FNumberOfReceivers; property NumberOfEmitters: Integer read FNumberOfEmitters; property NumberOfDataSamples: Integer read FNumberOfDataSamples; property NumberOfSources: Integer read FNumberOfSources; property ListenerPositions[Index: Integer]: TVector3 read GetListenerPositions; property ReceiverPositions[Index: Integer]: TVector3 read GetReceiverPositions; property SourcePositions[Index: Integer]: TVector3 read GetSourcePositions; property EmitterPositions[Index: Integer]: TVector3 read GetEmitterPositions; property ListenerUp: TVector3 read FListenerUp; property ListenerView: TVector3 read FListenerView; property ImpulseResponse[MeasurementIndex, ReceiverIndex: Integer]: JFloat64Array read GetImpulseResponse; property SampleRate[Index: Integer]: Float read GetSampleRate; property SampleRateCount: Integer read GetSampleRateCount; property Delay[Index: Integer]: Float read GetDelay; property DelayCount: Integer read GetDelayCount; end; function LoadSofaFile(Buffer: JArrayBuffer): TSofaFile; export; implementation uses WHATWG.Console; resourcestring RStrIndexOutOfBounds = 'Index out of bounds (%d)'; RStrSofaConventionMissing = 'File does not contain the SOFA convention'; { TSofaFile } function TSofaFile.GetDelay(Index: Integer): Float; begin if (Index < 0) or (Index >= Length(FDelay)) then raise Exception.Create(Format(RStrIndexOutOfBounds, [Index])); Result := FDelay[Index]; end; function TSofaFile.GetDelayCount: Integer; begin Result := Length(FDelay); end; function TSofaFile.GetEmitterPositions(Index: Integer): TVector3; begin if (Index < 0) or (Index >= Length(FEmitterPositions)) then raise Exception.Create(Format(RStrIndexOutOfBounds, [Index])); Result := FEmitterPositions[Index]; end; function TSofaFile.GetImpulseResponse(MeasurementIndex, ReceiverIndex: Integer): JFloat64Array; begin Result := FImpulseResponses[MeasurementIndex, ReceiverIndex]; end; function TSofaFile.GetListenerPositions(Index: Integer): TVector3; begin if (Index < 0) or (Index >= Length(FListenerPositions)) then raise Exception.Create(Format(RStrIndexOutOfBounds, [Index])); Result := FListenerPositions[Index]; end; function TSofaFile.GetReceiverPositions(Index: Integer): TVector3; begin if (Index < 0) or (Index >= Length(FReceiverPositions)) then raise Exception.Create(Format(RStrIndexOutOfBounds, [Index])); Result := FReceiverPositions[Index]; end; function TSofaFile.GetSampleRate(Index: Integer): Float; begin if (Index < 0) or (Index >= Length(FSampleRate)) then raise Exception.Create(Format(RStrIndexOutOfBounds, [Index])); Result := FSampleRate[Index]; end; function TSofaFile.GetSampleRateCount: Integer; begin Result := Length(FSampleRate); end; function TSofaFile.GetSourcePositions(Index: Integer): TVector3; begin if (Index < 0) or (Index >= Length(FSourcePositions)) then raise Exception.Create(Format(RStrIndexOutOfBounds, [Index])); Result := FSourcePositions[Index]; end; procedure TSofaFile.LoadFromBuffer(Buffer: JArrayBuffer); var HdfFile: THdfFile; Index: Integer; begin HdfFile := THdfFile.Create; try HdfFile.LoadFromBuffer(Buffer); if HdfFile.GetAttribute('Conventions') <> 'SOFA' then raise Exception.Create(RStrSofaConventionMissing); for Index := 0 to HdfFile.DataObject.DataObjectCount - 1 do ReadDataObject(HdfFile.DataObject.DataObject[Index]); ReadAttributes(HdfFile.DataObject); finally HdfFile.Free; end; end; procedure TSofaFile.ReadDataObject(DataObject: THdfDataObject); function GetDimension(Text: String): Integer; var TextPos: Integer; const CNetCdfDim = 'This is a netCDF dimension but not a netCDF variable.'; begin Result := 0; TextPos := Pos(CNetCdfDim, Text); if TextPos > 0 then begin Delete(Text, TextPos, 53); Result := StrToInt(Trim(Text)); end; end; function ConvertPosition(Position: TVector3): TVector3; begin Result.X := Position.Z * Cos(DegToRad(Position.Y)) * Cos(DegToRad(Position.X)); Result.Y := Position.Z * Cos(DegToRad(Position.Y)) * Sin(DegToRad(Position.X)); Result.Z := Position.Z * Sin(DegToRad(Position.Y)); end; const CClassIdentifier = 'CLASS'; CDimensionScaleIdentifier = 'DIMENSION_SCALE'; CNameIdentifier = 'NAME'; CTypeIdentifier = 'Type'; CCartesianIdentifier = 'cartesian'; begin DataObject.Data.Position := 0; if DataObject.Name = 'M' then begin Assert(DataObject.GetAttribute(CClassIdentifier) = CDimensionScaleIdentifier); FNumberOfMeasurements := GetDimension(DataObject.GetAttribute(CNameIdentifier)); end else if DataObject.Name = 'R' then begin Assert(DataObject.GetAttribute(CClassIdentifier) = CDimensionScaleIdentifier); FNumberOfReceivers := GetDimension(DataObject.GetAttribute(CNameIdentifier)); end else if DataObject.Name = 'E' then begin Assert(DataObject.GetAttribute(CClassIdentifier) = CDimensionScaleIdentifier); FNumberOfEmitters := GetDimension(DataObject.GetAttribute(CNameIdentifier)); end else if DataObject.Name = 'N' then begin Assert(DataObject.GetAttribute(CClassIdentifier) = CDimensionScaleIdentifier); FNumberOfDataSamples := GetDimension(DataObject.GetAttribute(CNameIdentifier)); end else if DataObject.Name = 'S' then begin Assert(DataObject.GetAttribute(CClassIdentifier) = CDimensionScaleIdentifier); var ItemCount := GetDimension(DataObject.GetAttribute(CNameIdentifier)); end else if DataObject.Name = 'I' then begin Assert(DataObject.GetAttribute(CClassIdentifier) = CDimensionScaleIdentifier); var ItemCount := GetDimension(DataObject.GetAttribute(CNameIdentifier)); end else if DataObject.Name = 'C' then begin Assert(DataObject.GetAttribute(CClassIdentifier) = CDimensionScaleIdentifier); var ItemCount := GetDimension(DataObject.GetAttribute(CNameIdentifier)); end else if DataObject.Name = 'ListenerPosition' then begin Assert(DataObject.Data.Size > 0); var ItemCount := DataObject.Data.Size div (3 * DataObject.DataType.Size); Assert(DataObject.DataType.DataClass = 1); var IsCartesian := True; if DataObject.HasAttribute(CTypeIdentifier) then IsCartesian := DataObject.GetAttribute(CTypeIdentifier) = CCartesianIdentifier; for var Index := 0 to ItemCount - 1 do begin var Position: TVector3; Position.X := DataObject.Data.ReadFloat(8); Position.Y := DataObject.Data.ReadFloat(8); Position.Z := DataObject.Data.ReadFloat(8); if not IsCartesian then Position := ConvertPosition(Position); FListenerPositions.Add(Position); end; end else if DataObject.Name = 'ReceiverPosition' then begin Assert(DataObject.Data.Size > 0); var ItemCount := DataObject.Data.Size div (3 * DataObject.DataType.Size); Assert(DataObject.DataType.DataClass = 1); var IsCartesian := True; if DataObject.HasAttribute(CTypeIdentifier) then IsCartesian := DataObject.GetAttribute(CTypeIdentifier) = CCartesianIdentifier; for var Index := 0 to ItemCount - 1 do begin var Position: TVector3; Position.X := DataObject.Data.ReadFloat(8); Position.Y := DataObject.Data.ReadFloat(8); Position.Z := DataObject.Data.ReadFloat(8); if not IsCartesian then Position := ConvertPosition(Position); FReceiverPositions.Add(Position); end; end else if DataObject.Name = 'SourcePosition' then begin Assert(DataObject.Data.Size > 0); var ItemCount := DataObject.Data.Size div (3 * DataObject.DataType.Size); FNumberOfSources := ItemCount; Assert(DataObject.DataType.DataClass = 1); var IsCartesian := True; if DataObject.HasAttribute(CTypeIdentifier) then IsCartesian := DataObject.GetAttribute(CTypeIdentifier) = CCartesianIdentifier; for var Index := 0 to ItemCount - 1 do begin var Position: TVector3; Position.X := DataObject.Data.ReadFloat(8); Position.Y := DataObject.Data.ReadFloat(8); Position.Z := DataObject.Data.ReadFloat(8); if not IsCartesian then Position := ConvertPosition(Position); FSourcePositions.Add(Position); end; end else if DataObject.Name = 'EmitterPosition' then begin Assert(DataObject.Data.Size > 0); var ItemCount := DataObject.Data.Size div (3 * DataObject.DataType.Size); Assert(DataObject.DataType.DataClass = 1); var IsCartesian := True; if DataObject.HasAttribute(CTypeIdentifier) then IsCartesian := DataObject.GetAttribute(CTypeIdentifier) = CCartesianIdentifier; for var Index := 0 to ItemCount - 1 do begin var Position: TVector3; Position.X := DataObject.Data.ReadFloat(8); Position.Y := DataObject.Data.ReadFloat(8); Position.Z := DataObject.Data.ReadFloat(8); if not IsCartesian then Position := ConvertPosition(Position); FEmitterPositions.Add(Position); end; end else if DataObject.Name = 'ListenerUp' then begin Assert(DataObject.Data.Size > 0); Assert(DataObject.DataType.DataClass = 1); FListenerUp.X := DataObject.Data.ReadFloat(8); FListenerUp.Y := DataObject.Data.ReadFloat(8); FListenerUp.Z := DataObject.Data.ReadFloat(8); end else if DataObject.Name = 'ListenerView' then begin Assert(DataObject.Data.Size > 0); Assert(DataObject.DataType.DataClass = 1); FListenerView.X := DataObject.Data.ReadFloat(8); FListenerView.Y := DataObject.Data.ReadFloat(8); FListenerView.Z := DataObject.Data.ReadFloat(8); end else if DataObject.Name = 'Data.IR' then begin Assert(DataObject.Data.Size > 0); var ItemCount := FNumberOfMeasurements * FNumberOfReceivers * FNumberOfDataSamples * 8; Assert(DataObject.Data.Size = ItemCount); FImpulseResponses.SetLength(FNumberOfMeasurements); for var MeasurementIndex := 0 to FNumberOfMeasurements - 1 do begin FImpulseResponses[MeasurementIndex].SetLength(FNumberOfReceivers); for var ReceiverIndex := 0 to FNumberOfReceivers - 1 do begin var ImpulseResponse := JFloat64Array.Create(FNumberOfDataSamples); for var Index := 0 to FNumberOfDataSamples - 1 do ImpulseResponse[Index] := DataObject.Data.ReadFloat(8); FImpulseResponses[MeasurementIndex, ReceiverIndex] := ImpulseResponse; end; end; end else if DataObject.Name = 'Data.SamplingRate' then begin Assert(DataObject.Data.Size > 0); var ItemCount := DataObject.Data.Size div DataObject.DataType.Size; for var Index := 0 to ItemCount - 1 do begin var SampleRate := DataObject.Data.ReadFloat(8); FSampleRate.Add(SampleRate); end; end else if DataObject.Name = 'Data.Delay' then begin Assert(DataObject.Data.Size > 0); var ItemCount := DataObject.Data.Size div DataObject.DataType.Size; for var Index := 0 to ItemCount - 1 do begin var Delay := DataObject.Data.ReadFloat(8); FDelay.Add(Delay); end; end; end; procedure TSofaFile.ReadAttributes(DataObject: THdfDataObject); var Index: Integer; begin for Index := 0 to DataObject.AttributeListCount - 1 do begin var Attribute := DataObject.AttributeListItem[Index]; var AttributeName := Attribute.Name; if AttributeName = 'DateModified' then FDateModified := Attribute.ValueAsString; if AttributeName = 'History' then FHistory := Attribute.ValueAsString; if AttributeName = 'Comment' then FComment := Attribute.ValueAsString; if AttributeName = 'License' then FLicense := Attribute.ValueAsString; if AttributeName = 'APIVersion' then FAPIVersion := Attribute.ValueAsString; if AttributeName = 'APIName' then FAPIName := Attribute.ValueAsString; if AttributeName = 'Origin' then FOrigin := Attribute.ValueAsString; if AttributeName = 'Title' then FTitle := Attribute.ValueAsString; if AttributeName = 'DateCreated' then FDateCreated := Attribute.ValueAsString; if AttributeName = 'References' then FReferences := Attribute.ValueAsString; if AttributeName = 'DataType' then FDataType := Attribute.ValueAsString; if AttributeName = 'Organization' then FOrganization := Attribute.ValueAsString; if AttributeName = 'RoomLocation' then FRoomLocation := Attribute.ValueAsString; if AttributeName = 'RoomType' then FRoomType := Attribute.ValueAsString; if AttributeName = 'ApplicationVersion' then FApplicationVersion := Attribute.ValueAsString; if AttributeName = 'ApplicationName' then FApplicationName := Attribute.ValueAsString; if AttributeName = 'AuthorContact' then FAuthorContact := Attribute.ValueAsString; end; end; procedure TSofaFile.SaveToBuffer(Buffer: JArrayBuffer); begin raise Exception.Create('Not yet implemented'); end; function LoadSofaFile(Buffer: JArrayBuffer): TSofaFile; begin Result := TSofaFile.Create; Result.LoadFromBuffer(Buffer); end; end.
unit TestBrickCamp.Repository.Redis; interface uses System.Classes, TestFramework, Spring.Container, Spring.Collections, Brickcamp.Repository.Redis, Redis.Commons, BrickCamp.IRedisRepository, BrickCamp.IRedisClientProvider, BrickCamp.ISettings, BrickCamp.TSettings ; type //integration test TestTRedisRepository = class(TTestCase) private function GetNewRedisClient : IRedisClient; function SetValue(redisClient : IRedisClient;value : string) : boolean; function GetRedisRepository : IRedisRepository; function GetConnectedRedisRepository(var Connected : Boolean) : IRedisRepository; public procedure SetUp; override; published procedure RedisClientSettings_Exist_Succeeds; procedure NewRedisClient_Defaults_Fails; procedure NewRedisClient_ConnectionSpecified_Succeeds; procedure NewRedisClient_SetValue_Succeeds; Procedure RedisRepository_Created_Succeeds; Procedure RedisRepository_Connected_Succeeds; Procedure RedisRepository_SetValue_Succeeds; Procedure RedisRepository_GetValue_Succeeds; end; implementation { TestTRedisEmployeeRepository } function TestTRedisRepository.GetConnectedRedisRepository(var Connected : Boolean) : IRedisRepository; begin Result := GetRedisRepository; if Assigned(Result) then Connected := result.Connnect; end; function TestTRedisRepository.GetNewRedisClient: IRedisClient; var RedisClientProvider : IRedisClientProvider; begin RedisClientProvider := GlobalContainer.Resolve<IRedisClientProvider>; RedisClientProvider.Initialise; result := RedisClientProvider.NewRedisClient; end; function TestTRedisRepository.GetRedisRepository: IRedisRepository; begin result := GlobalContainer.Resolve<IRedisRepository>; end; procedure TestTRedisRepository.NewRedisClient_ConnectionSpecified_Succeeds; var RedisClient : IRedisClient; begin RedisClient := GetNewRedisClient; Check(Assigned(RedisClient),'Check test connection parameters in ini file'); end; procedure TestTRedisRepository.NewRedisClient_Defaults_Fails; var RedisClientProvider : IRedisClientProvider; RedisClient : IRedisClient; begin RedisClientProvider := GlobalContainer.Resolve<IRedisClientProvider>; RedisClient := RedisClientProvider.NewRedisClient; Check(not Assigned(RedisClient),'Out of the box should not connect'); end; procedure TestTRedisRepository.NewRedisClient_SetValue_Succeeds; var RedisClient : IRedisClient; Passed : Boolean; begin RedisClient := GetNewRedisClient; Passed := SetValue(RedisClient,'BrickCamp'); Check(Passed); //this will except, underlying code passes back true if no except end; procedure TestTRedisRepository.RedisClientSettings_Exist_Succeeds; var BrickCampSettings: IBrickCampSettings; IpAddress : String; begin BrickCampSettings := GlobalContainer.Resolve<IBrickCampSettings>; IpAddress := BrickCampSettings.GetRedisIpAddress; CheckNotEqualsString(IpAddress,'','Setting Redis IpV4 address Not Found '); end; procedure TestTRedisRepository.RedisRepository_Connected_Succeeds; var CheckValue : Boolean; begin GetConnectedRedisRepository(CheckValue); Check(CheckValue); end; procedure TestTRedisRepository.RedisRepository_Created_Succeeds; var CheckValue : IRedisRepository; begin CheckValue := GetRedisRepository; Check(assigned(CheckValue)); end; procedure TestTRedisRepository.RedisRepository_GetValue_Succeeds; var RedisRepository : IRedisRepository; CheckValue : Boolean; StringToCheck : string; const VALUETOCHECK = 'V1'; begin RedisRepository := GetConnectedRedisRepository(CheckValue); if CheckValue then CheckValue := RedisRepository.SetValue('BrickCamp',VALUETOCHECK); if CheckValue then CheckValue := RedisRepository.GetValue('BrickCamp',StringToCheck); CheckEqualsString(StringToCheck,VALUETOCHECK,'Set Value failed, due to no connection or failure to set/get value'); end; procedure TestTRedisRepository.RedisRepository_SetValue_Succeeds; var RedisRepository : IRedisRepository; CheckValue : Boolean; begin RedisRepository := GetConnectedRedisRepository(CheckValue); if CheckValue then CheckValue := RedisRepository.SetValue('BrickCamp','V1'); Check(CheckValue,'Set Value failed, due to no connection or failure to set value'); end; procedure TestTRedisRepository.SetUp; begin inherited; end; function TestTRedisRepository.SetValue(redisClient: IRedisClient; value: string): boolean; begin result := RedisClient.&SET('firstname', 'BrickCamp'); end; initialization // Register any test cases with the test runner RegisterTest(TestTRedisRepository.Suite); //register spring 4d here. requires a run once set up..TODO move out initialisation GlobalContainer.RegisterType<TCbdSettings>; GlobalContainer.RegisterType<TRedisClientProvider>; GlobalContainer.RegisterType<TRedisRepository>; GlobalContainer.Build; end.
unit smf_play; interface uses SysUtils, Classes, Windows, smf_unit, mmsystem, gui_benri; { Clock の計算 Timebase = 四分音符分解能 Tempo = 一分間の四分音符数 1clock = 60000msec/Tempo/Timebase } type // プレイヤー(演奏を司るクラス) TSmfPlayer = class; TMidiThread = class(TThread) private FEventIndex: Integer; FStepInterval: Extended; FBaseTime: DWORD; FBaseTimeRevision: Integer; FWaitTime: DWORD; FMidiClockNextStep: Integer; FMidiClockCount: Integer; procedure UseTimeGetTime; procedure MidiOutProcTimeGetTime; procedure TempoChange(vTempo: Integer); procedure SetTempoRate(const Value: Extended); protected FPlayer: TSmfPlayer; FTempo: Integer; FTempoRate: Extended; FSong: TSmfSong; FTrack: TSmfTrack; procedure Execute; override; public UseSysEx: Boolean; UseCtrlChg: Boolean; UseBend: Boolean; NowTime: Integer; NowStep: Integer; constructor Create(Player: TSmfPlayer); virtual; property TempoRate: Extended read FTempoRate write SetTempoRate; end; ESmfPlayer = class(Exception); TSmfPlayer = class(TSmfCustomPlayer) private FIsPlaying: Boolean; function GetLength: Integer; protected MidiThread: TMidiThread; public UseLog: Boolean; UseMidiClock: Boolean; UseRepeatPlay : Boolean; // UseSysEx, UseCtrlChg, UseBend: Boolean; // WaitTime: Byte; //プレイヤーの負荷 [ 1(重) <---> x(軽) ] (ミリ秒単位で指定する) Position: Integer; //演奏開始位置 Tempo: Integer; TempoRate: Extended; property IsPlaying: Boolean read FIsPlaying; property Length: Integer read GetLength; procedure Open; //標準のポートを開く / 細かく指定したい場合は、 MidiOut.OpenPort を使う procedure Close; //標準のポートを閉じる procedure Play; procedure Stop; procedure LoadFromFile(FileName: string); procedure SaveToFile(FileName: string); constructor Create; override; end; var log: string; implementation { TSmfPlayer } procedure TSmfPlayer.Close; begin MidiOut.Close ; end; constructor TSmfPlayer.Create; begin inherited; WaitTime := 5{msec}; UseLog := False; UseMidiClock := True; UseRepeatPlay := False; Position := 0; // UseSysEx := True; UseCtrlChg := True; UseBend := True; // TempoRate := 1; end; function TSmfPlayer.GetLength: Integer; begin Result := 0; if Song.Count = 0 then Exit; if Song.Tracks[0].Count = 0 then Exit; Result := Song.Tracks[0].Events[Song.Tracks[0].Count -1].Time; end; procedure TSmfPlayer.LoadFromFile(FileName: string); begin Song.LoadFromFile(FileName); Song.SetDelay(AppPath + 'sakura_player.ini'); Song.TrackMix ; end; procedure TSmfPlayer.Open; begin if False = MidiOut.Open(-1) then raise ESmfPlayer.Create('MIDIポートが開けません。'); end; procedure TSmfPlayer.Play; begin if FIsPlaying then Exit; //イベントが0なら演奏できない if Song.Count = 0 then Exit; if Song.Tracks[0].Count = 0 then Exit; MidiThread := TMidiThread.Create(Self); MidiThread.Priority := tpTimeCritical; // MidiThread.UseSysEx := UseSysEx; MidiThread.UseCtrlChg := UseCtrlChg; MidiThread.UseBend := UseBend; MidiThread.TempoRate := TempoRate; // FIsPlaying := True; end; procedure TSmfPlayer.SaveToFile(FileName: string); begin Song.SaveToFile(FileName); end; procedure TSmfPlayer.Stop; begin FIsPlaying := False; MidiOut.Panic; if UseMidiClock then begin MidiOut.OutShortMsgE($FC,0,0); end; MidiThread.Terminate ; end; { TMidiThread } constructor TMidiThread.Create(Player: TSmfPlayer); procedure SetPosition; var Event: TSmfEvent; procedure PreSendEvent; var m: TSmfMeta; begin if (Event.ClassType <> TSmfNoteOff)and(Event.ClassType <> TSmfNoteOn)and(Event.ClassType <> TSmfSysEx) then begin if (Event.ClassType = TSmfMeta) then begin m := TSmfMeta(Event); if m.MetaType = META_TEMPO then TempoChange(m.AsTempo); end else Event.Send ; end; end; begin FEventIndex := 0; Event := FTrack.Events[0]; PreSendEvent; while Player.Position > Integer(Event.Time) do begin Inc(FEventIndex); if FTrack.Count <= FEventIndex then //インデックスが演奏より後ろの場合 begin FEventIndex := FEventIndex -1; Exit; end; Event := FTrack.Events[FEventIndex]; PreSendEvent; end; FBaseTime := DWORD( FBaseTime - Trunc( FStepInterval * FPlayer.Position )); // MIDI CLOCK FMidiClockCount := FSong.TimeBase div 24; FMidiClockNextStep := Trunc(Player.Position div FMidiClockCount) * FMidiClockCount + FMidiClockCount; if FPlayer.UseMidiClock then begin FPlayer.MidiOut.OutShortMsgE($FA, 0,0); end; end; begin //変数設定 UseSysEx := True; UseCtrlChg := True; UseBend := True; // FPlayer := Player; FSong := FPlayer.Song ; FTrack := FSong.Tracks[0]; if Player.InitTempo < 30 then Player.InitTempo := 120; FTempo := FPlayer.InitTempo ; FTempoRate := 1; FPlayer.Tempo := Trunc(FTempo * FTempoRate); FStepInterval := 60000 / {tempo}Player.InitTempo / FSong.TimeBase; FBaseTime := timeGetTime; FBaseTimeRevision := 0; FWaitTime := FPlayer.WaitTime ; if FStepInterval = 0 then FStepInterval := 5.2; if FWaitTime = 0 then FWaitTime := 1; // 頭だし SetPosition; //ログ記録用 if FPlayer.UseLog then begin Log := 'stime/etime(+delay) - event status'#13#10; end; inherited Create(False); FreeOnTerminate := True; end; procedure TMidiThread.Execute; begin UseTimeGetTime; end; procedure TMidiThread.MidiOutProcTimeGetTime; var Event: TSmfEvent; procedure SendEvent; var motari: Integer; begin //todo: イベント送出 motari := Trunc(Nowtime - Int64(Event.Time)* FStepInterval) ; //もたり具合を計算 if motari >= 300{msec} then Exit; //LOG if FPlayer.UseLog then begin NowStep := Trunc(NowTime / FStepInterval); log := log + Format('%5d(+%4dm) - 0x%2x'#13#10,[NowStep, motari, Event.Event]); if Length(log) > 4096 then begin log := Copy(log, Length(log)-4096+1, 4096); end; end; if (Event.ClassType = TSmfSysEx)and(UseSysEx = False) then Exit; if (Event.ClassType = TSmfControlChange)and(UseCtrlChg = False) then Exit; if (Event.ClassType = TSmfPitchBend)and(UseBend = False) then Exit; if Event.ClassType = TSmfMeta then begin if TSmfMeta(Event).MetaType = META_TEMPO then begin TempoChange(TSmfMeta(Event).AsTempo); end else Event.Send ; end else begin if FPlayer.Tempo <> FTempo then TempoChange(FPlayer.Tempo); Event.Send ; end; end; procedure EndOfTrack; begin if FPlayer.UseRepeatPlay = False then begin FPlayer.FIsPlaying := False; Terminate; Exit; end else begin FBaseTime := timeGetTime; FBaseTimeRevision := 0; FEventIndex := 0; end; end; begin NowTime := timeGetTime - FBaseTime; // 実時間 Inc(NowTime, FBaseTimeRevision); NowStep := Trunc(NowTime / FStepInterval); FPlayer.Position := NowStep; Event := FTrack.Events[FEventIndex]; // MIDI Clock if (FPlayer.UseMidiClock)and(NowStep >= FMidiClockNextStep) then begin Inc(FMidiClockNextStep, FMidiClockCount); FPlayer.MidiOut.OutShortMsgE($F8, 0, 0); end; while Integer(Event.Time) <= NowStep do begin SendEvent; Inc(FEventIndex); if FEventIndex >= FTrack.Count then begin //最後まで演奏した EndOfTrack; Exit; end; // 次のイベントをチェック Event := FTrack.Events[FEventIndex]; //次回送信するイベント if Integer(Event.Time) <= NowStep then begin NowTime := timeGetTime - FBaseTime; // 実時間を計測し直す(もたり対策) Inc(NowTime, FBaseTimeRevision); end; end; end; procedure TMidiThread.SetTempoRate(const Value: Extended); begin FTempoRate := Value; TempoChange(FTempo); end; procedure TMidiThread.TempoChange(vTempo: Integer); begin // テンポチェンジによる実時間との差を計測し、FBaseTimeRevision に記録 vTempo := Trunc(vTempo * TempoRate); FStepInterval := 60000 / vTempo / Integer(FSong.TimeBase); if FStepInterval <= 0 then FStepInterval := 5.2; NowTime := timeGetTime - FBaseTime; // 実時間 FBaseTimeRevision := Trunc(NowStep * FStepInterval) - NowTime; Inc(NowTime, FBaseTimeRevision); // 現在イベントの再計算 NowStep := Trunc(NowTime / FStepInterval); // MidiClock(24/4分音符) || 1step = TimeBase / 24 FMidiClockCount := FSong.TimeBase div 24; FMidiClockNextStep := Trunc(NowStep div FMidiClockCount) * FMidiClockCount + FMidiClockCount; // テンポを外部に知らせる場合 FPlayer.Tempo := vTempo ; FTempo := vTempo; end; procedure TMidiThread.UseTimeGetTime; begin timeBeginPeriod(FWaitTime); //タイマーの精度を設定 try try //演奏終了まで繰り返し while not Terminated do begin MidiOutProcTimeGetTime; //MIDIイベントの送出 Sleep(FWaitTime); //OSの負荷を減らすため end; except raise; end; finally timeEndPeriod(FWaitTime); //タイマーの精度を元に戻す end; end; end.
PROGRAM stringops; CONST lexbig = 'zzzLexically Great'; lexmiddle1 = 'ZZZLexically Middle+'; lexmiddle = 'ZZZLexically Middle'; lexmiddle2 = 'ZZZLexically Middl'; lexsmall = 'AAALexically Small'; lexnothing = '' VAR string1, string2 : string; BEGIN IF (lexbig <= lexmiddle) THEN writeln('ERROR: ', lexbig, ' <= ', lexmiddle) else writeln('OKAY: ', lexbig, ' > ', lexmiddle); IF (lexmiddle > lexmiddle1) THEN writeln('ERROR: ', lexmiddle, ' > ', lexmiddle1) else writeln('OKAY: ', lexmiddle, ' <= ', lexmiddle1); IF (lexmiddle <> lexmiddle) THEN writeln('ERROR: ', lexmiddle, ' <> ', lexmiddle) else writeln('OKAY: ', lexmiddle, ' = ', lexmiddle); IF (lexmiddle = lexnothing) THEN writeln('ERROR: ', lexmiddle, ' = ', lexnothing) else writeln('OKAY: ', lexmiddle, ' <> ', lexnothing); IF (lexnothing <> lexnothing) THEN writeln('ERROR: ', lexnothing, ' <> ', lexnothing) else writeln('OKAY: ', lexnothing, ' = ', lexnothing); IF (lexmiddle < lexmiddle2) THEN writeln('ERROR: ', lexmiddle, ' < ', lexmiddle2) else writeln('OKAY: ', lexmiddle, ' >= ', lexmiddle2); IF (lexsmall >= lexmiddle) THEN writeln('ERROR: ', lexsmall, ' >= ', lexmiddle) else writeln('OKAY: ', lexsmall, ' < ', lexmiddle) END.
unit fLabInfo; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, fAutoSz, ORFn, ORCtrls, VA508AccessibilityManager; type TfrmLabInfo = class(TfrmAutoSz) Panel1: TPanel; btnOK: TButton; memInfo: TCaptionMemo; cboTests: TORComboBox; procedure btnOKClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cboTestsNeedData(Sender: TObject; const StartFrom: string; Direction, InsertAt: Integer); procedure cboTestsClick(Sender: TObject); private { Private declarations } OKPressed: Boolean; public { Public declarations } end; var frmLabInfo: TfrmLabInfo; function ExecuteLabInfo: Boolean; implementation uses fLabs, rLabs; {$R *.DFM} function ExecuteLabInfo: Boolean; begin Result := False; frmLabInfo := TfrmLabInfo.Create(Application); try ResizeFormToFont(TForm(frmLabInfo)); frmLabInfo.ShowModal; if frmLabInfo.OKPressed then Result := True; finally frmLabInfo.Release; end; end; procedure TfrmLabInfo.btnOKClick(Sender: TObject); begin OKPressed := true; Close; end; procedure TfrmLabInfo.FormCreate(Sender: TObject); begin RedrawSuspend(cboTests.Handle); cboTests.InitLongList(''); RedrawActivate(cboTests.Handle); end; procedure TfrmLabInfo.cboTestsNeedData(Sender: TObject; const StartFrom: string; Direction, InsertAt: Integer); begin cboTests.ForDataUse(AllTests(StartFrom, Direction)); end; procedure TfrmLabInfo.cboTestsClick(Sender: TObject); begin inherited; FastAssign(TestInfo(cboTests.Items[cboTests.ItemIndex]), memInfo.Lines); end; end.
unit FIToolkit.Reports.Parser.Messages; interface uses System.Generics.Collections, FIToolkit.Reports.Parser.Types; type TFixInsightMessages = class (TList<TFixInsightMessage>) private type TCollectionNotifications = set of TCollectionNotification; strict private FSorted : Boolean; FUpdateActions : TCollectionNotifications; FUpdateCount : Integer; private procedure SetSorted(Value : Boolean); strict protected procedure Changed; protected procedure Notify(const Item : TFixInsightMessage; Action : TCollectionNotification); override; final; public constructor Create; procedure AddRange(const Values : array of TFixInsightMessage); procedure BeginUpdate; function Contains(Value : TFixInsightMessage) : Boolean; procedure EndUpdate; property Sorted : Boolean read FSorted write SetSorted; property UpdateCount : Integer read FUpdateCount; end; implementation { TFixInsightMessages } procedure TFixInsightMessages.AddRange(const Values : array of TFixInsightMessage); begin BeginUpdate; try inherited AddRange(Values); finally EndUpdate; end; end; procedure TFixInsightMessages.BeginUpdate; begin Inc(FUpdateCount); end; procedure TFixInsightMessages.Changed; begin if UpdateCount = 0 then try if FSorted and (cnAdded in FUpdateActions) then Sort; finally FUpdateActions := []; end; end; function TFixInsightMessages.Contains(Value : TFixInsightMessage) : Boolean; var i : Integer; begin if FSorted then Result := BinarySearch(Value, i) else Result := inherited Contains(Value); end; constructor TFixInsightMessages.Create; begin inherited Create(TFixInsightMessage.GetComparer); end; procedure TFixInsightMessages.EndUpdate; begin Dec(FUpdateCount); Changed; end; procedure TFixInsightMessages.Notify(const Item : TFixInsightMessage; Action : TCollectionNotification); begin inherited Notify(Item, Action); Include(FUpdateActions, Action); Changed; end; procedure TFixInsightMessages.SetSorted(Value : Boolean); begin if FSorted <> Value then begin Sort; FSorted := True; end; end; end.
unit const_array_of_record_1; interface implementation type TRec = record a: Int32; b: Int32; end; const Fields: array [3] of TRec = ([11, 1], [22, 2], [33, 3]); var f0a, f0b: Int32; f1a, f1b: Int32; f2a, f2b: Int32; procedure Test; begin f0a := Fields[0].a; f0b := Fields[0].b; f1a := Fields[1].a; f1b := Fields[1].b; f2a := Fields[2].a; f2b := Fields[2].b; end; initialization Test(); finalization Assert(f0a = 11); Assert(f0b = 1); Assert(f1a = 22); Assert(f1b = 2); Assert(f2a = 33); Assert(f2b = 3); end.
program TemperatureProbeInfo; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, uSMBIOS { you can add units after this }; function ByteToBinStr(AValue:Byte):string; const Bits: array[1..8] of byte = (128,64,32,16,8,4,2,1); var i: integer; begin Result:='00000000'; if (AValue<>0) then for i:=1 to 8 do if (AValue and Bits[i])<>0 then Result[i]:='1'; end; procedure GetTempProbeInfo; Var SMBios: TSMBios; LTempProbeInfo: TTemperatureProbeInformation; begin SMBios:=TSMBios.Create; try WriteLn('Temperature Probe Information'); WriteLn('-----------------------------'); if SMBios.HasTemperatureProbeInfo then for LTempProbeInfo in SMBios.TemperatureProbeInformation do begin WriteLn(Format('Description %s',[LTempProbeInfo.GetDescriptionStr])); WriteLn(Format('Location and Status %s',[ByteToBinStr(LTempProbeInfo.RAWTemperatureProbeInfo^.LocationandStatus)])); WriteLn(Format('Location %s',[LTempProbeInfo.GetLocation])); WriteLn(Format('Status %s',[LTempProbeInfo.GetStatus])); if LTempProbeInfo.RAWTemperatureProbeInfo^.MaximumValue=$8000 then WriteLn(Format('Maximum Value %s',['Unknown'])) else WriteLn(Format('Maximum Value %d C°',[LTempProbeInfo.RAWTemperatureProbeInfo^.MaximumValue div 10])); if LTempProbeInfo.RAWTemperatureProbeInfo^.MinimumValue=$8000 then WriteLn(Format('Minimum Value %s',['Unknown'])) else WriteLn(Format('Minimum Value %d C°',[LTempProbeInfo.RAWTemperatureProbeInfo^.MinimumValue div 10])); if LTempProbeInfo.RAWTemperatureProbeInfo^.Resolution=$8000 then WriteLn(Format('Resolution %s',['Unknown'])) else WriteLn(Format('Resolution %d C°',[LTempProbeInfo.RAWTemperatureProbeInfo^.Resolution div 1000])); if LTempProbeInfo.RAWTemperatureProbeInfo^.Tolerance=$8000 then WriteLn(Format('Tolerance %s',['Unknown'])) else WriteLn(Format('Tolerance %n C°',[LTempProbeInfo.RAWTemperatureProbeInfo^.Tolerance / 10])); WriteLn(Format('OEM Specific %.8x',[LTempProbeInfo.RAWTemperatureProbeInfo^.OEMdefined])); if LTempProbeInfo.RAWTemperatureProbeInfo^.Header.Length>$14 then if LTempProbeInfo.RAWTemperatureProbeInfo^.NominalValue=$8000 then WriteLn(Format('Nominal Value %s',['Unknown'])) else WriteLn(Format('Nominal Value %d C°',[LTempProbeInfo.RAWTemperatureProbeInfo^.NominalValue div 10])); WriteLn; end else Writeln('No Temperature Probe Info was found'); finally SMBios.Free; end; end; begin try GetTempProbeInfo; except on E:Exception do Writeln(E.Classname, ':', E.Message); end; Writeln('Press Enter to exit'); Readln; 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.5 7/23/04 6:53:28 PM RLebeau TFileStream access right tweak for Init() Rev 1.4 07/07/2004 17:41:38 ANeillans Added IdGlobal to uses, was not compiling cleanly due to missing function WriteStringToStream. Rev 1.3 6/29/04 1:20:14 PM RLebeau Updated DoLogWriteString() to call WriteStringToStream() instead Rev 1.2 10/19/2003 5:57:22 PM DSiders Added localization comments. Rev 1.1 2003.10.17 8:20:42 PM czhower Removed const Rev 1.0 3/22/2003 10:59:22 PM BGooijen Initial check in. ServerIntercept to ease debugging, data/status are logged to a file } unit IdServerInterceptLogFile; interface {$i IdCompilerDefines.inc} uses IdServerInterceptLogBase, IdGlobal, Classes; type TIdServerInterceptLogFile = class(TIdServerInterceptLogBase) protected FFileStream: TFileStream; FFilename:string; public procedure Init; override; destructor Destroy; override; procedure DoLogWriteString(const AText: string); override; published property Filename: string read FFilename write FFilename; end; implementation uses IdBaseComponent, SysUtils; { TIdServerInterceptLogFile } destructor TIdServerInterceptLogFile.Destroy; begin FreeAndNil(FFileStream); inherited Destroy; end; procedure TIdServerInterceptLogFile.Init; begin inherited Init; if not IsDesignTime then begin if FFilename = '' then begin FFilename := ChangeFileExt(ParamStr(0), '.log'); {do not localize} //BGO: TODO: Do we keep this, or maybe raise an exception? end; FFileStream := TIdAppendFileStream.Create(Filename); end; end; procedure TIdServerInterceptLogFile.DoLogWriteString(const AText: string); begin WriteStringToStream(FFileStream, AText); end; end.
unit SearchUtil; interface uses { VCL } SysUtils, Variants, Classes, StdCtrls, Controls, Forms, Graphics, Windows, Dialogs, ExtCtrls, ComCtrls, DB, SqlExpr, FMTBcd, DBClient, DBGrids, { helsonsant } DataUtil, UnModelo, UnFabricaDeModelos, UnTeclado; type TPesquisa = class(TObject) private FAcaoAntesDeAtivar: TNotifyEvent; FAcaoAposSelecionar: TNotifyEvent; FEdit: TCustomEdit; FFiltro: string; FList: TDBGrid; FModelo: TModelo; FParent: TControl; FTeclado: TTeclado; FFormulario: TForm; private FOnChange : TNotifyEvent; FOnEnter : TNotifyEvent; FOnExit : TNotifyEvent; FOnKeyDown : TKeyEvent; protected procedure ActivateList(const Sender: TObject); procedure DeactivateList(const Sender: TObject); procedure Selecionar; public property ControleDeEdicao: TCustomEdit read FEdit; property Modelo: TModelo read FModelo; constructor Create(const EditControl: TCustomEdit = nil; const Modelo: TModelo = nil; const Parent: TControl = nil; const AcaoAposSelecionar: TNotifyEvent = nil; const AcaoAntesDeAtivar: TNotifyEvent = nil); reintroduce; function Descarregar: TPesquisa; procedure FiltrarPor(const Criterio: string); function Formulario(const Formulario: TForm): TPesquisa; procedure OnChange(Sender: TObject); procedure OnEnter(Sender: TObject); procedure OnExit(Sender: TObject); procedure OnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure OnKeyPress(Sender: TObject); procedure OnKeyUp(Sender: TObject); procedure ListOnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ListOnDblClick(Sender: TObject); end; ConstrutorDePesquisas = class of TConstrutorDePesquisas; TConstrutorDePesquisas = class public class function AcaoAntesDeAtivar(const EventoDeAcaoAntesDeAtivar: TNotifyEvent): ConstrutorDePesquisas; class function AcaoAposSelecao(const EventoDeAcaoAposSelecao: TNotifyEvent): ConstrutorDePesquisas; class function ControleDeEdicao(const ReferenciaCampoDeEdicao: TCustomEdit): ConstrutorDePesquisas; class function Construir: TPesquisa; class function FabricaDeModelos(const FabricaDeModelos: TFabricaDeModelos): ConstrutorDePesquisas; class function Formulario(const Formulario: TForm): ConstrutorDePesquisas; class function Modelo(const NomeModelo: string): ConstrutorDePesquisas; class function PainelDePesquisa(const ReferenciaPainelDePesquisa: TControl): ConstrutorDePesquisas; end; var FPesquisas: TStringList; FCampoDeEdicao: TCustomEdit; FModelo: string; FPainelDePesquisa: TControl; FAcaoAposSelecao: TNotifyEvent; FFabricaDeModelos: TFabricaDeModelos; FAcaoAntesDeAtivar: TNotifyEvent; FForm: TForm; implementation procedure TPesquisa.ActivateList(const Sender: TObject); begin if Assigned(Self.FAcaoAntesDeAtivar) then Self.FAcaoAntesDeAtivar(Self); if not Self.FList.Visible then begin Self.FList.Align := alClient; Self.FList.Visible := True; Self.FList.Parent := TWinControl(Sender); Self.FParent.Height := 240; Self.FParent.Visible := True; end; end; function TPesquisa.Descarregar: TPesquisa; begin // Desfaz Referencias FFabricaDeModelos.DescarregarModelo(Self.FModelo); Self.FModelo := nil; Self.FEdit := nil; Self.FAcaoAposSelecionar := nil; Self.FParent := nil; // Libera objetos instanciados Self.FList.DataSource := nil; FreeAndNil(Self.FList); Result := Self; end; constructor TPesquisa.Create(const EditControl: TCustomEdit = nil; const Modelo: TModelo = nil; const Parent: TControl = nil; const AcaoAposSelecionar: TNotifyEvent = nil; const AcaoAntesDeAtivar: TNotifyEvent = nil); begin inherited Create(); Self.FModelo := Modelo; Self.FParent := Parent; Self.FAcaoAntesDeAtivar := AcaoAntesDeAtivar; Self.FAcaoAposSelecionar := AcaoAposSelecionar; // Referência ao Controle de Edição Self.FEdit := EditControl; // Captura eventos necessários à pesquisa // Salva eventos originais Self.FOnChange := TEdit(EditControl).OnChange; Self.FOnEnter := TEdit(EditControl).OnEnter; Self.FOnExit := TEdit(EditControl).OnExit; Self.FOnKeyDown := TEdit(EditControl).OnKeyDown; // Captura para Pesquisa TEdit(Self.FEdit).OnChange := Self.OnChange; TEdit(Self.FEdit).OnEnter := Self.OnEnter; TEdit(Self.FEdit).OnExit := Self.OnExit; TEdit(Self.FEdit).OnKeyDown := Self.OnKeyDown; // Grid Self.FList := TDBGrid.Create(nil); Self.FList.BorderStyle := bsNone; Self.FList.Visible := False; Self.FList.DataSource := Self.FModelo.DataSource(); Self.FList.Ctl3D := False; Self.FList.Options := Self.FList.Options - [dgTitles, dgEditing, dgIndicator, dgColLines, dgRowLines] + [dgRowSelect]; Self.FList.Font.Name := 'Segoe UI'; Self.FList.Font.Size := 16; Self.FList.Font.Style := [fsBold]; Self.FList.OnKeyDown := Self.ListOnKeyDown; Self.FList.OnDblClick := Self.ListOnDblClick; end; procedure TPesquisa.DeactivateList(const Sender: TObject); begin Self.FParent.Visible := False; Self.FList.Visible := False; end; procedure TPesquisa.ListOnDblClick(Sender: TObject); begin Self.Selecionar(); Self.DeactivateList(Sender); end; procedure TPesquisa.ListOnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then begin Self.DeactivateList(Sender); Self.FEdit.SetFocus; end else if Key = VK_RETURN then begin Self.Selecionar; Self.DeactivateList(Sender); end else if not (Key in [VK_DOWN, VK_UP]) then Self.FEdit.SetFocus; end; procedure TPesquisa.OnChange(Sender: TObject); var _edit: TEdit; _nomeDoCampo, _filtro: string; begin if Assigned(Self.FOnChange) then Self.FOnChange(Sender); _edit := TEdit(Sender); if _edit.HelpKeyword <> '' then _nomeDoCampo := _edit.HelpKeyword else _nomeDoCampo := Copy(_edit.Name, 4, 1024); Self.ActivateList(Self.FParent); _filtro := Criterio.Campo(_nomeDoCampo).Como(_edit.Text).Obter; if Self.FFiltro <> '' then _filtro := _filtro + Criterio.ConectorE + Self.FFiltro; Self.FModelo.CarregarPor(_filtro); end; procedure TPesquisa.OnEnter(Sender: TObject); begin if Assigned(Self.FOnEnter) then Self.FOnEnter(Sender); // if Self.FFormulario <> nil then // begin // if Self.FTeclado = nil then // begin // Self.FTeclado := TTeclado.Create(nil); // Self.FTeclado.Top := Self.FFormulario.Height - Self.FTeclado.Height; // Self.FTeclado.Parent := Self.FFormulario; // Self.FTeclado.ControleDeEdicao(Self.ControleDeEdicao); // end; // Self.FTeclado.Visible := True; // end; end; procedure TPesquisa.OnExit(Sender: TObject); begin if Assigned(Self.FOnExit) then Self.FOnExit(Sender); if Self.FTeclado <> nil then Self.FTeclado.Visible := False; end; procedure TPesquisa.OnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Assigned(Self.FOnKeyDown) then Self.FOnKeyDown(Sender, Key, Shift); if Key = VK_ESCAPE then TCustomEdit(Sender).Clear else if Key = VK_RETURN then begin Self.Selecionar(); Self.DeactivateList(Sender); end else if Key = VK_DOWN then Self.FList.SetFocus() else TCustomEdit(Sender).SetFocus(); end; procedure TPesquisa.OnKeyPress(Sender: TObject); begin end; procedure TPesquisa.OnKeyUp(Sender: TObject); begin end; procedure TPesquisa.Selecionar; begin if Assigned(Self.FAcaoAposSelecionar) then Self.FAcaoAposSelecionar(Self) end; { TConstrutorDePesquisas } class function TConstrutorDePesquisas.AcaoAntesDeAtivar( const EventoDeAcaoAntesDeAtivar: TNotifyEvent): ConstrutorDePesquisas; begin FAcaoAntesDeAtivar := EventoDeAcaoAntesDeAtivar; Result := Self; end; class function TConstrutorDePesquisas.AcaoAposSelecao( const EventoDeAcaoAposSelecao: TNotifyEvent): ConstrutorDePesquisas; begin FAcaoAposSelecao := EventoDeAcaoAposSelecao; Result := Self; end; class function TConstrutorDePesquisas.ControleDeEdicao( const ReferenciaCampoDeEdicao: TCustomEdit): ConstrutorDePesquisas; begin Result := Self; FCampoDeEdicao := ReferenciaCampoDeEdicao; end; class function TConstrutorDePesquisas.Construir: TPesquisa; var _modelo: TModelo; begin _modelo := FFabricaDeModelos.ObterModelo(FModelo); Result := TPesquisa.Create( FCampoDeEdicao, _modelo, FPainelDePesquisa, FAcaoAposSelecao, FAcaoAntesDeAtivar); Result.Formulario(FForm); end; class function TConstrutorDePesquisas.FabricaDeModelos( const FabricaDeModelos: TFabricaDeModelos): ConstrutorDePesquisas; begin FFabricaDeModelos := FabricaDeModelos; Result := Self; end; class function TConstrutorDePesquisas.Modelo( const NomeModelo: string): ConstrutorDePesquisas; begin FModelo := NomeModelo; Result := Self; end; class function TConstrutorDePesquisas.PainelDePesquisa( const ReferenciaPainelDePesquisa: TControl): ConstrutorDePesquisas; begin FPainelDePesquisa := ReferenciaPainelDePesquisa; Result := Self; end; procedure TPesquisa.FiltrarPor(const Criterio: string); begin Self.FFiltro := Criterio; end; class function TConstrutorDePesquisas.Formulario( const Formulario: TForm): ConstrutorDePesquisas; begin FForm := Formulario; Result := Self; end; function TPesquisa.Formulario(const Formulario: TForm): TPesquisa; begin Self.FFormulario := Formulario; Result := Self; end; end.
unit ClassPonuka; interface uses Windows, Graphics, Classes, Grids, StdCtrls; const Left_def: integer = 200; Right_def : integer = 100; Top_def : integer = 50; Bottom_def : integer = 200; Vyska_def : integer = 500; type TPonuka = class private Kom : TStringList; Model : TStringList; BezDph : TStringList; SDph : TStringList; Nakupna : TStringList; Koef, Dph, CelkomS, CelkomBez : real; Adresa : array of string; Datum : string; Dodaci : boolean; //Tlač PocetStran : integer; PocetRiadkov : integer; KoniecTlace : boolean; Zoom : real; Canvas : TCanvas; procedure VytlacStranku; public constructor Create; destructor Destroy; override; function FormatNumber( S : string ) : string; procedure PonukaToForm( StringGrid : TStringGrid; EditKoef, EditDPH, EditDatum, EditS, EditBez : TEdit; Memo : TMemo ); procedure FormToPonuka( StringGrid : TStringGrid; EditKoef, EditDPH, EditDatum, EditS, EditBez : TEdit; Memo : TMemo ); procedure Uloz( Cesta : string ); procedure Otvor( Cesta : string ); procedure Tlac; procedure ExportToHTML( FileName : string ); end; var Ponuka : TPonuka; implementation uses ExtCtrls, Sysutils, Printers, FormMoznosti, FormTlacPon, Dialogs, Forms, GifImage, Ini; //============================================================================== //============================================================================== // // Constructor // //============================================================================== //============================================================================== constructor TPonuka.Create; begin inherited; Kom := TStringList.Create; Model := TStringList.Create; SDph := TStringList.Create; BezDph := TStringList.Create; Nakupna := TStringList.Create; Koef := 0; Dph := 0; CelkomS := 0; CelkomBez := 0; Dodaci := False; end; //============================================================================== //============================================================================== // // Destructor // //============================================================================== //============================================================================== destructor TPonuka.Destroy; begin Kom.Free; Model.Free; SDph.Free; BezDph.Free; Nakupna.Free; inherited; end; //============================================================================== //============================================================================== // // Tlač // //============================================================================== //============================================================================== procedure TPonuka.VytlacStranku; procedure StringToRiadky( S : string; Riadky : TStringList; Width : integer ); var I : integer; Slovo, Riadok : string; begin Riadky.Clear; I := 1; Riadok := ''; while I <= Length( S ) do begin // Načítanie slova while (S[I] = ' ') and (I <= Length( S ) ) do Inc( I ); if I > Length( S ) then break; Slovo := ''; while (S[I] <> ' ') and (I <= Length( S ) ) do begin Slovo := Slovo + S[I]; Inc( I ); end; if I > Length( S ) then break; if Canvas.TextWidth( Slovo ) > Width then exit; if Canvas.TextWidth( Riadok+Slovo ) <= Width then Riadok := Riadok+Slovo+' ' else begin Delete( Riadok , Length( Riadok ) , 1 ); Riadky.Add( Riadok ); Riadok := Slovo+' '; end; end; Delete( Riadok , Length( Riadok ) , 1 ); Riadky.Add( Riadok ); end; var I, J, K, L : integer; Posl : longint; Stlpce : array[1..4] of integer; VysTab, VysRiad : integer; Dest, Src : TRect; S : string; Riadky : TStringList; Left, Right, Top, Bottom, Vyska : integer; begin Left := Round( Left_def*Zoom ); Top := Round( Top_def*Zoom ); Right := Round( Right_def*Zoom ); Bottom := Round( Bottom_def*Zoom ); Vyska := Round( Vyska_def*Zoom ); KoniecTlace := True; Posl := Top; Canvas.Font.Name := FormTlacPonuka.ComboBoxFont.Items[ FormTlacPonuka.ComboBoxFont.ItemIndex ]; Canvas.Font.Size := 8; // Výšky VysRiad := Canvas.TextHeight( 'Í' ) + Round(10*Zoom); VysTab := VysRiad + Round(30*Zoom); // Šírka stĺpcov for I := 1 to 4 do Stlpce[I] := 0; if FormTlacPonuka.Stlpce[1] then begin Stlpce[1] := Canvas.TextWidth( 'Komponenty' )+Round( 40*Zoom ); for I := 0 to Kom.Count-1 do begin J := Canvas.TextWidth( Kom[I] )+Round( 40*Zoom ); if J > Stlpce[1] then Stlpce[1] := J; end; end; if FormTlacPonuka.Stlpce[3] then begin Stlpce[3] := Canvas.TextWidth( 'Cena bez DPH' )+Round( 40*Zoom ); for I := 0 to BezDph.Count-1 do begin J := Canvas.TextWidth( BezDph[I] )+Round( 40*Zoom ); if J > Stlpce[3] then Stlpce[3] := J; end; J := Canvas.TextWidth( FormatNumber( FloatToStr( CelkomBez ) ) )+Round( 40*Zoom ); if J > Stlpce[3] then Stlpce[3] := J; end; if FormTlacPonuka.Stlpce[4] then begin Stlpce[4] := Canvas.TextWidth( 'Cena s DPH' )+Round( 40*Zoom ); for I := 0 to SDph.Count-1 do begin J := Canvas.TextWidth( SDph[I] )+Round( 40*Zoom ); if J > Stlpce[4] then Stlpce[4] := J; end; J := Canvas.TextWidth( FormatNumber( FloatToStr( CelkomBez ) ) )+Round( 40*Zoom ); if J > Stlpce[4] then Stlpce[4] := J; end; if FormTlacPonuka.Stlpce[2] then Stlpce[2] := Round( Printer.PageWidth*Zoom )-Left-Right-Stlpce[1]-Stlpce[3]-Stlpce[4]; if PocetStran = 0 then begin // Hlavička if FormMozn.Header <> nil then begin Dest.Left := Left; Dest.Right := Round( Printer.PageWidth*Zoom )-Right; Dest.Top := Top; Dest.Bottom := Top+Vyska; case FormMozn.RadioGroup1.ItemIndex of 0 : begin Src := FormMozn.Header.Bitmap.Canvas.ClipRect; if Src.Bottom > Vyska then Src.Bottom := Vyska; if Src.Right > Dest.Right-Dest.Left then Src.Right := Dest.Right-Dest.Left; Dest.Bottom := Dest.Top + Src.Bottom; Dest.Right := Dest.Left + Src.Right; Canvas.CopyRect( Dest , FormMozn.Header.Bitmap.Canvas , Src ); end; 1 : Canvas.StretchDraw( Dest , FormMozn.Header.Bitmap ); end; end; Inc( Posl , Vyska ); with Canvas do begin Pen.Color := clBlack; Pen.Width := 3; MoveTo( Left , Posl+Round( 20*Zoom ) ); LineTo( Round( Printer.PageWidth*Zoom )-Right , Posl+Round( 20*Zoom ) ); end; Inc( Posl , Round( 60*Zoom ) ); // Adresa Canvas.Font.Color := clBlack; Canvas.Font.Size := 15; J := 0; for I := 0 to Length( Adresa )-1 do begin K := Canvas.TextWidth( Adresa[I] ); if K > J then J := K; end; K := Canvas.TextHeight( 'Í' ) + Round( 10*Zoom ); for I := 0 to Length( Adresa )-1 do begin Canvas.TextOut( Round( Printer.PageWidth*Zoom )-Right-J-Round( 20*Zoom ) , Posl , Adresa[I] ); Inc( Posl , K ); end; Canvas.Pen.Width := 1; Canvas.Brush.Style := bsClear; { Canvas.Rectangle( Round( Printer.PageWidth*Zoom )-Right-J-40 , Posl-Length(Adresa)*K , Round( Printer.PageWidth*Zoom )-Right , Posl+10 );} // Nadpis with Canvas do begin Font.Size := 25; TextOut( Left , (((Posl-Length(Adresa)*K)+(Posl+Round( 10*Zoom ))) div 2)- (TextHeight('Cenová ponuka') div 2) , 'Cenová ponuka' ); end; Inc( Posl , Round( 50*Zoom ) ); end; // Hlavička tabulky if PocetRiadkov <= Kom.Count-1 then begin Canvas.Font.Size := 8; Canvas.Brush.Style := bsSolid; Canvas.Brush.Color := clLtGray; J := Left; for I := 1 to 4 do if FormTlacPonuka.Stlpce[I] then begin Canvas.Rectangle( J , Posl , J+Stlpce[I] , Posl+VysTab ); case I of 1 : S := 'Komponenty'; 2 : S := 'Model'; 3 : S := 'Cena bez DPH'; 4 : S := 'Cena s DPH'; end; Canvas.TextOut( J+Round( 20*Zoom ) , ((2*Posl+VysTab) div 2)-Canvas.TextHeight( S )div 2 , S ); Inc( J , Stlpce[I] ); end; Canvas.Brush.Style := bsClear; Inc( Posl , VysTab ); end; Riadky := TStringList.Create; for I := PocetRiadkov to Kom.Count-1 do begin K := 1; if FormTlacPonuka.Stlpce[2] then begin // Model StringToRiadky( Model[I] , Riadky , Stlpce[2]-Round( 40*Zoom ) ); K := Riadky.Count; if K = 0 then K := 1; if Riadky.Count*VysTab > Round( Printer.PageHeight*Zoom )-Bottom then begin PocetRiadkov := I; Inc( PocetStran ); KoniecTlace := False; break; end; end; J := Left; if FormTlacPonuka.Stlpce[1] then begin // Komponenty Canvas.TextOut( Left+Round( 20*Zoom ) , (((Posl)+(Posl+VysTab)) div 2)-(Canvas.TextHeight( Kom[I] )div 2) , Kom[I] ); Canvas.Rectangle( J , Posl , J+Stlpce[1] , Posl+VysTab*K ); Inc( J , Stlpce[1] ); end; if FormTlacPonuka.Stlpce[2] then begin Canvas.Rectangle( J , Posl , J+Stlpce[2] , Posl+VysTab*K ); Inc( J , Stlpce[2] ); end; if FormTlacPonuka.Stlpce[3] then begin // Cena bez DPH Canvas.Rectangle( J , Posl , J+Stlpce[3] , Posl+VysTab*K ); Inc( J , Stlpce[3] ); end; if FormTlacPonuka.Stlpce[4] then begin // Cena s DPH Canvas.Rectangle( J , Posl , J+Stlpce[4] , Posl+VysTab*K ); end; if FormTlacPonuka.Stlpce[2] then begin // Model for L := 0 to Riadky.Count-1 do begin Canvas.TextOut( Left+Round( 20*Zoom )+Stlpce[1] , (((Posl)+(Posl+VysTab)) div 2)-Canvas.TextHeight( Riadky[L] )div 2 , Riadky[L] ); Inc( Posl , VysTab ); end; if Riadky.Count > 0 then Dec( Posl , VysTab ); end; if FormTlacPonuka.Stlpce[3] then begin // Cena bez DPH Canvas.TextOut( Left+Stlpce[1]+Stlpce[2]+Stlpce[3]-Round( 20*Zoom )-Canvas.TextWidth( BezDph[I] ) , (((Posl)+(Posl+VysTab)) div 2)-Canvas.TextHeight( BezDph[I] )div 2 , BezDph[I] ); end; if FormTlacPonuka.Stlpce[4] then begin // Cena s DPH Canvas.TextOut( Left+Stlpce[1]+Stlpce[2]+Stlpce[3]+Stlpce[4]-Round( 20*Zoom )-Canvas.TextWidth( SDph[I] ) , (((Posl)+(Posl+VysTab)) div 2)-Canvas.TextHeight( SDph[I] )div 2 , SDph[I] ); end; Inc( Posl , VysTab ); if Posl > Round( Printer.PageHeight*Zoom )-Bottom then begin PocetRiadkov := I+1; Inc( PocetStran ); KoniecTlace := False; break; end; end; // Celkom if KoniecTlace then begin StringToRiadky( FormMozn.Memo.Text , Riadky , Round( Printer.PageWidth*Zoom )-(2*Left)-2*Right ); if Round( Printer.PageHeight*Zoom )-Bottom-Posl < 6*VysTab+(VysRiad*(Riadky.Count+1)) then begin PocetRiadkov := Kom.Count; KoniecTlace := False; Inc( PocetStran ); exit; end; Inc( Posl , VysTab ); with Canvas do begin Brush.Color := clLtGray; Brush.Style := bsSolid; Pen.Color := clBlack; Rectangle( Left , Posl , Round( Printer.PageWidth*Zoom )-Right , Posl+VysTab ); Brush.Style := bsClear; TextOut( Left+Round( 20*Zoom ) , (((Posl)+(Posl+VysTab)) div 2)-Canvas.TextHeight( 'CELKOM' )div 2 , 'C E L K O M' ); if FormTlacPonuka.Stlpce[3] then begin TextOut( Left+Stlpce[1]+Stlpce[2]+Stlpce[3]-Round( 20*Zoom )- Canvas.TextWidth( FormatNumber( FloatToStr( CelkomBez ) ) ), (((Posl)+(Posl+VysTab)) div 2)-Canvas.TextHeight( FloatToStr( CelkomBez ) )div 2 , FormatNumber( FloatToStr( CelkomBez ) ) ); MoveTo( Left+Stlpce[1]+Stlpce[2] , Posl ); LineTo( Left+Stlpce[1]+Stlpce[2] , Posl+VysTab ); end; if FormTlacPonuka.Stlpce[4] then begin TextOut( Left+Stlpce[1]+Stlpce[2]+Stlpce[3]+Stlpce[4]-Round( 20*Zoom )- Canvas.TextWidth( FormatNumber( FloatToStr( CelkomS ) ) ) , (((Posl)+(Posl+VysTab)) div 2)-Canvas.TextHeight( FloatToStr( CelkomS ) )div 2 , FormatNumber( FloatToStr( CelkomS ) ) ); MoveTo( Left+Stlpce[1]+Stlpce[2]+Stlpce[3] , Posl ); LineTo( Left+Stlpce[1]+Stlpce[2]+Stlpce[3] , Posl+VysTab ); end; Inc( Posl , 2*VysTab ); for I := 0 to Riadky.Count-1 do begin TextOut( Left , Posl , Riadky[I] ); Inc( Posl , VysRiad ); end; Inc( Posl , 4*VysTab ); TextOut( Left , Posl , 'V Bratislave dňa '+Datum ); TextOut( Round( Printer.PageWidth*Zoom )-Right-Round( 500*Zoom )-TextWidth( 'S pozdravom' ) , Posl , 'S pozdravom' ); end; end; Riadky.Free; end; function TPonuka.FormatNumber( S : string ) : string; var I : integer; begin Result := S; I := Pos( ',' , S ); if I = 0 then begin Result := S+',00' end else begin if I+2 <= Length( S ) then Delete( S , I+2 , Length( S )-(I+1) ); Result := S+'0'; end; end; //============================================================================== //============================================================================== // // I N T E R F A C E // //============================================================================== //============================================================================== //============================================================================== // Convert //============================================================================== procedure TPonuka.PonukaToForm( StringGrid : TStringGrid; EditKoef, EditDPH, EditDatum, EditS, EditBez : TEdit; Memo : TMemo ); var I : integer; begin StringGrid.RowCount := Kom.Count+1; if StringGrid.RowCount = 1 then begin StringGrid.RowCount := StringGrid.RowCount+1; StringGrid.FixedRows := 1; end; for I := 0 to Kom.Count-1 do begin StringGrid.Cells[0,I+1] := Kom[I]; StringGrid.Cells[1,I+1] := Model[I]; StringGrid.Cells[2,I+1] := BezDph[I]; StringGrid.Cells[3,I+1] := SDph[I]; StringGrid.Cells[4,I+1] := Nakupna[I]; end; EditKoef.Text := FloatToStr( Koef ); EditDPH.Text := FloatToStr( DPH ); EditS.Text := FloatToStr( CelkomS ); EditBez.Text := FloatToStr( CelkomBez ); EditDatum.Text := Datum; Memo.Clear; for I := 0 to Length( Adresa )-1 do Memo.Lines.Add( Adresa[I] ); end; procedure TPonuka.FormToPonuka( StringGrid : TStringGrid; EditKoef, EditDPH, EditDatum, EditS, EditBez : TEdit; Memo : TMemo ); var I : integer; begin Kom.Clear; Model.Clear; SDph.Clear; BezDph.Clear; Nakupna.Clear; for I := 1 to StringGrid.RowCount-1 do begin Kom.Add( StringGrid.Cells[0,I] ); Model.Add( StringGrid.Cells[1,I] ); BezDph.Add( StringGrid.Cells[2,I] ); SDph.Add( StringGrid.Cells[3,I] ); Nakupna.Add( StringGrid.Cells[4,I] ); end; Koef := StrToFloat( EditKoef.Text ); DPH := StrToFloat( EditDPH.Text ); Datum := EditDatum.Text; CelkomS := StrToFloat( EditS.Text ); CelkomBez := StrToFloat( EditBez.Text ); SetLength( Adresa , Memo.Lines.Count ); for I := 0 to Memo.Lines.Count-1 do Adresa[I] := Memo.Lines[I]; end; //============================================================================== // Práca so súbormi //============================================================================== procedure TPonuka.Uloz( Cesta : string ); var I : integer; begin Assign( Output , Cesta ); {$I-} Rewrite( Output ); {$I+} if IOResult <> 0 then begin MessageDlg( 'Súbor '+Cesta+' sa nedá vytvoriť!' , mtError , [mbOK] , 0 ); exit; end; if Dodaci then Writeln( 'ANO' ) else Writeln( 'NIE' ); Writeln( Datum ); Writeln( Kom.Count ); for I := 0 to Kom.Count-1 do begin Writeln( Kom[I] ); Writeln( Model[I] ); Writeln( BezDph[I] ); Writeln( SDph[I] ); Writeln( Nakupna[I] ); end; Writeln( Koef ); Writeln( DPH ); for I := 0 to Length( Adresa )-1 do Writeln( Adresa[I] ); CloseFile( Output ); end; procedure TPonuka.Otvor( Cesta : string ); var I, N : integer; S : string; begin AssignFile( Input , Cesta ); {$I-} Reset( Input ); {$I+} if IOResult <> 0 then begin MessageDlg( 'Súbor '+Cesta+' sa nedá otvoriť!' , mtError , [mbOK] , 0 ); exit; end; Kom.Clear; Model.Clear; BezDph.Clear; SDph.Clear; Nakupna.Clear; Readln( S ); if S = 'ANO' then Dodaci := True else Dodaci := False; Readln( Datum ); Readln( N ); for I := 1 to N do begin Readln( S ); Kom.Add( S ); Readln( S ); Model.Add( S ); Readln( S ); BezDph.Add( S ); Readln( S ); SDph.Add( S ); Readln( S ); Nakupna.Add( S ); end; Readln( Koef ); Readln( DPH ); SetLength( Adresa , 0 ); while not EoF( Input ) do begin SetLength( Adresa , Length( Adresa )+1 ); Readln( Adresa[Length( Adresa )-1] ); end; CloseFile( Input ); end; //============================================================================== // Tlač //============================================================================== procedure TPonuka.Tlac; begin if FormTlacPonuka.ShowModal = 1 then begin Zoom := 1; PocetStran := 0; PocetRiadkov := 0; KoniecTlace := False; Canvas := Printer.Canvas; repeat Printer.BeginDoc; VytlacStranku; Printer.EndDoc; until KoniecTlace; end; end; procedure TPonuka.ExportToHTML( FileName : string ); var F : textfile; I : integer; S : string; Bmp : TBitmap; begin Bmp := TBitmap.Create; try Bmp.LoadFromFile( exe_dir+'\logo.bmp' ); Bmp.SaveToFile( ExtractFilePath( FileName )+'logo.bmp' ); finally Bmp.Free; end; AssignFile( F , FileName ); {$I-} Rewrite( F ); {$I+} if IOResult <> 0 then exit; Writeln( F , '<html>' ); Writeln( F , '<head>' ); Writeln( F , '<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">' ); Writeln( F , '<title>PC PROMPT - Cenová ponuka</title>' ); Writeln( F , '</head>' ); // Tab1 // H L A V I Č K A Writeln( F , '<body>' ); Writeln( F , '<div align="left">' ); Writeln( F , '' ); Writeln( F , '<table border="0" width="710" height="135">' ); Writeln( F , '<tr>' ); Writeln( F , '<td width="162" height="70" rowspan="3">' ); Writeln( F , '<p align="center"><img border="0" src="logo.bmp" width="150" height="150"></td>' ); Writeln( F , '<td width="532" height="44"><p align="center"><font face="ZurichCalligraphic" size="7"><span style="letter-spacing: 6">PC' ); Writeln( F , 'PROMPT, s.r.o.</span></font></p>' ); Writeln( F , '</td>' ); Writeln( F , '</tr>' ); Writeln( F , '<tr>' ); Writeln( F , '<td width="532" height="24"><p align="center"><font face="ZurichCalligraphic" size="5"><span style="letter-spacing: 6">Bajkalská' ); Writeln( F , '27, 827 21 Bratislava</span></font></p>' ); Writeln( F , '</td>' ); Writeln( F , '</tr>' ); Writeln( F , '<tr>' ); Writeln( F , '<td width="532" height="1"><p align="center"><font face="ZurichCalligraphic" size="5"><span style="letter-spacing: 6">tel./fax:07-5342' ); Writeln( F , '1040, 5248 228</span></font></p>' ); Writeln( F , '</td>' ); Writeln( F , '</tr>' ); Writeln( F , '</table>' ); Writeln( F , '</div>' ); // Tab2 Writeln( F , '<div align="left">' ); Writeln( F , '<table border="0" width="710" height="51">' ); Writeln( F , '<tr>' ); Writeln( F , '<td width="445" height="15">&nbsp</td>' ); Writeln( F , '<td width="248" height="15">&nbsp</td>' ); Writeln( F , '</tr>' ); // A D R E S A if Length( Adresa ) = 0 then begin S := ''; I := 1; end else begin S := Adresa[0]; I := Length( Adresa ); end; Writeln( F , '<tr>' ); Writeln( F , '<td width="445" height="85" rowspan="',I,'"><font size="6">Cenová ponuka</font></td>' ); Writeln( F , '<td width="248" height="17" valign="top" align="left">'+S+'</td>' ); Writeln( F , '</tr>' ); for I := 1 to Length( Adresa )-1 do begin Writeln( F , '<tr>' ); Writeln( F , '<td width="248" height="18" valign="top" align="left">'+Adresa[I]+'</td>' ); Writeln( F , '</tr>' ); end; Writeln( F , '<tr>' ); Writeln( F , '<td width="445" height="1">&nbsp</td>' ); Writeln( F , '<td width="248" height="1" valign="top" align="left">&nbsp</td>' ); Writeln( F , '</tr>' ); Writeln( F , '</table>' ); Writeln( F , '</div>' ); // Tab3 Writeln( F , '<div align="left">' ); Writeln( F , '<table border="1" width="710" height="1" cellspacing="1" cellpadding="2">' ); Writeln( F , '<tr>' ); Writeln( F , '<td width="101" height="10" bgcolor="#C0C0C0">Komponenty</td>' ); Writeln( F , '<td width="341" height="10" bgcolor="#C0C0C0">Model</td>' ); Writeln( F , '<td width="131" height="10" bgcolor="#C0C0C0" align="center">Cena bez DPH</td>' ); Writeln( F , '<td width="117" height="10" bgcolor="#C0C0C0" align="center">Cena s DPH</td>' ); Writeln( F , '</tr>' ); for I := 0 to Kom.Count-1 do begin Writeln( F , '<tr>' ); Writeln( F , '<td width="103" height="7">'+Kom[I]+'</td>' ); Writeln( F , '<td width="339" height="7">'+Model[I]+'</td>' ); Writeln( F , '<td width="131" height="7"><p align="right">'+BezDPH[I]+'</td>' ); Writeln( F , '<td width="117" height="7"><p align="right">'+SDPH[I]+'</td>' ); Writeln( F , '</tr>' ); end; Writeln( F , '<tr>' ); Writeln( F , '<td width="442" height="10" colspan="2" bgcolor="#C0C0C0">C E L K O M</td>' ); Writeln( F , '<td width="131" height="10" bgcolor="#C0C0C0" align="right">'+FormatNumber( FloatToStr( CelkomBez ) )+'</td>' ); Writeln( F , '<td width="117" height="10" bgcolor="#C0C0C0" align="right">'+FormatNumber( FloatToStr( CelkomS ) )+'</td>' ); Writeln( F , '</tr>' ); Writeln( F , '</table>' ); Writeln( F , '</div>' ); // S P O L O Č N Ý T E X T Writeln( F , '<div align="left">' ); Writeln( F , '<table border="0" width="710" height="1">' ); Writeln( F , '<tr>' ); Writeln( F , '<td width="700" height="1">&nbsp</td>' ); Writeln( F , '</tr>' ); Writeln( F , '<tr>' ); Writeln( F , '<td width="700" height="44">' ); Writeln( F , FormMozn.Memo.Text ); Writeln( F , '</td>' ); Writeln( F , '</tr>' ); Writeln( F , '<tr>' ); Writeln( F , '<td width="700" height="1">&nbsp</td>' ); Writeln( F , '</tr>' ); Writeln( F , '</table>' ); Writeln( F , '</div>' ); Writeln( F , '<div align="left">' ); Writeln( F , '<table border="0" width="710" height="127">' ); Writeln( F , '<tr>' ); Writeln( F , '<td width="447" height="127" valign="bottom">' ); Writeln( F , '<p align="left">V Bratislave d&#328;a '+Datum+'</td>' ); Writeln( F , '<td width="253" height="127" valign="bottom">S pozdravom</td>' ); Writeln( F , '</tr>' ); Writeln( F , '</table>' ); Writeln( F , '</div>' ); Writeln( F , '</body>' ); Writeln( F , '</html>' ); CloseFile( F ); end; end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------} unit untEasyUtilConst; interface const //插件扩展参数 EASY_PLUGIN_EXT = '.dfm'; //脚本扩展参数 EASY_SCRIPT_EXT = '.psc'; EASY_RootGUID = '{00000000-0000-0000-0000-000000000000}'; EASY_OPERATE_ADD = '增加'; EASY_OPERATE_EDIT = '修改'; EASY_OPERATE_DELETE = '删除'; EASY_SYS_ERROR = '系统错误'; EASY_SYS_HINT = '系统提示'; EASY_SYS_EXCEPTION = '系统异常'; EASY_SYS_EXIT = '系统退出'; EASY_SYS_ABORT = '系统中断'; EASY_SYS_NOTNULL = '不能为空值!'; EASY_SYS_DATANOCHANGE = '数据未发生变更,不能进行保存!'; EASY_SYS_SAVE_SUCCESS = '保存成功!'; EASY_SYS_SAVE_FAILED = '保存失败,原因:'; //包加载文件不存在 EASY_BPL_NOTFOUND = '加载指定的文件%s已丢失!'; //数据库连接 EASY_DB_CONNECT_ERROR = '服务器连接失败, 原因:' ; EASY_DB_CONNECT_ERROR1 = '1、请检查应用服务器是否开启;' ; EASY_DB_CONNECT_ERROR2 = '2、请检查客户端参数设置是否正确.' ; EASY_DB_NOTFILE = '系统文件丢失,原因:数据模块丢失!'; EASY_DB_INITERROR = '数据模块初始化失败,请检查数据连接模块!'; EASY_DB_LOADERROR = '数据模块加载失败,原因:数据模块损坏或丢失!'; //闪窗体 EASY_SPLASH_NOTFILE = '系统文件丢失,原因:闪窗体(SplashForm.dll)文件丢失!'; //登录窗体 EASY_LOGIN_NOTFILE = '系统登录文件丢失!'; //主窗体显示时 EASY_DISPLAYUSERINFO_WELCOME = '欢迎 '; EASY_DISPLAYUSERINFO_DEPT = '部门 '; EASY_DISPLAYUSERINFO_NULL = '此用户未有员工使用,无法登录系统!'; EASY_DISPLAYUSERINFO_MORE = '此用户有多个员工使用,系统已阻止登录!'; EASY_STATUBAR_APP = '应用程序类型 '; EASY_STATUBAR_DBHOST = ' 数据服务器 '; //权限管理 EASY_RIGHT_TOPARENT = '只能对父节点或根节点进行资源权限分配!'; //系统加密密钥 EASY_KEY_DB = 'ABC1?*_+23XZY'; EASY_KEY_FILE = 'acAB13XZ?*_+'; EASY_KEY_IM = 'ABC_abc*12'; EASY_KEY_MAIL = 'EASYMAILc*1'; EASY_KEY_OTERHR = 'EASYOTHER?*KEY'; EASY_DBCONNECT_SUCCESS = '服务器连接设置成功,重新登录软件生效!'; //插件加载 EASY_PLUGIN_LOAD_FAILED = '加载插件%s失败,原因:'; EASY_PLUGIN_CANNOT_LOAD = '不能加载插件:%s 原因:未找到插件入口函数!'; type //操作数据状态 TEasyOperateType = (eotAdd, eotEdit, eotDelete, eotNone); implementation end.
{$R-} {Range checking off} {$B+} {Boolean complete evaluation on} {$S+} {Stack checking on} {$I+} {I/O checking on} {$N-} {No numeric coprocessor} {$M 65500,16384,655360} {Turbo 3 default stack and heap} program SetProb; {Copyright 1985 by Bob Keefer} {SetProb.Pas creates a 3-dimensional byte array, Probability[X,Y,Z], in which are stored the relative probability of each 3-letter trigram found in an input text. Once the table is completed, it is stored in the disc file PROB.DAT.} {To use this program to add more data to an existing version of PROB.DAT, modify procedure ZeroProb so that it reads Probability[X,Y,Z] from PROB.DAT instead of zeroing the array. This can be done by commenting out the lines marked with a single * and restoring the lines marked with a double **.} Uses Crt; var Ch1, Ch2, Ch3 : char; X, Y, Z : integer; Filename : string[15]; TheFile : text; Datafile : file of integer; Probability : array [0..26,0..26,0..26] of integer; procedure ZeroProb; var X,Y,Z : integer; begin {assign (Datafile,'Prob.dat');} {**} {reset(Datafile);} {**} for X:=0 to 26 do begin for Y:=0 to 26 do begin for Z:= 0 to 26 do begin {*} Probability[X,Y,Z] := 0; {**} {read(Datafile,Probability[X,Y,Z]);} end; end; end; {close (Datafile);} {**} end; {ZeroProb} procedure ScaleProb; var X,Y,Z : integer; begin for X:=0 to 26 do begin for Y:=0 to 26 do begin for Z:= 0 to 26 do begin Probability[X,Y,Z] := (Probability[X,Y,Z] + 1) div 2; end; end; end; end; {ScaleProb} procedure StartUp; begin clrscr; writeln('SetProb.Pas'); writeln('Copyright 1985 by Bob Keefer'); writeln; write ('Enter filename: '); readln (Filename); assign (TheFile, Filename); reset (TheFile); end; function Cleanup ( A : integer ) : integer; begin if (A>64) and (A<91) then Cleanup := A-64 else Cleanup := 0; end; {function Cleanup} procedure Countem; begin Ch1 := #32; Ch2 := #32; while not EOF (TheFile) do begin read(TheFile,Ch3); X := Cleanup(ord(upcase(Ch1))); Y := Cleanup(ord(upcase(Ch2))); Z := Cleanup(ord(upcase(Ch3))); if not (((X=0) and (Y=0)) or ((Y=0) and (Z=0))) then Probability[X,Y,Z] := Probability[X,Y,Z] + 1; if Probability[X,Y,Z] >32000 then ScaleProb; Ch1:=Ch2; Ch2:=Ch3; end; end; {Countem} procedure WriteData; var X,Y,Z : integer; begin for X := 0 to 26 do begin for Y := 0 to 26 do begin for Z := 0 to 26 do begin write(Datafile,Probability[X,Y,Z]); end; end; end; end; {procedure WriteData} begin {program SetProb} ZeroProb; Startup; Countem; assign(Datafile,'Prob.dat'); rewrite(Datafile); WriteData; close(DataFile); close(TheFile); write(#7); end. 
unit MobilePermissions.Permissions.Android; interface uses {$IF CompilerVersion >= 33.0} System.Permissions, {$ENDIF} {$IFDEF ANDROID} Androidapi.Helpers, Androidapi.JNI.Os, Androidapi.JNI.JavaTypes, {$ENDIF} System.SysUtils, System.StrUtils, MobilePermissions.Permissions.Interfaces; type TMobilePermissionsAndroid = class(TInterfacedObject, IMobilePermissions) private FAndroidVersion: Integer; procedure SetAndroidVersion; public function Request(Permissions: System.TArray<System.string>): IMobilePermissions; constructor create; destructor Destroy; override; class function New: IMobilePermissions; end; implementation { TMobilePermissionsAndroid } constructor TMobilePermissionsAndroid.create; begin FAndroidVersion := 0; end; destructor TMobilePermissionsAndroid.Destroy; begin inherited; end; procedure TMobilePermissionsAndroid.SetAndroidVersion; {$IFDEF ANDROID} var VVersionOSStr: String; {$ENDIF} begin if FAndroidVersion = 0 then begin {$IFDEF ANDROID} VVersionOSStr := JStringToString(TJBuild_VERSION.JavaClass.RELEASE); if Pos('.', VVersionOSStr) > 0 then VVersionOSStr := Copy(VVersionOSStr, Pos('.', VVersionOSStr)-1); FAndroidVersion := StrToInt(VVersionOSStr); {$ENDIF} end; end; class function TMobilePermissionsAndroid.New: IMobilePermissions; begin result := Self.Create; end; function TMobilePermissionsAndroid.Request(Permissions: System.TArray<System.string>): IMobilePermissions; begin result := Self; SetAndroidVersion; {$IF CompilerVersion >= 33.0} if (FAndroidVersion > 6) then PermissionsService.RequestPermissions(Permissions, nil, nil); {$ENDIF} end; end.
unit uTerminal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Actions, Vcl.ActnList, uMain; type TTerminal = class(TForm) edtMsg: TEdit; memMsg: TMemo; btnClose: TButton; ActionList1: TActionList; actClose: TAction; btnClear: TButton; btnSend: TButton; procedure FormCreate(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure edtMsgKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnCloseClick(Sender: TObject); procedure edtMsgKeyPress(Sender: TObject; var Key: Char); procedure btnSendClick(Sender: TObject); private procedure MsgSendAndRecv; { Private 宣言 } public { Public 宣言 } end; var Terminal: TTerminal; implementation {$R *.dfm} procedure TTerminal.btnClearClick(Sender: TObject); begin memMsg.Clear; edtMsg.Clear; end; procedure TTerminal.btnCloseClick(Sender: TObject); begin Close; end; procedure TTerminal.btnSendClick(Sender: TObject); begin MsgSendAndRecv; end; procedure TTerminal.edtMsgKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_RETURN) then MsgSendAndRecv; end; procedure TTerminal.edtMsgKeyPress(Sender: TObject; var Key: Char); begin // OnKeyDownでBeep音を鳴らさないための処理 if key = #13 then // #13 = Return Key := #0; end; procedure TTerminal.FormCreate(Sender: TObject); begin btnClearClick(btnClear); end; procedure TTerminal.MsgSendAndRecv(); var s,t: string; begin try begin edtMsg.Text := Trim(edtMsg.Text); if Length(edtMsg.Text) = 0 then exit; if edtMsg.Text = 'Z' then // Bufferクリアコマンド GS-232にはない begin Main.Gs232.DoCmd(edtMsg.Text); memMsg.Lines.Add('-->' + edtMsg.Text); exit; end; Main.Gs232.DoCmd(edtMsg.Text); memMsg.Lines.Add('-->' + edtMsg.Text); end; s := Copy(edtMsg.Text, 1, 1); if (s = 'C') or (s = 'N') then // 応答メッセージがあるコマンド // if (s = 'C') or (s = 'N') or (s = 'O') or (s = 'F') then // 'O' 'F' 未対応 begin t := Main.Gs232.DoRecv(20); t := StringReplace(t, #13#10, '', [rfReplaceAll]); if t <> '' then memMsg.Lines.Add('<--' + t); end else if (s = 'H') then // ヘルプコマンド begin t := Main.Gs232.DoRecv(1024); if t <> '' then memMsg.Lines.Add(t); end; finally edtMsg.Clear; edtMSG.SetFocus; end; end; end.
unit OverloadTestForm; interface // running this program raises an exception by design uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.Memo, FMX.Controls.Presentation, FMX.ScrollBox; type TForm1 = class(TForm) Memo1: TMemo; Button1: TButton; Button2: TButton; Button3: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } public procedure Show (const msg: string); end; var Form1: TForm1; implementation {$R *.fmx} uses System.Math; procedure Show (const msg: string); begin Form1.Show(msg) end; procedure ShowMsg (str: string); overload; begin Show ('Message: ' + str); end; procedure ShowMsg (FormatStr: string; Params: array of const); overload; begin Show ('Message: ' + Format (FormatStr, Params)); end; procedure ShowMsg (I: Integer; Str: string); overload; begin ShowMsg (I.ToString + ' ' + Str); end; function Add (N: Integer; S: Single): Single; overload; begin Result := N + S; end; function Add (S: Single; N: Integer): Single; overload; begin Result := N + S; end; procedure NewMessage (Msg: string; Caption: string = 'Message'; Separator: string = ': '); overload; begin Show (Caption + Separator + Msg); end; // uncommenting this overloaded procedure will cause an ambiguous call //procedure NewMessage (Str: string; I: Integer = 0); overload; //begin // writeln (Str + ': ' + IntToStr (I)) //end; procedure TForm1.Button1Click(Sender: TObject); begin ShowMsg ('Hello'); ShowMsg ('Total = %d.', [100]); ShowMsg (10, 'MBytes'); // ShowMsg (10.0, 'Hello'); end; procedure TForm1.Button2Click(Sender: TObject); begin Show (Add (10, 10.0).ToString); Show (Add (10.0, 10).ToString); // Show (Add (10, 10).ToString); // ambiguous call Show (Add (10, 10.ToSingle).ToString); end; procedure TForm1.Button3Click(Sender: TObject); begin NewMessage ('Something wrong here!'); NewMessage ('Something wrong here!', 'Attention'); NewMessage ('Hello', 'Message', '--'); end; procedure TForm1.Show(const msg: string); begin Memo1.Lines.Add(msg); end; end.
//////////////////////////////////////////////////////////////////////////////// // // // FileName : SUITrackBar.pas // Creator : Shen Min // Date : 2002-11-20 V1-V3 // 2003-06-30 V4 // Comment : // // Copyright (c) 2002-2003 Sunisoft // http://www.sunisoft.com // Email: support@sunisoft.com // //////////////////////////////////////////////////////////////////////////////// unit SUITrackBar; interface {$I SUIPack.inc} uses Windows, Messages, SysUtils, Classes, Controls, Graphics, ExtCtrls, Forms, Math, SUIImagePanel, SUIThemes, SUIProgressBar, SUIMgr; type TsuiTrackBar = class(TCustomPanel) private m_BarImage : TPicture; m_Timer : TTimer; m_Slider : TsuiImagePanel; m_Min : Integer; m_Max : Integer; m_Position : Integer; m_LastPos : Integer; m_Orientation : TsuiProgressBarOrientation; m_FileTheme : TsuiFileTheme; m_UIStyle : TsuiUIStyle; m_ShowTick : Boolean; m_Transparent : Boolean; m_OnChange : TNotifyEvent; m_CustomPicture : Boolean; m_LastChange : Integer; m_bSlidingFlag : Boolean; m_MouseDownPos : Integer; m_Frequency : Integer; procedure SetBarImage(const Value: TPicture); procedure SetMax(const Value: Integer); procedure SetMin(const Value: Integer); procedure SetPosition(const Value: Integer); procedure SetUIStyle(const Value: TsuiUIStyle); procedure SetOrientation(const Value: TsuiProgressBarOrientation); function GetSliderImage: TPicture; procedure SetSliderImage(const Value: TPicture); virtual; procedure SetTransparent(const Value: Boolean); procedure UpdateControl(); procedure UpdateSlider(); function GetSliderPosFromPosition() : TPoint; function GetPositionFromFromSliderPos(X, Y : Integer) : Integer; procedure UpdatePositionValue(X, Y : Integer; Update : Boolean); procedure SetPageSize(const Value: Integer); procedure SetLineSize(const Value: Integer); procedure SetShowTick(const Value: Boolean); procedure SetFileTheme(const Value: TsuiFileTheme); procedure SetFrequency(const Value: Integer); procedure OnSliderMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure OnSliderMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure OnTimer(Sender : TObject); procedure SetSize(); procedure PaintTick(const Buf : TBitmap); procedure WMERASEBKGND(var Msg : TMessage); message WM_ERASEBKGND; procedure WMGetDlgCode(var Msg: TWMGetDlgCode); message WM_GETDLGCODE; procedure CMFocusChanged(var Msg: TCMFocusChanged); message CM_FOCUSCHANGED; protected m_PageSize : Integer; m_LineSize : Integer; procedure UpdatePicture(); virtual; function CustomPicture() : Boolean; virtual; function SUICanFocus() : Boolean; virtual; procedure Paint(); override; procedure Resize(); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure KeyDown(var Key: word; Shift: TShiftState); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; function SliderTransparent() : boolean; virtual; property LastChange : Integer read m_LastChange; public m_BarImageBuf : TBitmap; constructor Create(AOwner : TComponent); override; destructor Destroy(); override; property UseCustomPicture : Boolean read m_CustomPicture write m_CustomPicture; published property Orientation : TsuiProgressBarOrientation read m_Orientation write SetOrientation; property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme; property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle; property BarImage : TPicture read m_BarImage write SetBarImage; property SliderImage : TPicture read GetSliderImage write SetSliderImage; property Max : Integer read m_Max write SetMax; property Min : Integer read m_Min write SetMin; property Position : Integer read m_Position write SetPosition; property PageSize : Integer read m_PageSize write SetPageSize; property LineSize : Integer read m_LineSize write SetLineSize; property ShowTick : Boolean read m_ShowTick write SetShowTick; property Transparent : Boolean read m_Transparent write SetTransparent; property Frequency : Integer read m_Frequency write SetFrequency; property Align; property Alignment; property BiDiMode; property Anchors; property Color; property DragKind; property DragMode; property Enabled; property ParentBiDiMode; property ParentFont; property ParentColor; property ParentShowHint; property ShowHint; property TabOrder; property TabStop; property Visible; property OnChange : TNotifyEvent read m_OnChange write m_OnChange; property OnCanResize; property OnClick; property OnContextPopup; property OnDockDrop; property OnDockOver; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDock; property OnStartDrag; property OnUnDock; end; TsuiScrollTrackBar = class(TsuiTrackBar) private function GetSliderVisible: Boolean; procedure SetSliderVisible(const Value: Boolean); protected function SliderTransparent() : boolean; override; function CustomPicture() : Boolean; override; function SUICanFocus() : Boolean; override; public constructor Create(AOwner : TComponent); override; procedure UpdateSliderSize(); property SliderVisible : Boolean read GetSliderVisible write SetSliderVisible; property LastChange; end; implementation uses SUIPublic; { TsuiTrackBar } constructor TsuiTrackBar.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle - [csAcceptsControls]; m_BarImageBuf := TBitmap.Create(); m_BarImage := TPicture.Create(); m_Slider := TsuiImagePanel.Create(self); m_Slider.Parent := self; m_Slider.OnMouseDown := OnSliderMouseDown; m_Slider.OnMouseUp := OnSliderMouseUp; m_Timer := nil; Min := 0; Max := 10; Position := 0; m_LastPos := 0; Orientation := suiHorizontal; PageSize := 2; LineSize := 1; m_ShowTick := true; ParentColor := true; m_bSlidingFlag := false; TabStop := true; m_CustomPicture := false; m_Frequency := 1; m_LastChange := 0; UIStyle := GetSUIFormStyle(AOwner); UpdateSlider(); end; destructor TsuiTrackBar.Destroy; begin m_Slider.Free(); m_Slider := nil; m_BarImage.Free(); m_BarImage := nil; m_BarImageBuf.Free(); m_BarImageBuf := nil; inherited; end; function TsuiTrackBar.GetSliderPosFromPosition: TPoint; var nY : Integer; begin if m_Orientation = suiHorizontal then begin nY := Height - m_Slider.Height; if nY < 0 then nY := 0; Result.Y := nY div 2; if m_Max = m_Min then Result.X := 0 else Result.X := ((m_Position - m_Min) * (Width - m_Slider.Width)) div (m_Max - m_Min); end else begin nY := Width - m_Slider.Width; if nY < 0 then nY := 0; Result.X := nY div 2; if m_Max = m_Min then Result.Y := 0 else Result.Y := ((m_Position - m_Min) * (Height - m_Slider.Height)) div (m_Max - m_Min); end; end; function TsuiTrackBar.GetSliderImage: TPicture; begin Result := m_Slider.Picture; end; procedure TsuiTrackBar.Paint; var Buf : TBitmap; nTop : Integer; R : TRect; begin Buf := TBitmap.Create(); Buf.Width := Width; Buf.Height := Height; if m_Transparent then begin DoTrans(Buf.Canvas, self); end else begin Buf.Canvas.Brush.Color := Color; Buf.Canvas.FillRect(Rect(0, 0, Buf.Width, Buf.Height)); end; if m_Orientation = suiHorizontal then begin nTop := (Height - m_BarImage.Height) div 2; BitBlt( Buf.Canvas.Handle, 0, nTop, Buf.Width, nTop + m_BarImage.Height, m_BarImageBuf.Canvas.Handle, 0, 0, SRCCOPY ); end else begin nTop := (Width - m_BarImage.Height) div 2; BitBlt( Buf.Canvas.Handle, nTop, 0, nTop + m_BarImage.Width, Height, m_BarImageBuf.Canvas.Handle, 0, 0, SRCCOPY ); end; if Focused and TabStop then begin R := Rect(0, 0, Width, Height); Buf.Canvas.Brush.Style := bsSolid; Buf.Canvas.DrawFocusRect(R); end; if m_ShowTick then PaintTick(Buf); Canvas.Draw(0, 0, Buf); Buf.Free(); end; procedure TsuiTrackBar.SetBarImage(const Value: TPicture); begin m_BarImage.Assign(Value); UpdateControl(); end; procedure TsuiTrackBar.SetMax(const Value: Integer); begin if m_Max = Value then Exit; m_Max := Value; if m_Max < m_Min then m_Max := m_Min; if m_Max < m_Position then m_Position := m_Max; UpdateSlider(); end; procedure TsuiTrackBar.SetMin(const Value: Integer); begin if m_Min = Value then Exit; m_Min := Value; if m_Min > m_Max then m_Min := m_Max; if m_Min > m_Position then m_Position := m_Min; UpdateSlider(); end; procedure TsuiTrackBar.SetOrientation(const Value: TsuiProgressBarOrientation); begin if m_Orientation = Value then Exit; m_Orientation := Value; UpdateControl(); end; procedure TsuiTrackBar.SetPosition(const Value: Integer); begin if Value < m_Min then m_Position := m_Min else if Value > m_Max then m_Position := m_Max else m_Position := Value; UpdateSlider(); end; procedure TsuiTrackBar.SetSliderImage(const Value: TPicture); begin m_Slider.Picture.Assign(Value); Repaint(); end; procedure TsuiTrackBar.SetUIStyle(const Value: TsuiUIStyle); begin m_UIStyle := Value; UpdateControl(); {$IFDEF RES_MACOS} if m_UIStyle = MacOS then Transparent := true; {$ENDIF} end; procedure TsuiTrackBar.UpdateSlider; var SliderPos : TPoint; begin SliderPos := GetSliderPosFromPosition(); PlaceControl(m_Slider, SliderPos); Repaint(); if m_Position <> m_LastPos then begin m_LastChange := m_Position - m_LastPos; m_LastPos := m_Position; if Assigned(m_OnChange) then m_OnChange(self); end; end; procedure TsuiTrackBar.Resize; begin inherited; UpdateControl(); end; procedure TsuiTrackBar.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; if not m_bSlidingFlag then begin if (X < 0) or (X > Width) or (Y < 0) or (Y > Height) then if m_Timer <> nil then begin m_Timer.Free(); m_Timer := nil; end; Exit; end; UpdatePositionValue(X, Y, false); PlaceControl(m_Slider, GetSliderPosFromPosition()); if m_Position <> m_LastPos then begin m_LastChange := m_Position - m_LastPos; if Assigned(m_OnChange) then m_OnChange(self); m_LastPos := m_Position; end; end; procedure TsuiTrackBar.OnSliderMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if m_Orientation = suiHorizontal then m_MouseDownPos := X else m_MouseDownPos := Y; m_bSlidingFlag := true; if SUICanFocus() and CanFocus and Enabled then SetFocus(); SetCapture(Handle); if Assigned(OnMouseDown) then OnMouseDown(self, Button, Shift, m_Slider.Left + X, m_Slider.Top + Y); end; procedure TsuiTrackBar.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if Button <> mbLeft then Exit; if m_Orientation = suiHorizontal then begin if X > GetSliderPosFromPosition().X then Position := Math.Min(Position + m_PageSize, GetPositionFromFromSliderPos(X, Y)) else if X < GetSliderPosFromPosition().X then Position := Math.Max(Position - m_PageSize, GetPositionFromFromSliderPos(X, Y)) end else begin if Y > GetSliderPosFromPosition().Y then Position := Math.Min(Position + m_PageSize, GetPositionFromFromSliderPos(X, Y)) else if Y < GetSliderPosFromPosition().Y then Position := Math.Max(Position - m_PageSize, GetPositionFromFromSliderPos(X, Y)) end; if m_Timer = nil then begin m_Timer := TTimer.Create(nil); m_Timer.OnTimer := OnTimer; m_Timer.Interval := 100; m_Timer.Enabled := true; end; if SUICanFocus() and CanFocus() and Enabled then SetFocus(); end; procedure TsuiTrackBar.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if m_Timer <> nil then begin m_Timer.Free(); m_Timer := nil; end; m_bSlidingFlag := false; ReleaseCapture(); end; function TsuiTrackBar.GetPositionFromFromSliderPos(X, Y: Integer): Integer; begin if m_Orientation = suiHorizontal then begin if Width = m_Slider.Width then Result := 0 else Result := Round((X - m_Slider.Width div 2) * (m_Max - m_Min) / (Width - m_Slider.Width)) + m_Min end else begin if Height = m_Slider.Height then Result := 0 else Result := Round((Y - m_Slider.Height div 2) * (m_Max - m_Min) / (Height - m_Slider.Height)) + m_Min; end; end; procedure TsuiTrackBar.SetSize(); begin if m_Orientation = suiHorizontal then Height := Math.Max(m_BarImage.Height, m_Slider.Height) else Width := Math.Max(m_BarImage.Height, m_Slider.Width); Repaint(); end; procedure TsuiTrackBar.WMERASEBKGND(var Msg: TMessage); begin // do nothing end; procedure TsuiTrackBar.UpdatePicture; var R : TRect; bFileTheme : boolean; OutUIStyle : TsuiUIStyle; begin if CustomPicture() then Exit; bFileTheme := UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle); if m_Orientation = suiHorizontal then begin if bFileTheme then begin m_FileTheme.GetBitmap(SUI_THEME_TRACKBAR_BAR, m_BarImage.Bitmap); m_FileTheme.GetBitmap(SUI_THEME_TRACKBAR_SLIDER, SliderImage.Bitmap); end else begin GetInsideThemeBitmap(OutUIStyle, SUI_THEME_TRACKBAR_BAR, m_BarImage.Bitmap); GetInsideThemeBitmap(OutUIStyle, SUI_THEME_TRACKBAR_SLIDER, SliderImage.Bitmap); end; m_BarImageBuf.Width := Width; m_BarImageBuf.Height := m_BarImage.Height; R := Rect(0, 0, m_BarImageBuf.Width, m_BarImageBuf.Height); m_BarImageBuf.Canvas.Brush.Color := Color; m_BarImageBuf.Canvas.FillRect(R); SpitDrawHorizontal(m_BarImage.Bitmap, m_BarImageBuf.Canvas, R, false); end else begin if bFileTheme then begin m_FileTheme.GetBitmap(SUI_THEME_TRACKBAR_BAR, m_BarImage.Bitmap); m_FileTheme.GetBitmap(SUI_THEME_TRACKBAR_SLIDER_V, SliderImage.Bitmap); end else begin GetInsideThemeBitmap(OutUIStyle, SUI_THEME_TRACKBAR_BAR, m_BarImage.Bitmap); GetInsideThemeBitmap(OutUIStyle, SUI_THEME_TRACKBAR_SLIDER_V, SliderImage.Bitmap); end; m_BarImageBuf.Width := Height; m_BarImageBuf.Height := m_BarImage.Height; R := Rect(0, 0, m_BarImageBuf.Width, m_BarImageBuf.Height); m_BarImageBuf.Canvas.Brush.Color := Color; m_BarImageBuf.Canvas.FillRect(R); SpitDrawHorizontal(m_BarImage.Bitmap, m_BarImageBuf.Canvas, R, false); RoundPicture(m_BarImageBuf); end; m_Slider.Transparent := SliderTransparent(); m_Slider.AutoSize := true; end; procedure TsuiTrackBar.UpdateControl; begin UpdatePicture(); SetSize(); UpdateSlider(); Repaint(); end; procedure TsuiTrackBar.UpdatePositionValue(X, Y : Integer; Update : Boolean); var nPos : Integer; begin nPos := GetPositionFromFromSliderPos(X, Y); if nPos > m_Max then nPos := m_Max else if nPos < m_Min then nPos := m_Min; if Update then Position := nPos else m_Position := nPos; end; procedure TsuiTrackBar.OnTimer(Sender: TObject); var P : TPoint; begin GetCursorPos(P); P := ScreenToClient(P); if m_Orientation = suiHorizontal then begin if P.X > GetSliderPosFromPosition().X then Position := Math.Min(Position + 3 * m_PageSize, GetPositionFromFromSliderPos(P.X, P.Y)) else if P.X < GetSliderPosFromPosition().X then Position := Math.Max(Position - 3 * m_PageSize, GetPositionFromFromSliderPos(P.X, P.Y)) end else begin if P.Y > GetSliderPosFromPosition().Y then Position := Math.Min(Position + m_PageSize, GetPositionFromFromSliderPos(P.X, P.Y)) else if P.Y < GetSliderPosFromPosition().Y then Position := Math.Max(Position - m_PageSize, GetPositionFromFromSliderPos(P.X, P.Y)) end; end; procedure TsuiTrackBar.SetPageSize(const Value: Integer); begin if (Value < 0) or (Value > m_Max) then Exit; m_PageSize := Value; end; procedure TsuiTrackBar.CMFocusChanged(var Msg: TCMFocusChanged); begin inherited; Repaint(); end; procedure TsuiTrackBar.SetFileTheme(const Value: TsuiFileTheme); begin m_FileTheme := Value; SetUIStyle(m_UIStyle); end; procedure TsuiTrackBar.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if ( (Operation = opRemove) and (AComponent = m_FileTheme) )then begin m_FileTheme := nil; SetUIStyle(SUI_THEME_DEFAULT); end; end; procedure TsuiTrackBar.SetTransparent(const Value: Boolean); begin m_Transparent := Value; Repaint(); end; procedure TsuiTrackBar.KeyDown(var Key: word; Shift: TShiftState); begin inherited; case Key of VK_PRIOR: Position := Position - PageSize; VK_NEXT: Position := Position + PageSize; VK_END: Position := Max; VK_HOME: Position := Min; VK_LEFT: Position := Position - LineSize; VK_RIGHT: Position := Position + LineSize; VK_UP: Position := Position - LineSize; VK_DOWN: Position := Position + LineSize; end; end; procedure TsuiTrackBar.WMGetDlgCode(var Msg: TWMGetDlgCode); begin inherited; Msg.Result := DLGC_WANTARROWS; end; procedure TsuiTrackBar.SetLineSize(const Value: Integer); begin if (Value < 0) or (Value > m_Max) then Exit; m_LineSize := Value; end; procedure TsuiTrackBar.PaintTick(const Buf : TBitmap); var x : Integer; i : Integer; nLen : Integer; nStart : Integer; Freq : Integer; begin if m_Max = m_Min then Exit; if m_Orientation = suiHorizontal then begin nLen := Width - m_Slider.Width; nStart := m_Slider.Width div 2; Freq := 0; for i := m_Min to m_Max do begin if i <> m_Max then begin if Freq <> m_Frequency then begin Inc(Freq); if Freq <> 1 then Continue end else Freq := 1; end; x := nStart + nLen * (i - m_Min) div (m_Max - m_Min); Buf.Canvas.MoveTo(x, Height - 3); Buf.Canvas.LineTo(x, Height); end; end else begin nLen := Height - m_Slider.Height; nStart := m_Slider.Height div 2; Freq := 0; for i := m_Min to m_Max do begin if i <> m_Max then begin if Freq <> m_Frequency then begin Inc(Freq); if Freq <> 1 then Continue end else Freq := 1; end; x := nStart + nLen * (i - m_Min) div (m_Max - m_Min); Buf.Canvas.MoveTo(0, x); Buf.Canvas.LineTo(3, x); Buf.Canvas.MoveTo(Width - 3, x); Buf.Canvas.LineTo(Width, x); end; end; end; procedure TsuiTrackBar.SetShowTick(const Value: Boolean); begin m_ShowTick := Value; Repaint(); end; function TsuiTrackBar.SliderTransparent: boolean; begin if m_Orientation = suiHorizontal then Result := true else Result := false; end; function TsuiTrackBar.CustomPicture: Boolean; begin Result := m_CustomPicture; end; procedure TsuiTrackBar.SetFrequency(const Value: Integer); begin m_Frequency := Value; Repaint(); end; procedure TsuiTrackBar.OnSliderMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Assigned(OnMouseUp) then OnMouseUp(self, Button, Shift, m_Slider.Left + X, m_Slider.Top + Y); end; function TsuiTrackBar.SUICanFocus: Boolean; begin Result := true; end; { TsuiScrollTrackBar } constructor TsuiScrollTrackBar.Create(AOwner: TComponent); begin inherited; TabStop := false; m_Slider.TabStop := false; m_Slider.ControlStyle := self.ControlStyle; end; function TsuiScrollTrackBar.CustomPicture: Boolean; begin Result := true; end; function TsuiScrollTrackBar.GetSliderVisible: Boolean; begin Result := m_Slider.Visible; end; procedure TsuiScrollTrackBar.SetSliderVisible(const Value: Boolean); begin if m_Slider.Visible <> Value then m_Slider.Visible := Value; end; function TsuiScrollTrackBar.SliderTransparent: boolean; begin Result := false; end; function TsuiScrollTrackBar.SUICanFocus: Boolean; begin Result := false; end; procedure TsuiScrollTrackBar.UpdateSliderSize; begin m_Slider.AutoSize := true; end; end.
unit UserIterface; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DimensionsUnit, DimensionGraphicsUnit, StdCtrls, ComCtrls, ExtCtrls, RuleConfig, CreatePoints, ExtDlgs; type TUserInterfaceForm = class(TForm) Panel1: TPanel; Panel2: TPanel; PageControl1: TPageControl; tsOneFrame: TTabSheet; tsAllFrames: TTabSheet; btnChooseRule: TButton; CreatePointsBtn: TButton; IterateBtn: TButton; IterationsLbl: TLabel; SaveDataBtn: TButton; SaveImageBtn: TButton; LoadDataBtn: TButton; IterateCountEdit: TEdit; UpDown1: TUpDown; OneFrameImage: TImage; AllFramesImage: TImage; Panel3: TPanel; FrameLabel: TLabel; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; Panel4: TPanel; NextBtn: TButton; PrevBtn: TButton; PlayBtn: TButton; SavePictureDialog1: TSavePictureDialog; // procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnChooseRuleClick(Sender: TObject); procedure CreatePointsBtnClick(Sender: TObject); procedure NextBtnClick(Sender: TObject); procedure PrevBtnClick(Sender: TObject); procedure IterateBtnClick(Sender: TObject); procedure PageControl1Change(Sender: TObject); procedure SaveDataBtnClick(Sender: TObject); procedure LoadDataBtnClick(Sender: TObject); procedure SaveImageBtnClick(Sender: TObject); private fZSpaceIndex: Integer; function GetZSpaceIndex: Integer; procedure SetZSpaceIndex(const Value: Integer); procedure RefreshViews; { Private declarations } public Automata : TAutomata; property ZSpaceIndex : Integer read GetZSpaceIndex write SetZSpaceIndex; end; var UserInterfaceForm: TUserInterfaceForm; implementation {$R *.dfm} procedure TUserInterfaceForm.FormCreate(Sender: TObject); begin Automata := TAutomata.Create; ZSpaceIndex := 1; UpDown1.Position := 1; end; procedure TUserInterfaceForm.FormDestroy(Sender: TObject); begin Automata.Free; end; procedure TUserInterfaceForm.btnChooseRuleClick(Sender: TObject); begin RuleConfigForm.ShowModal; ZSpaceIndex := 1; end; procedure TUserInterfaceForm.CreatePointsBtnClick(Sender: TObject); begin CreatePointsFrm.ShowModal; ZSpaceIndex := 1; end; function TUserInterfaceForm.GetZSpaceIndex: Integer; begin Result := FZSpaceIndex; end; procedure TUserInterfaceForm.SetZSpaceIndex(const Value: Integer); var NewVal : Integer; begin NewVal := Value; if (NewVal < 1) then NewVal := SpaceSize; if (NewVal > SpaceSize) then NewVal := 1; FZSpaceIndex := NewVal; RefreshViews; end; procedure TUserInterfaceForm.RefreshViews; begin if PageControl1.ActivePageIndex = 0 then begin OneFrameImage.Picture.Assign(XYSpaceToBitmap(Automata.Space, ZSpaceIndex)); FrameLabel.Caption := 'SLICE:' + IntToStr(ZSpaceIndex); end else begin AllFramesImage.Picture.Assign(SpaceToBitmap(Automata.Space)); IterationsLbl.Caption := 'Iterations:' + IntToStr(Automata.Iterations); end; end; procedure TUserInterfaceForm.NextBtnClick(Sender: TObject); begin ZSpaceIndex := ZSpaceIndex + 1; end; procedure TUserInterfaceForm.PrevBtnClick(Sender: TObject); begin ZSpaceIndex := ZSpaceIndex - 1; end; procedure TUserInterfaceForm.IterateBtnClick(Sender: TObject); var IterateCount : Integer; begin for IterateCount := 1 to UpDown1.Position do begin Automata.Iterate; Application.ProcessMessages; IterationsLbl.Caption := 'Iterations:' + IntToStr(Automata.Iterations); end; ZSpaceIndex := 1; end; procedure TUserInterfaceForm.PageControl1Change(Sender: TObject); begin RefreshViews; end; procedure TUserInterfaceForm.SaveDataBtnClick(Sender: TObject); begin if SaveDialog1.Execute then begin Automata.SaveToText(SaveDialog1.FileName); end; end; procedure TUserInterfaceForm.LoadDataBtnClick(Sender: TObject); begin if OpenDialog1.Execute then begin Automata.LoadFromText(OpenDialog1.FileName); ZSpaceIndex := 1; end; end; procedure TUserInterfaceForm.SaveImageBtnClick(Sender: TObject); begin if SavePictureDialog1.Execute then begin OneFrameImage.Picture.SaveToFile(SavePictureDialog1.FileName); end; end; end.
unit ncTipoTran; interface uses SysUtils, Variants, DB, MD5, Dialogs, Classes, Windows, ClasseCS, ncClassesBase; type TncTipoTran = class ( TncClasse ) private Ftipo: Byte; Fuser: Boolean; Festoque: Boolean; Fcaixa: Boolean; Fnome: String; Fentrada: Boolean; Femite_nfe: Boolean; Fmovest: Boolean; Fatualiza_custo: Boolean; Fvisivel: Boolean; Fpagto: Boolean; Fsel_endereco: Boolean; Ftipocad: Byte; Fprecocusto_nfe: Boolean; protected function GetChave: Variant; override; public constructor Create; function TipoClasse: Integer; override; function NomeTela: String; published property Tipo: Byte read FTipo write FTipo; property User: Boolean read FUser write FUser; property Estoque: Boolean read Festoque write FEstoque; property Caixa: Boolean read Fcaixa write FCaixa; property Nome: String read Fnome write FNome; property Entrada: Boolean read FEntrada write FEntrada; property Emite_nfe: Boolean read Femite_nfe write Femite_nfe; property MovEst: Boolean read Fmovest write Fmovest; property Atualiza_Custo: Boolean read Fatualiza_custo write FAtualiza_Custo; property Visivel: Boolean read Fvisivel write FVisivel; property Pagto: Boolean read Fpagto write FPagto; property Sel_Endereco: Boolean read Fsel_endereco write Fsel_endereco; property TipoCad: Byte read Ftipocad write Ftipocad; property PrecoCusto_nfe: Boolean read Fprecocusto_nfe write Fprecocusto_nfe; end; TncListaTipoTran = class ( TListaClasseCS ) private function GetTipoTran(I: Integer): TncTipoTran; function GetPorTipo(aTipo: Byte): TncTipoTran; public constructor Create; procedure Assign(aFrom: TncListaTipoTran); destructor Destroy; override; function NewItem: TncTipoTran; function MovEst(aTipo: Byte): Boolean; property Itens[I: Integer]: TncTipoTran read GetTipoTran; default; property PorTipo[aID: Byte]: TncTipoTran read GetPorTipo; end; var gListaTipoTran : TncListaTipoTran = nil; implementation { TncTipoTran } uses uNexTransResourceStrings_PT; constructor TncTipoTran.Create; begin inherited; Ftipo := 0; Fnome := ''; Ftipocad := tipocad_nenhum; Fuser := False; Fprecocusto_nfe := False; Festoque := False; Fcaixa := False; Fentrada := False; Femite_nfe := False; Fmovest := False; Fatualiza_custo := False; Fvisivel := False; Fpagto := False; Fsel_endereco := False; end; function TncTipoTran.GetChave: Variant; begin Result := FTipo; end; function TncTipoTran.NomeTela: String; begin case Tipo of trEstEntrada : Result := rsEntradaEstTela; trEstSaida : Result := rsSaidaEstTela; else Result := Nome; end; end; function TncTipoTran.TipoClasse: Integer; begin Result := tcTipoTran; end; { TncListaTipoTran } procedure TncListaTipoTran.Assign(aFrom: TncListaTipoTran); var i: integer; begin Limpa; for I := 0 to aFrom.Count - 1 do NewItem.Assign(aFrom.Itens[i]); end; constructor TncListaTipoTran.Create; begin inherited Create(tcTipoTran); end; destructor TncListaTipoTran.Destroy; var i: integer; begin for I := 0 to Count-1 do Itens[i].ProcNotificar := nil; inherited; end; function TncListaTipoTran.GetPorTipo(aTipo: Byte): TncTipoTran; var I: Integer; begin for I := 0 to Count - 1 do if Itens[I].Tipo = aTipo then begin Result := Itens[I]; Exit; end; Result := nil; end; function TncListaTipoTran.GetTipoTran(I: Integer): TncTipoTran; begin Result := TncTipoTran(GetItem(I)); end; function TncListaTipoTran.MovEst(aTipo: Byte): Boolean; var T: TncTipoTran; begin T := PorTipo[aTipo]; Result := Assigned(T) and T.MovEst; end; function TncListaTipoTran.NewItem: TncTipoTran; begin Result := TncTipoTran.Create; Add(Result); end; initialization gListaTipoTran := TncListaTipoTran.Create; finalization gListaTipoTran.Free; end.
unit Walkers; interface uses Canvases, RootObject; type IWalker = interface ['{8D1FF79F-4251-4A1D-8214-0ADE721C009B}'] procedure SetAngle(Val: extended); function GetAngle: extended; property Angle: extended read GetAngle write SetAngle; procedure Turn(AAngle: extended); procedure Forward(Canvas: IMyCanvas; Distance: extended); end; TAngleHolder = class(TRootObject) protected Angle: extended; procedure SetAngle(Val: extended); function GetAngle: extended; procedure Turn(AAngle: extended); public constructor Create; override; end; TStraightWalker = class(TAngleHolder, IWalker) public procedure Forward(Canvas: IMyCanvas; Distance: extended); end; TCurveWalker = class(TStraightWalker, IWalker) public procedure Forward(Canvas: IMyCanvas; Distance: extended); end; implementation { TAngleHolder } constructor TAngleHolder.Create; begin end; procedure TAngleHolder.SetAngle(Val: extended); begin Angle := Val; end; function TAngleHolder.GetAngle: extended; begin Result := Angle; end; procedure TAngleHolder.Turn(AAngle: extended); begin Angle := Angle + AAngle; end; { TStraightWalker } procedure TStraightWalker.Forward(Canvas: IMyCanvas; Distance: extended); var p: TPointEx; begin p := Canvas.GetCurPoint; p.X := p.X + Distance * cos(Angle); p.Y := p.Y + Distance * sin(Angle); Canvas.LineTo(p) end; { TCurveWalker } procedure TCurveWalker.Forward(Canvas: IMyCanvas; Distance: extended); const pcnt = 8; // кол-во сегментов на которое разбиваем дистанцию turn = 0.0375 * pi; // угол повората между сегментами var ang: extended; dist: extended; i: integer; begin ang := Angle; dist := Distance / pcnt; for i := 1 to pcnt do begin inherited Forward(Canvas, dist); Angle := ang + i * turn; end; Angle := ang; end; end.
(* SafeArrayStackUnit: SWa, 2020-05-27 *) (* ------------------- *) (* A stack which stores its elements in an array and prevents stack over-/ *) (* underflows. *) (* ========================================================================= *) UNIT SafeArrayStackUnit; INTERFACE USES ArrayStackUnit; TYPE SafeArrayStack = ^SafeArrayStackObj; SafeArrayStackObj = OBJECT(ArrayStackObj) PUBLIC CONSTRUCTOR Init(size: INTEGER); DESTRUCTOR Done; VIRTUAL; PROCEDURE Push(e: INTEGER); VIRTUAL; PROCEDURE Pop(VAR e: INTEGER); VIRTUAL; END; (* SafeArrayStackObj *) FUNCTION NewSafeArrayStack(size: INTEGER): SafeArrayStack; IMPLEMENTATION CONSTRUCTOR SafeArrayStackObj.Init(size: INTEGER); BEGIN (* SafeArrayStackObj.Init *) INHERITED Init(size); END; (* SafeArrayStackObj.Init*) DESTRUCTOR SafeArrayStackObj.Done; BEGIN (* SafeArrayStackObj.Done *) INHERITED Done; END; (* SafeArrayStackObj.Done *) PROCEDURE SafeArrayStackObj.Push(e: INTEGER); BEGIN (* SafeArrayStackObj.Push *) IF (IsFull) THEN BEGIN WriteLn('ERROR: Stack is full'); HALT; END; (* IF *) INHERITED Push(e); END; (* SafeArrayStackObj.Push *) PROCEDURE SafeArrayStackObj.Pop(VAR e: INTEGER); BEGIN (* SafeArrayStackObj.Pop *) IF (IsEmpty) THEN BEGIN WriteLn('ERROR: Stack is empty'); HALT; END; (* IF *) INHERITED Pop(e); END; (* SafeArrayStackObj.Pop *) FUNCTION NewSafeArrayStack(size: INTEGER): SafeArrayStack; VAR a: SafeArrayStack; BEGIN (* NewSafeArrayStack *) New(a, Init(size)); NewSafeArrayStack := a; END; (* NewSafeArrayStack *) END. (* SafeArrayStackUnit *)
unit xElecLine; interface uses xElecPoint, SysUtils, Classes; type /// <summary> /// 电线或一点类 /// </summary> TElecLine = class private FCurrent: TElecPoint; FVoltage: TElecPoint; FLineName: string; FOnChange: TNotifyEvent; FConnPoints: TStringList; FOnwner: TObject; FCurrentList: TStringList; FWID: Integer; FOnChangeCurrent: TNotifyEvent; FOnChangeVol: TNotifyEvent; procedure ValueChange(Sender : TObject); procedure ValueChangeVol(Sender : TObject); procedure ValueChangeCurrent(Sender : TObject); function GetConnPointInfo(nIndex: Integer): TElecLine; public constructor Create; destructor Destroy; override; /// <summary> /// 所属对象 /// </summary> property Onwner : TObject read FOnwner write FOnwner; /// <summary> /// 线名称 /// </summary> property LineName : string read FLineName write FLineName; /// <summary> /// 电压 /// </summary> property Voltage : TElecPoint read FVoltage write FVoltage; /// <summary> /// 电流 /// </summary> property Current : TElecPoint read FCurrent write FCurrent; /// <summary> /// 改变事件 /// </summary> property OnChange : TNotifyEvent read FOnChange write FOnChange; /// <summary> /// 改变事件 /// </summary> property OnChangeVol : TNotifyEvent read FOnChangeVol write FOnChangeVol; /// <summary> /// 改变事件 /// </summary> property OnChangeCurrent : TNotifyEvent read FOnChangeCurrent write FOnChangeCurrent; /// <summary> /// 值赋值 /// </summary> procedure AssignValue(ALine : TElecLine); /// <summary> /// 清除权值 /// </summary> procedure ClearWValue; /// <summary> /// 传递电压值 /// </summary> procedure SendVolValue; /// <summary> /// 递归电流权值 /// </summary> procedure CalcCurrWValue; /// <summary> /// 传递电流值 /// </summary> procedure SendCurrentValue; /// <summary> /// 权值ID /// </summary> property WID : Integer read FWID write FWID; public /// <summary> /// 连接点列表 /// </summary> property ConnPoints : TStringList read FConnPoints write FConnPoints; property ConnPointInfo[nIndex:Integer] : TElecLine read GetConnPointInfo; /// <summary> /// 添加连接点 /// </summary> procedure ConnPointAdd(APoint : TElecLine; bSetOther : Boolean = True); /// <summary> /// 删除连接点 /// </summary> procedure ConnPointDel(APoint : TElecLine); /// <summary> /// 获取连接点 /// </summary> function GetConnPoint(APoint : TElecLine): Integer; /// <summary> /// 清空连接点 /// </summary> procedure ClearConnPoint; public /// <summary> /// 实际流经电流列表 /// </summary> property CurrentList : TStringList read FCurrentList write FCurrentList; /// <summary> /// 清空电流列表 /// </summary> procedure ClearCurrentList; /// <summary> /// 添加电流到列表 /// </summary> procedure AddCurrent(AElecLine : TElecLine); /// <summary> /// 设置值 /// </summary> procedure SetValue(sLineName: string; dVolValue, dVolAngle, dCurrValue, dCurrAngle : Double; bIsLowPoint, bIsHighPoint, bVolRoot : Boolean); end; implementation uses xElecFunction; { TElecLine } procedure TElecLine.AddCurrent(AElecLine: TElecLine); begin FCurrentList.AddObject('', AElecLine); end; procedure TElecLine.AssignValue(ALine: TElecLine); begin if Assigned(ALine) then begin FVoltage.AssignValue(ALine.Voltage); FCurrent.AssignValue(ALine.Current); end; end; procedure TElecLine.ConnPointAdd(APoint: TElecLine; bSetOther : Boolean); var nIndex : Integer; begin if Assigned(APoint) then begin // 本节点添加到对方节点的连接列表里 if bSetOther then APoint.ConnPointAdd(Self, False); nIndex := GetConnPoint(APoint); if nIndex = -1 then begin FConnPoints.AddObject('', APoint); end; end; end; procedure TElecLine.CalcCurrWValue; procedure SetValue( nWValue, nWID: Integer; AElec : TElecLine); var i: Integer; AConn : TElecLine; AConnW, AConnElec : TWeightValue; nValue : Integer; begin AConnElec := AElec.Current.WeightValue[nWID]; nValue := AConnElec.WValue + 1; for i := 0 to AElec.ConnPoints.Count - 1 do begin AConn := TElecLine(AElec.ConnPoints.Objects[i]); AConnW := AConn.Current.WeightValue[nWID]; if AConnW.WValue > AConnElec.WValue then begin AConnW.WValue := nValue; SetValue(AConnW.WValue, nWID, AConn); end; end; end; var AW : TWeightValue; j : Integer; begin if FCurrent.IsLowPoint and (FCurrent.WValueList.Count > 0) then begin for j := 0 to FCurrent.WValueList.Count - 1 do begin AW := TWeightValue(FCurrent.WValueList.Objects[j]); SetValue(AW.WValue, AW.WID, Self); end; end; end; procedure TElecLine.ClearConnPoint; var i : Integer; begin // 删除对方节点最本节点的连接 for i := 0 to FConnPoints.Count - 1 do TElecLine(FConnPoints.Objects[i]).ConnPointDel(Self); FConnPoints.Clear; end; procedure TElecLine.ClearCurrentList; begin FCurrentList.Clear; end; procedure TElecLine.ClearWValue; begin FCurrent.ClearWValue; end; procedure TElecLine.ConnPointDel(APoint: TElecLine); var nIndex : Integer; begin nIndex := GetConnPoint(APoint); if nIndex <> -1 then begin FConnPoints.Delete(nIndex); end; end; function TElecLine.GetConnPoint(APoint: TElecLine): Integer; var i: Integer; begin Result := -1; if Assigned(APoint) then begin for i := 0 to FConnPoints.Count - 1 do begin if FConnPoints.Objects[i] = APoint then begin Result := i; Break; end; end; end; end; constructor TElecLine.Create; begin FCurrent:= TElecPoint.Create; FVoltage:= TElecPoint.Create; FConnPoints:= TStringList.Create; FCurrentList:= TStringList.Create; FCurrent.OnChange := ValueChangeCurrent; FVoltage.OnChange := ValueChangeVol; FCurrent.Owner := Self; FVoltage.Owner := Self; FWID := C_WEIGHT_VALUE_INVALID; end; destructor TElecLine.Destroy; begin FCurrent.Free; FVoltage.Free; FConnPoints.Free; FCurrentList.Free; inherited; end; function TElecLine.GetConnPointInfo( nIndex: Integer): TElecLine; begin if (nIndex >= 0) and (nIndex < FConnPoints.Count) then begin Result := TElecLine(FConnPoints.Objects[nIndex]); end else begin Result := nil; end; end; procedure TElecLine.SendCurrentValue; procedure SetValue( AElecRoot, AElec : TElecLine; nWID : Integer); var i: Integer; AConn : TElecLine; AConnW, AConnElec : TWeightValue; begin for i := 0 to AElec.ConnPoints.Count - 1 do begin AConn := TElecLine(AElec.ConnPoints.Objects[i]); AConnW := AConn.Current.WeightValue[nWID]; AConnElec := AElec.Current.WeightValue[nWID]; if (AConnW.WValue < AConnElec.WValue) and (AConnW.WValue < C_WEIGHT_VALUE_INVALID) then begin AConn.AddCurrent(AElecRoot); SetValue(AElecRoot, AConn, nWID); end; end; end; begin if FCurrent.IsHighPoint then begin AddCurrent(Self); SetValue( Self, Self, FWID); end; end; procedure TElecLine.SendVolValue; procedure SetValue( dVolValue, dAngle : Double; AElec : TElecLine); var i: Integer; AConn : TElecLine; begin if Abs(dVolValue) > 0.001 then begin for i := 0 to AElec.ConnPoints.Count - 1 do begin AConn := TElecLine(AElec.ConnPoints.Objects[i]); if (Abs(AConn.Voltage.Value) < 0.0001) then begin AConn.Voltage.Angle := dAngle; AConn.Voltage.Value := dVolValue; SetValue(dVolValue,dAngle, AConn); end; end; end; end; begin SetValue(FVoltage.Value, FVoltage.Angle, Self); end; procedure TElecLine.SetValue(sLineName: string; dVolValue, dVolAngle, dCurrValue, dCurrAngle: Double; bIsLowPoint, bIsHighPoint, bVolRoot: Boolean); begin FLineName := sLineName; FVoltage.Value := dVolValue; FVoltage.Angle := dVolAngle; FCurrent.Value := dCurrValue; FCurrent.Angle := dCurrAngle; FCurrent.IsLowPoint := bIsLowPoint; FCurrent.IsHighPoint := bIsHighPoint; FVoltage.IsVolRoot := bVolRoot; end; procedure TElecLine.ValueChange(Sender: TObject); begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TElecLine.ValueChangeCurrent(Sender: TObject); begin ValueChange(Sender); if Assigned(FOnChangeCurrent) then FOnChangeCurrent(Self); end; procedure TElecLine.ValueChangeVol(Sender: TObject); begin ValueChange(Sender); if Assigned(FOnChangeVol) then FOnChangeVol(Self); end; end.
unit U.SampleData; interface type TSampleData = class private class procedure CreatePizzas; class procedure CreateCustomers; class procedure CreateOrders; public class procedure CheckForSampleData; end; implementation uses Model.Interfaces, iORM, System.IOUtils, Model.Order, System.SysUtils, Model.OrderItem, FireDAC.Comp.Client, Model.PhoneNumber, Model.Customer; { TsampleData } class procedure TSampleData.CheckForSampleData; var LMemTable: TFDMemTable; begin io.StartTransaction; try try LMemTable := io.SQL('SELECT COUNT(*) FROM [TPizza]').ToMemTable; if LMemTable.Fields[0].AsInteger = 0 then begin Self.CreatePizzas; Self.CreateCustomers; Self.CreateOrders; end; io.CommitTransaction; except io.RollbackTransaction; end; finally if Assigned(LMemTable) then LMemTable.Free; end; end; class procedure TSampleData.CreateCustomers; var LCustomer: TCustomer; begin LCustomer := TCustomer.Create; LCustomer.FirstName := 'Maurizio'; LCustomer.LastName := 'Del Magno'; LCustomer.Address := 'Riccione, viale Napoli 24'; LCustomer.Numbers.Add( TPhoneNumber.Create('Mobile', '329 058 3381') ); LCustomer.Numbers.Add( TPhoneNumber.Create('Home', '0541 605 905') ); LCustomer.Numbers.Add( TPhoneNumber.Create('Office', '0541 127 687') ); io.Persist(LCustomer); LCustomer.Free; LCustomer := TCustomer.Create; LCustomer.FirstName := 'Omar'; LCustomer.LastName := 'Bossoni'; LCustomer.Address := 'Quinzano d''Oglio, via Dei Mille 3'; LCustomer.Numbers.Add( TPhoneNumber.Create('Mobile', '336 172 3874') ); LCustomer.Numbers.Add( TPhoneNumber.Create('Office', '030 388 998') ); io.Persist(LCustomer); LCustomer.Free; LCustomer := TCustomer.Create; LCustomer.FirstName := 'Thomas'; LCustomer.LastName := 'Ranzetti'; LCustomer.Address := 'Quinzano d''Oglio, via Roma 45'; LCustomer.Numbers.Add( TPhoneNumber.Create('Mobile', '348 736 8729') ); io.Persist(LCustomer); LCustomer.Free; LCustomer := TCustomer.Create; LCustomer.FirstName := 'Fabio'; LCustomer.LastName := 'Codebue'; LCustomer.Address := 'Brescia, via Della Repubblica 10'; LCustomer.Numbers.Add( TPhoneNumber.Create('Mobile', '329 835 7638') ); LCustomer.Numbers.Add( TPhoneNumber.Create('Mobile', '331 763 2788') ); LCustomer.Numbers.Add( TPhoneNumber.Create('Home', '030 798 387') ); LCustomer.Numbers.Add( TPhoneNumber.Create('Office', '030 542 983') ); io.Persist(LCustomer); LCustomer.Free; LCustomer := TCustomer.Create; LCustomer.FirstName := 'Marco'; LCustomer.LastName := 'Mottadelli'; LCustomer.Address := 'Besana in Brianza, via Einstein 5'; LCustomer.Numbers.Add( TPhoneNumber.Create('Mobile', '328 123 5678') ); LCustomer.Numbers.Add( TPhoneNumber.Create('Office', '021 865 879') ); io.Persist(LCustomer); LCustomer.Free; LCustomer := TCustomer.Create; LCustomer.FirstName := 'Carlo'; LCustomer.LastName := 'Narcisi'; LCustomer.Address := 'Rimini, viale Cervino 123'; LCustomer.Numbers.Add( TPhoneNumber.Create('Mobile', '387 143 8739') ); LCustomer.Numbers.Add( TPhoneNumber.Create('Home', '0541 694 289') ); LCustomer.Numbers.Add( TPhoneNumber.Create('Office', '0541 987 654') ); io.Persist(LCustomer); LCustomer.Free; LCustomer := TCustomer.Create; LCustomer.FirstName := 'Antonio'; LCustomer.LastName := 'Polito'; LCustomer.Address := 'Battipaglia, via Dei Luminari 187'; LCustomer.Numbers.Add( TPhoneNumber.Create('Mobile', '399 736 9988') ); LCustomer.Numbers.Add( TPhoneNumber.Create('Office', '081 555 666') ); io.Persist(LCustomer); LCustomer.Free; end; class procedure TSampleData.CreateOrders; var LOrder: TOrder; begin LOrder := TOrder.Create; LOrder.Note := '19:30 BEN COTTA!!!'; LOrder.Customer := io.Load<TCustomer>.ByOID(1).ToObject; LOrder.OrderItems.Add( TOrderItem.Create(io.Load<IPizza>.ByOID(1).ToObject, 1) ); LOrder.OrderItems.Add( TOrderItem.Create(io.Load<IPizza>.ByOID(2).ToObject, 3) ); io.Persist(LOrder); LOrder.Free; LOrder := TOrder.Create; LOrder.Note := '19:45'; LOrder.Customer := io.Load<TCustomer>.ByOID(2).ToObject; LOrder.OrderItems.Add( TOrderItem.Create(io.Load<IPizza>.ByOID(2).ToObject, 3) ); LOrder.OrderItems.Add( TOrderItem.Create(io.Load<IPizza>.ByOID(3).ToObject, 5) ); LOrder.OrderItems.Add( TOrderItem.Create(io.Load<IPizza>.ByOID(4).ToObject, 1) ); io.Persist(LOrder); LOrder.Free; LOrder := TOrder.Create; LOrder.Note := '20:05 ALLERGICO AI CAPPERI'; LOrder.Customer := io.Load<TCustomer>.ByOID(3).ToObject; LOrder.OrderItems.Add( TOrderItem.Create(io.Load<IPizza>.ByOID(1).ToObject, 3) ); LOrder.OrderItems.Add( TOrderItem.Create(io.Load<IPizza>.ByOID(5).ToObject, 2) ); LOrder.OrderItems.Add( TOrderItem.Create(io.Load<IPizza>.ByOID(6).ToObject, 2) ); io.Persist(LOrder); LOrder.Free; end; class procedure TSampleData.CreatePizzas; var LPizza: IPizza; begin LPizza := io.Create<IPizza>; LPizza.Name := 'Margherita pizza'; LPizza.Price := 4.5; LPizza.Photo.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'MargheritaPizza.jpg')); io.Persist(LPizza); LPizza := io.Create<IPizza>; LPizza.Name := 'Capricciosa pizza'; LPizza.Price := 6.5; LPizza.Photo.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'CapricciosaPizza.jpg')); io.Persist(LPizza); LPizza := io.Create<IPizza>; LPizza.Name := 'Pepperoni pizza'; LPizza.Price := 5.7; LPizza.Photo.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'PepperoniPizza.jpg')); io.Persist(LPizza); LPizza := io.Create<IPizza>; LPizza.Name := 'Love pizza'; LPizza.Price := 8.5; LPizza.Photo.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'LovePizza.jpg')); io.Persist(LPizza); LPizza := io.Create<IPizza>; LPizza.Name := 'Four seasons pizza'; LPizza.Price := 7.5; LPizza.Photo.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'Pizza4Stagioni.jpg')); io.Persist(LPizza); LPizza := io.Create<IPizza>; LPizza.Name := 'Tuna & onion pizza'; LPizza.Price := 7.2; LPizza.Photo.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'PizzaTonnoCipolla.jpg')); io.Persist(LPizza); end; end.
unit MediaStream.UrlFormats; interface uses SysUtils,Windows; //Медиа-сервер function MakeMs3sUrl(const aIp: string; aPort: word; const aSourceName: string): string; overload; function MakeMs3sUrl(const aIp: string; aPort: word; const aSourceName: string; const aUser,aPassword: string): string; overload; //MSCP function MakeMscpUrl(const aIp: string; aPort: word; const aSourceName: string): string; overload; function MakeMscpUrl(const aIp: string; aPort: word; const aSourceName: string; const aUser,aPassword: string): string; overload; //RTSP function MakeRtspUrl(const aIp: string; aPort: word; const aSourceName: string): string; overload; function MakeRtspUrl(const aIp: string; aPort: word; const aSourceName,aUserName,aUserPassword: string): string; overload; //Http function MakeHttpUrl(const aIp: string; aPort: word; const aSourceName: string): string; overload; function MakeHttpUrl(const aIp: string; aPort: word; const aSourceName,aUserName,aUserPassword: string): string; overload; //Файл function MakeFileUrl(const aFilePath: string): string; //Ip-камеры Beward function MakeBewardUrl(const aIp: string; aPort: word; aChannel: integer; aChannelProfile: integer): string;overload; function MakeBewardUrl(const aIp: string; aPort: word; aChannel: integer; aChannelProfile: integer; const aUserName,aUserPassword: string): string;overload; //Файловое хранилище function MakeRecordStorageUrl(const aDataBaseConnectionString: string; const aSourceName: string): string; //компресионные карты HikVision function MakeHikVisionCompCardUrl(const aChannelNo: integer; const aChannelProfile: integer): string; function ParseRtspUrl(const url:string; var aAddress: string; var aPort: Word; var aUrlSuffix: string; var aUserName: string; var aUserPassword: string):boolean; function ParseHttpUrl(const url:string; var aAddress: string; var aPort: Word; var aUrlSuffix: string; var aUserName: string; var aUserPassword: string):boolean; function ParseMs3sUrl(const url:string; var aAddress: string; var aPort: Word; var aUrlSuffix: string; var aUserName: string; var aUserPassword: string):boolean; function ParseMscpUrl(const url:string; var aAddress: string; var aPort: Word; var aUrlSuffix: string; var aUserName: string; var aUserPassword: string):boolean; function ParseBewardUrl(const url:string; var aAddress: string; var aPort: Word; var aChannelNo: integer; var aChannelProfile: integer; var aUserName: string; var aUserPassword: string):boolean; function ParseFileUrl(const url:string; var aFileName: string):boolean; function ParseHikVisionCompCardUrl(const url:string; var aChannelNo: integer; var aChannelProfile: integer):boolean; implementation uses StrUtils, MediaServer.Net.Definitions; function MakeMs3sUrl(const aIp: string; aPort: word; const aSourceName: string): string; begin result:=Format('ms3s://%s:%d/%s',[aIp,aPort,aSourceName]); end; function MakeMs3sUrl(const aIp: string; aPort: word; const aSourceName: string; const aUser,aPassword: string): string; overload; begin result:=Format('ms3s://%s:%s@%s:%d/%s',[aUser,aPassword,aIp,aPort,aSourceName]); end; function MakeMscpUrl(const aIp: string; aPort: word; const aSourceName: string): string; begin result:=Format('mscp://%s:%d/%s',[aIp,aPort,aSourceName]); end; function MakeMscpUrl(const aIp: string; aPort: word; const aSourceName: string; const aUser,aPassword: string): string; overload; begin result:=Format('mscp://%s:%s@%s:%d/%s',[aUser,aPassword,aIp,aPort,aSourceName]); end; function MakeRtspUrl(const aIp: string; aPort: word; const aSourceName: string): string; begin if aPort=0 then aPort:=554; result:=Format('rtsp://%s:%d/%s',[aIp,aPort,aSourceName]); end; function MakeRtspUrl(const aIp: string; aPort: word; const aSourceName,aUserName,aUserPassword: string): string; begin if (aUserName='') and (aUserPassword='') then result:=MakeRtspUrl(aIp,aPort,aSourceName) else result:=Format('rtsp://%s:%s@%s:%d/%s',[aUsername,aUserPassword,aIp,aPort,aSourceName]); end; function MakeHttpUrl(const aIp: string; aPort: word; const aSourceName: string): string; begin if aPort=0 then aPort:=80; result:=Format('http://%s:%d/%s',[aIp,aPort,aSourceName]); end; function MakeHttpUrl(const aIp: string; aPort: word; const aSourceName,aUserName,aUserPassword: string): string; begin if (aUserName='') and (aUserPassword='') then result:=MakeHttpUrl(aIp,aPort,aSourceName) else result:=Format('http://%s:%s@%s:%d/%s',[aUsername,aUserPassword,aIp,aPort,aSourceName]); end; function MakeFileUrl(const aFilePath: string): string; begin result:='file://'+StringReplace(aFilePath,'\','/',[rfReplaceAll]); end; function MakeBewardUrl(const aIp: string; aPort: word; aChannel: integer; aChannelProfile: integer): string; begin result:=Format('bwrd://%s:%d/%d/%d',[aIp,aPort,aChannel+1,aChannelProfile+1]); end; function MakeBewardUrl(const aIp: string; aPort: word; aChannel: integer; aChannelProfile: integer; const aUserName,aUserPassword: string): string;overload; begin result:=Format('bwrd://%s:%s@%s:%d/%d/%d',[aUserName,aUserPassword, aIp,aPort,aChannel+1,aChannelProfile+1]); end; function MakeRecordStorageUrl(const aDataBaseConnectionString: string; const aSourceName: string): string; begin result:=Format('rstg://%s/%s',[aDataBaseConnectionString,aSourceName]); result:=StringReplace(result,'\','/',[rfReplaceAll]); end; function MakeHikVisionCompCardUrl(const aChannelNo: integer; const aChannelProfile: integer): string; begin //HikVision Compression Card result:=Format('hvcc://%d/%d',[aChannelNo+1,aChannelProfile+1]); end; // =================================== PARSING ================================= procedure SkipSpaces(var aPtr: PChar); begin //пропускаем пробела while aPtr^<>#0 do begin if not CharInSet(aPtr^,[' ',#9]) then break; Inc(aPtr); end; end; function SplitString(const S: string; var SLeft,SRight: string; const Separator: string):boolean; var i : integer; aTmp: string; begin i:=Pos(Separator,S); if (i=0) then begin SLeft :=S; SRight:=''; result:=false; end else begin aTmp:=s; SLeft:=copy(aTmp,1,i-1); SRight:=copy(aTmp,i+Length(Separator),$7FFFFFFF); result:=true; end; end; function ParseAnyUrl(const aPrefix: string; const url:string; var aAddress: string; var aPort: Word; var aUrlSuffix: string; var aUserName: string; var aUserPassword: string):boolean; var aPtr: PChar; i: integer; aTmp: string; begin aUserName:=''; aUserPassword:=''; // Parse the URL as "rtsp://<address>:<port>/<etc>" // (with ":<port>" and "/<etc>" optional) // Also, skip over any "<username>[:<password>]@" preceding <address> aPtr:=PChar(url); //Адрес SkipSpaces(aPtr); if AnsiStrLIComp(aPtr,PChar(aPrefix+'://'),Length(aPrefix)+3)=0 then inc(aPtr,7) else if AnsiStrLIComp(aPtr,PChar(aPrefix+':/'),Length(aPrefix)+2)=0 then inc(aPtr,6); aAddress:=''; aURLSuffix:=aPtr; //Адрес должен быть до ближайшего / i:=Pos('/',aURLSuffix); if i=0 then begin aAddress:=aURLSuffix; aURLSuffix:=''; end else begin aAddress:=Copy(aURLSuffix,1,i-1); aURLSuffix:=Copy(aURLSuffix,i+1,High(integer)); end; result:=aAddress<>''; if SplitString(aAddress,aTmp,aAddress,'@') then begin SplitString(aTmp,aUserName,aUserPassword,':'); end else aAddress:=aTmp; if result then begin try if SplitString(aAddress,aAddress,aTmp,':') then begin if TryStrToInt(aTmp,i) then aPort:=i; end; except result:=false; end; end; end; function ParseRtspUrl(const url:string; var aAddress: string; var aPort: Word; var aUrlSuffix: string; var aUserName: string; var aUserPassword: string):boolean; begin aPort:=554; result:=ParseAnyUrl('rtsp',url,aAddress,aPort,aUrlSuffix,aUserName,aUserPassword); end; function ParseHttpUrl(const url:string; var aAddress: string; var aPort: Word; var aUrlSuffix: string; var aUserName: string; var aUserPassword: string):boolean; begin aPort:=80; result:=ParseAnyUrl('Http',url,aAddress,aPort,aUrlSuffix,aUserName,aUserPassword); end; function ParseMs3sUrl(const url:string; var aAddress: string; var aPort: Word; var aUrlSuffix: string; var aUserName: string; var aUserPassword: string):boolean; begin aPort:=MediaServer.Net.Definitions.icCommandServerPort; result:=ParseAnyUrl('ms3s',url,aAddress,aPort,aUrlSuffix,aUserName,aUserPassword); end; function ParseMscpUrl(const url:string; var aAddress: string; var aPort: Word; var aUrlSuffix: string; var aUserName: string; var aUserPassword: string):boolean; begin aPort:=MediaServer.Net.Definitions.icMscpServerPort; result:=ParseAnyUrl('mscp',url,aAddress,aPort,aUrlSuffix,aUserName,aUserPassword); end; function ParseBewardUrl(const url:string; var aAddress: string; var aPort: Word; var aChannelNo: integer; var aChannelProfile: integer; var aUserName: string; var aUserPassword: string):boolean; var aURLSuffix: string; aChannelNoStr: string; aChannelProfileStr: string; begin aPort:=5000; result:=ParseAnyUrl('bwrd',url,aAddress,aPort,aUrlSuffix,aUserName,aUserPassword); SplitString(aURLSuffix,aChannelNoStr,aChannelProfileStr,'/'); aChannelNo:=StrToIntDef(aChannelNoStr,1)-1; aChannelProfile:=StrToIntDef(aChannelProfileStr,1)-1; end; function ParseFileUrl(const url:string; var aFileName: string):boolean; begin if StartsText('file://',url) then begin aFileName:=StringReplace(Copy(url,8,High(Word)),'/','\',[rfReplaceAll]); end else if StartsText('file:/',url) then begin aFileName:=StringReplace(Copy(url,7,High(Word)),'/','\',[rfReplaceAll]); end else aFileName:=url; result:=true; end; function ParseHikVisionCompCardUrl(const url:string; var aChannelNo: integer; var aChannelProfile: integer):boolean; var aChannelNoStr: string; aChannelProfileStr: string; p: Word; aUN,aUP: string; begin result:=ParseAnyUrl('hvcc',url,aChannelNoStr,p,aChannelProfileStr,aUP,aUN); aChannelNo:=StrToIntDef(aChannelNoStr,0); aChannelProfile:=StrToIntDef(aChannelProfileStr,0); end; end.
unit StrUnit; (*------------------------------------------------------------------------------ 汎用文字列処理を定義したユニット 全ての関数は、マルチバイト文字(S-JIS)に対応している 作成者:クジラ飛行机( web@kujirahand.com ) https://sakuramml.com 作成日:2001/11/24 履歴: 2002/04/09 途中に#0を含む文字列でも検索置換できるように修正 ------------------------------------------------------------------------------*) interface uses {$ifdef Win32} Windows, {$endif} SysUtils, Classes, EasyMasks, Variants; type TCharSet = set of Char; var LeadBytes: TCharSet; (******************************************************************************) // multibyte function {文字列検索 // nバイト目の文字の位置を返す} function JPosEx(const sub, str:string; idx:Integer): Integer; {文字列置換} function JReplace(const Str, oldStr, newStr:string; repAll:Boolean): string; {文字列置換拡張版} function JReplaceEx(const Str, oldStr, newStr:string; repAll:Boolean; useCase:Boolean): string; {デリミタ文字列までの単語を切り出す。(切り出した単語にデリミタは含まない。) 切り出し後は、元の文字列strから、切り出した文字列+デリミタ分を削除する。} function GetToken(const delimiter: String; var str: string): String; {Multibyte文字数を得る} function JLength(const str: string): Integer; {Multibyte文字列を切り出す} function JCopy(const str: string; Index, Count: Integer): string; {Mutibyte文字列を検索する} function JPosM(const sub, str: string): Integer; {------------------------------------------------------------------------------} {文字種類の変換} {全角変換} function convToFull(const str: string): string; {半角変換} function convToHalf(const str: string): string; {数字とアルファベットと記号のみ半角に変換する/但し遅い} function convToHalfAnk(const str: string): string; {------------------------------------------------------------------------------} {文字種類の判別} function IsHiragana(const str: string): Boolean; function IsKatakana(const str: string): Boolean; function Asc(const str: string): Integer; //文字コードを得る function IsNumStr(const str: string): Boolean; //文字列が全て数値かどうか判断 {------------------------------------------------------------------------------} {HTML処理} {HTML から タグを取り除く} function DeleteTag(const html: string): String; {HTMLの指定タグで囲われた部分を抜き出す} function GetTag(var html:string; tag: string): string; function GetTags(html:string; tag: string): string; {------------------------------------------------------------------------------} {トークン処理} {トークン切り出し/区切り文字分を進める} function GetTokenChars(delimiter: TCharSet; var ptr:PChar): string; {ネストする()の内容を抜き出す} function GetKakko(var pp: PChar): string; {------------------------------------------------------------------------------} {日時処理} {日付の加算 ex)3ヵ月後 IncDate('2001/10/30','0/3/0') 三日前 IncDate('2001/1/1','-0/0/3')} function IncDate(BaseDate: TDateTime; AddDate: string): TDateTime; {時間の加算 ex)3時間後 IncTime('15:0:0','3:0:0') 三秒前 IncTime('12:45:0','-0:0:3')} function IncTime(BaseTime: TDateTime; AddTime: string): TDateTime; {西暦、和暦に対応した日付変換用関数} function StrToDateStr(str: string): string; {西暦、和暦に対応した日付変換用関数} function StrToDateEx(str: string): TDateTime; {TDateTimeを、和暦に変換する} function DateToWareki(d: TDateTime): string; {------------------------------------------------------------------------------} {その他} {Insert Comma 3keta} function InsertYenComma(const yen: string): string; {文字を出来る限り数値に変換する} function StrToValue(const str: string): Extended; function WildMatch(Filename,Mask:string):Boolean; {gyousoroe} function CutLine(line: string; cnt,tabCnt: Integer; kinsoku: string): string; {------------------------------------------------------------------------------} implementation {行揃えする} function CutLine(line: string; cnt,tabCnt: Integer; kinsoku: string): string; (* const GYOUTOU_KINSI = '、。,.・?!゛゜ヽヾゝゞ々ー)]}」』!),.:;?]}。」、・ー゙゚'; *) var p, pr,pr_s: PChar; i,len: Integer; procedure CopyOne; begin pr^ := p^; Inc(pr); Inc(p); end; procedure InsCrLf; var next_c: string; begin //禁則処理(行頭禁則文字) if kinsoku<>'' then begin if p^ in LeadBytes then begin next_c := p^ + (p+1)^; end else begin next_c := p^; end; if JPosEx(next_c, kinsoku, 1)>0 then begin if p^ in LeadBytes then begin CopyOne; CopyOne; end else begin CopyOne; end; end; end; pr^ := #13; Inc(pr); pr^ := #10; Inc(pr); i := 0; end; begin if cnt<=0 then begin Result := line; Exit; end; len := Length(line); SetLength(Result, len + (len div cnt)*2 + 1); pr := PChar(Result); pr_s := pr; p := PChar(line); i := 0; while p^ <> #0 do begin if p^ in LeadBytes then begin if (i+2) > cnt then InsCrLf; CopyOne; CopyOne; Inc(i,2); end else begin if i >= cnt then InsCrLf; if p^ in [#13,#10] then begin Inc(p); if p^ in[#13,#10] then Inc(p); InsCrLf; end else if p^ = #9 then begin CopyOne; Inc(i, tabCnt); end else begin CopyOne; Inc(i); end; end; end; pr^ := #0; Result := string( pr_s ); end; {TDateTimeを、和暦に変換する} function DateToWareki(d: TDateTime): string; var y, yy, mm, dd: Word; sy: string; const MEIJI = 1869; TAISYO = 1912; SYOWA = 1926; HEISEI = 1989; begin DecodeDate(d, yy, mm, dd); if (MEIJI<=yy)and(yy<TAISYO) then begin y := yy-MEIJI+1; if y=1 then sy := '元年' else sy := IntToStr(y)+'年'; Result := Format('明治'+sy+'%d月%d日',[mm,dd]); end else if (TAISYO<=yy)and(yy<SYOWA) then begin y := yy-TAISYO+1; if y=1 then sy := '元年' else sy := IntToStr(y)+'年'; Result := Format('大正'+sy+'%d月%d日',[mm,dd]); end else if (SYOWA<=yy)and(yy<HEISEI) then begin y := yy-SYOWA+1; if y=1 then sy := '元年' else sy := IntToStr(y)+'年'; Result := Format('昭和'+sy+'%d月%d日',[mm,dd]); end else if (HEISEI<=yy) then begin y := yy-HEISEI+1; if y=1 then sy := '元年' else sy := IntToStr(y)+'年'; Result := Format('平成'+sy+'%d月%d日',[mm,dd]); end; end; {MutiByte文字数を得る} function JLength(const str: string): Integer; var p: PChar; begin p := PChar(str); Result := 0; while p^ <> #0 do begin if p^ in LeadBytes then Inc(p,2) else Inc(p); Inc(Result); end; end; {MutiByte文字列を切り出す} function JCopy(const str: string; Index, Count: Integer): string; var i, iTo: Integer; p: PChar; ch: string; begin i := 1; iTo := Index + Count -1; p := PChar(str); Result := ''; while (p^ <> #0) do begin if p^ in LeadBytes then begin ch := p^ + (p+1)^; Inc(p,2); end else begin ch :=p^; Inc(p); end; if (Index <= i) and (i <= iTo) then begin Result := Result + ch; end; Inc(i); if iTo < i then Break; end; end; {MutiByte文字列を検索する} function JPosM(const sub, str: string): Integer; var i, len: Integer; p, ps: PChar; begin i := 1; Result := 0; p := PChar(str); ps := PChar(sub); len := Length(sub); while p^ <> #0 do begin if StrLComp(p, ps, len) = 0 then begin Result := i; Break; end; if p^ in LeadBytes then begin Inc(p,2); end else begin Inc(p); end; Inc(i); end; end; function Asc(const str: string): Integer; //文字コードを得る begin if str='' then begin Result := 0; Exit; end; if str[1] in LeadBytes then begin Result := (Ord(str[1]) shl 8) + Ord(str[2]); end else Result := Ord(str[1]); end; {西暦、和暦に対応した日付変換用関数} function StrToDateStr(str: string): string; begin Result:=''; if str='' then Exit; Result := FormatDateTime( 'yyyy/mm/dd', StrToDateEx(str) ); end; function StrToDateEx(str: string): TDateTime; begin Result := Now; if str='' then Exit; if Pos('.',str)>0 then str := JReplace(str,'.','/',True); Result := VarToDateTime(str); end; {時間の加算 ex)3時間後 IncTime('15:0:0','3:0:0') 三秒前 IncTime('12:45:0','-0:0:3')} function IncTime(BaseTime: TDateTime; AddTime: string): TDateTime; var flg: string; h,n,s, hh,nn,ss,dummy: Word; th,tn,ts: Integer; begin flg := Copy(AddTime,1,1); if (flg='-')or(flg='+') then Delete(AddTime, 1,1); DecodeTime(BaseTime, h, n, s, dummy); hh := StrToIntDef(getToken(':', AddTime),0); nn := StrToIntDef(getToken(':', AddTime),0); ss := StrToIntDef(AddTime, 0); if flg <> '-' then begin Inc(h,hh); Inc(n,nn); Inc(s,ss); while True do begin while s >= 60 do begin Dec(s,60); Inc(n); end; while n >= 60 do begin Dec(n,60); Inc(h); end; h := h mod 24; if(s<60)and(n<60)then Break; end; end else begin //Dec(h,hh); Dec(n,nn); Dec(s,ss); th := h - hh; tn := n - nn; ts := s - ss; while True do begin while ts < 0 do begin Inc(ts,60); Dec(tn); end; if tn < 1 then begin tn := 59; Dec(th); if th < 1 then begin th := 23; end; end; while th < 0 do begin Inc(th,24); end; if(ts>=0)and(tn>=1)then begin h := Word(th); n := Word(tn); s := Word(ts); Break; end; end; end; Result := EncodeTime(h,n,s,0); end; {日付の加算 ex)3ヵ月後 IncDate('2001/10/30','0/3/0') 三日前 IncDate('2001/1/1','-0/0/3')} function IncDate(BaseDate: TDateTime; AddDate: string): TDateTime; var flg: string; y,m,d, yy,mm,dd: Word; maxD: Word; ty,tm,td: Integer; begin flg := Copy(AddDate,1,1); if (flg='-')or(flg='+') then Delete(AddDate, 1,1); DecodeDate(BaseDate, y, m, d); yy := StrToIntDef(getToken('/', AddDate),0); mm := StrToIntDef(getToken('/', AddDate),0); dd := StrToIntDef(AddDate, 0); if flg <> '-' then begin Inc(y,yy); Inc(m,mm); // 月の足し算 if m > 12 then begin Inc(y, (m div 12)); m := m mod 12; end; maxD := (SysUtils.MonthDays[IsLeapYear(y)])[m]; if d > maxD then d := maxD; Inc(d,dd); // 日の足し算 while True do begin maxD := (SysUtils.MonthDays[IsLeapYear(y)])[m]; if d > maxD then begin Inc(m); if m > 12 then begin Inc(y); Dec(m,12); end; Dec(d, maxD); end else Break; end; end else begin //Dec(y,yy); Dec(m,mm); Dec(d,dd); ty := y-yy; tm := m-mm; //月の引き算 while tm < 1 do begin Inc(tm,12); Dec(ty,1); end; td := d; if ty<1900 then begin raise ERangeError.Create('1900年以下は計算できません。'); end; maxD := (SysUtils.MonthDays[IsLeapYear(ty)])[tm]; if td > maxD then td := maxD; td := td-dd; //日の引き算 while True do begin if td < 1 then begin Dec(tm); if tm < 1 then begin Dec(ty); tm := 12; end; maxD := (SysUtils.MonthDays[IsLeapYear(ty)])[tm]; Inc(td, maxD); end else if (ty>=1)and(tm>=1)and(td>=1) then begin y := ty; m := tm; d := td; Break; end else Break; end; end; Result := EncodeDate(y,m,d); end; procedure skipSpace(var p: PChar); begin while p^ in [' ',#9] do Inc(p); end; {ネストする()の内容を抜き出す} function GetKakko(var pp: PChar): string; const CH_STR1 = '"'; CH_STR2 = ''''; var nest, len: Integer; tmp, buf: PChar; IsStr, IsStr2: Boolean; begin Result := ''; skipSpace(pp); nest := 0; IsStr := False; IsStr2 := False; if pp^ = '(' then begin Inc(nest); Inc(pp); end; tmp := pp; while pp^ <> #0 do begin if pp^ in LeadBytes then begin Inc(pp,2); continue; end else case pp^ of CH_STR1: begin if IsStr2 = False then IsStr := not IsStr; Inc(pp); end; CH_STR2: begin if IsStr = False then IsStr2 := not IsStr2; Inc(pp); end; '\': begin Inc(pp); if IsStr then if pp^ in LeadBytes then Inc(pp,2) else Inc(pp); end; '(': begin Inc(pp); if (IsStr=False)and(IsStr2=False) then begin Inc(nest); continue; end; end; ')': begin Inc(pp); if (IsStr=False)and(IsStr2=False) then begin Dec(nest); if nest = 0 then Break; continue; end; end; else Inc(pp); end; end; len := pp - tmp -1; if len<=0 then begin if nest <> 0 then begin pp := tmp; raise Exception.Create('")"が対応していません。'); end; Exit; end; if nest > 0 then raise Exception.Create('")"が対応していません。'); GetMem(buf, len + 1); try StrLCopy(buf, tmp, len); (buf+len)^ := #0; Result := string( PChar(buf) ); finally FreeMem(buf); end; end; function WildMatch(Filename,Mask:string):Boolean; begin Result := MatchesMask(Filename, Mask); end; {文字列を数値に変換する} function StrToValue(const str: string): Extended; var st,p,mem,pt: PChar; len, sig: Integer; buf: string; begin // はじめに、数字を半角にする if str='' then begin Result := 0; Exit; end; buf := Trim(JReplace(convToHalf(str),',','',True));//カンマを削除 p := PChar(buf); while p^ in [' ',#9] do Inc(p); if p^='$' then begin Result := StrToIntDef(buf,0); Exit; end; sig := 1; if p^ = '+' then Inc(p) else if p^ ='-' then begin Inc(p); sig := -1; end; st := p; while p^ in ['0'..'9'] do Inc(p); if p^ = '.' then begin Inc(p); // skip . while True do begin if p^ in ['0'..'9'] then Inc(p) else if p^ in ['e','E'] then begin pt := p; Inc(p); if p^ in ['+','-'] then Inc(p); if p^ in ['0'..'9'] then begin while p^ in ['0'..'9'] do Inc(p); Break; end else begin p := pt; Break; end; end else Break; end; end; len := p - st; if len=0 then begin Result:=0; Exit; end; GetMem(mem, len+1); try StrLCopy(mem, st, len); (mem+len)^ := #0; Result := sig * StrToFloat(string(mem)); finally FreeMem(mem); end; end; function GetToken(const delimiter: String; var str: string): String; var i: Integer; begin i := JPosEx(delimiter, str,1); if i=0 then begin Result := str; str := ''; Exit; end; Result := Copy(str, 1, i-1); Delete(str,1,i + Length(delimiter) -1); end; {HTML から タグを取り除く} function DeleteTag(const html: string): String; var i: Integer; txt: String; TagIn: Boolean; begin txt := Trim(html); if txt = '' then Exit; i := 1; Result := ''; TagIn := False; while i <= Length(txt) do begin if txt[i] in SysUtils.LeadBytes then begin if TagIn=False then Result := Result + txt[i] + txt[i+1]; Inc(i,2); Continue; end; case txt[i] of '<': //TAG in begin TagIn := True; Inc(i); end; '>': //TAG out begin TagIn := False; Inc(i); end; else begin if TagIn then begin // to skip Inc(i); end else begin Result := Result + txt[i]; Inc(i); end; end; end; end; end; {HTMLの指定タグで囲われた部分を抜き出す} function GetTag(var html:string; tag: string): string; var top, p,pp, res_in, res_out: PChar; ltag,utag: string; len: Integer; begin if (Copy(tag,1,1)='<')and(Copy(tag,Length(tag),1)='>') then begin Delete(tag,1,1); Delete(tag,Length(tag),1); end; Result := ''; if html='' then Exit; p := PChar(html); top := p; ltag := LowerCase(tag); utag := UpperCase(tag); res_in := nil; //res_out := nil; // 頭出し while p^ <> #0 do begin if p^ = '<' then begin pp := p; Inc(pp); if (StrLComp(pp, PChar(ltag), Length(ltag))=0)or (StrLComp(pp, PChar(utag), Length(utag))=0) then begin res_in := p; while not(p^ in ['>',#0]) do Inc(p); if p^='>' then Inc(p); Break; end; end; Inc(p); end; if (res_in = nil)or(p^=#0) then begin html := ''; Exit; end; res_out := (p-1); // 最後出し while p^ <> #0 do begin if (p^ = '<')and((p+1)^='/') then begin Inc(p,2); if (StrLComp(p, PChar(ltag), Length(ltag))=0)or (StrLComp(p, PChar(utag), Length(utag))=0) then begin while not(p^ in ['>',#0]) do Inc(p); res_out := p; Break; end; end; Inc(p); end; if (res_out=nil) then begin html := ''; Exit; end; len := res_out - res_in + 1; SetLength(Result, len+1); StrLCopy(PChar(result),res_in, len); Result[len+1] := #0; Result := string( PChar(Result) ); // len := res_out - top; Delete(html,1, len); end; function GetTags(html:string; tag: string): string; var s: string; begin Result := ''; while html <> '' do begin s := GetTag(html, tag); if s<>'' then Result := Result + s + #13#10; end; end; function InsertYenComma(const yen: string): string; begin if Pos('.',yen)=0 then begin Result := FormatCurr('#,##0', StrToValue(yen)); end else begin Result := FormatCurr('#,##0.00', StrToValue(yen)); end; end; function JPosEx(const sub, str:string; idx:Integer): Integer; var p, sub_p, temp: PChar; len, str_len: Integer; begin Result := 0; // 関数の引数エラーチェック str_len := Length(str); if str_len < idx then Exit; if idx < 1 then idx := 1; if (sub='')or(str='') then Exit; // 検索準備 temp := PChar(str); p:= temp; Inc(p, idx-1); sub_p := PChar(sub); len := Length(sub); // 文字列中をループしながら検索(リニアサーチ) while ((p-temp+1) <= str_len) do begin if AnsiStrLComp(sub_p, p, len)=0 then begin Result := (p - temp) + 1; Exit; end; if p^ in SysUtils.LeadBytes then Inc(p,2) else Inc(p); end; end; function JReplace(const Str, oldStr, newStr:string; repAll:Boolean): string; var i, idx:Integer; begin Result := Str; // **** i := JPosEx(oldStr, Str, 1); if i=0 then Exit; Delete(result, i, Length(oldStr)); Insert(newStr, result, i); idx := i + Length(newStr); if repAll = False then Exit; // *** Loop while True do begin i := JPosEx(oldStr, result, idx); if i=0 then Exit; Delete(result, i, Length(oldStr)); Insert(newStr, result, i); idx := i + Length(newStr); end; end; function JReplaceEx(const Str, oldStr, newStr:string; repAll:Boolean; useCase:Boolean): string; var i, idx:Integer; oldStrFind: string; strFind: string; begin Result := Str; oldStrFind := UpperCase(oldStr); strFind := UpperCase(Result); // **** i := JPosEx(oldStrFind, strFind, 1); if i=0 then Exit; Delete(result, i, Length(oldStr)); Insert(newStr, result, i); idx := i + Length(newStr); if repAll = False then Exit; // *** Loop while True do begin oldStrFind := UpperCase(oldStr); strFind := UpperCase(Result); i := JPosEx(oldStrFind, strFind, idx); if i=0 then Exit; Delete(result, i, Length(oldStr)); Insert(newStr, result, i); idx := i + Length(newStr); end; end; function convToFull(const str: string): string; begin Result := str; raise Exception.Create('not implements'); end; function convToHalf(const str: string): string; begin Result := convToHalfAnk(str); end; function convToHalfAnk(const str: string): string; var p,pr: PChar; s: string; i: Integer; const HALF_JOUKEN = '0123456789'+ 'abcdefghijklmnopqrstuvwxyz'+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'+ '!”#$%&’()=−¥[]{}_/><,.@‘ '; begin SetLength(Result, Length(str)+1);//とりあえず適当な大きさを確保 p := PChar(str); pr := PChar(Result); while p^ <> #0 do begin if p^ in LeadBytes then begin s := p^ + (p+1)^; i := Pos(s, HALF_JOUKEN); if (i>0)and(((i-1)mod 2)=0) then //文字が途中で分断されているのを防ぐため、mod 2=0 でチェック begin s := convToHalf(s); pr^ := s[1]; Inc(pr); Inc(p,2); end else begin pr^ := p^; Inc(pr); Inc(p); pr^ := p^; Inc(pr); Inc(p); end; end else begin // 既に ank pr^ := p^ ; Inc(pr); Inc(p); end; end; pr^ := #0; Result := string(PChar(Result)); end; function convToFullAnk(const str: string): string; begin Result := str; end; {トークン処理} {トークン切り出し/区切り文字分を進める} function GetTokenChars(delimiter: TCharSet; var ptr:PChar): string; begin Result := ''; while ptr^ <> #0 do begin if ptr^ in LeadBytes then begin Result := Result + ptr^ + (ptr+1)^; Inc(ptr,2); end else begin if ptr^ in delimiter then begin Inc(ptr); Break; end; Result := Result + ptr^; Inc(ptr); end; end; end; function IsHiragana(const str: string): Boolean; var code: Integer; begin Result := False; if Length(str)<2 then Exit; code := (Ord(str[1])shl 8) + Ord(str[2]); if ($82A0 <= code)and(code <= $833E) then Result := True; end; function IsKatakana(const str: string): Boolean; var code: Integer; begin Result := False; if Length(str)<2 then Exit; code := (Ord(str[1])shl 8) + Ord(str[2]); if ($8340 <= code)and(code <= $839D) then Result := True; end; function IsNumStr(const str: string): Boolean; //文字列が全て数値かどうか判断 var p: PChar; begin Result := False; p := PChar(str); if not (p^ in ['0'..'9']) then Exit; Inc(p); while p^ <> #0 do begin if p^ in ['0'..'9','e','E','+','-','.'] then //浮動小数点に対応 Inc(p) else Exit; end; Result := True; end; Initialization begin LeadBytes := [#$80..#$FF]; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit WebContnrs; interface uses System.Classes, System.SysUtils; type ENamedVariantsError = class(Exception); TAbstractNamedVariants = class(TPersistent) private FUpdateCount: Integer; function GetName(Index: Integer): string; function GetValue(const Name: string): Variant; procedure ReadData(Reader: TReader); procedure SetValue(const Name: string; const Value: Variant); procedure WriteData(Writer: TWriter); procedure AddNamedVariants(ANamedVariants: TAbstractNamedVariants); function GetVariant(Index: Integer): Variant; procedure PutVariant(Index: Integer; const Value: Variant); protected procedure DefineProperties(Filer: TFiler); override; procedure Error(const Msg: string; Data: Integer); overload; function Get(Index: Integer; out AName: string; out AValue: Variant): Boolean; virtual; abstract; function GetCapacity: Integer; virtual; function GetCount: Integer; virtual; abstract; procedure Put(Index: Integer; const AName: string; const AValue: Variant); virtual; abstract; procedure SetCapacity(NewCapacity: Integer); virtual; procedure SetUpdateState(Updating: Boolean); virtual; property UpdateCount: Integer read FUpdateCount; function CompareStrings(const S1, S2: string): Integer; virtual; public destructor Destroy; override; function Add(const S: string; const AValue: Variant): Integer; virtual; procedure Append(const S: string; const AValue: Variant); procedure Assign(Source: TPersistent); override; procedure BeginUpdate; procedure Clear; virtual; abstract; procedure Delete(Index: Integer); virtual; abstract; procedure EndUpdate; function Equals(ANamedVariants: TAbstractNamedVariants): Boolean; reintroduce; procedure Exchange(Index1, Index2: Integer); virtual; function IndexOfName(const Name: string): Integer; virtual; procedure Insert(Index: Integer; const S: string; const AValue: Variant); virtual; abstract; procedure Move(CurIndex, NewIndex: Integer); virtual; property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount; property Names[Index: Integer]: string read GetName; property Values[const Name: string]: Variant read GetValue write SetValue; property Variants[Index: Integer]: Variant read GetVariant write PutVariant; end; PNamedVariantItem = ^TNamedVariantItem; TNamedVariantItem = record FString: string; FVariant: Variant; end; PNamedVariantList = ^TNamedVariantList; TNamedVariantList = array[0..2000000000 div sizeof(TNamedVariantItem)] of TNamedVariantItem; TNamedVariantsList = class(TAbstractNamedVariants) private FList: PNamedVariantList; FCount: Integer; FCapacity: Integer; procedure Grow; protected procedure SetCapacity(NewCapacity: Integer); override; function GetCapacity: Integer; override; function Get(Index: Integer; out AName: string; out AValue: Variant): Boolean; override; procedure Put(Index: Integer; const AName: string; const AValue: Variant); override; function GetCount: Integer; override; public destructor Destroy; override; procedure Clear; override; procedure Delete(Index: Integer); override; procedure Insert(Index: Integer; const S: string; const AValue: Variant); override; end; implementation uses {$IFDEF MSWINDOWS} Winapi.Windows, {$ENDIF} System.Variants, System.RTLConsts; { TAbstractNamedVariants } function TAbstractNamedVariants.Add(const S: string; const AValue: Variant): Integer; begin Result := GetCount; Insert(Result, S, AValue); end; procedure TAbstractNamedVariants.Append(const S: string; const AValue: Variant); begin Add(S, AValue); end; procedure TAbstractNamedVariants.AddNamedVariants(ANamedVariants: TAbstractNamedVariants); var I: Integer; S: string; V: Variant; begin BeginUpdate; try for I := 0 to ANamedVariants.Count - 1 do begin ANamedVariants.Get(I, S, V); Add(S, V); end; finally EndUpdate; end; end; procedure TAbstractNamedVariants.Assign(Source: TPersistent); begin if Source is TAbstractNamedVariants then begin BeginUpdate; try Clear; AddNamedVariants(TAbstractNamedVariants(Source)); finally EndUpdate; end; Exit; end; inherited Assign(Source); end; procedure TAbstractNamedVariants.BeginUpdate; begin if FUpdateCount = 0 then SetUpdateState(True); Inc(FUpdateCount); end; function TAbstractNamedVariants.CompareStrings(const S1, S2: string): Integer; begin Result := AnsiCompareText(S1, S2); end; procedure TAbstractNamedVariants.DefineProperties(Filer: TFiler); function DoWrite: Boolean; begin if Filer.Ancestor <> nil then begin Result := True; if Filer.Ancestor is TAbstractNamedVariants then Result := not Equals(TAbstractNamedVariants(Filer.Ancestor)) end else Result := Count > 0; end; begin Filer.DefineProperty('NamedVariants', ReadData, WriteData, DoWrite); end; destructor TAbstractNamedVariants.Destroy; begin inherited; end; procedure TAbstractNamedVariants.EndUpdate; begin Dec(FUpdateCount); if FUpdateCount = 0 then SetUpdateState(False); end; function TAbstractNamedVariants.Equals(ANamedVariants: TAbstractNamedVariants): Boolean; var I, Count: Integer; begin Result := False; Count := GetCount; if Count <> ANamedVariants.GetCount then Exit; for I := 0 to Count - 1 do if (Names[I] <> ANamedVariants.Names[I]) or (Variants[I] <> ANamedVariants.Variants[I]) then Exit; Result := True; end; procedure TAbstractNamedVariants.Error(const Msg: string; Data: Integer); begin raise ENamedVariantsError.CreateFmt(Msg, [Data]); end; procedure TAbstractNamedVariants.Exchange(Index1, Index2: Integer); var TempVariant: Variant; TempName: string; begin BeginUpdate; try Get(Index1, TempName, TempVariant); Put(Index1, Names[Index2], Variants[Index2]); Put(Index2, TempName, TempVariant); finally EndUpdate; end; end; function TAbstractNamedVariants.GetCapacity: Integer; begin // descendents may optionally override/replace this default implementation Result := Count; end; function TAbstractNamedVariants.GetValue(const Name: string): Variant; var I: Integer; begin I := IndexOfName(Name); if I >= 0 then Result := GetVariant(I) else Result := Unassigned; end; function TAbstractNamedVariants.IndexOfName(const Name: string): Integer; begin for Result := 0 to GetCount - 1 do if CompareStrings(GetName(Result), Name) = 0 then Exit; Result := -1; end; procedure TAbstractNamedVariants.Move(CurIndex, NewIndex: Integer); var TempVariant: Variant; TempName: string; begin if CurIndex <> NewIndex then begin BeginUpdate; try Get(CurIndex, TempName, TempVariant); Delete(CurIndex); Insert(NewIndex, TempName, TempVariant); finally EndUpdate; end; end; end; procedure TAbstractNamedVariants.ReadData(Reader: TReader); var V: Variant; S: string; begin Reader.ReadListBegin; BeginUpdate; try Clear; while not Reader.EndOfList do begin S := Reader.ReadString; V := Reader.ReadVariant; Add(S, V); end; finally EndUpdate; end; Reader.ReadListEnd; end; procedure TAbstractNamedVariants.SetCapacity(NewCapacity: Integer); begin // do nothing - descendents may optionally implement this method end; procedure TAbstractNamedVariants.SetUpdateState(Updating: Boolean); begin // do nothing end; procedure TAbstractNamedVariants.SetValue(const Name: string; const Value: Variant); var I: Integer; begin I := IndexOfName(Name); if I < 0 then Add(Name, Value) else PutVariant(I, Value); end; procedure TAbstractNamedVariants.WriteData(Writer: TWriter); var I: Integer; begin Writer.WriteListBegin; for I := 0 to Count - 1 do begin Writer.WriteString(Names[I]); Writer.WriteVariant(Variants[I]); end; Writer.WriteListEnd; end; function TAbstractNamedVariants.GetName(Index: Integer): string; var TempVariant: Variant; begin Get(Index, Result, TempVariant); end; function TAbstractNamedVariants.GetVariant(Index: Integer): Variant; var TempName: string; begin Get(Index, TempName, Result); end; procedure TAbstractNamedVariants.PutVariant(Index: Integer; const Value: Variant); begin Put(Index, GetName(Index), Value); end; { TNamedVariantsList } destructor TNamedVariantsList.Destroy; begin inherited Destroy; if FCount <> 0 then Finalize(FList^[0], FCount); FCount := 0; SetCapacity(0); end; procedure TNamedVariantsList.Clear; begin if FCount <> 0 then begin Finalize(FList^[0], FCount); FCount := 0; SetCapacity(0); end; end; procedure TNamedVariantsList.Delete(Index: Integer); begin if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); Finalize(FList^[Index]); Dec(FCount); if Index < FCount then System.Move(FList^[Index + 1], FList^[Index], (FCount - Index) * SizeOf(TNamedVariantItem)); end; function TNamedVariantsList.Get(Index: Integer; out AName: string; out AValue: Variant): Boolean; begin Result := True; if (Index < 0) or (Index >= FCount) then Error(sListIndexError, Index); AName := FList^[Index].FString; AValue := FList^[Index].FVariant; end; function TNamedVariantsList.GetCapacity: Integer; begin Result := FCapacity; end; function TNamedVariantsList.GetCount: Integer; begin Result := FCount; end; procedure TNamedVariantsList.Grow; var Delta: Integer; begin if FCapacity > 64 then Delta := FCapacity div 4 else if FCapacity > 8 then Delta := 16 else Delta := 4; SetCapacity(FCapacity + Delta); end; procedure TNamedVariantsList.Insert(Index: Integer; const S: string; const AValue: Variant); begin if (Index < 0) or (Index > FCount) then Error(SListIndexError, Index); if FCount = FCapacity then Grow; if Index < FCount then System.Move(FList^[Index], FList^[Index + 1], (FCount - Index) * SizeOf(TNamedVariantItem)); with FList^[Index] do begin Pointer(FString) := nil; FillChar(TVarData(FVariant), sizeof(TVarData), 0); FVariant := AValue; FString := S; end; Inc(FCount); end; procedure TNamedVariantsList.Put(Index: Integer; const AName: string; const AValue: Variant); begin if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); FList^[Index].FString := AName; FList^[Index].FVariant := AValue; end; procedure TNamedVariantsList.SetCapacity(NewCapacity: Integer); begin ReallocMem(FList, NewCapacity * SizeOf(TNamedVariantItem)); FCapacity := NewCapacity; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLFileMP3<p> Support for MP3 format.<p> <b>History : </b><font size=-1><ul> <li>25/07/09 - DaStr - Added $I GLScene.inc <li>06/05/09 - DanB - Creation from split from GLSoundFileObjects.pas </ul></font> } unit GLFileMP3; interface {$I GLScene.inc} uses System.Classes, GLApplicationFileIO, GLSoundFileObjects; type // TGLMP3File // {: Support for MP3 format.<p> *Partial* support only, access to PCMData is NOT supported. } TGLMP3File = class (TGLSoundFile) private { Public Declarations } data : array of Byte; // used to store MP3 bitstream protected { Protected Declarations } public { Private Declarations } function CreateCopy(AOwner: TPersistent) : TDataFile; override; class function Capabilities : TDataFileCapabilities; override; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; procedure PlayOnWaveOut; override; function WAVData : Pointer; override; function WAVDataSize : Integer; override; function PCMData : Pointer; override; function LengthInBytes : Integer; override; end; implementation // ------------------ // ------------------ TGLMP3File ------------------ // ------------------ // CreateCopy // function TGLMP3File.CreateCopy(AOwner: TPersistent) : TDataFile; begin Result:=inherited CreateCopy(AOwner); if Assigned(Result) then begin TGLMP3File(Result).data := Copy(data); end; end; // Capabilities // class function TGLMP3File.Capabilities : TDataFileCapabilities; begin Result:=[dfcRead, dfcWrite]; end; // LoadFromStream // procedure TGLMP3File.LoadFromStream(stream : TStream); begin // MP3 isn't actually, just loaded directly... Assert(Assigned(stream)); SetLength(data, stream.Size); if Length(data)>0 then stream.Read(data[0], Length(data)); end; // SaveToStream // procedure TGLMP3File.SaveToStream(stream: TStream); begin if Length(data)>0 then stream.Write(data[0], Length(data)); end; // PlayOnWaveOut // procedure TGLMP3File.PlayOnWaveOut; begin Assert(False, 'MP3 playback on WaveOut not supported.'); end; // WAVData // function TGLMP3File.WAVData : Pointer; begin if Length(data)>0 then Result:=@data[0] else Result:=nil; end; // WAVDataSize // function TGLMP3File.WAVDataSize : Integer; begin Result:=Length(data); end; // PCMData // function TGLMP3File.PCMData : Pointer; begin Result:=nil; end; // LengthInBytes // function TGLMP3File.LengthInBytes : Integer; begin Result:=0; end; initialization RegisterSoundFileFormat('mp3', 'MPEG Layer3 files', TGLMP3File); end.
{ KOL MCK } // Do not remove this line! {$DEFINE KOL_MCK} unit OptionsForm; interface {$IFDEF KOL_MCK} uses Windows, Messages, KOL, KOLMHFontDialog {$IF Defined(KOL_MCK)}{$ELSE}, mirror, Classes, Controls, mckCtrls, mckObjs, Graphics, MCKMHFontDialog {$IFEND (place your units here->)}, Types, KOLHilightEdit, Gutter, Hilighter; {$ELSE} {$I uses.inc} Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, MCKMHFontDialog; {$ENDIF} type {$IF Defined(KOL_MCK)} {$I MCKfakeClasses.inc} {$IFDEF KOLCLASSES} {$I TFormOptionsclass.inc} {$ELSE OBJECTS} PFormOptions = ^TFormOptions; {$ENDIF CLASSES/OBJECTS} {$IFDEF KOLCLASSES}{$I TFormOptions.inc}{$ELSE} TFormOptions = object(TObj) {$ENDIF} Form: PControl; {$ELSE not_KOL_MCK} TFormOptions = class(TForm) {$IFEND KOL_MCK} KOLForm: TKOLForm; OKButton: TKOLButton; CancelButton: TKOLButton; OptionsTabs: TKOLTabControl; PageGeneral: TKOLTabPage; PageEditor: TKOLTabPage; SmartTabsCheck: TKOLCheckBox; GutterCheck: TKOLCheckBox; AutocompletionCheck: TKOLCheckBox; HilightCheck: TKOLCheckBox; KeepSpacesCheck: TKOLCheckBox; OverwriteCheck: TKOLCheckBox; TabSizeEdit: TKOLEditBox; RightMarginEdit: TKOLEditBox; AutocompleteEdit: TKOLEditBox; Label1: TKOLLabel; ColorDialog: TKOLColorDialog; FontPanel: TKOLPanel; FontButton: TKOLButton; StyleCombo: TKOLComboBox; FontColorPanel: TKOLPanel; BackColorPanel: TKOLPanel; BoldCheck: TKOLCheckBox; ItalicCheck: TKOLCheckBox; UnderlineCheck: TKOLCheckBox; StrikeCheck: TKOLCheckBox; EditorPanel: TKOLPanel; CurLineColorPanel: TKOLPanel; RightMarginColorPanel: TKOLPanel; FontDialog: TKOLMHFontDialog; ResetStylesButton: TKOLButton; SavePosCheck: TKOLCheckBox; HotkeysList: TKOLListView; HotkeysCheck: TKOLCheckBox; ColorMenu: TKOLPopupMenu; StylesGroupBox: TKOLGroupBox; function KOLFormMessage(var Msg: TMsg; var Rslt: Integer): Boolean; procedure CancelButtonClick(Sender: PObj); procedure OKButtonClick(Sender: PObj); procedure KOLFormShow(Sender: PObj); procedure KOLFormFormCreate(Sender: PObj); procedure StyleComboChange(Sender: PObj); procedure StyleCheckClick(Sender: PObj); procedure ColorPanelClick(Sender: PObj); procedure AutocompleteEditChange(Sender: PObj); procedure AutocompletionCheckClick(Sender: PObj); procedure GutterCheckClick(Sender: PObj); procedure HilightCheckClick(Sender: PObj); procedure KeepSpacesCheckClick(Sender: PObj); procedure OverwriteCheckClick(Sender: PObj); procedure RightMarginEditChange(Sender: PObj); procedure SmartTabsCheckClick(Sender: PObj); procedure TabSizeEditChange(Sender: PObj); procedure FontButtonClick(Sender: PObj); procedure HotkeysListKeyDown(Sender: PControl; var Key: Integer; Shift: Cardinal); procedure HotkeysListMouseDblClk(Sender: PControl; var Mouse: TMouseEventData); procedure ResetStylesButtonClick(Sender: PObj); procedure HotkeysListLeave(Sender: PObj); procedure HotkeysListMouseDown(Sender: PControl; var Mouse: TMouseEventData); procedure HotkeysCheckClick(Sender: PObj); procedure ColorMenuSelect(Sender: PMenu; Item: Integer); procedure ColorMenuCustom(Sender: PMenu; Item: Integer); private procedure SetOption(Option: TOptionEdit; State: Boolean); procedure SetPanelColor(Panel: PControl; Color: TColor); { Private declarations } public Ini: PIniFile; SampleEditor: PHilightMemo; SampleGutter: PControl; SampleHilighter: PCHilighter; procedure ReadWriteSettings(Mode: TIniFileMode); end; var FormOptions {$IFDEF KOL_MCK} : PFormOptions {$ELSE} : TFormOptions {$ENDIF} ; {$IFDEF KOL_MCK} procedure NewFormOptions( var Result: PFormOptions; AParent: PControl ); {$ENDIF} implementation uses MainForm; const SPressButton = 'Press key...'; {$IF Defined(KOL_MCK)}{$ELSE}{$R *.DFM}{$IFEND} {$IFDEF KOL_MCK} {$I OptionsForm_1.inc} {$ENDIF} function TFormOptions.KOLFormMessage(var Msg: TMsg; var Rslt: Integer): Boolean; begin Result := false; if Msg.message = WM_CLOSE then Form.Hide; end; procedure TFormOptions.CancelButtonClick(Sender: PObj); begin Form.Close; //TODO: reset SampleEditor/Hilighter/Gutter settings end; procedure TFormOptions.OKButtonClick(Sender: PObj); var i: Integer; begin for i := 0 to HotkeysList.LVCount - 1 do FormMain.ActionList.Actions[i].Accelerator := TMenuAccelerator(HotkeysList.LVItemData[i]); ReadWriteSettings(ifmWrite); Form.ModalResult := ID_OK; Form.Close; end; procedure TFormOptions.KOLFormShow(Sender: PObj); var i: Integer; begin Form.ModalResult := 0; ReadWriteSettings(ifmRead); HotkeysList.Enabled := HotkeysCheck.Checked; HotkeysList.Clear; for i := 0 to FormMain.ActionList.Count - 1 do begin HotkeysList.LVItemAdd(FormMain.ActionList.Actions[i].Hint); HotkeysList.LVItemData[i] := Cardinal(FormMain.ActionList.Actions[i].Accelerator); HotkeysList.LVItems[i, 1] := GetAcceleratorText(FormMain.ActionList.Actions[i].Accelerator); end; AutocompletionCheck.Checked := oeAutoCompletion in SampleEditor.Edit.Options; HilightCheck.Checked := oeHighlight in SampleEditor.Edit.Options; KeepSpacesCheck.Checked := oeKeepTrailingSpaces in SampleEditor.Edit.Options; OverwriteCheck.Checked := oeOverwrite in SampleEditor.Edit.Options; SmartTabsCheck.Checked := oeSmartTabs in SampleEditor.Edit.Options; GutterCheck.Checked := SampleGutter.Visible; AutocompleteEdit.Visible := AutocompletionCheck.Checked; AutocompleteEdit.Text := Int2Str(SampleEditor.Edit.AutoCompleteMinWordLength); RightMarginEdit.Text := Int2Str(SampleEditor.Edit.RightMarginChars); TabSizeEdit.Text := Int2Str(SampleEditor.Edit.TabSize); FontPanel.Font.Assign(SampleEditor.Font); FontPanel.Caption := FontPanel.Font.FontName; StyleCombo.CurIndex := 0; StyleCombo.OnChange(StyleCombo); CurLineColorPanel.Visible := GutterCheck.Checked; SetPanelColor(CurLineColorPanel, SampleGutter.Color1); SetPanelColor(RightMarginColorPanel, SampleEditor.Edit.RightMarginColor); end; procedure TFormOptions.KOLFormFormCreate(Sender: PObj); var i: Integer; Bitmap: PBitmap; Style: THilightStyle; begin Ini := OpenIniFile(ChangeFileExt(ExePath, '.ini')); for i := 1 to ColorMenu.Count - 1 do begin Bitmap := NewBitmap(GetSystemMetrics(SM_CXMENUCHECK), GetSystemMetrics(SM_CXMENUCHECK)); Bitmap.Canvas.Pen.Color := clBlack; Bitmap.Canvas.Brush.Color := Integer(ColorMenu.Items[ColorMenu.ItemHandle[i]].Tag); Bitmap.Canvas.Rectangle(0, 0, Bitmap.Width, Bitmap.Height); ColorMenu.ItemBitmap[i] := Bitmap.Handle; ColorMenu.Add2AutoFree(Bitmap); end; New(SampleHilighter, Create); Form.Add2AutoFree(SampleHilighter); SampleEditor := NewHilightEdit(EditorPanel); with SampleEditor^ do begin Border := 0; Align := caClient; ExStyle := (ExStyle and not WS_EX_CLIENTEDGE) or WS_EX_STATICEDGE; Edit.Options := [oeReadOnly, oeSmartTabs, oeHighlight, oeAutoCompletion]; Edit.TabSize := 4; Edit.RightMarginColor := clSilver; Edit.OnScanToken := SampleHilighter.ScanToken; Edit.Text := '//Highlighting sample'#13#10+ '#include <stdio.h>'#13#10#13#10+ 'int main(void)'#13#10+ '{'#13#10+ #9'printf("Hello World!\n");'#13#10+ #9'return 0;'#13#10+ '}'; end; SampleGutter := NewGutter(EditorPanel, SampleEditor).SetSize(32, 0).SetAlign(caLeft); SampleGutter.Color1 := clSkyBlue; for Style := Low(THilightStyle) to High(THilightStyle) do StyleCombo.ItemData[StyleCombo.Add(StyleNames[Style])] := Integer(Style); ReadWriteSettings(ifmRead); end; procedure TFormOptions.StyleComboChange(Sender: PObj); begin with SampleHilighter.Styles[THilightStyle(StyleCombo.ItemData[StyleCombo.CurIndex])] do begin SetPanelColor(FontColorPanel, fontcolor); SetPanelColor(BackColorPanel, backcolor); BoldCheck.Checked := fsBold in fontstyle; ItalicCheck.Checked := fsItalic in fontstyle; UnderlineCheck.Checked := fsUnderline in fontstyle; StrikeCheck.Checked := fsStrikeOut in fontstyle; end; end; procedure TFormOptions.StyleCheckClick(Sender: PObj); begin with SampleHilighter.Styles[THilightStyle(StyleCombo.ItemData[StyleCombo.CurIndex])] do begin fontstyle := []; if BoldCheck.Checked then fontstyle := fontstyle + [fsBold]; if ItalicCheck.Checked then fontstyle := fontstyle + [fsItalic]; if UnderlineCheck.Checked then fontstyle := fontstyle + [fsUnderline]; if StrikeCheck.Checked then fontstyle := fontstyle + [fsStrikeOut]; end; SampleEditor.Invalidate; end; procedure TFormOptions.ColorPanelClick(Sender: PObj); var i: Integer; P: TPoint; begin ColorMenu.Tag := Cardinal(Sender); with PControl(Sender)^ do begin P := Point(Left, Top + Height); ClientToScreen(ParentWindow, P); ColorMenu.ItemChecked[0] := true; for i := 1 to ColorMenu.Count - 1 do begin ColorMenu.ItemChecked[i] := TColor(ColorMenu.Items[ColorMenu.ItemHandle[i]].Tag) = Color; if ColorMenu.ItemChecked[i] then ColorMenu.ItemChecked[0] := false; end; end; ColorMenu.Popup(P.X, P.Y); end; procedure TFormOptions.SetPanelColor(Panel: PControl; Color: TColor); begin Panel.Color := Color; if 74 * (Color and $FF) + 163 * ((Color shr 8) and $FF) + 19 * ((Color shr 16) and $FF) >= 32768 then Panel.Font.Color := clBlack else Panel.Font.Color := clWhite; end; procedure TFormOptions.AutocompleteEditChange(Sender: PObj); begin SampleEditor.Edit.AutoCompleteMinWordLength := Str2Int(AutocompleteEdit.Text); end; procedure TFormOptions.AutocompletionCheckClick(Sender: PObj); begin SetOption(oeAutoCompletion, AutocompletionCheck.Checked); AutocompleteEdit.Visible := AutocompletionCheck.Checked; end; procedure TFormOptions.GutterCheckClick(Sender: PObj); begin SampleGutter.Visible := GutterCheck.Checked; CurLineColorPanel.Visible := GutterCheck.Checked; end; procedure TFormOptions.HilightCheckClick(Sender: PObj); begin SetOption(oeHighlight, HilightCheck.Checked); end; procedure TFormOptions.KeepSpacesCheckClick(Sender: PObj); begin SetOption(oeKeepTrailingSpaces, KeepSpacesCheck.Checked); end; procedure TFormOptions.OverwriteCheckClick(Sender: PObj); begin SetOption(oeOverwrite, OverwriteCheck.Checked); end; procedure TFormOptions.RightMarginEditChange(Sender: PObj); begin SampleEditor.Edit.RightMarginChars := Str2Int(RightMarginEdit.Text); SampleEditor.Invalidate; end; procedure TFormOptions.SetOption(Option: TOptionEdit; State: Boolean); begin if State then SampleEditor.Edit.Options := SampleEditor.Edit.Options + [Option] else SampleEditor.Edit.Options := SampleEditor.Edit.Options - [Option]; SampleEditor.Invalidate; end; procedure TFormOptions.SmartTabsCheckClick(Sender: PObj); begin SetOption(oeSmartTabs, SmartTabsCheck.Checked); end; procedure TFormOptions.TabSizeEditChange(Sender: PObj); begin SampleEditor.Edit.TabSize := Str2Int(TabSizeEdit.Text); SampleEditor.Invalidate; end; procedure TFormOptions.FontButtonClick(Sender: PObj); begin FontDialog.InitFont.Assign(FontPanel.Font); FontDialog.Font.Assign(FontPanel.Font); if not FontDialog.Execute then Exit; FontPanel.Font.Assign(FontDialog.Font); FontPanel.Caption := FontPanel.Font.FontName; SampleEditor.Font.Assign(FontDialog.Font); SampleGutter.Font.Assign(FontDialog.Font); end; procedure TFormOptions.HotkeysListKeyDown(Sender: PControl; var Key: Integer; Shift: Cardinal); begin if (HotkeysList.Tag > 0) and not (Key in [VK_ALT, VK_CONTROL, VK_SHIFT, VK_ESCAPE]) then begin if (GetKeyState(VK_MENU) and $80) <> 0 then Shift := Shift or FALT; HotkeysList.LVItemData[HotkeysList.Tag - 1] := Cardinal(MakeAccelerator(Shift or FVIRTKEY, Key)); HotkeysListLeave(Sender); end; end; procedure TFormOptions.HotkeysListMouseDblClk(Sender: PControl; var Mouse: TMouseEventData); begin if HotkeysList.LVCurItem >= 0 then begin HotkeysList.Tag := HotkeysList.LVCurItem + 1; HotkeysList.LVItems[HotkeysList.LVCurItem, 1] := SPressButton; end; end; procedure TFormOptions.ReadWriteSettings(Mode: TIniFileMode); var i: Integer; Style: THilightStyle; begin Ini.Mode := Mode; Ini.Section := 'General'; SavePosCheck.Checked := Ini.ValueBoolean('SaveFormPosition', SavePosCheck.Checked); Ini.Section := 'Accelerators'; HotkeysCheck.Checked := Ini.ValueBoolean('Use', HotkeysCheck.Checked); if HotkeysCheck.Checked then with FormMain.ActionList^ do for i := 0 to Count - 1 do Actions[i].Accelerator := TMenuAccelerator(Ini.ValueInteger(Actions[i].Name, Integer(Actions[i].Accelerator))) else Ini.ClearSection; Ini.Section := 'Editor'; with SampleEditor.Edit^ do begin SetOption(oeAutocompletion, Ini.ValueBoolean('Autocomplete', oeAutocompletion in Options)); SetOption(oeHighlight, Ini.ValueBoolean('Highlight', oeHighlight in Options)); SetOption(oeKeepTrailingSpaces, Ini.ValueBoolean('KeepSpaces', oeKeepTrailingSpaces in Options)); SetOption(oeOverwrite, Ini.ValueBoolean('Overwrite', oeOverwrite in Options)); SetOption(oeSmartTabs, Ini.ValueBoolean('SmartTabs', oeSmartTabs in Options)); AutoCompleteMinWordLength := Ini.ValueInteger('CompleteAfter', AutoCompleteMinWordLength); RightMarginChars := Ini.ValueInteger('RightMargin', RightMarginChars); RightMarginColor := Ini.ValueInteger('RightMarginColor', RightMarginColor); TabSize := Ini.ValueInteger('TabSize', TabSize); end; SampleEditor.Font.FontName := Ini.ValueString('FontName', SampleEditor.Font.FontName); SampleEditor.Font.FontHeight := Ini.ValueInteger('FontHeight', SampleEditor.Font.FontHeight); SampleGutter.Font.Assign(SampleEditor.Font); SampleGutter.Visible := Ini.ValueBoolean('Gutter', SampleGutter.Visible); SampleGutter.Color1 := Ini.ValueInteger('CurLineColor', SampleGutter.Color1); Ini.Section := 'Styles'; for Style := Low(THilightStyle) to High(THilightStyle) do with SampleHilighter.Styles[Style] do begin fontcolor := Ini.ValueInteger(StyleNames[Style] + '.FontColor', fontcolor); backcolor := Ini.ValueInteger(StyleNames[Style] + '.BackColor', backcolor); fontstyle := TFontStyle(Byte(Ini.ValueInteger(StyleNames[Style] + '.Style', Byte(fontstyle)))); end; end; procedure TFormOptions.ResetStylesButtonClick(Sender: PObj); begin SampleHilighter.Styles := DefStyles; SampleEditor.Invalidate; end; procedure TFormOptions.HotkeysListLeave(Sender: PObj); begin if HotkeysList.Tag > 0 then HotkeysList.LVItems[HotkeysList.Tag - 1, 1] := GetAcceleratorText(TMenuAccelerator(HotkeysList.LVItemData[HotkeysList.Tag - 1])); HotkeysList.Tag := 0; end; procedure TFormOptions.HotkeysListMouseDown(Sender: PControl; var Mouse: TMouseEventData); begin HotkeysListLeave(Sender); end; procedure TFormOptions.HotkeysCheckClick(Sender: PObj); begin HotkeysList.Enabled := HotkeysCheck.Checked; end; procedure TFormOptions.ColorMenuSelect(Sender: PMenu; Item: Integer); var Color: TColor; begin Color := TColor(Sender.Items[Item].Tag); SetPanelColor(PControl(Sender.Tag), Color); with SampleHilighter.Styles[THilightStyle(StyleCombo.ItemData[StyleCombo.CurIndex])] do begin if PControl(Sender.Tag) = FontColorPanel then fontcolor := Color; if PControl(Sender.Tag) = BackColorPanel then backcolor := Color; end; if PControl(Sender.Tag) = CurLineColorPanel then SampleGutter.Color1 := Color; if PControl(Sender.Tag) = RightMarginColorPanel then SampleEditor.Edit.RightMarginColor := Color; SampleEditor.Invalidate; end; procedure TFormOptions.ColorMenuCustom(Sender: PMenu; Item: Integer); begin ColorDialog.CustomColors[1] := PControl(Sender.Tag).Color; ColorDialog.Color := PControl(Sender.Tag).Color; if ColorDialog.Execute then begin Sender.Items[Item].Tag := Cardinal(ColorDialog.Color); ColorMenuSelect(Sender, Item); end; end; end.
unit DataManager; interface uses Windows, SysUtils, Classes, DB, DBClient, FMTBcd, Provider, SqlExpr, { Fluente } UnModelo; type TDataManager = class(TObject) private FSystem: TFlSystem; FDataObjects: TList; FDataProxy: TFlDataProxy; protected function GetConnection(ADataObject: TFlComp = nil; AConnection: TFlConnection = nil): TFlConnection; function NewDataObjectInstance(ADataObjectClassName: string; AConnection: TFlConnection): TFlDataObject; public constructor Create(ADataProxy: TFlDataProxy); reintroduce; procedure ClearInstance(Sender: TObject); function FindDataObject(ADataObject: TFlComp; const ACreateIt: Boolean = True): TFlDataObject; function GetAssemblyConnection: TFlAssembly; function GetDataObject(ADataObjectCode: string): TFlDataObject; overload; function GetDataObject(ADataObject: TFlComp; AUpdated: Boolean = False; AConnection: TFlConnection = nil): TFlDataObject; overload; function GetDataObjects: TList; function GetDataProxy: TFlDataProxy; function GetSystem: TFlSystem; procedure SetSystem(ASystem: TFlSystem); published end; implementation uses Dialogs; { TFlDataManager } function TFlDataManager.FindDataObject(ADataObject: TFlComp; const ACreateIt: Boolean = True): TFlDataObject; var i: Integer; iComp: TFlComp; begin Result := nil; for i := 0 to Self.GetDataObjects().Count-1 do begin iComp := TFlComp(TFlDataObject(Self.GetDataObjects().Items[i]).GetComp()); if (iComp <> nil) and (iComp.Info.Code = ADataObject.Info.Code) then begin Result := TFlDataObject(Self.GetDataObjects().Items[i]); Break; end; end; if (Result = nil) and ACreateIt then Result := Self.GetDataObject(ADataObject); end; function TFlDataManager.GetDataObject(ADataObject: TFlComp; AUpdated: Boolean = False; AConnection: TFlConnection = nil): TFlDataObject; var iConnection: TFlConnection; iDataObjectCode, iDataObjectName: string; begin iConnection := Self.GetConnection(ADataObject, AConnection); iDataObjectCode := ADataObject.Info.Code; iDataObjectName := 'T' + iConnection.GetConnectionItem.DriverName + iDataObjectCode; Result := Self.NewDataObjectInstance(iDataObjectName, iConnection); end; function TFlDataManager.GetDataObjects: TList; begin if Self.FDataObjects = nil then Self.FDataObjects := TList.Create; Result := Self.FDataObjects; end; constructor TFlDataManager.Create(ADataProxy: TFlDataProxy); begin inherited Create(); Self.FDataProxy := ADataProxy; end; function TFlDataManager.GetDataProxy: TFlDataProxy; begin Result := Self.FDataProxy; end; procedure TFlDataManager.ClearInstance(Sender: TObject); begin while Self.FDataObjects.Count > 0 do begin TFlDataObject(Self.FDataObjects.Items[0]).ClearInstance(Self); TFlDataObject(Self.FDataObjects.Items[0]).Free; Self.FDataObjects.Delete(0); end; Self.FDataObjects.Free; Self.FDataObjects := nil; end; function TFlDataManager.GetSystem: TFlSystem; begin Result := Self.FSystem; end; procedure TFlDataManager.SetSystem(ASystem: TFlSystem); begin Self.FSystem := ASystem; end; function TFlDataManager.GetConnection(ADataObject: TFlComp = nil; AConnection: TFlConnection = nil): TFlConnection; begin if (ADataObject <> nil) and (ADataObject.Info.Connection <> '') then Result := Self.GetDataProxy().GetConnection(ADataObject.Info.Connection) else if AConnection <> nil then Result := AConnection else if Self.GetSystem().DefaultConnectionName <> '' then Result := Self.GetDataProxy().GetConnection(Self.GetSystem().DefaultConnectionName) else Result := Self.GetDataProxy().GetDefaultLocalConnection(); end; function TFlDataManager.GetDataObject(ADataObjectCode: string): TFlDataObject; var iConnection: TFlConnection; iDataObjectCode, iDataObjectName: string; begin iConnection := Self.GetConnection(); iDataObjectCode := ADataObjectCode; iDataObjectName := 'T' + iConnection.GetConnectionItem.DriverName + iDataObjectCode; Result := Self.NewDataObjectInstance(iDataObjectName, iConnection); end; function TFlDataManager.NewDataObjectInstance(ADataObjectClassName: string; AConnection: TFlConnection): TFlDataObject; var iDataObjectClass: TFlDataObjectClass; begin iDataObjectClass := TFlDataObjectClass(Classes.GetClass(ADataObjectClassName)); if iDataObjectClass <> nil then Result := TComponentClass(iDataObjectClass).Create(nil) as TFlDataObject else Result := TFlDataObject.Create(nil); Result.SetConnection(AConnection); Result.SetSystem(Self.GetSystem()); Result.InitInstance(Self); Self.GetDataObjects().Add(Result); end; function TFlDataManager.GetAssemblyConnection: TFlAssembly; begin Result := Self.GetDataProxy().GetDefaultAssemblyConnection(); end; end.
unit AnimateImpl1; interface uses Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls, ComServ, StdVCL, AXCtrls, DelCtrls_TLB, ComCtrls; type TAnimateX = class(TActiveXControl, IAnimateX) private { Private declarations } FDelphiControl: TAnimate; FEvents: IAnimateXEvents; procedure CloseEvent(Sender: TObject); procedure OpenEvent(Sender: TObject); procedure StartEvent(Sender: TObject); procedure StopEvent(Sender: TObject); protected { Protected declarations } procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override; procedure EventSinkChanged(const EventSink: IUnknown); override; procedure InitializeControl; override; function ClassNameIs(const Name: WideString): WordBool; safecall; function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall; function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall; function Get_Active: WordBool; safecall; function Get_AutoSize: WordBool; safecall; function Get_BiDiMode: TxBiDiMode; safecall; function Get_Center: WordBool; safecall; function Get_Color: OLE_COLOR; safecall; function Get_CommonAVI: TxCommonAVI; safecall; function Get_Cursor: Smallint; safecall; function Get_DoubleBuffered: WordBool; safecall; function Get_Enabled: WordBool; safecall; function Get_FileName: WideString; safecall; function Get_FrameCount: Integer; safecall; function Get_FrameHeight: Integer; safecall; function Get_FrameWidth: Integer; safecall; function Get_Open: WordBool; safecall; function Get_ParentColor: WordBool; safecall; function Get_Repetitions: Integer; safecall; function Get_ResHandle: Integer; safecall; function Get_ResId: Integer; safecall; function Get_ResName: WideString; safecall; function Get_StartFrame: Smallint; safecall; function Get_StopFrame: Smallint; safecall; function Get_Timers: WordBool; safecall; function Get_Transparent: WordBool; safecall; function Get_Visible: WordBool; safecall; function GetControlsAlignment: TxAlignment; safecall; function IsRightToLeft: WordBool; safecall; function UseRightToLeftAlignment: WordBool; safecall; function UseRightToLeftReading: WordBool; safecall; function UseRightToLeftScrollBar: WordBool; safecall; procedure AboutBox; safecall; procedure FlipChildren(AllLevels: WordBool); safecall; procedure InitiateAction; safecall; procedure Play(FromFrame, ToFrame: Smallint; Count: Integer); safecall; procedure Reset; safecall; procedure Seek(Frame: Smallint); safecall; procedure Set_Active(Value: WordBool); safecall; procedure Set_AutoSize(Value: WordBool); safecall; procedure Set_BiDiMode(Value: TxBiDiMode); safecall; procedure Set_Center(Value: WordBool); safecall; procedure Set_Color(Value: OLE_COLOR); safecall; procedure Set_CommonAVI(Value: TxCommonAVI); safecall; procedure Set_Cursor(Value: Smallint); safecall; procedure Set_DoubleBuffered(Value: WordBool); safecall; procedure Set_Enabled(Value: WordBool); safecall; procedure Set_FileName(const Value: WideString); safecall; procedure Set_Open(Value: WordBool); safecall; procedure Set_ParentColor(Value: WordBool); safecall; procedure Set_Repetitions(Value: Integer); safecall; procedure Set_ResHandle(Value: Integer); safecall; procedure Set_ResId(Value: Integer); safecall; procedure Set_ResName(const Value: WideString); safecall; procedure Set_StartFrame(Value: Smallint); safecall; procedure Set_StopFrame(Value: Smallint); safecall; procedure Set_Timers(Value: WordBool); safecall; procedure Set_Transparent(Value: WordBool); safecall; procedure Set_Visible(Value: WordBool); safecall; procedure Stop; safecall; end; implementation uses ComObj, About1; { TAnimateX } procedure TAnimateX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); begin { Define property pages here. Property pages are defined by calling DefinePropertyPage with the class id of the page. For example, DefinePropertyPage(Class_AnimateXPage); } end; procedure TAnimateX.EventSinkChanged(const EventSink: IUnknown); begin FEvents := EventSink as IAnimateXEvents; end; procedure TAnimateX.InitializeControl; begin FDelphiControl := Control as TAnimate; FDelphiControl.OnClose := CloseEvent; FDelphiControl.OnOpen := OpenEvent; FDelphiControl.OnStart := StartEvent; FDelphiControl.OnStop := StopEvent; end; function TAnimateX.ClassNameIs(const Name: WideString): WordBool; begin Result := FDelphiControl.ClassNameIs(Name); end; function TAnimateX.DrawTextBiDiModeFlags(Flags: Integer): Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlags(Flags); end; function TAnimateX.DrawTextBiDiModeFlagsReadingOnly: Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly; end; function TAnimateX.Get_Active: WordBool; begin Result := FDelphiControl.Active; end; function TAnimateX.Get_AutoSize: WordBool; begin Result := FDelphiControl.AutoSize; end; function TAnimateX.Get_BiDiMode: TxBiDiMode; begin Result := Ord(FDelphiControl.BiDiMode); end; function TAnimateX.Get_Center: WordBool; begin Result := FDelphiControl.Center; end; function TAnimateX.Get_Color: OLE_COLOR; begin Result := OLE_COLOR(FDelphiControl.Color); end; function TAnimateX.Get_CommonAVI: TxCommonAVI; begin Result := Ord(FDelphiControl.CommonAVI); end; function TAnimateX.Get_Cursor: Smallint; begin Result := Smallint(FDelphiControl.Cursor); end; function TAnimateX.Get_DoubleBuffered: WordBool; begin Result := FDelphiControl.DoubleBuffered; end; function TAnimateX.Get_Enabled: WordBool; begin Result := FDelphiControl.Enabled; end; function TAnimateX.Get_FileName: WideString; begin Result := WideString(FDelphiControl.FileName); end; function TAnimateX.Get_FrameCount: Integer; begin Result := FDelphiControl.FrameCount; end; function TAnimateX.Get_FrameHeight: Integer; begin Result := FDelphiControl.FrameHeight; end; function TAnimateX.Get_FrameWidth: Integer; begin Result := FDelphiControl.FrameWidth; end; function TAnimateX.Get_Open: WordBool; begin Result := FDelphiControl.Open; end; function TAnimateX.Get_ParentColor: WordBool; begin Result := FDelphiControl.ParentColor; end; function TAnimateX.Get_Repetitions: Integer; begin Result := FDelphiControl.Repetitions; end; function TAnimateX.Get_ResHandle: Integer; begin Result := Integer(FDelphiControl.ResHandle); end; function TAnimateX.Get_ResId: Integer; begin Result := FDelphiControl.ResId; end; function TAnimateX.Get_ResName: WideString; begin Result := WideString(FDelphiControl.ResName); end; function TAnimateX.Get_StartFrame: Smallint; begin Result := FDelphiControl.StartFrame; end; function TAnimateX.Get_StopFrame: Smallint; begin Result := FDelphiControl.StopFrame; end; function TAnimateX.Get_Timers: WordBool; begin Result := FDelphiControl.Timers; end; function TAnimateX.Get_Transparent: WordBool; begin Result := FDelphiControl.Transparent; end; function TAnimateX.Get_Visible: WordBool; begin Result := FDelphiControl.Visible; end; function TAnimateX.GetControlsAlignment: TxAlignment; begin Result := TxAlignment(FDelphiControl.GetControlsAlignment); end; function TAnimateX.IsRightToLeft: WordBool; begin Result := FDelphiControl.IsRightToLeft; end; function TAnimateX.UseRightToLeftAlignment: WordBool; begin Result := FDelphiControl.UseRightToLeftAlignment; end; function TAnimateX.UseRightToLeftReading: WordBool; begin Result := FDelphiControl.UseRightToLeftReading; end; function TAnimateX.UseRightToLeftScrollBar: WordBool; begin Result := FDelphiControl.UseRightToLeftScrollBar; end; procedure TAnimateX.AboutBox; begin ShowAnimateXAbout; end; procedure TAnimateX.FlipChildren(AllLevels: WordBool); begin FDelphiControl.FlipChildren(AllLevels); end; procedure TAnimateX.InitiateAction; begin FDelphiControl.InitiateAction; end; procedure TAnimateX.Play(FromFrame, ToFrame: Smallint; Count: Integer); begin FDelphiControl.Play(FromFrame, ToFrame, Count); end; procedure TAnimateX.Reset; begin FDelphiControl.Reset; end; procedure TAnimateX.Seek(Frame: Smallint); begin FDelphiControl.Seek(Frame); end; procedure TAnimateX.Set_Active(Value: WordBool); begin FDelphiControl.Active := Value; end; procedure TAnimateX.Set_AutoSize(Value: WordBool); begin FDelphiControl.AutoSize := Value; end; procedure TAnimateX.Set_BiDiMode(Value: TxBiDiMode); begin FDelphiControl.BiDiMode := TBiDiMode(Value); end; procedure TAnimateX.Set_Center(Value: WordBool); begin FDelphiControl.Center := Value; end; procedure TAnimateX.Set_Color(Value: OLE_COLOR); begin FDelphiControl.Color := TColor(Value); end; procedure TAnimateX.Set_CommonAVI(Value: TxCommonAVI); begin FDelphiControl.CommonAVI := TCommonAVI(Value); end; procedure TAnimateX.Set_Cursor(Value: Smallint); begin FDelphiControl.Cursor := TCursor(Value); end; procedure TAnimateX.Set_DoubleBuffered(Value: WordBool); begin FDelphiControl.DoubleBuffered := Value; end; procedure TAnimateX.Set_Enabled(Value: WordBool); begin FDelphiControl.Enabled := Value; end; procedure TAnimateX.Set_FileName(const Value: WideString); begin FDelphiControl.FileName := String(Value); end; procedure TAnimateX.Set_Open(Value: WordBool); begin FDelphiControl.Open := Value; end; procedure TAnimateX.Set_ParentColor(Value: WordBool); begin FDelphiControl.ParentColor := Value; end; procedure TAnimateX.Set_Repetitions(Value: Integer); begin FDelphiControl.Repetitions := Value; end; procedure TAnimateX.Set_ResHandle(Value: Integer); begin FDelphiControl.ResHandle := Cardinal(Value); end; procedure TAnimateX.Set_ResId(Value: Integer); begin FDelphiControl.ResId := Value; end; procedure TAnimateX.Set_ResName(const Value: WideString); begin FDelphiControl.ResName := String(Value); end; procedure TAnimateX.Set_StartFrame(Value: Smallint); begin FDelphiControl.StartFrame := Value; end; procedure TAnimateX.Set_StopFrame(Value: Smallint); begin FDelphiControl.StopFrame := Value; end; procedure TAnimateX.Set_Timers(Value: WordBool); begin FDelphiControl.Timers := Value; end; procedure TAnimateX.Set_Transparent(Value: WordBool); begin FDelphiControl.Transparent := Value; end; procedure TAnimateX.Set_Visible(Value: WordBool); begin FDelphiControl.Visible := Value; end; procedure TAnimateX.Stop; begin FDelphiControl.Stop; end; procedure TAnimateX.CloseEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnClose; end; procedure TAnimateX.OpenEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnOpen; end; procedure TAnimateX.StartEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnStart; end; procedure TAnimateX.StopEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnStop; end; initialization TActiveXControlFactory.Create( ComServer, TAnimateX, TAnimate, Class_AnimateX, 1, '{695CDAD3-02E5-11D2-B20D-00C04FA368D4}', 0, tmApartment); end.
unit PaymentDetail; interface uses Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopupDetail, RzButton, RzTabs, Vcl.StdCtrls, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, Vcl.Mask, RzEdit, Vcl.DBCtrls, RzDBCmbo, RzCmboBx, Data.DB, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzRadChk, DateUtils, Math; type TfrmPaymentDetail = class(TfrmBasePopupDetail) edPrincipal: TRzNumericEdit; edInterest: TRzNumericEdit; edPenalty: TRzNumericEdit; urlPrincipalAmortization: TRzURLLabel; urlInterestAmortization: TRzURLLabel; cbxFullPayment: TRzCheckBox; urlLedger: TRzURLLabel; urlAmortization: TRzURLLabel; urlInterestDueOnPaymentDate: TRzURLLabel; urlTotalInterestDue: TRzURLLabel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Label15: TLabel; lblLoanId: TLabel; lblType: TLabel; lblLoanBalance: TLabel; lblInterestDeficit: TLabel; lblPrincipalDeficit: TLabel; lblRemainingAmount: TLabel; lblAccount: TLabel; lblLastTransaction: TLabel; lblDays: TLabel; lblTotal: TLabel; procedure FormCreate(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure edPrincipalChange(Sender: TObject); procedure edInterestChange(Sender: TObject); procedure edPenaltyChange(Sender: TObject); procedure urlPrincipalAmortizationClick(Sender: TObject); procedure urlInterestAmortizationClick(Sender: TObject); procedure cbxFullPaymentClick(Sender: TObject); procedure urlLedgerClick(Sender: TObject); procedure urlAmortizationClick(Sender: TObject); procedure urlInterestDueOnPaymentDateClick(Sender: TObject); procedure urlTotalInterestDueClick(Sender: TObject); private { Private declarations } procedure SetTotalAmount; procedure GetFullPayment; procedure SetLoanDetails; procedure OpenLedger; public { Public declarations } protected procedure Save; override; procedure Cancel; override; procedure BindToObject; override; function ValidEntry: boolean; override; end; implementation {$R *.dfm} uses Payment, IFinanceDialogs, FormsUtil, LoanLedger, PaymentData, LoanClassification; procedure TfrmPaymentDetail.cbxFullPaymentClick(Sender: TObject); begin inherited; GetFullPayment; end; procedure TfrmPaymentDetail.edInterestChange(Sender: TObject); begin inherited; pmt.Details[pmt.DetailCount-1].Interest := edInterest.Value; SetTotalAmount; end; procedure TfrmPaymentDetail.edPenaltyChange(Sender: TObject); begin inherited; pmt.Details[pmt.DetailCount-1].Penalty := edPenalty.Value; SetTotalAmount; end; procedure TfrmPaymentDetail.edPrincipalChange(Sender: TObject); begin inherited; pmt.Details[pmt.DetailCount-1].Principal := edPrincipal.Value; SetTotalAmount; end; procedure TfrmPaymentDetail.FormCreate(Sender: TObject); begin SetLoanDetails; end; procedure TfrmPaymentDetail.FormKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key = #13 then Save; // enter key end; procedure TfrmPaymentDetail.GetFullPayment; var i: integer; begin i := pmt.Client.IndexOf(pmt.Details[pmt.DetailCount-1].Loan); if cbxFullPayment.Checked then begin edPrincipal.Value := pmt.Client.ActiveLoans[i].Balance; if pmt.Client.ActiveLoans[i].IsFixed then edInterest.Value := pmt.Client.ActiveLoans[i].InterestTotalDue - pmt.Client.ActiveLoans[i].Rebate else edInterest.Value := pmt.Client.ActiveLoans[i].FullPaymentInterest + pmt.Client.ActiveLoans[i].InterestTotalDue; end else begin edPrincipal.Clear; edInterest.Clear; end; pmt.Details[pmt.DetailCount-1].IsFullPayment := cbxFullPayment.Checked; edPrincipal.Enabled := not cbxFullPayment.Checked; edInterest.Enabled := not cbxFullPayment.Checked; urlPrincipalAmortization.Enabled := not cbxFullPayment.Checked; urlInterestAmortization.Enabled := not cbxFullPayment.Checked; SetLoanDetails; end; procedure TfrmPaymentDetail.OpenLedger; begin with TfrmLoanLedger.Create(self,dmPayment.dscLedger) do begin ShowModal; Free; end end; procedure TfrmPaymentDetail.Save; begin end; procedure TfrmPaymentDetail.BindToObject; begin inherited; end; procedure TfrmPaymentDetail.Cancel; var detail: TPaymentDetail; begin detail := pmt.Details[pmt.DetailCount-1]; pmt.RemoveDetail(detail.Loan); end; procedure TfrmPaymentDetail.SetTotalAmount; var amount: currency; begin with lblTotal do begin amount := pmt.Details[pmt.DetailCount-1].TotalAmount; // change colour if amount < 0 then Color := clRed else Color := clBlack; Caption := 'Total amount: ' + FormatCurr('###,###,##0.00',amount); end; end; procedure TfrmPaymentDetail.urlAmortizationClick(Sender: TObject); var i: integer; begin i := pmt.Client.IndexOf(pmt.Details[pmt.DetailCount-1].Loan); if pmt.Client.ActiveLoans[i].Amortization = (pmt.Client.ActiveLoans[i].InterestAmortisation + pmt.Client.ActiveLoans[i].PrincipalAmortisation) then begin edInterest.Value := pmt.Client.ActiveLoans[i].InterestAmortisation; edPrincipal.Value := pmt.Client.ActiveLoans[i].PrincipalAmortisation; end else begin edInterest.Value := pmt.Client.ActiveLoans[i].InterestAmortisation; if (pmt.Client.ActiveLoans[i].Amortization - pmt.Client.ActiveLoans[i].InterestAmortisation) > 0 then edPrincipal.Value := pmt.Client.ActiveLoans[i].Amortization - pmt.Client.ActiveLoans[i].InterestAmortisation; end end; procedure TfrmPaymentDetail.urlInterestAmortizationClick(Sender: TObject); var i: integer; begin i := pmt.Client.IndexOf(pmt.Details[pmt.DetailCount-1].Loan); edInterest.Value := pmt.Client.ActiveLoans[i].InterestAmortisation; end; procedure TfrmPaymentDetail.urlInterestDueOnPaymentDateClick(Sender: TObject); var i: integer; begin i := pmt.Client.IndexOf(pmt.Details[pmt.DetailCount-1].Loan); edInterest.Value := pmt.Client.ActiveLoans[i].InterestDueOnPaymentDate; end; procedure TfrmPaymentDetail.urlLedgerClick(Sender: TObject); begin inherited; OpenLedger; end; procedure TfrmPaymentDetail.urlPrincipalAmortizationClick(Sender: TObject); var i: integer; begin i := pmt.Client.IndexOf(pmt.Details[pmt.DetailCount-1].Loan); edPrincipal.Value := pmt.Client.ActiveLoans[i].PrincipalAmortisation; end; procedure TfrmPaymentDetail.urlTotalInterestDueClick(Sender: TObject); var i: integer; begin i := pmt.Client.IndexOf(pmt.Details[pmt.DetailCount-1].Loan); edInterest.Value := pmt.Client.ActiveLoans[i].InterestTotalDue; end; function TfrmPaymentDetail.ValidEntry: boolean; var error: string; LDetail: TPaymentDetail; begin LDetail := pmt.Details[pmt.DetailCount-1]; if LDetail.Principal < 0 then error := 'Invalid value for principal.' else if LDetail.Interest < 0 then error := 'Invalid value for interest.' else if LDetail.TotalAmount <= 0 then error := 'No amount entered.' else if LDetail.Principal > LDetail.Loan.Balance then error := 'Principal amount is greater than to the loan balance.' // else if (not LDetail.IsFullPayment) and (LDetail.Interest > LDetail.Loan.InterestTotalDue) then // error := 'Interest amount is greater than the total interest due.' else if (not LDetail.IsFullPayment) and (LDetail.Principal > LDetail.Loan.Balance) then error := 'Principal amount is equal to the loan balance. If this is a full payment posting, tick the FULL PAYMENT box instead.' else if (pmt.IsWithdrawal) and (LDetail.TotalAmount > pmt.Withdrawn) then error := 'Total amount is greater than the remaining withdrawn amount.'; if error <> '' then ShowErrorBox(error); Result := error = ''; end; procedure TfrmPaymentDetail.SetLoanDetails; var i: integer; begin i := pmt.Client.IndexOf(pmt.Details[pmt.DetailCount-1].Loan); // get the ledger pmt.Client.ActiveLoans[i].RetrieveLedger; pmt.Client.ActiveLoans[i].GetPaymentDue(pmt.Date); // set labels lblLoanId.Caption := pmt.Client.ActiveLoans[i].Id; lblType.Caption := pmt.Client.ActiveLoans[i].LoanTypeName; lblAccount.Caption := pmt.Client.ActiveLoans[i].AccountTypeName + ' - ' + pmt.Client.ActiveLoans[i].InterestMethodName; lblLoanBalance.Caption := FormatCurr('###,###,##0.00', pmt.Client.ActiveLoans[i].Balance); lblPrincipalDeficit.Caption := FormatCurr('###,###,##0.00;(###,###,##0.00);-', pmt.Client.ActiveLoans[i].PrincipalDeficit); lblInterestDeficit.Caption := FormatCurr('###,###,##0.00;(###,###,##0.00);-', pmt.Client.ActiveLoans[i].InterestDeficit); urlAmortization.Caption := FormatCurr('###,###,##0.00', pmt.Client.ActiveLoans[i].Amortization); {if pmt.Details[pmt.DetailCount-1].IsFullPayment then begin if (pmt.Client.ActiveLoans[i].IsFixed) or ((pmt.Client.ActiveLoans[i].IsDiminishing) and (pmt.Client.ActiveLoans[i].DiminishingType = dtScheduled)) then urlInterestDueOnPaymentDate.Caption := FormatCurr('###,###,##0.00;-;', pmt.Client.ActiveLoans[i].FullPaymentInterest) else urlInterestDueOnPaymentDate.Caption := FormatCurr('###,###,##0.00;-;', pmt.Client.ActiveLoans[i].InterestDueOnPaymentDate); end else} urlInterestDueOnPaymentDate.Caption := FormatCurr('###,###,##0.00;-;', pmt.Client.ActiveLoans[i].InterestDueOnPaymentDate); urlTotalInterestDue.Caption := FormatCurr('###,###,##0.00;-;-', pmt.Client.ActiveLoans[i].InterestTotalDue); lblLastTransaction.Caption := FormatDateTime('mm/dd/yyyy', pmt.Client.ActiveLoans[i].LastTransactionDate); lblDays.Caption := IntToStr(DaysBetween(pmt.Date,pmt.Client.ActiveLoans[i].LastTransactionDate)); urlPrincipalAmortization.Caption := FormatCurr('###,###,##0.00', pmt.Client.ActiveLoans[i].PrincipalAmortisation); urlInterestAmortization.Caption := FormatCurr('###,###,##0.00', pmt.Client.ActiveLoans[i].InterestAmortisation); lblRemainingAmount.Caption := 'Remaining amount: ' + FormatCurr('###,###,##0.00', pmt.Withdrawn - pmt.TotalAmount); lblRemainingAmount.Visible := pmt.IsWithdrawal; end; end.
unit frmUserGroupInfo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, uUserInfo; type TfUserGroupInfo = class(TForm) pgc1: TPageControl; ts1: TTabSheet; lbl1: TLabel; lbl3: TLabel; edtGroupName: TEdit; edtGroupDesc: TEdit; ts2: TTabSheet; lbl4: TLabel; lbl5: TLabel; lstAllRight: TListBox; lstCurrRight: TListBox; btnAdd: TButton; btnDel: TButton; btnAddAll: TButton; btnDelAll: TButton; btnCancel: TButton; btnOK: TButton; lblNotice: TLabel; procedure btnCancelClick(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnDelClick(Sender: TObject); procedure btnAddAllClick(Sender: TObject); procedure btnDelAllClick(Sender: TObject); private { Private declarations } FUserGroup : TUserGroup; procedure ShowAllRights; procedure ShowGroupRights; procedure MoveToGroupList(AFromList, AToList: TListBox); procedure MoveAll(AFromList, AToList: TListBox); public { Public declarations } procedure ShowInfo(AUserGroup : TUserGroup); procedure SaveInfo; end; var fUserGroupInfo: TfUserGroupInfo; implementation uses uUserControl, xFunction; {$R *.dfm} procedure TfUserGroupInfo.MoveAll(AFromList, AToList: TListBox); var I: Integer; begin for I := AFromList.Count - 1 downto 0 do begin AToList.Items.AddObject(AFromList.Items.Strings[I], AFromList.Items.Objects[I]); AFromList.Items.Delete(I); end; end; procedure TfUserGroupInfo.btnOKClick(Sender: TObject); procedure CheckUserGroup; begin if UserControl.CheckUGNameExists(edtGroupName.Text) then begin MessageBox(0, '该组名已存在,请使用其他名称!', '错误', mrok); pgc1.ActivePageIndex := 0; edtGroupName.SetFocus; end else ModalResult := mrOk; end; begin if edtGroupName.Text = '' then begin MessageBox(0, '组名不能为空!', '错误', mrok); pgc1.ActivePageIndex := 0; edtGroupName.SetFocus; end else begin if Assigned(FUserGroup) then begin if Assigned(UserControl) then begin if FUserGroup.ID = -1 then begin CheckUserGroup; end else begin if FUserGroup.Embedded then ModalResult := mrCancel else begin if FUserGroup.GroupName <> Trim(edtGroupName.Text) then CheckUserGroup else ModalResult := mrOk; end; end; end; end; end; end; procedure TfUserGroupInfo.MoveToGroupList(AFromList, AToList: TListBox); var I: Integer; begin for I := 0 to AFromList.Count - 1 do if AFromList.Selected[I] then begin AToList.Items.AddObject(AFromList.Items.Strings[I], AFromList.Items.Objects[I]); AFromList.Items.Delete(I); Break; end; end; procedure TfUserGroupInfo.btnAddAllClick(Sender: TObject); begin MoveAll(lstAllRight, lstCurrRight); end; procedure TfUserGroupInfo.btnAddClick(Sender: TObject); begin MoveToGroupList(lstAllRight, lstCurrRight); end; procedure TfUserGroupInfo.btnCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TfUserGroupInfo.btnDelAllClick(Sender: TObject); begin MoveAll(lstCurrRight, lstAllRight); end; procedure TfUserGroupInfo.btnDelClick(Sender: TObject); begin MoveToGroupList(lstCurrRight, lstAllRight); end; procedure TfUserGroupInfo.SaveInfo; var i : integer; ARight : TUserRight; begin if Assigned(FUserGroup) then begin FUserGroup.GroupName := Trim(edtGroupName.Text); FUserGroup.Description := Trim(edtGroupDesc.Text); ClearStringList(FUserGroup.Rights); for i := 0 to lstCurrRight.Items.Count - 1 do begin ARight := TUserRight.Create; ARight.Assign(TUserRight(lstCurrRight.Items.Objects[i])); FUserGroup.Rights.AddObject(ARight.RightName, ARight); end; end; end; procedure TfUserGroupInfo.ShowAllRights; var AUserRightList : TStringList; i : integer; begin AUserRightList := UserControl.UserRightList; lstAllRight.Clear; lstCurrRight.Clear; for I := 0 to AUserRightList.Count - 1 do begin with lstAllRight.Items do begin AddObject(TUserRight(AUserRightList.Objects[i]).RightName, AUserRightList.Objects[i]); end; end; end; procedure TfUserGroupInfo.ShowGroupRights; var i: Integer; nIndex : Integer; begin for i := 0 to FUserGroup.Rights.Count - 1 do begin nIndex := lstAllRight.Items.IndexOf( FUserGroup.Rights[ i ] ); if nIndex <> -1 then lstAllRight.Selected[ nIndex ] := True; MoveToGroupList( lstAllRight, lstCurrRight ); end; end; procedure TfUserGroupInfo.ShowInfo(AUserGroup: TUserGroup); begin FUserGroup := AUserGroup; if Assigned(FUserGroup) then begin if Assigned(UserControl) then begin edtGroupName.Text := FUserGroup.GroupName; edtGroupDesc.Text := FUserGroup.Description; ShowAllRights; if FUserGroup.ID <> -1 then begin ShowGroupRights; if FUserGroup.Embedded then begin ts1.Enabled := False; ts2.Enabled := False; lblNotice.Caption := '系统内置,不能编辑修改'; lblNotice.Visible := True; end; end; end; end; end; end.
unit ClassWords; interface uses ClassBSTree; const IS_WORD_FLAG = 32; LAST_FLAG = 64; HAS_CHILD_FLAG = 128; CHAR_MASK = 31; END_OF_WORDS = 'END OF WORDS'; type TWordsCallback = procedure( Word : string ) of object; TWords = class private FTree : TBSTree; FCallback : TWordsCallback; FCounter : integer; function UnpackWords( var F : File; Word : string ) : TBSTreeChildren; procedure CreateTree( FileName : string ); procedure EnumWordsRec( Tree : TBSTree; Word : string ); public constructor Create( FileName : string ); destructor Destroy; override; function ExistsWord( Word : string ) : boolean; procedure EnumWords( Callback : TWordsCallback ); end; implementation uses UnitFormWait; //============================================================================== // Constructor / destructor //============================================================================== constructor TWords.Create( FileName : string ); begin inherited Create; FTree := TBSTree.Create( #0 , false ); FCallback := nil; CreateTree( FileName ); end; destructor TWords.Destroy; begin FTree.Free; inherited; end; //============================================================================== // P R I V A T E //============================================================================== function TWords.UnpackWords( var F : File; Word : string ) : TBSTreeChildren; var B : byte; C : char; Last : boolean; Chars : array of record C : char; IsWord : boolean; HasChildren : boolean; end; I : integer; begin Last := false; SetLength( Chars , 0 ); repeat BlockRead( F , B , 1 ); Inc( FCounter ); if (FCounter = 2000) then begin FCounter := 0; FormWait.ProgressBar.StepBy( 2000 ); end; C := char((B and CHAR_MASK) + Ord( 'a' )); SetLength( Chars , Length( Chars )+1 ); Chars[Length( Chars )-1].C := C; if ((B and HAS_CHILD_FLAG) <> 0) then Chars[Length( Chars )-1].HasChildren := true else Chars[Length( Chars )-1].HasChildren := false; if ((B and IS_WORD_FLAG) <> 0) then Chars[Length( Chars )-1].IsWord := true else Chars[Length( Chars )-1].IsWord := false; if ((B and LAST_FLAG) <> 0) then Last := true; until Last; SetLength( Result , Length( Chars ) ); for I := 0 to Length( Chars )-1 do begin Result[I] := TBSTree.Create( Chars[I].C , Chars[I].IsWord ); SetLength( Result[I].Children , 0 ); end; for I := 0 to Length( Chars )-1 do if (Chars[I].HasChildren) then Result[I].Children := UnpackWords( F , Word + Chars[I].C ); end; procedure TWords.CreateTree( FileName : string ); var F : File; begin AssignFile( F , FileName ); Reset( F , 1 ); FormWait := TFormWait.Create( nil ); try FormWait.ProgressBar.Min := 0; FormWait.ProgressBar.Max := FileSize( F ); FormWait.ProgressBar.Position := 0; FormWait.ProgressBar.Step := 1; FormWait.Show; FormWait.Update; FCounter := 0; FTree.Children := UnpackWords( F , '' ); FormWait.Close; finally FormWait.Free; end; CloseFile( F ); end; procedure TWords.EnumWordsRec( Tree : TBSTree; Word : string ); var I : integer; begin if (Tree.IsWord) then FCallback( Word ); for I := Low( Tree.Children ) to High( Tree.Children ) do EnumWordsRec( Tree.Children[I] , Word+Tree.Children[I].C ); end; //============================================================================== // P U B L I C //============================================================================== function TWords.ExistsWord( Word : string ) : boolean; var T : TBSTree; I, J : integer; Found : boolean; begin Result := false; T := FTree; I := 1; repeat Found := false; for J := Low( T.Children ) to High( T.Children ) do if (T.Children[J].C = Word[I]) then begin Inc( I ); if ((I > Length( Word )) and (T.Children[J].IsWord)) then Result := true; T := T.Children[J]; Found := true; break; end; until ((I > Length( Word )) or (not Found)); end; procedure TWords.EnumWords( Callback : TWordsCallback ); begin FCallback := Callback; if (not Assigned( FCallback )) then exit; EnumWordsRec( FTree , '' ); FCallback( END_OF_WORDS ); end; end.
unit Firebird.Scanner.TokenKind.Tests; interface uses DUnitX.TestFramework, Nathan.Firebird.Validator.Syntax.Keywords.Intf, Nathan.Firebird.Validator.Syntax.Keywords.Types; {$M+} type [TestFixture] TTestFb25Token = class private FCut: IFb25Token; public [Setup] procedure SetUp(); [TearDown] procedure TearDown(); published [Test] [TestCase('Prop01', 'Nathan,fb25None')] [TestCase('Prop02', 'CREATE,fb25CREATE')] [TestCase('Prop03', '^,fb25Roof')] procedure Test_Properties(const Value: string; ATokenKind: TFb25TokenKind); end; {$M-} implementation uses Nathan.Firebird.Validator.Syntax.Keywords.Token, Nathan.Firebird.Validator.Syntax.Keywords.Scanner; { TTestFb25Token } procedure TTestFb25Token.SetUp; begin FCut := nil; end; procedure TTestFb25Token.TearDown; begin FCut := nil; end; procedure TTestFb25Token.Test_Properties(const Value: string; ATokenKind: TFb25TokenKind); begin FCut := TFb25Token.Create(Value, ATokenKind); Assert.AreEqual(Value, FCut.Value); Assert.AreEqual(ATokenKind, FCut.Token); end; initialization TDUnitX.RegisterTestFixture(TTestFb25Token, 'TokenKind'); end.
unit uDmERP; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.PG, FireDAC.Phys.PGDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Dialogs, Vcl.Forms, System.Variants, Xml.xmldom, Xml.XMLIntf, Xml.XMLDoc, Xml.Win.msxmldom, StrUtils, { Classes } uFuncoes; type TDmERP = class(TDataModule) fdConnERP: TFDConnection; qyCliente: TFDQuery; dlPhysPg: TFDPhysPgDriverLink; qyCidade: TFDQuery; qyCidadePesq: TFDQuery; qyClientePesq: TFDQuery; qyIndInscEstPesq: TFDQuery; qyRepresentante: TFDQuery; qyRepresPesq: TFDQuery; qyUsuario: TFDQuery; qyPermissaoUsuario: TFDQuery; qyCobranca: TFDQuery; qyCobrancaContatoRel: TFDQuery; qyCobrancaContato: TFDQuery; qyCobrancaSituacao: TFDQuery; dsCobrancaSituacao: TDataSource; qyAviso: TFDQuery; qyAuxiliar: TFDQuery; qyIntSupItensCfgPad: TFDQuery; qyIntComCarga: TFDQuery; qyIntComItemPedImpresso: TFDQuery; qyEmpresa: TFDQuery; qyFatDiario: TFDQuery; qyFatDiarioPesq: TFDQuery; qyVeiculo: TFDQuery; qyVeiculoPesq: TFDQuery; qySetor: TFDQuery; qyUsuarioTela: TFDQuery; qyUsuarioPesq: TFDQuery; qyTelasDisponiveis: TFDQuery; qyTela: TFDQuery; qyTelaPesq: TFDQuery; qyPatrimonioTipo: TFDQuery; qyPatrimonioTipoPesq: TFDQuery; qyPatrimonio: TFDQuery; qyPatrimonioPesq: TFDQuery; qyPatrimonioManut: TFDQuery; qyPatrimonioManutPesq: TFDQuery; dsPatrimonioSituacao: TDataSource; qyPatrimonioSituacao: TFDQuery; qyCobrancaContatocdcobranca: TIntegerField; qyCobrancaContatocdcobrancacontato: TIntegerField; qyCobrancaContatodtcontato: TDateField; qyCobrancaContatonmcontato: TWideStringField; qyCobrancaContatodeobscontato: TWideStringField; qyCobrancaContatoflretornar: TWideStringField; qyCobrancaContatodtretorno: TDateField; qyCobrancaContatohrretorno: TIntegerField; qyCobrancaContatodtcadastro: TDateField; qyCobrancaContatohrcadastro: TIntegerField; qyCobrancaContatocdusuariocadastro: TIntegerField; qyCobrancaContatodtalteracao: TDateField; qyCobrancaContatohralteracao: TIntegerField; qyCobrancaContatocdusuarioalteracao: TIntegerField; qyCobrancaContatodehrretorno: TWideStringField; qyCobrancaContatodehrretornogrid: TWideStringField; qyCobrancaContatonmusucad: TWideStringField; qyCobrancaContatonmusualt: TWideStringField; qyFornecedor: TFDQuery; qyFornecedorTipo: TFDQuery; qyMotorista: TFDQuery; qyDocumentoTipo: TFDQuery; qyDespesaTipo: TFDQuery; qyBordero: TFDQuery; qyDocumento: TFDQuery; qyBorderoRel: TFDQuery; qyDocumentoRel: TFDQuery; qyIntComPedidosAntigos: TFDQuery; qyIntComItensPedAntigos: TFDQuery; qyIntSupItensCfgPadcditem: TWideStringField; qyIntSupItensCfgPadcdtipoalcarecnum: TIntegerField; qyIntSupItensCfgPadcdtipoalca: TIntegerField; qyIntSupItensCfgPaddetipoalca: TWideStringField; qyIntSupItensCfgPadcdadornorecnum: TIntegerField; qyIntSupItensCfgPadcdadorno: TIntegerField; qyIntSupItensCfgPaddeadorno: TWideStringField; qyIntSupItensCfgPadcdchavetarecnum: TIntegerField; qyIntSupItensCfgPadcdchaveta: TIntegerField; qyIntSupItensCfgPaddechaveta: TWideStringField; qyIntSupItensCfgPadcdforracaorecnum: TIntegerField; qyIntSupItensCfgPadcdforracao: TIntegerField; qyIntSupItensCfgPaddeforracao: TWideStringField; qyIntSupItensCfgPaddtcadastro: TDateField; qyIntSupItensCfgPadhrcadastro: TIntegerField; qyIntSupItensCfgPadcdusuariocadastro: TIntegerField; qyIntSupItensCfgPaddtalteracao: TDateField; qyIntSupItensCfgPadhralteracao: TIntegerField; qyIntSupItensCfgPadcdusuarioalteracao: TIntegerField; qyEstoqueProducaoRel: TFDQuery; qyClassifFiscal: TFDQuery; qyClasFisTaxaIbpt: TFDQuery; qyUnidadeMedida: TFDQuery; qyItemGrupo: TFDQuery; qyItemSubGrupo: TFDQuery; qyItemFamilia: TFDQuery; qyItem: TFDQuery; qyVariavel: TFDQuery; qyVariavelItens: TFDQuery; qyItemVinculoVariavel: TFDQuery; qyItemVinculoVariavelcditem: TWideStringField; qyItemVinculoVariavelcdvariavel: TIntegerField; qyItemVinculoVariavelcdvariavelitempadrao: TIntegerField; qyItemVinculoVariaveldtcadastro: TDateField; qyItemVinculoVariavelhrcadastro: TIntegerField; qyItemVinculoVariavelcdusuariocadastro: TIntegerField; qyItemVinculoVariaveldehrcadastro: TWideStringField; qyItemVinculoVariaveldeitem: TWideStringField; qyItemVinculoVariaveldevariavel: TWideStringField; qyItemVinculoVariaveldevariavelitempadrao: TWideStringField; qyItemVinculoVariavelnmusucad: TWideStringField; qyItemVarItensLib: TFDQuery; qyItemVariavelItensBloq: TFDQuery; qyItemVariavelItensBloqcditem: TWideStringField; qyItemVariavelItensBloqcdvariavel: TIntegerField; qyItemVariavelItensBloqcdvariavelitem: TIntegerField; qyItemVariavelItensBloqdtcadastro: TDateField; qyItemVariavelItensBloqhrcadastro: TIntegerField; qyItemVariavelItensBloqcdusuariocadastro: TIntegerField; qyItemVariavelItensBloqdevalor: TWideStringField; qyItemVarItensLibcdvariavelitem: TIntegerField; qyItemVarItensLibdevalor: TWideStringField; qyItemVarItensLibcdvariavel: TIntegerField; qyUsuarioMensagem: TFDQuery; qyColaborador: TFDQuery; qyColabSituacaoHst: TFDQuery; qyCargo: TFDQuery; qyColabPonto: TFDQuery; qyColabPontoRel: TFDQuery; qyIntIndItemRelacionado: TFDQuery; qyIntIndItemRelacionadoRel: TFDQuery; qyProducaoDiariaRel: TFDQuery; qyExtratoViagem: TFDQuery; qyIntIndMaterialMovEnt: TFDQuery; qyMaterialMovSit: TFDQuery; qyIntIndMaterialSolic: TFDQuery; qyIntIndMaterialMovSai: TFDQuery; qyIntIndMatEstoqueConsulta: TFDQuery; qyIntIndMaterialMovConsulta: TFDQuery; qyUsuariocdusuario: TIntegerField; qyUsuarionmusuario: TWideStringField; qyUsuarioflativo: TWideStringField; qyUsuariodelogin: TWideStringField; qyUsuariodesenha: TWideStringField; qyUsuariodeemail: TWideStringField; qyUsuariodtcadastro: TDateField; qyUsuariohrcadastro: TIntegerField; qyUsuariocdusuariocadastro: TIntegerField; qyUsuariodtalteracao: TDateField; qyUsuariohralteracao: TIntegerField; qyUsuariocdusuarioalteracao: TIntegerField; qyUsuariocdsetor: TIntegerField; qyUsuariocdcolaborador: TIntegerField; qyUsuariodesetor: TWideStringField; qyUsuariodehrcadastro: TWideStringField; qyUsuariodehralteracao: TWideStringField; qyUsuarionmusucad: TWideStringField; qyUsuarionmusualt: TWideStringField; qyTransportadora: TFDQuery; qyBanco: TFDQuery; qyAgencia: TFDQuery; qyConta: TFDQuery; qyCobrancaTipo: TFDQuery; qyColabDependentes: TFDQuery; qyColabDependentescdcolaborador: TIntegerField; qyColabDependentescdcolabdependentes: TIntegerField; qyColabDependentesnmdependente: TWideStringField; qyColabDependentescdgrauparentesco: TIntegerField; qyColabDependentesdtnascimento: TDateField; qyColabDependentesdtcadastro: TDateField; qyColabDependenteshrcadastro: TIntegerField; qyColabDependentescdusuariocadastro: TIntegerField; qyColabDependentesdtalteracao: TDateField; qyColabDependenteshralteracao: TIntegerField; qyColabDependentescdusuarioalteracao: TIntegerField; qyColabDependentesdehrcadastro: TWideStringField; qyColabDependentesdehralteracao: TWideStringField; qyColabDependentesnmusucad: TWideStringField; qyColabDependentesnmusualt: TWideStringField; qyColabDependentesdegrauparentesco: TWideStringField; qyEscala: TFDQuery; qyColabSetorHst: TFDQuery; qyColabCargoHst: TFDQuery; qyColabEscalaHst: TFDQuery; qyColabSalarioHst: TFDQuery; qyEscalaItem: TFDQuery; qyEscalaItemcdescala: TIntegerField; qyEscalaItemcdescalaitem: TIntegerField; qyEscalaItemdeescalaitem: TWideStringField; qyEscalaItemdtcadastro: TDateField; qyEscalaItemhrcadastro: TIntegerField; qyEscalaItemcdusuariocadastro: TIntegerField; qyEscalaItemdtalteracao: TDateField; qyEscalaItemhralteracao: TIntegerField; qyEscalaItemcdusuarioalteracao: TIntegerField; qyEscalaItemdehrcadastro: TWideStringField; qyEscalaItemdehralteracao: TWideStringField; qyEscalaItemnmusucad: TWideStringField; qyEscalaItemnmusualt: TWideStringField; qyColaboradorRel: TFDQuery; qyEmpresaLogo: TFDQuery; qyIntIndBaixaProducao: TFDQuery; qyIntIndBaixaProducaocditem: TWideStringField; qyIntIndBaixaProducaocdsetor: TIntegerField; qyIntIndBaixaProducaocdidqtde: TIntegerField; qyIntIndBaixaProducaodeitem: TWideStringField; qyIntIndBaixaProducaodtbaixa: TDateField; qyIntIndBaixaProducaohrbaixa: TIntegerField; qyIntIndBaixaProducaocdusuariobaixa: TIntegerField; qyIntIndBaixaProducaodehrbaixa: TWideStringField; qyIntIndBaixaProducaodesetor: TWideStringField; qyIntIndBaixaProducaonmusubaixa: TWideStringField; qyIntIndBaixaProducaoflemestoque: TWideStringField; qyIntIndBaixaProducaodtcadpedido: TDateField; qyIntIndBaixaProducaocdpedido: TIntegerField; qyIntIndBaixaProducaocdseqped: TIntegerField; qyIntIndBaixaProducaocdidqtdeseqped: TIntegerField; qyIntIndBaixaProducaonuqtdtotalitem: TIntegerField; qyIntIndBaixaProducaocdcliente: TIntegerField; qyIntIndBaixaProducaocdcarga: TIntegerField; qyIntIndBaixaProducaodecarga: TWideStringField; qyIntIndBaixaProducaoflehsetorexpedicao: TWideStringField; qyIntIndBaixaProducaoflehsetorembalagem: TWideStringField; qyIntIndBaixaProducaoflehsetormontagem: TWideStringField; qyIntIndBaixaProducaocdtamanho: TIntegerField; qyIntIndBaixaProducaodetamanho: TWideStringField; qyIntIndBaixaProducaocdcor: TIntegerField; qyIntIndBaixaProducaodecor: TWideStringField; qyIntIndBaixaProducaocdalca: TIntegerField; qyIntIndBaixaProducaodealca: TWideStringField; qyIntIndBaixaProducaocdadorno: TIntegerField; qyIntIndBaixaProducaodeadorno: TWideStringField; qyIntIndBaixaProducaocdchaveta: TIntegerField; qyIntIndBaixaProducaodechaveta: TWideStringField; qyIntIndBaixaProducaocdforracao: TIntegerField; qyIntIndBaixaProducaodeforracao: TWideStringField; qyIntIndBaixaProducaocdimagem: TIntegerField; qyIntIndBaixaProducaodeimagem: TWideStringField; qyIntIndBaixaProducaocditemrelacionado: TIntegerField; qyIntIndBaixaProducaocditembase: TWideStringField; qyIntIndBaixaProducaodeitembase: TWideStringField; qyIntIndBaixaProducaocdtamanhobase: TIntegerField; qyIntIndBaixaProducaodetamanhobase: TWideStringField; qyIntIndBaixaProducaodesetorant: TWideStringField; qyIntIndBaixaProducaoflehsetantmont: TWideStringField; qyIntIndBaixaProducaoflehrevenda: TWideStringField; qyIntIndBaixaProducaodtalteracao: TDateField; qyIntIndBaixaProducaohralteracao: TIntegerField; qyIntIndBaixaProducaocdusuarioalteracao: TIntegerField; qyIntIndBaixaProducaoflehacessorio: TWideStringField; qyIntIndBaixaProducaocdempresa: TIntegerField; qyIntIndBaixaProducaonmempresa: TWideStringField; qyIntIndBaixaProducaoflmovestsetorant: TWideStringField; qyIntIndBaixaProducaocdsetoranterior: TIntegerField; qyIntIndBaixaProducaocdidqtdeanterior: TIntegerField; qyIntComCargaPesq: TFDQuery; qyReciboAvulso: TFDQuery; qyReciboAvulsoRel: TFDQuery; qyIntIndMaterialEstoqueRel: TFDQuery; qyNatureza: TFDQuery; qyCentroCusto: TFDQuery; qyUsuarioConexao: TFDQuery; qyUsuarioChat: TFDQuery; qyPedido: TFDQuery; qyCidadeDW: TFDQuery; qyClienteDW: TFDQuery; qyRepresentanteDW: TFDQuery; qyVariavelDW: TFDQuery; qyVariavelItensDW: TFDQuery; qyItemGrupoDW: TFDQuery; qyItemSubGrupoDW: TFDQuery; qyItemDW: TFDQuery; qyItemCombinacaoVendaDW: TFDQuery; qyVendasDW: TFDQuery; qyTempoDW: TFDQuery; qyIntSupItensCfgPadcdtipoalcaseq: TIntegerField; qyIntSupItensCfgPadcdadornoseq: TIntegerField; qyIntSupItensCfgPadcdchavetaseq: TIntegerField; qyIntSupItensCfgPadcdforracaoseq: TIntegerField; qyIntSupItensCfgPadflcobrarcor: TWideStringField; qyIntComCotaFin: TFDQuery; qyIntComCargaAlerta: TFDQuery; qyIntComCargaAlertacdcarga: TIntegerField; qyIntComCargaAlertacdcargaalerta: TIntegerField; qyIntComCargaAlertadecargaalerta: TWideStringField; qyIntComCargaAlertadtcadastro: TDateField; qyIntComCargaAlertahrcadastro: TIntegerField; qyIntComCargaAlertacdusuariocadastro: TIntegerField; qyIntComCargaAlertadtalteracao: TDateField; qyIntComCargaAlertahralteracao: TIntegerField; qyIntComCargaAlertacdusuarioalteracao: TIntegerField; qyIntComCargaAlertadehrcadastro: TWideStringField; qyIntComCargaAlertadehralteracao: TWideStringField; qyIntComCargaAlertanmusucad: TWideStringField; qyIntComCargaAlertanmusualt: TWideStringField; qyIntComCargaAlertaPesq: TFDQuery; qyIntSupItensCfgPadflativo: TWideStringField; procedure fdConnERPError(ASender, AInitiator: TObject; var AException: Exception); procedure DataModuleCreate(Sender: TObject); procedure qyClienteAfterScroll(DataSet: TDataSet); procedure qyClienteNewRecord(DataSet: TDataSet); procedure qyRepresentanteAfterScroll(DataSet: TDataSet); procedure qyCobrancaNewRecord(DataSet: TDataSet); procedure qyCobrancaContatoBeforePost(DataSet: TDataSet); procedure qyCobrancaContatoBeforeOpen(DataSet: TDataSet); procedure qyCobrancaAfterScroll(DataSet: TDataSet); procedure qyCobrancaContatoNewRecord(DataSet: TDataSet); procedure qyCobrancaBeforePost(DataSet: TDataSet); procedure qyClienteBeforePost(DataSet: TDataSet); procedure qyCidadeBeforePost(DataSet: TDataSet); procedure qyRepresentanteBeforePost(DataSet: TDataSet); procedure qyUsuarioBeforePost(DataSet: TDataSet); procedure qyAvisoBeforePost(DataSet: TDataSet); procedure qyIntSupItensCfgPaddetipoalcaValidate(Sender: TField); procedure qyIntSupItensCfgPaddechavetaValidate(Sender: TField); procedure qyIntSupItensCfgPaddeforracaoValidate(Sender: TField); procedure qyIntSupItensCfgPaddeadornoValidate(Sender: TField); procedure qyIntSupItensCfgPadBeforePost(DataSet: TDataSet); procedure qyCobrancaContatoAfterScroll(DataSet: TDataSet); procedure qyEmpresaBeforePost(DataSet: TDataSet); procedure qyEmpresaAfterScroll(DataSet: TDataSet); procedure qyFatDiarioBeforePost(DataSet: TDataSet); procedure qyFatDiarioNewRecord(DataSet: TDataSet); procedure qyVeiculoBeforePost(DataSet: TDataSet); procedure qyVeiculoAfterScroll(DataSet: TDataSet); procedure qySetorBeforePost(DataSet: TDataSet); procedure qyUsuarioNewRecord(DataSet: TDataSet); procedure qyUsuarioPesqAfterClose(DataSet: TDataSet); procedure qyUsuarioTelaBeforeOpen(DataSet: TDataSet); procedure qyTelasDisponiveisBeforeOpen(DataSet: TDataSet); procedure qyUsuarioTelaBeforePost(DataSet: TDataSet); procedure qyUsuarioAfterScroll(DataSet: TDataSet); procedure qyTelaBeforePost(DataSet: TDataSet); procedure qyTelaNewRecord(DataSet: TDataSet); procedure qyTelaPesqAfterClose(DataSet: TDataSet); procedure qyPatrimonioTipoPesqAfterClose(DataSet: TDataSet); procedure qyPatrimonioTipoBeforePost(DataSet: TDataSet); procedure qyPatrimonioPesqAfterClose(DataSet: TDataSet); procedure qyPatrimonioBeforePost(DataSet: TDataSet); procedure qyPatrimonioManutPesqAfterClose(DataSet: TDataSet); procedure qyPatrimonioManutBeforePost(DataSet: TDataSet); procedure qyPatrimonioManutNewRecord(DataSet: TDataSet); procedure qyFornecedorBeforePost(DataSet: TDataSet); procedure qyFornecedorAfterScroll(DataSet: TDataSet); procedure qyFornecedorNewRecord(DataSet: TDataSet); procedure qyRepresentanteNewRecord(DataSet: TDataSet); procedure qyFornecedorTipoBeforePost(DataSet: TDataSet); procedure qyMotoristaBeforePost(DataSet: TDataSet); procedure qyDocumentoTipoBeforePost(DataSet: TDataSet); procedure qyDespesaTipoBeforePost(DataSet: TDataSet); procedure qyBorderoBeforePost(DataSet: TDataSet); procedure qyDocumentoBeforePost(DataSet: TDataSet); procedure qyDocumentoNewRecord(DataSet: TDataSet); procedure qyIntComItensPedAntigosBeforeOpen(DataSet: TDataSet); procedure qyIntComPedidosAntigosAfterScroll(DataSet: TDataSet); procedure qyIntComItemPedImpressoBeforePost(DataSet: TDataSet); procedure qySetorNewRecord(DataSet: TDataSet); procedure qyClassifFiscalBeforePost(DataSet: TDataSet); procedure qyClasFisTaxaIbptBeforeOpen(DataSet: TDataSet); procedure qyClassifFiscalAfterScroll(DataSet: TDataSet); procedure qyClassifFiscalNewRecord(DataSet: TDataSet); procedure qyItemFamiliaBeforePost(DataSet: TDataSet); procedure qyItemGrupoBeforePost(DataSet: TDataSet); procedure qyItemNewRecord(DataSet: TDataSet); procedure qyVariavelBeforePost(DataSet: TDataSet); procedure qyVariavelAfterScroll(DataSet: TDataSet); procedure qyVariavelItensBeforeOpen(DataSet: TDataSet); procedure qyVariavelItensBeforePost(DataSet: TDataSet); procedure qyItemVinculoVariavelcdvariavelValidate(Sender: TField); procedure qyItemVinculoVariavelcdvariavelitempadraoValidate(Sender: TField); procedure qyItemVinculoVariavelBeforePost(DataSet: TDataSet); procedure qyItemVinculoVariavelAfterOpen(DataSet: TDataSet); procedure qyItemVinculoVariavelAfterPost(DataSet: TDataSet); procedure qyUsuarioMensagemBeforePost(DataSet: TDataSet); procedure qyColaboradorAfterScroll(DataSet: TDataSet); procedure qyColaboradorBeforePost(DataSet: TDataSet); procedure qyCargoBeforePost(DataSet: TDataSet); procedure qyColaboradorAfterPost(DataSet: TDataSet); procedure qyColabPontoBeforePost(DataSet: TDataSet); procedure qyIntIndItemRelacionadoBeforePost(DataSet: TDataSet); procedure qyIntIndMaterialMovEntBeforePost(DataSet: TDataSet); procedure qyIntIndMaterialMovEntNewRecord(DataSet: TDataSet); procedure qyIntIndMaterialSolicBeforePost(DataSet: TDataSet); procedure qyIntIndMaterialMovSaiBeforePost(DataSet: TDataSet); procedure qyIntIndMaterialMovSaiNewRecord(DataSet: TDataSet); procedure qyIntIndMaterialSolicAfterScroll(DataSet: TDataSet); procedure qyIntIndMaterialMovSaiBeforeOpen(DataSet: TDataSet); procedure qyIntIndMaterialSolicNewRecord(DataSet: TDataSet); procedure qyTransportadoraAfterScroll(DataSet: TDataSet); procedure qyTransportadoraBeforePost(DataSet: TDataSet); procedure qyTransportadoraNewRecord(DataSet: TDataSet); procedure qyMotoristaAfterScroll(DataSet: TDataSet); procedure qyAgenciaAfterScroll(DataSet: TDataSet); procedure qyAgenciaBeforePost(DataSet: TDataSet); procedure qyContaBeforePost(DataSet: TDataSet); procedure qyCobrancaTipoBeforePost(DataSet: TDataSet); procedure qyCobrancaTipoNewRecord(DataSet: TDataSet); procedure qyIntIndBaixaProducaoBeforePost(DataSet: TDataSet); procedure qyColaboradorNewRecord(DataSet: TDataSet); procedure qyColabDependentesBeforePost(DataSet: TDataSet); procedure qyEscalaBeforePost(DataSet: TDataSet); procedure qyEscalaItemBeforePost(DataSet: TDataSet); procedure qyEscalaAfterScroll(DataSet: TDataSet); procedure qyIntComCargaNewRecord(DataSet: TDataSet); procedure qyReciboAvulsoBeforePost(DataSet: TDataSet); procedure qyReciboAvulsoAfterScroll(DataSet: TDataSet); procedure qyReciboAvulsoNewRecord(DataSet: TDataSet); procedure qyNaturezaNewRecord(DataSet: TDataSet); procedure qyUsuarioConexaoBeforePost(DataSet: TDataSet); procedure qyUsuarioChatBeforePost(DataSet: TDataSet); procedure qyPedidoNewRecord(DataSet: TDataSet); procedure qyPedidoBeforePost(DataSet: TDataSet); procedure qyTempoDWBeforePost(DataSet: TDataSet); procedure qyIntSupItensCfgPadflcobrarcorGetText(Sender: TField; var Text: string; DisplayText: Boolean); procedure qyIntComCotaFinBeforePost(DataSet: TDataSet); procedure qyIntComCargaAlertaBeforePost(DataSet: TDataSet); procedure qyIntComCargaAfterScroll(DataSet: TDataSet); private FscdItemVinculo : String; procedure GravarCamposAutomaticos(const qyDados : TFDQuery); //--------- Integração --------------------------------------------------------- procedure GravarCamposItensVarItens(const icdVar : Integer; const sdeVarItem, scdFieldRecNum, scdFieldMasc : String ); //--------- Fim Integração ----------------------------------------------------- public procedure UsuarioConectado(const sConectado : String); procedure CarregarInfoCep(const sCep : String; var sdeEndereco, sdeComplemento, sdeBairro : String; var icdCidade : Integer ); function RegistrarPonto : Boolean; function TelaValida : String; procedure GravarTela; procedure ExcluirTela; function UsuarioValido : String; procedure GravarUsuario; procedure ExcluirUsuario; function EmpresaValida : String; procedure GravarEmpresa; procedure ExcluirEmpresa; function SetorValido : String; procedure GravarSetor; procedure ExcluirSetor; function VeiculoValido : String; procedure GravarVeiculo; procedure ExcluirVeiculo; function MotoristaValido : String; procedure GravarMotorista; procedure ExcluirMotorista; function FornecedorTipoValido : String; procedure GravarFornecedorTipo; procedure ExcluirFornecedorTipo; function CentroCustoValido : String; procedure GravarCentroCusto; procedure ExcluirCentroCusto; function FornecedorValido : String; procedure GravarFornecedor; procedure ExcluirFornecedor; function ClienteValido : String; procedure GravarCliente; procedure ExcluirCliente; function RepresentanteValido : String; procedure GravarRepresentante; procedure ExcluirRepresentante; function TransportadoraValida : String; procedure GravarTransportadora; procedure ExcluirTransportadora; function BancoValido : String; procedure GravarBanco; procedure ExcluirBanco; function AgenciaValida : String; procedure GravarAgencia; procedure ExcluirAgencia; function ContaValida : String; procedure GravarConta; procedure ExcluirConta; function CobrancaTipoValida : String; procedure GravarCobrancaTipo; procedure ExcluirCobrancaTipo; function ReciboAvulsoValido : String; procedure GravarReciboAvulso; procedure ExcluirReciboAvulso; function EscalaValida : String; procedure GravarEscala; procedure ExcluirEscala; function EscalaItemValido : String; procedure GravarEscalaItem; procedure ExcluirEscalaItem; function CargoValido : String; procedure GravarCargo; procedure ExcluirCargo; function ColaboradorValido : String; procedure GravarColaborador; procedure ExcluirColaborador; function ColabDependenteValido : String; procedure GravarColabDependente; procedure ExcluirColabDependente; function PedidoValido : String; procedure GravarPedido; procedure ExcluirPedido; function UnidadeMedidaValida : String; procedure GravarUnidadeMedida; procedure ExcluirUnidadeMedida; function ItemGrupoValido : String; procedure GravarItemGrupo; procedure ExcluirItemGrupo; function ItemSubGrupoValido : String; procedure GravarItemSubGrupo; procedure ExcluirItemSubGrupo; function ItemFamiliaValida : String; procedure GravarItemFamilia; procedure ExcluirItemFamilia; function ItemValido : String; procedure GravarItem; procedure ExcluirItem; function TipoPatrimonioValido : String; procedure GravarTipoPatrimonio; procedure ExcluirTipoPatrimonio; function PatrimonioValido : String; procedure GravarPatrimonio; procedure ExcluirPatrimonio; function ClassifFiscalValida : String; procedure GravarClassifFiscal; procedure ExcluirClassifFiscal; function DocumentoTipoValido : String; procedure GravarDocumentoTipo; procedure ExcluirDocumentoTipo; function DespesaTipoValido : String; procedure GravarDespesaTipo; procedure ExcluirDespesaTipo; function VariavelValida : String; procedure GravarVariavel; procedure ExcluirVariavel; function VariavelItemValido : String; procedure GravarVariavelItem; procedure ExcluirVariavelItem; function ItemVinculoVariavelValido : String; procedure GravarItemVinculoVariavel; procedure ExcluirItemVinculoVariavel; function PatrimonioManutencaoValida : String; procedure GravarPatrimonioManutencao; procedure ExcluirPatrimonioManutencao; function BorderoValido : String; procedure GravarBordero; procedure ExcluirBordero; function DocumentoValido : String; procedure GravarDocumento; procedure ExcluirDocumento; function CobrancaValida : String; procedure GravarCobranca; procedure ExcluirCobranca; function CobrancaContatoValido : String; procedure GravarCobrancaContato; procedure ExcluirCobrancaContato; function FatDiarioValido : String; procedure GravarFatDiario; procedure ExcluirFatDiario; function NaturezaValida : String; procedure GravarNatureza; procedure ExcluirNatureza; //--------- Integração --------------------------------------------------------- function ItemRelacionadoValido : String; procedure GravarItemRelacionado; procedure ExcluirItemRelacionado; function CargaValida : String; procedure GravarCarga; procedure ExcluirCarga; function CargaAlertaValida : String; procedure GravarCargaAlerta; procedure ExcluirCargaAlerta; function BaixaProducaoValida : TStringList; procedure GravarBaixaProducao; procedure ExcluirBaixaProducao; function MaterialMovValido(const qyMov : TFDQuery) : String; procedure GravarMaterialMov(const qyMov : TFDQuery; const bExibirMsg : Boolean); procedure ExcluirMaterialMov(const qyMov : TFDQuery); procedure BeforePostMaterialMov(const qyMov : TFDQuery); function MaterialSolicValido : String; procedure GravarMaterialSolic; procedure ExcluirMaterialSolic; //--------- Fim Integração ----------------------------------------------------- end; var DmERP: TDmERP; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses UTelaInicial, uDmIntegracao; {$R *.dfm} procedure TDmERP.CarregarInfoCep(const sCep : String; var sdeEndereco, sdeComplemento, sdeBairro : String; var icdCidade : Integer ); resourcestring __rINFORME_NR_CEP = 'Informe o número do cep.'; __rCEP_INVALIDO = 'O número do CEP deve ser composto por 8 bytes.'; __rCEP_NAO_ENCONTRADO = 'Cep não encontrado.'; const _rCep = 'cep'; _rLogradouro = 'logradouro'; _rBairro = 'bairro'; _rLocalidade = 'localidade'; _rComplemento = 'complemento'; _rUF = 'uf'; _rWS = 'https://viacep.com.br/ws/'; _rXML = '/xml/'; _rERRO = 'erro'; _rTrue = 'true'; var _rDXML : IXMLDocument; snmCidade, sSgEstado, sCepNum : String; stDados : TStringList; begin sCepNum := SomenteNumeros(sCep); { if sCepNum.IsEmpty then begin Aviso(__rINFORME_NR_CEP); Abort; end; if sCepNum.Length <> 8 then begin Aviso(__rCEP_INVALIDO); Abort; end; } _rDXML := TXMLDocument.Create(nil); try _rDXML.FileName := _rWS + sCepNum + _rXML; _rDXML.Active := True; { Quando consultado um CEP de formato válido, porém inexistente, } { por exemplo: "99999999", o retorno conterá um valor de "erro" } { igual a "true". Isso significa que o CEP consultado não foi } { encontrado na base de dados. https://viacep.com.br/ } if _rDXML.DocumentElement.ChildValues[0] = _rTrue then Aviso(__rCEP_NAO_ENCONTRADO) else begin sCepNum := _rDXML.DocumentElement.ChildNodes[_rCep].Text; sdeEndereco := _rDXML.DocumentElement.ChildNodes[_rLogradouro].Text; sdeComplemento := _rDXML.DocumentElement.ChildNodes[_rComplemento].Text; sdeBairro := _rDXML.DocumentElement.ChildNodes[_rBairro].Text; snmCidade := _rDXML.DocumentElement.ChildNodes[_rLocalidade].Text; sSgEstado := _rDXML.DocumentElement.ChildNodes[_rUF].Text; if (Trim(snmCidade) <> '') and (Trim(sSgEstado) <> '') then begin snmCidade := RemoverAcentos(snmCidade); snmCidade := UpperCase(snmCidade); stDados := TStringList.Create; ExecuteSimplesSql(fdConnERP, 'SELECT cdCidade ' + ' FROM erp.cidade ' + ' WHERE UPPER(erp.RemoverAcento(nmCidade)) = ' + QuotedStr(snmCidade) + ' AND sgEstado = ' + QuotedStr(sSgEstado), 'cdCidade', stDados ); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then icdCidade := StrToIntDef(stDados.Strings[0], 0); if Assigned(stDados) then FreeAndNil(stDados); end; end; finally _rDXML := nil; end; end; procedure TDmERP.GravarCamposAutomaticos(const qyDados : TFDQuery); var dthrAtual : TDateTime; begin dthrAtual := DataHoraAtual(fdConnERP); if qyDados.State = dsInsert then begin if Assigned(qyDados.FindField('cdUsuarioCadastro')) then qyDados.FieldByName('cdUsuarioCadastro').AsInteger := FTelaInicial.FcdUsuario; if Assigned(qyDados.FindField('nmUsuCad')) then begin if qyDados.FieldByName('nmUsuCad').ReadOnly then qyDados.FieldByName('nmUsuCad').ReadOnly := False; qyDados.FieldByName('nmUsuCad').AsString := FTelaInicial.FnmUsuario; end; if Assigned(qyDados.FindField('dtCadastro')) then qyDados.FieldByName('dtCadastro').AsDateTime := Trunc(dthrAtual); if Assigned(qyDados.FindField('hrCadastro')) then qyDados.FieldByName('hrCadastro').AsInteger := HoraParaMinutos(dthrAtual); if Assigned(qyDados.FindField('dehrCadastro')) then begin if qyDados.FieldByName('dehrCadastro').ReadOnly then qyDados.FieldByName('dehrCadastro').ReadOnly := False; qyDados.FieldByName('dehrCadastro').AsString := FormatDateTime('hh:mm', dthrAtual); end; end else begin if Assigned(qyDados.FindField('cdUsuarioAlteracao')) then qyDados.FieldByName('cdUsuarioAlteracao').AsInteger := FTelaInicial.FcdUsuario; if Assigned(qyDados.FindField('nmUsuAlt')) then begin if qyDados.FieldByName('nmUsuAlt').ReadOnly then qyDados.FieldByName('nmUsuAlt').ReadOnly := False; qyDados.FieldByName('nmUsuAlt').AsString := FTelaInicial.FnmUsuario; end; if Assigned(qyDados.FindField('dtAlteracao')) then qyDados.FieldByName('dtAlteracao').AsDateTime := Trunc(dthrAtual); if Assigned(qyDados.FindField('hrAlteracao')) then qyDados.FieldByName('hrAlteracao').AsInteger := HoraParaMinutos(dthrAtual); if Assigned(qyDados.FindField('dehrAlteracao')) then begin if qyDados.FieldByName('dehrAlteracao').ReadOnly then qyDados.FieldByName('dehrAlteracao').ReadOnly := False; qyDados.FieldByName('dehrAlteracao').AsString := FormatDateTime('hh:mm', dthrAtual); end; end; end; procedure TDmERP.UsuarioConectado(const sConectado : String); var dthrAtual : TDateTime; begin dthrAtual := DataHoraAtual(DmERP.fdConnERP); if qyUsuarioConexao.Active then qyUsuarioConexao.Close; qyUsuarioConexao.MacroByName('filtro').Clear; qyUsuarioConexao.MacroByName('filtro').Value := ' WHERE cdUsuario = ' + IntToStr(FTelaInicial.FcdUsuario) + ' AND dtConexao = ' + QuotedStr(FormatDateTime('dd/mm/yyyy', dthrAtual)); qyUsuarioConexao.Open(); qyUsuarioConexao.Insert; qyUsuarioConexao.FieldByName('cdUsuario').AsInteger := FTelaInicial.FcdUsuario; qyUsuarioConexao.FieldByName('nmComputador').AsString := RetornaNomeComputador; qyUsuarioConexao.FieldByName('deIp').AsString := RetornaIpComputador; qyUsuarioConexao.FieldByName('dtConexao').AsDateTime := Trunc(dthrAtual); qyUsuarioConexao.FieldByName('hrConexao').AsInteger := HoraParaMinutos(dthrAtual); qyUsuarioConexao.FieldByName('flconectado').AsString := sConectado; qyUsuarioConexao.Post; qyUsuarioConexao.Close; qyUsuarioConexao.MacroByName('filtro').Clear; end; function TDmERP.RegistrarPonto : Boolean; var dthrAtual : TDateTime; sFlEntSai : String; begin Result := FTelaInicial.FcdColaborador > 0; if not Result then Aviso('Usuário não vinculado a um colaborador.') else begin if qyColabPonto.Active then qyColabPonto.Close; dthrAtual := DataHoraAtual(fdConnERP); qyColabPonto.MacroByName('filtro').Value := ' WHERE cdColaborador = ' + IntToStr(FTelaInicial.FcdColaborador) + ' AND dtPonto = ' + QuotedStr(FormatDateTime('dd/mm/yyyy', dthrAtual)); qyColabPonto.Open(); qyColabPonto.Last; if qyColabPonto.FieldByName('flEntSai').AsString = 'E' then sFlEntSai := 'S' else sFlEntSai := 'E'; qyColabPonto.Insert; qyColabPonto.FieldByName('cdColaborador').AsInteger := FTelaInicial.FcdColaborador; qyColabPonto.FieldByName('dtPonto').AsDateTime := Trunc(dthrAtual); qyColabPonto.FieldByName('hrPonto').AsString := FormatDateTime('hh:nn:ss', dthrAtual); qyColabPonto.FieldByName('flEntSai').AsString := sFlEntSai; qyColabPonto.Post; end; end; function TDmERP.TelaValida : String; begin Result := ''; if (Trim(qyTela.FieldByName('deTituloTela').AsString) = '') then AdicionaLinha(Result, ' - Item menu tela deve ser informado'); if (Trim(qyTela.FieldByName('deTituloPai').AsString) = '') then AdicionaLinha(Result, ' - Item menu pai deve ser informado'); if (Trim(qyTela.FieldByName('nmForm').AsString) = '') then AdicionaLinha(Result, ' - Classe do form deve ser informada'); end; procedure TDmERP.GravarTela; var strValidacao : String; bInserindo : Boolean; begin strValidacao := TelaValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyTela.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyTela); qyTela.Post; fdConnERP.Commit; if bInserindo then Informacao('Tela inserida com sucesso.') else Informacao('Tela alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirTela; begin if qyTela.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyTela.Delete; Informacao('Tela excluída com sucesso.'); end; end; end; function TDmERP.UsuarioValido : String; var stDados : TStringList; sAux : String; begin Result := ''; if (Trim(qyUsuario.FieldByName('deLogin').AsString) = '') then AdicionaLinha(Result, ' - Login deve ser informado') else begin sAux := ''; if qyUsuario.State <> dsInsert then sAux := ' AND cdUsuario <> ' + qyUsuario.FieldByName('cdUsuario').AsString; stDados := TStringList.Create; ExecuteSimplesSql(fdConnERP, 'SELECT cdUsuario ' + ' FROM erp.usuario ' + ' WHERE deLogin = ' + QuotedStr(qyUsuario.FieldByName('deLogin').AsString) + ' AND flAtivo = ''S'' ' + sAux, 'cdUsuario', stDados ); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then AdicionaLinha(Result, ' - Login já existe vinculado a outro cadastro'); if Assigned(stDados) then FreeAndNil(stDados); end; if (Trim(qyUsuario.FieldByName('deSenha').AsString) = '') then AdicionaLinha(Result, ' - Senha deve ser informada'); if (qyUsuario.FieldByName('cdSetor').IsNull) then AdicionaLinha(Result, ' - Setor deve ser informado'); end; procedure TDmERP.GravarUsuario; var strValidacao : String; bInserindo : Boolean; begin strValidacao := UsuarioValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyUsuario.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyUsuario); qyUsuario.Post; fdConnERP.Commit; if bInserindo then Informacao('Usuário inserido com sucesso.') else Informacao('Usuário alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirUsuario; begin if qyUsuario.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin if not qyUsuarioTela.Active then qyUsuarioTela.Open(); qyUsuarioTela.First; while not qyUsuarioTela.Eof do qyUsuarioTela.Delete; qyUsuario.Delete; Informacao('Usuário excluído com sucesso.'); end; end; end; function TDmERP.EmpresaValida : String; begin Result := ''; if (Trim(qyEmpresa.FieldByName('deCnpj').AsString) = '') then AdicionaLinha(Result, ' - CNPJ deve ser informado'); if (Trim(qyEmpresa.FieldByName('deRazaoSocial').AsString) = '') then AdicionaLinha(Result, ' - Razão social deve ser informada'); if (qyEmpresa.FieldByName('cdCidade').AsInteger > 0) and (Trim(qyEmpresa.FieldByName('nuInscEst').AsString) <> '') then begin if qyCidadePesq.Active then qyCidadePesq.Close; qyCidadePesq.MacroByName('filtro').Value := ' WHERE cdCidade=' + qyEmpresa.FieldByName('cdCidade').AsString; qyCidadePesq.Open(); if not qyCidadePesq.IsEmpty then begin if not ValidaInscEst(qyEmpresa.FieldByName('nuInscEst').AsString, qyCidadePesq.FieldByName('sgEstado').AsString ) then AdicionaLinha(Result, ' - Inscrição estadual inválida para o estado ' + qyEmpresa.FieldByName('sgEstado').AsString); end; end; end; procedure TDmERP.GravarEmpresa; var strValidacao : String; bInserindo : Boolean; begin strValidacao := EmpresaValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyEmpresa.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyEmpresa); qyEmpresa.Post; fdConnERP.Commit; if bInserindo then Informacao('Empresa inserida com sucesso.') else Informacao('Empresa alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirEmpresa; begin if qyEmpresa.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyEmpresa.Delete; Informacao('Empresa excluída com sucesso.'); end; end; end; function TDmERP.SetorValido : String; var stDados : TStringList; begin Result := ''; if (Trim(qySetor.FieldByName('deSetor').AsString) = '') then AdicionaLinha(Result, ' - Descrição do setor'); if (qySetor.FieldByName('cdSetorAnterior').AsInteger > 0) and (qySetor.FieldByName('cdSetor').AsInteger > 0) then begin if (qySetor.FieldByName('cdSetorAnterior').AsInteger = qySetor.FieldByName('cdSetor').AsInteger) then AdicionaLinha(Result, ' - Setor anterior não pode ser o mesmo que o principal'); if qySetor.State = dsEdit then begin stDados := TStringList.Create; ExecuteSimplesSql(fdConnERP, 'SELECT deSetor ' + ' FROM erp.setor ' + ' WHERE cdSetorAnterior = ' + qySetor.FieldByName('cdSetorAnterior').AsString + ' AND cdSetor <> ' + qySetor.FieldByName('cdSetor').AsString, 'deSetor', stDados ); if (stDados.Count > 0) and (Trim(stDados.Strings[0]) <> '') then AdicionaLinha(Result, ' - Setor anterior já atribuído ao setor "' + Trim(stDados.Strings[0]) + '"'); if Assigned(stDados) then FreeAndNil(stDados); end; end; end; procedure TDmERP.GravarSetor; var strValidacao : String; bInserindo : Boolean; begin strValidacao := SetorValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qySetor.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qySetor); qySetor.Post; fdConnERP.Commit; if bInserindo then Informacao('Setor inserido com sucesso.') else Informacao('Setor alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirSetor; begin if qySetor.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qySetor.Delete; Informacao('Setor excluído com sucesso.'); end; end; end; function TDmERP.VeiculoValido : String; var stDados : TStringList; begin Result := ''; if (qyVeiculo.FieldByName('cdVeiculoTipo').IsNull) then AdicionaLinha(Result, ' - Tipo de veículo deve ser informado'); if (Trim(qyVeiculo.FieldByName('dePlaca').AsString) = '') then AdicionaLinha(Result, ' - Placa deve ser informada') else begin stDados := TStringList.Create; if qyVeiculo.State = dsInsert then begin ExecuteSimplesSql(fdConnERP, 'SELECT cdVeiculo ' + ' FROM erp.veiculo ' + ' WHERE dePlaca = ' + QuotedStr(UpperCase(Trim(qyVeiculo.FieldByName('dePlaca').AsString))), 'cdVeiculo', stDados ); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then AdicionaLinha(Result, ' - Placa informada já existe para outro cadastro'); end else begin ExecuteSimplesSql(fdConnERP, 'SELECT cdVeiculo ' + ' FROM erp.veiculo ' + ' WHERE dePlaca = ' + QuotedStr(UpperCase(Trim(qyVeiculo.FieldByName('dePlaca').AsString))) + ' AND cdVeiculo <> ' + qyVeiculo.FieldByName('cdVeiculo').AsString, 'cdVeiculo', stDados ); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then AdicionaLinha(Result, ' - Placa informada já existe para outro cadastro'); end; if Assigned(stDados) then FreeAndNil(stDados); end; end; procedure TDmERP.GravarVeiculo; var strValidacao : String; bInserindo : Boolean; begin strValidacao := VeiculoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyVeiculo.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyVeiculo); qyVeiculo.Post; fdConnERP.Commit; if bInserindo then Informacao('Veículo inserido com sucesso.') else Informacao('Veículo alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirVeiculo; begin if qyVeiculo.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyVeiculo.Delete; Informacao('Veículo excluído com sucesso.'); end; end; end; function TDmERP.MotoristaValido : String; begin Result := ''; if (Trim(qyMotorista.FieldByName('nmMotorista').AsString) = '') then AdicionaLinha(Result, ' - Nome do motorista deve ser informado'); end; procedure TDmERP.GravarMotorista; var strValidacao : String; bInserindo : Boolean; begin strValidacao := MotoristaValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyMotorista.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyMotorista); qyMotorista.Post; fdConnERP.Commit; if bInserindo then Informacao('Motorista inserido com sucesso.') else Informacao('Motorista alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirMotorista; begin if qyMotorista.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyMotorista.Delete; Informacao('Motorista excluído com sucesso.'); end; end; end; procedure TDmERP.qyUsuarioChatBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyUsuarioChat, 'usuarioChat', 'cdUsuarioChat', qyUsuarioChat.FieldByName('cdUsuarioChat').AsInteger); end; procedure TDmERP.qyUsuarioConexaoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyUsuarioConexao, 'usuarioConexao', 'cdUsuarioConexao', qyUsuarioConexao.FieldByName('cdUsuarioConexao').AsInteger); end; function TDmERP.FornecedorTipoValido : String; begin Result := ''; if (Trim(qyFornecedorTipo.FieldByName('deFornecedorTipo').AsString) = '') then AdicionaLinha(Result, ' - Descrição do tipo de fornecedor deve ser informada'); end; procedure TDmERP.GravarFornecedorTipo; var strValidacao : String; bInserindo : Boolean; begin strValidacao := FornecedorTipoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyFornecedorTipo.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyFornecedorTipo); qyFornecedorTipo.Post; fdConnERP.Commit; if bInserindo then Informacao('Tipo de Fornecedor inserido com sucesso.') else Informacao('Tipo de Fornecedor alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirFornecedorTipo; begin if qyFornecedorTipo.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyFornecedorTipo.Delete; Informacao('Tipo de Fornecedor excluído com sucesso.'); end; end; end; function TDmERP.CentroCustoValido : String; begin Result := ''; if (Trim(qyCentroCusto.FieldByName('deCentroCusto').AsString) = '') then AdicionaLinha(Result, ' - Descrição do centro de custo deve ser informada'); end; procedure TDmERP.GravarCentroCusto; var strValidacao : String; bInserindo : Boolean; begin strValidacao := CentroCustoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyCentroCusto.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyCentroCusto); qyCentroCusto.Post; fdConnERP.Commit; if bInserindo then Informacao('Centro de Custo inserido com sucesso.') else Informacao('Centro de Custo alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirCentroCusto; begin if qyCentroCusto.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyCentroCusto.Delete; Informacao('Centro de Custo excluído com sucesso.'); end; end; end; function TDmERP.FornecedorValido : String; begin Result := ''; if (Trim(qyFornecedor.FieldByName('deCpfCnpj').AsString) <> '') and (not (ValidaCpfCnpj(qyFornecedor.FieldByName('deCpfCnpj').AsString))) then begin if (qyFornecedor.FieldByName('flFisJur').AsString = 'J') then AdicionaLinha(Result, ' - CNPJ inválido') else AdicionaLinha(Result, ' - CPF inválido'); end; if (qyFornecedor.FieldByName('flFisJur').AsString = 'J') then begin if (Trim(qyFornecedor.FieldByName('deCpfCnpj').AsString) = '') then AdicionaLinha(Result, ' - Para pessoa jurídica, o CNPJ deve ser informado'); if (Trim(qyFornecedor.FieldByName('deRazaoSocial').AsString) = '') then AdicionaLinha(Result, ' - Para pessoa jurídica, a razão social deve ser informada'); end; if (qyFornecedor.FieldByName('cdCidade').AsInteger > 0) and (Trim(qyFornecedor.FieldByName('nuInscEst').AsString) <> '') then begin if qyCidadePesq.Active then qyCidadePesq.Close; qyCidadePesq.MacroByName('filtro').Value := ' WHERE cdCidade=' + qyFornecedor.FieldByName('cdCidade').AsString; qyCidadePesq.Open(); if not qyCidadePesq.IsEmpty then begin if not ValidaInscEst(qyFornecedor.FieldByName('nuInscEst').AsString, qyCidadePesq.FieldByName('sgEstado').AsString ) then AdicionaLinha(Result, ' - Inscrição estadual inválida para o estado ' + qyCidade.FieldByName('sgEstado').AsString); end; end; end; procedure TDmERP.GravarFornecedor; var strValidacao : String; bInserindo : Boolean; begin strValidacao := FornecedorValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyFornecedor.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyFornecedor); qyFornecedor.Post; fdConnERP.Commit; if bInserindo then Informacao('Fornecedor inserido com sucesso.') else Informacao('Fornecedor alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirFornecedor; begin if qyFornecedor.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyFornecedor.Delete; Informacao('Fornecedor excluído com sucesso.'); end; end; end; function TDmERP.ClienteValido : String; begin Result := ''; if (Trim(qyCliente.FieldByName('deCpfCnpj').AsString) <> '') and (not (ValidaCpfCnpj(qyCliente.FieldByName('deCpfCnpj').AsString))) then begin if (qyCliente.FieldByName('flFisJur').AsString = 'J') then AdicionaLinha(Result, ' - CNPJ inválido') else AdicionaLinha(Result, ' - CPF inválido'); end; if (qyCliente.FieldByName('flFisJur').AsString = 'J') then begin if (Trim(qyCliente.FieldByName('deCpfCnpj').AsString) = '') then AdicionaLinha(Result, ' - Para pessoa jurídica, o CNPJ deve ser informado'); if (Trim(qyCliente.FieldByName('deRazaoSocial').AsString) = '') then AdicionaLinha(Result, ' - Para pessoa jurídica, a razão social deve ser informada'); end; if (qyCliente.FieldByName('cdCidade').AsInteger > 0) and (Trim(qyCliente.FieldByName('nuInscEst').AsString) <> '') then begin if qyCidadePesq.Active then qyCidadePesq.Close; qyCidadePesq.MacroByName('filtro').Value := ' WHERE cdCidade=' + qyCliente.FieldByName('cdCidade').AsString; qyCidadePesq.Open(); if not qyCidadePesq.IsEmpty then begin if not ValidaInscEst(qyCliente.FieldByName('nuInscEst').AsString, qyCidadePesq.FieldByName('sgEstado').AsString ) then AdicionaLinha(Result, ' - Inscrição estadual inválida para o estado ' + qyCidade.FieldByName('sgEstado').AsString); end; end; end; procedure TDmERP.GravarCliente; var strValidacao : String; bInserindo : Boolean; begin strValidacao := ClienteValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyCliente.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyCliente); qyCliente.Post; fdConnERP.Commit; if bInserindo then Informacao('Cliente inserido com sucesso.') else Informacao('Cliente alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirCliente; begin if qyCliente.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyCliente.Delete; Informacao('Cliente excluído com sucesso.'); end; end; end; function TDmERP.TransportadoraValida : String; begin Result := ''; if (Trim(qyTransportadora.FieldByName('deCpfCnpj').AsString) <> '') and (not (ValidaCpfCnpj(qyTransportadora.FieldByName('deCpfCnpj').AsString))) then begin if (qyTransportadora.FieldByName('flFisJur').AsString = 'J') then AdicionaLinha(Result, ' - CNPJ inválido') else AdicionaLinha(Result, ' - CPF inválido'); end; if (qyTransportadora.FieldByName('flFisJur').AsString = 'J') then begin if (Trim(qyTransportadora.FieldByName('deCpfCnpj').AsString) = '') then AdicionaLinha(Result, ' - Para pessoa jurídica, o CNPJ deve ser informado'); if (Trim(qyTransportadora.FieldByName('deRazaoSocial').AsString) = '') then AdicionaLinha(Result, ' - Para pessoa jurídica, a razão social deve ser informada'); end; if (qyTransportadora.FieldByName('cdCidade').AsInteger > 0) and (Trim(qyTransportadora.FieldByName('nuInscEst').AsString) <> '') then begin if qyCidadePesq.Active then qyCidadePesq.Close; qyCidadePesq.MacroByName('filtro').Value := ' WHERE cdCidade=' + qyTransportadora.FieldByName('cdCidade').AsString; qyCidadePesq.Open(); if not qyCidadePesq.IsEmpty then begin if not ValidaInscEst(qyTransportadora.FieldByName('nuInscEst').AsString, qyCidadePesq.FieldByName('sgEstado').AsString ) then AdicionaLinha(Result, ' - Inscrição estadual inválida para o estado ' + qyCidade.FieldByName('sgEstado').AsString); end; end; end; procedure TDmERP.GravarTransportadora; var strValidacao : String; bInserindo : Boolean; begin strValidacao := TransportadoraValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyTransportadora.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyTransportadora); qyTransportadora.Post; fdConnERP.Commit; if bInserindo then Informacao('Transportadora inserida com sucesso.') else Informacao('Transportadora alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirTransportadora; begin if qyTransportadora.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyTransportadora.Delete; Informacao('Transportadora excluída com sucesso.'); end; end; end; procedure TDmERP.qyAgenciaAfterScroll(DataSet: TDataSet); begin qyAgencia.FieldByName('deCnpj').EditMask := '99.999.999/9999-99;0;_'; qyAgencia.FieldByName('nuFone1').EditMask := '(99) 9999-99999;0;_'; qyAgencia.FieldByName('nuFone2').EditMask := '(99) 9999-99999;0;_'; qyAgencia.FieldByName('nuFax').EditMask := '(99) 9999-99999;0;_'; qyAgencia.FieldByName('nuCep').EditMask := '99999-999;0;_'; end; procedure TDmERP.qyAgenciaBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyAgencia, 'agencia', 'cdAgencia', qyAgencia.FieldByName('cdAgencia').AsInteger); end; procedure TDmERP.qyAvisoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyAviso, 'aviso', 'cdAviso', qyAviso.FieldByName('cdAviso').AsInteger); end; procedure TDmERP.qyBorderoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyBordero, 'bordero', 'cdBordero', qyBordero.FieldByName('cdBordero').AsInteger); end; procedure TDmERP.qyCargoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyCargo, 'cargo', 'cdCargo', qyCargo.FieldByName('cdCargo').AsInteger); end; procedure TDmERP.qyCidadeBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyCidade, 'cidade', 'cdCidade', qyCidade.FieldByName('cdCidade').AsInteger); end; procedure TDmERP.qyClasFisTaxaIbptBeforeOpen(DataSet: TDataSet); begin qyClasFisTaxaIbpt.ParamByName('cdClassifFiscal').AsInteger := qyClassifFiscal.FieldByName('cdClassifFiscal').AsInteger; end; procedure TDmERP.qyClassifFiscalAfterScroll(DataSet: TDataSet); begin if qyClasFisTaxaIbpt.Active then qyClasFisTaxaIbpt.Close; qyClasFisTaxaIbpt.Open(); end; procedure TDmERP.qyClassifFiscalBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyClassifFiscal, 'classifFiscal', 'cdClassifFiscal', qyClassifFiscal.FieldByName('cdClassifFiscal').AsInteger); end; procedure TDmERP.qyClassifFiscalNewRecord(DataSet: TDataSet); begin qyClassifFiscal.FieldByName('flCalculaStCnae').AsString := 'N'; qyClassifFiscal.FieldByName('flAbatePisCofins').AsString := 'N'; qyClassifFiscal.FieldByName('flImprimeNota').AsString := 'N'; qyClassifFiscal.FieldByName('flUtilizaDnf').AsString := 'N'; qyClassifFiscal.FieldByName('flIcmsReducaoPf').AsString := 'N'; qyClassifFiscal.FieldByName('flIcmsReducaoIndustria').AsString := 'N'; qyClassifFiscal.FieldByName('flEntraDesoneracao').AsString := 'N'; qyClassifFiscal.FieldByName('flUtilizaIbpt').AsString := 'N'; end; procedure TDmERP.qyClienteAfterScroll(DataSet: TDataSet); begin if qyCliente.FieldByName('flFisJur').AsString = 'J' then qyCliente.FieldByName('deCpfCnpj').EditMask := '99.999.999/9999-99;0;_' else qyCliente.FieldByName('deCpfCnpj').EditMask := '999.999.999-99;0;_'; qyCliente.FieldByName('nuFone1').EditMask := '(99) 9999-99999;0;_'; qyCliente.FieldByName('nuFone2').EditMask := '(99) 9999-99999;0;_'; qyCliente.FieldByName('nuCelular').EditMask := '(99) 99999-9999;0;_'; qyCliente.FieldByName('nuFax').EditMask := '(99) 9999-99999;0;_'; qyCliente.FieldByName('nuCep').EditMask := '99999-999;0;_'; end; procedure TDmERP.qyClienteBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyCliente, 'cliente', 'cdCliente', qyCliente.FieldByName('cdCliente').AsInteger); end; procedure TDmERP.qyClienteNewRecord(DataSet: TDataSet); begin qyCliente.FieldByName('flAtivo').AsString := 'S'; qyCliente.FieldByName('flIsentoInscEst').AsString := 'S'; end; procedure TDmERP.qyCobrancaAfterScroll(DataSet: TDataSet); begin if qyCobrancaContato.Active then qyCobrancaContato.Close; qyCobrancaContato.Open(); end; procedure TDmERP.qyCobrancaBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyCobranca, 'cobranca', 'cdCobranca', qyCobranca.FieldByName('cdCobranca').AsInteger); end; procedure TDmERP.qyCobrancaContatoAfterScroll(DataSet: TDataSet); begin qyCobrancaContato.FieldByName('dehrRetorno').EditMask := '99:99;0;_'; end; procedure TDmERP.qyCobrancaContatoBeforeOpen(DataSet: TDataSet); begin qyCobrancaContato.ParamByName('cdCobranca').AsInteger := qyCobranca.FieldByName('cdCobranca').AsInteger; end; procedure TDmERP.qyCobrancaContatoBeforePost(DataSet: TDataSet); var stDados : TStringList; begin if qyCobrancaContato.State = dsInsert then begin qyCobrancaContato.FieldByName('cdCobranca').AsInteger := qyCobranca.FieldByName('cdCobranca').AsInteger; stDados := TStringList.Create; try ExecuteSimplesSql(fdConnERP, 'SELECT MAX(cdCobrancaContato) AS ultCod ' + ' FROM erp.cobrancaContato ' + ' WHERE cdCobranca = ' + qyCobranca.FieldByName('cdCobranca').AsString, 'ultCod', stDados ); qyCobrancaContato.FieldByName('cdCobrancaContato').AsInteger := StrToIntDef(stDados.Strings[0], 0) + 1 finally if Assigned(stDados) then FreeAndNil(stDados); end; end; if qyCobrancaContato.FieldByName('dehrRetorno').AsString <> '' then begin qyCobrancaContato.FieldByName('hrRetorno').AsInteger := StrToIntDef(Copy(qyCobrancaContato.FieldByName('dehrRetorno').AsString, 3, 2), 0) + (StrToIntDef(Copy(qyCobrancaContato.FieldByName('dehrRetorno').AsString, 1, 2), 0) * 60); qyCobrancaContato.FieldByName('dehrRetornoGrid').AsString := Copy(qyCobrancaContato.FieldByName('dehrRetorno').AsString, 1, 2) + ':' + Copy(qyCobrancaContato.FieldByName('dehrRetorno').AsString, 3, 2); end else qyCobrancaContato.FieldByName('hrRetorno').Clear; end; procedure TDmERP.qyCobrancaContatoNewRecord(DataSet: TDataSet); begin qyCobrancaContato.FieldByName('dtContato').AsDateTime := Trunc(DataHoraAtual(fdConnERP)); qyCobrancaContato.FieldByName('flRetornar').AsString := 'S'; end; procedure TDmERP.qyCobrancaNewRecord(DataSet: TDataSet); begin qyCobranca.FieldByName('cdSituacao').AsInteger := 1; end; procedure TDmERP.qyCobrancaTipoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyCobrancaTipo, 'cobrancaTipo', 'cdCobrancaTipo', qyCobrancaTipo.FieldByName('cdCobrancaTipo').AsInteger); end; procedure TDmERP.qyCobrancaTipoNewRecord(DataSet: TDataSet); begin qyCobrancaTipo.FieldByName('flContabilidade').AsString := 'N'; qyCobrancaTipo.FieldByName('flFluxoCaixa').AsString := 'N'; qyCobrancaTipo.FieldByName('flEntraConcialiacao').AsString := 'N'; qyCobrancaTipo.FieldByName('nuDiasAcrescimo').AsInteger := 0; end; procedure TDmERP.qyColabDependentesBeforePost(DataSet: TDataSet); begin if qyColabDependentes.State = dsInsert then begin qyColabDependentes.FieldByName('cdColaborador').AsInteger := qyColaborador.FieldByName('cdColaborador').AsInteger; GerarCodigo(fdConnERP, qyColabDependentes, 'colabDependentes', 'cdColabDependentes', qyColabDependentes.FieldByName('cdColabDependentes').AsInteger, ' WHERE cdColaborador = ' + qyColaborador.FieldByName('cdColaborador').AsString ); end; end; procedure TDmERP.qyColaboradorAfterPost(DataSet: TDataSet); procedure GravarHistorico(const qyDados : TFDQuery; const sNomeTabela, sNomeCampoChave, sNomeCampoData : String); var dthrHst, dthrAtual : TDateTime; begin if qyAuxiliar.Active then qyAuxiliar.Close; qyAuxiliar.SQL.Text := 'SELECT ' + sNomeCampoChave + ', ' + sNomeCampoData + ' FROM erp.' + sNomeTabela + ' WHERE cdColaborador = ' + qyColaborador.FieldByName('cdColaborador').AsString + ' ORDER BY ' + sNomeCampoData + ' DESC, hrCadastro DESC'; qyAuxiliar.Open(); if (qyAuxiliar.IsEmpty) or (qyAuxiliar.FieldByName(sNomeCampoChave).Value <> qyColaborador.FieldByName(sNomeCampoChave).Value) then begin dthrAtual := DataHoraAtual(fdConnERP); dthrHst := dthrAtual; if (not qyAuxiliar.IsEmpty) then dthrHst := qyAuxiliar.FieldByName(sNomeCampoData).AsDateTime; if qyDados.Active then qyDados.Close; qyDados.MacroByName('filtro').Value := ' WHERE cdColaborador = ' + qyColaborador.FieldByName('cdColaborador').AsString + ' AND ' + sNomeCampoChave + ' = ' + AnsiReplaceStr(qyColaborador.FieldByName(sNomeCampoChave).AsString, ',', '.') + ' AND ' + sNomeCampoData + ' = ' + QuotedStr(FormatDateTime('dd/mm/yyyy', dthrHst)); qyDados.Open(); if not qyDados.IsEmpty then qyDados.Delete; qyDados.Insert; qyDados.FieldByName('cdColaborador').AsInteger := qyColaborador.FieldByName('cdColaborador').AsInteger; qyDados.FieldByName(sNomeCampoChave).Value := qyColaborador.FieldByName(sNomeCampoChave).Value; qyDados.FieldByName(sNomeCampoData).AsDateTime := Trunc(dthrAtual); qyDados.FieldByName('cdUsuarioCadastro').AsInteger := FTelaInicial.FcdUsuario; qyDados.FieldByName('dtCadastro').AsDateTime := Trunc(dthrAtual); qyDados.FieldByName('hrCadastro').AsInteger := HoraParaMinutos(dthrAtual); qyDados.Post; end; qyAuxiliar.Close; end; begin if (qyColaborador.Active) and (not qyColaborador.IsEmpty) and (qyColaborador.FieldByName('cdColaborador').AsInteger > 0) then begin if (qyColaborador.FieldByName('cdColabSituacao').AsInteger > 0) then GravarHistorico(qyColabSituacaoHst, 'colabSituacaoHst', 'cdColabSituacao', 'dtSituacao'); if (qyColaborador.FieldByName('cdSetor').AsInteger > 0) then GravarHistorico(qyColabSetorHst, 'colabSetorHst', 'cdSetor', 'dtHistorico'); if (qyColaborador.FieldByName('cdEscala').AsInteger > 0) then GravarHistorico(qyColabEscalaHst, 'colabEscalaHst', 'cdEscala', 'dtHistorico'); if (qyColaborador.FieldByName('cdCargo').AsInteger > 0) then GravarHistorico(qyColabCargoHst, 'colabCargoHst', 'cdCargo', 'dtHistorico'); if (qyColaborador.FieldByName('vlSalario').AsCurrency > 0) then GravarHistorico(qyColabSalarioHst, 'colabSalarioHst', 'vlSalario', 'dtHistorico'); end; end; procedure TDmERP.qyColaboradorAfterScroll(DataSet: TDataSet); begin qyColaborador.FieldByName('deCpf').EditMask := '999.999.999-99;0;_'; qyColaborador.FieldByName('nuFone').EditMask := '(99) 9999-99999;0;_'; qyColaborador.FieldByName('nuCelular').EditMask := '(99) 99999-9999;0;_'; qyColaborador.FieldByName('nuCep').EditMask := '99999-999;0;_'; if qyColabDependentes.Active then qyColabDependentes.Close; qyColabDependentes.MacroByName('filtro').Clear; qyColabDependentes.ParamByName('cdColaborador').AsInteger := qyColaborador.FieldByName('cdColaborador').AsInteger; qyColabDependentes.Open(); end; procedure TDmERP.qyColaboradorBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyColaborador, 'colaborador', 'cdColaborador', qyColaborador.FieldByName('cdColaborador').AsInteger); end; procedure TDmERP.qyColaboradorNewRecord(DataSet: TDataSet); begin qyColaborador.FieldByName('flEstudante').AsString := 'N'; qyColaborador.FieldByName('flUsaValeTransp').AsString := 'N'; qyColaborador.FieldByName('cdColabSituacao').AsInteger := 1; qyColaborador.FieldByName('nuDiasContratoExp').AsInteger := 0; qyColaborador.FieldByName('nuDiasContratoExpExtra').AsInteger := 0; qyColaborador.FieldByName('cdSalarioTipo').AsInteger := 1; qyColaborador.FieldByName('vlSalario').AsCurrency := 0; qyColaborador.FieldByName('vlValeTransp').AsCurrency := 0; qyColaborador.FieldByName('vlPercAdicInsalub').AsCurrency := 0; qyColaborador.FieldByName('vlPercAdicPeric').AsCurrency := 0; end; procedure TDmERP.qyColabPontoBeforePost(DataSet: TDataSet); begin GravarCamposAutomaticos(qyColabPonto); end; procedure TDmERP.qyContaBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyConta, 'conta', 'cdConta', qyConta.FieldByName('cdConta').AsInteger); end; procedure TDmERP.qyDespesaTipoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyDespesaTipo, 'despesaTipo', 'cdDespesaTipo', qyDespesaTipo.FieldByName('cdDespesaTipo').AsInteger); end; procedure TDmERP.qyDocumentoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyDocumento, 'documento', 'cdDocumento', qyDocumento.FieldByName('cdDocumento').AsInteger); end; procedure TDmERP.qyDocumentoNewRecord(DataSet: TDataSet); var dthrAtual : TDateTime; wDia, wMes, wAno : Word; begin dthrAtual := DataHoraAtual(fdConnERP); dthrAtual := Trunc(dthrAtual); DecodeDate(dthrAtual, wAno, wMes, wDia); qyDocumento.FieldByName('dtCompetencia').AsDateTime := EncodeDate(wAno, wMes, 1); qyDocumento.FieldByName('flContabiliza').AsString := 'N'; end; procedure TDmERP.qyDocumentoTipoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyDocumentoTipo, 'documentoTipo', 'cdDocumentoTipo', qyDocumentoTipo.FieldByName('cdDocumentoTipo').AsInteger); end; procedure TDmERP.qyEmpresaAfterScroll(DataSet: TDataSet); begin qyEmpresa.FieldByName('deCnpj').EditMask := '99.999.999/9999-99;0;_'; qyEmpresa.FieldByName('nuFone1').EditMask := '(99) 9999-99999;0;_'; qyEmpresa.FieldByName('nuFone2').EditMask := '(99) 9999-99999;0;_'; qyEmpresa.FieldByName('nuCelular').EditMask := '(99) 99999-9999;0;_'; qyEmpresa.FieldByName('nuFax').EditMask := '(99) 9999-99999;0;_'; qyEmpresa.FieldByName('nuCep').EditMask := '99999-999;0;_'; end; procedure TDmERP.qyEmpresaBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyEmpresa, 'empresa', 'cdEmpresa', qyEmpresa.FieldByName('cdEmpresa').AsInteger); end; procedure TDmERP.qyEscalaAfterScroll(DataSet: TDataSet); begin if qyEscalaItem.Active then qyEscalaItem.Close; qyEscalaItem.MacroByName('filtro').Clear; qyEscalaItem.ParamByName('cdEscala').AsInteger := qyEscala.FieldByName('cdEscala').AsInteger; qyEscalaItem.Open(); end; procedure TDmERP.qyEscalaBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyEscala, 'escala', 'cdEscala', qyEscala.FieldByName('cdEscala').AsInteger, ''); end; procedure TDmERP.qyEscalaItemBeforePost(DataSet: TDataSet); begin if qyEscalaItem.State = dsInsert then begin qyEscalaItem.FieldByName('cdEscala').AsInteger := qyEscala.FieldByName('cdEscala').AsInteger; GerarCodigo(fdConnERP, qyEscalaItem, 'escalaItem', 'cdEscalaItem', qyEscalaItem.FieldByName('cdEscalaItem').AsInteger, ' WHERE cdEscala = ' + qyEscala.FieldByName('cdEscala').AsString ); end; end; procedure TDmERP.qyFatDiarioBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyFatDiario, 'fatDiario', 'cdFatDiario', qyFatDiario.FieldByName('cdFatDiario').AsInteger); end; procedure TDmERP.qyFatDiarioNewRecord(DataSet: TDataSet); var dtAtual : TDateTime; begin dtAtual := DataHoraAtual(fdConnERP); qyFatDiario.FieldByName('dtMovimento').AsDateTime := Trunc(dtAtual); end; procedure TDmERP.qyFornecedorAfterScroll(DataSet: TDataSet); begin if qyFornecedor.FieldByName('flFisJur').AsString = 'J' then qyFornecedor.FieldByName('deCpfCnpj').EditMask := '99.999.999/9999-99;0;_' else qyFornecedor.FieldByName('deCpfCnpj').EditMask := '999.999.999-99;0;_'; qyFornecedor.FieldByName('nuFone1').EditMask := '(99) 9999-99999;0;_'; qyFornecedor.FieldByName('nuFone2').EditMask := '(99) 9999-99999;0;_'; qyFornecedor.FieldByName('nuCelular').EditMask := '(99) 99999-9999;0;_'; qyFornecedor.FieldByName('nuFax').EditMask := '(99) 9999-99999;0;_'; qyFornecedor.FieldByName('nuCep').EditMask := '99999-999;0;_'; end; procedure TDmERP.qyFornecedorBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyFornecedor, 'fornecedor', 'cdFornecedor', qyFornecedor.FieldByName('cdFornecedor').AsInteger); end; procedure TDmERP.qyFornecedorNewRecord(DataSet: TDataSet); begin qyFornecedor.FieldByName('flAtivo').AsString := 'S'; qyFornecedor.FieldByName('flIsentoInscEst').AsString := 'S'; end; procedure TDmERP.qyFornecedorTipoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyFornecedorTipo, 'fornecedorTipo', 'cdFornecedorTipo', qyFornecedorTipo.FieldByName('cdFornecedorTipo').AsInteger); end; procedure TDmERP.qyIntComCargaAfterScroll(DataSet: TDataSet); begin if qyIntComCargaAlerta.Active then qyIntComCargaAlerta.Close; qyIntComCargaAlerta.MacroByName('filtro').Clear; qyIntComCargaAlerta.ParamByName('cdCarga').AsInteger := qyIntComCarga.FieldByName('cdCarga').AsInteger; qyIntComCargaAlerta.Open(); end; procedure TDmERP.qyIntComCargaAlertaBeforePost(DataSet: TDataSet); begin if qyIntComCargaAlerta.State = dsInsert then begin qyIntComCargaAlerta.FieldByName('cdCarga').AsInteger := qyIntComCarga.FieldByName('cdCarga').AsInteger; GerarCodigo(fdConnERP, qyIntComCargaAlerta, 'intComCargaAlerta', 'cdCargaAlerta', qyIntComCargaAlerta.FieldByName('cdCargaAlerta').AsInteger, ' WHERE cdCarga = ' + qyIntComCarga.FieldByName('cdCarga').AsString ); end; end; procedure TDmERP.qyIntComCargaNewRecord(DataSet: TDataSet); begin qyIntComCarga.FieldByName('cdSituacao').AsInteger := 1; qyIntComCarga.FieldByName('cdPrioridade').AsInteger := 1; qyIntComCarga.FieldByName('flSetorLixa').AsString := 'N'; qyIntComCarga.FieldByName('flSetorFaturamento').AsString := 'N'; qyIntComCarga.FieldByName('flSetorExpedicao').AsString := 'N'; end; procedure TDmERP.qyIntComCotaFinBeforePost(DataSet: TDataSet); begin GravarCamposAutomaticos(qyIntComCotaFin); end; procedure TDmERP.qyIntComItemPedImpressoBeforePost(DataSet: TDataSet); var dthrAtual : TDateTime; begin dthrAtual := DataHoraAtual(fdConnERP); if qyIntComItemPedImpresso.State = dsInsert then begin qyIntComItemPedImpresso.FieldByName('flEnvProducao').AsString := 'N'; qyIntComItemPedImpresso.FieldByName('cdUsuarioImpressao').AsInteger := FTelaInicial.FcdUsuario; qyIntComItemPedImpresso.FieldByName('dtCadastro').AsDateTime := Trunc(dthrAtual); qyIntComItemPedImpresso.FieldByName('hrCadastro').AsInteger := HoraParaMinutos(dthrAtual); end; end; procedure TDmERP.qyIntComItensPedAntigosBeforeOpen(DataSet: TDataSet); begin qyIntComItensPedAntigos.ParamByName('cdPedido').AsInteger := qyIntComPedidosAntigos.FieldByName('cdPedido').AsInteger; end; procedure TDmERP.qyIntComPedidosAntigosAfterScroll(DataSet: TDataSet); begin if qyIntComItensPedAntigos.Active then qyIntComItensPedAntigos.Close; qyIntComItensPedAntigos.Open(); end; procedure TDmERP.qyIntSupItensCfgPadBeforePost(DataSet: TDataSet); begin GravarCamposAutomaticos(qyIntSupItensCfgPad); end; procedure TDmERP.qyIntSupItensCfgPaddeadornoValidate(Sender: TField); begin GravarCamposItensVarItens(19, Sender.AsString, 'cdAdornoRecNum', 'cdAdorno'); end; procedure TDmERP.qyIntSupItensCfgPaddechavetaValidate(Sender: TField); begin GravarCamposItensVarItens(20, Sender.AsString, 'cdChavetaRecNum', 'cdChaveta'); end; procedure TDmERP.qyIntSupItensCfgPaddeforracaoValidate(Sender: TField); begin GravarCamposItensVarItens(25, Sender.AsString, 'cdForracaoRecNum', 'cdForracao'); end; procedure TDmERP.qyIntSupItensCfgPaddetipoalcaValidate(Sender: TField); begin GravarCamposItensVarItens(15, Sender.AsString, 'cdTipoAlcaRecNum', 'cdTipoAlca'); end; procedure TDmERP.qyIntSupItensCfgPadflcobrarcorGetText(Sender: TField; var Text: string; DisplayText: Boolean); begin if SameText(Sender.FieldName, 'flCobrarCor') then Text := ''; end; procedure TDmERP.qyItemFamiliaBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyItemFamilia, 'itemFamilia', 'cdItemFamilia', qyItemFamilia.FieldByName('cdItemFamilia').AsInteger); end; procedure TDmERP.qyItemGrupoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyItemGrupo, 'itemGrupo', 'cdItemGrupo', qyItemGrupo.FieldByName('cdItemGrupo').AsInteger); end; procedure TDmERP.qyItemNewRecord(DataSet: TDataSet); begin qyItem.FieldByName('flAtivo').AsString := 'S'; qyItem.FieldByName('flItemRevenda').AsString := 'N'; end; procedure TDmERP.qyIntIndBaixaProducaoBeforePost(DataSet: TDataSet); begin GravarCamposAutomaticos(DmERP.qyIntIndBaixaProducao); end; procedure TDmERP.qyIntIndItemRelacionadoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyIntIndItemRelacionado, 'intIndItemRelacionado', 'cdItemRelacionado', qyIntIndItemRelacionado.FieldByName('cdItemRelacionado').AsInteger); end; procedure TDmERP.qyItemVinculoVariavelAfterOpen(DataSet: TDataSet); begin FscdItemVinculo := qyItemVinculoVariavel.FieldByName('cdItem').AsString; end; procedure TDmERP.qyItemVinculoVariavelAfterPost(DataSet: TDataSet); begin FscdItemVinculo := qyItemVinculoVariavel.FieldByName('cdItem').AsString; end; procedure TDmERP.qyItemVinculoVariavelBeforePost(DataSet: TDataSet); var strValidacao : String; begin if (qyItemVinculoVariavel.State = dsInsert) and (Trim(FscdItemVinculo) <> '') then qyItemVinculoVariavel.FieldByName('cdItem').AsString := FscdItemVinculo; strValidacao := ItemVinculoVariavelValido; if Trim(strValidacao) <> '' then begin Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao); qyItemVinculoVariavel.Cancel; end; end; procedure TDmERP.qyItemVinculoVariavelcdvariavelitempadraoValidate( Sender: TField); var stDados : TStringList; begin if (qyItemVinculoVariavel.Active) and (not qyItemVinculoVariavel.FieldByName('cdVariavelItemPadrao').IsNull) and (qyItemVinculoVariavel.State in dsEditModes) then begin if (qyItemVinculoVariavel.FieldByName('cdVariavel').IsNull) then Aviso('Informe a variável antes.') else begin stDados := TStringList.Create; ExecuteSimplesSql(fdConnERP, 'SELECT deValor ' + ' FROM erp.variavelItens ' + ' WHERE cdVariavel = ' + qyItemVinculoVariavel.FieldByName('cdVariavel').AsString + ' AND cdVariavelItem = ' + qyItemVinculoVariavel.FieldByName('cdVariavelItemPadrao').AsString, 'deValor', stDados ); if (stDados.Count > 0) and (Trim(stDados.Strings[0]) <> '') then qyItemVinculoVariavel.FieldByName('deVariavelItemPadrao').AsString := Trim(stDados.Strings[0]) else begin Aviso('Valor inválido.'); qyItemVinculoVariavel.FieldByName('cdVariavelItemPadrao').Clear; qyItemVinculoVariavel.FieldByName('deVariavelItemPadrao').Clear; end; if Assigned(stDados) then FreeAndNil(stDados); end; end; end; procedure TDmERP.qyItemVinculoVariavelcdvariavelValidate(Sender: TField); var stDados : TStringList; begin if (qyItemVinculoVariavel.Active) and (not qyItemVinculoVariavel.FieldByName('cdVariavel').IsNull) and (qyItemVinculoVariavel.State in dsEditModes) then begin qyItemVinculoVariavel.FieldByName('cdVariavelItemPadrao').Clear; qyItemVinculoVariavel.FieldByName('deVariavelItemPadrao').Clear; stDados := TStringList.Create; ExecuteSimplesSql(fdConnERP, 'SELECT deVariavel ' + ' FROM erp.variavel ' + ' WHERE cdVariavel = ' + qyItemVinculoVariavel.FieldByName('cdVariavel').AsString, 'deVariavel', stDados ); if (stDados.Count > 0) and (Trim(stDados.Strings[0]) <> '') then qyItemVinculoVariavel.FieldByName('deVariavel').AsString := Trim(stDados.Strings[0]) else begin Aviso('Valor inválido.'); qyItemVinculoVariavel.FieldByName('cdVariavel').Clear; qyItemVinculoVariavel.FieldByName('deVariavel').Clear; end; if Assigned(stDados) then FreeAndNil(stDados); end; end; procedure TDmERP.qyIntIndMaterialMovEntBeforePost(DataSet: TDataSet); begin BeforePostMaterialMov(qyIntIndMaterialMovEnt); end; procedure TDmERP.BeforePostMaterialMov(const qyMov : TFDQuery); var dthrAtual : TDateTime; stDados : TStringList; procedure GravarCamposSit; begin qyMov.FieldByName('cdUsuarioSituacaoMov').AsInteger := FTelaInicial.FcdUsuario; qyMov.FieldByName('dtSituacaoMov').AsDateTime := Trunc(dthrAtual); qyMov.FieldByName('hrSituacaoMov').AsInteger := HoraParaMinutos(dthrAtual); if qyMov.FieldByName('nmUsuSit').ReadOnly then qyMov.FieldByName('nmUsuSit').ReadOnly := False; qyMov.FieldByName('nmUsuSit').AsString := FTelaInicial.FnmUsuario; if qyMov.FieldByName('dehrSituacaoMov').ReadOnly then qyMov.FieldByName('dehrSituacaoMov').ReadOnly := False; qyMov.FieldByName('dehrSituacaoMov').AsString := FormatDateTime('hh:mm', dthrAtual); end; begin GerarCodigo(fdConnERP, qyMov, 'intIndMaterialMovimento', 'cdMaterialMovimento', qyMov.FieldByName('cdMaterialMovimento').AsInteger); stDados := TStringList.Create; dthrAtual := DataHoraAtual(fdConnERP); if qyMov.State = dsInsert then begin qyMov.FieldByName('dtMovimento').AsDateTime := Trunc(dthrAtual); qyMov.FieldByName('hrMovimento').AsInteger := HoraParaMinutos(dthrAtual); GravarCamposSit; end else if (qyMov.State = dsEdit) then begin stDados.Clear; ExecuteSimplesSql(fdConnERP, 'SELECT cdSituacaoMovimento ' + ' FROM erp.intIndMaterialMovimento ' + ' WHERE cdMaterialMovimento = ' + qyMov.FieldByName('cdMaterialMovimento').AsString, 'cdSituacaoMovimento', stDados ); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) and (StrToIntDef(stDados.Strings[0], 0) = 1) and (StrToIntDef(stDados.Strings[0], 0) <> qyMov.FieldByName('cdSituacaoMovimento').AsInteger) then GravarCamposSit; end; if Assigned(stDados) then FreeAndNil(stDados); end; procedure TDmERP.qyIntIndMaterialMovEntNewRecord(DataSet: TDataSet); begin qyIntIndMaterialMovEnt.FieldByName('cdSituacaoMovimento').AsInteger := 2; qyIntIndMaterialMovEnt.FieldByName('flTipoMovimento').AsString := 'E'; end; procedure TDmERP.qyIntIndMaterialMovSaiBeforeOpen(DataSet: TDataSet); begin qyIntIndMaterialMovSai.ParamByName('cdMaterialSolicitacao').AsInteger := qyIntIndMaterialSolic.FieldByName('cdMaterialSolicitacao').AsInteger; end; procedure TDmERP.qyIntIndMaterialMovSaiBeforePost(DataSet: TDataSet); begin BeforePostMaterialMov(qyIntIndMaterialMovSai); end; procedure TDmERP.qyIntIndMaterialMovSaiNewRecord(DataSet: TDataSet); begin qyIntIndMaterialMovSai.FieldByName('cdSituacaoMovimento').AsInteger := 2; qyIntIndMaterialMovSai.FieldByName('flTipoMovimento').AsString := 'S'; end; procedure TDmERP.qyIntIndMaterialSolicAfterScroll(DataSet: TDataSet); begin if qyIntIndMaterialMovSai.Active then qyIntIndMaterialMovSai.Close; qyIntIndMaterialMovSai.Open(); end; procedure TDmERP.qyIntIndMaterialSolicBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyIntIndMaterialSolic, 'intIndMaterialSolicitacao', 'cdMaterialSolicitacao', qyIntIndMaterialSolic.FieldByName('cdMaterialSolicitacao').AsInteger); end; procedure TDmERP.qyIntIndMaterialSolicNewRecord(DataSet: TDataSet); begin qyIntIndMaterialSolic.FieldByName('flTipoSolicitacao').AsString := 'I'; end; procedure TDmERP.qyMotoristaAfterScroll(DataSet: TDataSet); begin qyMotorista.FieldByName('deCpf').EditMask := '999.999.999-99;0;_'; end; procedure TDmERP.qyMotoristaBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyMotorista, 'motorista', 'cdMotorista', qyMotorista.FieldByName('cdMotorista').AsInteger); end; procedure TDmERP.qyNaturezaNewRecord(DataSet: TDataSet); begin qyNatureza.FieldByName('flDentroEstado').AsString := 'S'; qyNatureza.FieldByName('flExportacao').AsString := 'N'; qyNatureza.FieldByName('flDrawback').AsString := 'N'; qyNatureza.FieldByName('flDevolucao').AsString := 'N'; qyNatureza.FieldByName('flDevolucaoOutraOper').AsString := 'N'; qyNatureza.FieldByName('flConsignacao').AsString := 'N'; qyNatureza.FieldByName('flVendaFutura').AsString := 'N'; qyNatureza.FieldByName('flOperacaoTriangular').AsString := 'N'; qyNatureza.FieldByName('flBonificacao').AsString := 'N'; qyNatureza.FieldByName('flNaturezaServico').AsString := 'N'; qyNatureza.FieldByName('flNaturezaTransporte').AsString := 'N'; qyNatureza.FieldByName('flVendaOrdemSemValor').AsString := 'N'; qyNatureza.FieldByName('flVendaOrgaoPublico').AsString := 'N'; qyNatureza.FieldByName('flIpiIncideIcms').AsString := 'N'; qyNatureza.FieldByName('flIpiIncidePisCofins').AsString := 'N'; qyNatureza.FieldByName('flIpiCred50Perc').AsString := 'N'; qyNatureza.FieldByName('flIcmsCalcPartSimples').AsString := 'N'; qyNatureza.FieldByName('flIcmsMsgAprovCred').AsString := 'N'; qyNatureza.FieldByName('flIcmsCalcSubstTrib').AsString := 'N'; qyNatureza.FieldByName('flIcmsReducaoCalc').AsString := 'N'; qyNatureza.FieldByName('flIcmsCalcStUsoCon').AsString := 'N'; qyNatureza.FieldByName('flIcmsDebCreLivros').AsString := 'N'; qyNatureza.FieldByName('flMovFinanceiro').AsString := 'N'; qyNatureza.FieldByName('flMovFiscal').AsString := 'N'; qyNatureza.FieldByName('flFaturamento').AsString := 'N'; qyNatureza.FieldByName('flMovEstoque').AsString := 'N'; qyNatureza.FieldByName('flEstoqueTerceiros').AsString := 'N'; qyNatureza.FieldByName('flEstoqueArmazenagem').AsString := 'N'; qyNatureza.FieldByName('flEntraCalcRentab').AsString := 'N'; qyNatureza.FieldByName('flAbateRentab').AsString := 'N'; qyNatureza.FieldByName('flConsideraSisDec').AsString := 'N'; qyNatureza.FieldByName('flMsgLeiTransp').AsString := 'N'; qyNatureza.FieldByName('flUtilizaControleTerc').AsString := 'N'; qyNatureza.FieldByName('flGeraValorCalcBonif').AsString := 'N'; qyNatureza.FieldByName('flMovSelos').AsString := 'N'; qyNatureza.FieldByName('flOperSemCredSt').AsString := 'N'; qyNatureza.FieldByName('flOperSemCredIpi').AsString := 'N'; qyNatureza.FieldByName('cdPisBase').AsInteger := 3; qyNatureza.FieldByName('cdCofinsBase').AsInteger := 3; qyNatureza.FieldByName('cdSimplesBase').AsInteger := 3; qyNatureza.FieldByName('flIsencaoPisCofins').AsString := 'N'; qyNatureza.FieldByName('flRetencaoPisCofinsCsll').AsString := 'N'; qyNatureza.FieldByName('flAbatePisCofinsTitNf').AsString := 'N'; qyNatureza.FieldByName('flProdMonofasSn').AsString := 'N'; qyNatureza.FieldByName('flDiferencaIcms').AsString := 'N'; end; procedure TDmERP.qyPatrimonioBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyPatrimonio, 'patrimonio', 'cdPatrimonio', qyPatrimonio.FieldByName('cdPatrimonio').AsInteger); end; procedure TDmERP.qyPatrimonioManutBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyPatrimonioManut, 'patrimonioManutencao', 'cdPatrimonioManutencao', qyPatrimonioManut.FieldByName('cdPatrimonioManutencao').AsInteger); end; procedure TDmERP.qyPatrimonioManutNewRecord(DataSet: TDataSet); begin qyPatrimonioManut.FieldByName('cdSituacao').AsInteger := 1; end; procedure TDmERP.qyPatrimonioManutPesqAfterClose(DataSet: TDataSet); begin qyPatrimonioManutPesq.MacroByName('filtro').Clear; end; procedure TDmERP.qyPatrimonioPesqAfterClose(DataSet: TDataSet); begin qyPatrimonioPesq.MacroByName('filtro').Clear; end; procedure TDmERP.qyPatrimonioTipoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyPatrimonioTipo, 'patrimonioTipo', 'cdPatrimonioTipo', qyPatrimonioTipo.FieldByName('cdPatrimonioTipo').AsInteger); end; procedure TDmERP.qyPatrimonioTipoPesqAfterClose(DataSet: TDataSet); begin qyPatrimonioTipoPesq.MacroByName('filtro').Clear; end; procedure TDmERP.qyPedidoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyPedido, 'pedido', 'cdPedido', qyPedido.FieldByName('cdPedido').AsInteger); end; procedure TDmERP.qyPedidoNewRecord(DataSet: TDataSet); var dthrAtual : TDateTime; begin dthrAtual := DataHoraAtual(fdConnERP); qyPedido.FieldByName('cdPedidoTipo').AsInteger := 1; qyPedido.FieldByName('cdPedidoSituacao').AsInteger := 1; qyPedido.FieldByName('dtEmissao').AsDateTime := Trunc(dthrAtual); qyPedido.FieldByName('flDescontoPorItem').AsString := 'N'; end; procedure TDmERP.GravarCamposItensVarItens(const icdVar : Integer; const sdeVarItem, scdFieldRecNum, scdFieldMasc : String ); var sFieldSeq : String; begin if qyIntSupItensCfgPad.State in dsEditModes then begin sFieldSeq := AnsiReplaceStr(scdFieldRecNum, 'RecNum', 'Seq'); try DmIntegracao.fdConnInteg.Connected := True; DmIntegracao.qyItensVarItens.Open(); DmIntegracao.qyItensVarItens.First; if DmIntegracao.qyItensVarItens.Locate('codigo_variavel;valor', VarArrayOf([icdVar, sdeVarItem]), [] ) then begin qyIntSupItensCfgPad.FieldByName(scdFieldRecNum).AsInteger := DmIntegracao.qyItensVarItens.FieldByName('recNum').AsInteger; qyIntSupItensCfgPad.FieldByName(scdFieldMasc).AsInteger := DmIntegracao.qyItensVarItens.FieldByName('mascara').AsInteger; qyIntSupItensCfgPad.FieldByName(sFieldSeq).AsInteger := DmIntegracao.qyItensVarItens.FieldByName('seq').AsInteger; end else begin qyIntSupItensCfgPad.FieldByName(scdFieldRecNum).Clear; qyIntSupItensCfgPad.FieldByName(scdFieldMasc).Clear; qyIntSupItensCfgPad.FieldByName(sFieldSeq).Clear; end; except on E: EFDDBEngineException do begin Erro(E.message); end; end; if DmIntegracao.qyItensVarItens.Active then DmIntegracao.qyItensVarItens.Close; DmIntegracao.fdConnInteg.Connected := False; end; end; function TDmERP.CobrancaValida : String; begin Result := ''; if qyCobranca.FieldByName('cdCliente').IsNull then AdicionaLinha(Result, ' - Cliente deve ser informado'); if qyCobranca.FieldByName('vlCobranca').IsNull then AdicionaLinha(Result, ' - Valor da cobrança deve ser informado'); if (Trim(qyCobranca.FieldByName('deTextoCobranca').AsString) = '') then AdicionaLinha(Result, ' - Texto da cobrança deve ser informado'); end; procedure TDmERP.GravarCobranca; var strValidacao : String; bInserindo : Boolean; begin strValidacao := CobrancaValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyCobranca.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyCobranca); qyCobranca.Post; fdConnERP.Commit; if bInserindo then Informacao('Cobrança inserida com sucesso.') else Informacao('Cobrança alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirCobranca; begin if (qyCobranca.Active) then begin if (qyCobranca.FieldByName('cdSituacao').AsInteger = 2) then Aviso('Cobrança já finalizada.') else if Pergunta('Confirma a exclusão deste registro?') then begin if not qyCobrancaContato.Active then qyCobrancaContato.Open(); qyCobrancaContato.First; while not qyCobrancaContato.Eof do qyCobrancaContato.Delete; qyCobranca.Delete; Informacao('Cobrança excluída com sucesso.'); end; end; end; function TDmERP.CobrancaContatoValido : String; begin Result := ''; if qyCobrancaContato.FieldByName('dtContato').IsNull then AdicionaLinha(Result, ' - Data do contato deve ser informada'); if (Trim(qyCobrancaContato.FieldByName('nmContato').AsString) = '') then AdicionaLinha(Result, ' - Pessoa do contato deve ser informada'); if (qyCobrancaContato.FieldByName('flRetornar').AsString = 'S') and (qyCobrancaContato.FieldByName('dtRetorno').IsNull) then AdicionaLinha(Result, ' - Data de retorno deve ser informada'); if (not qyCobrancaContato.FieldByName('dtContato').IsNull) and (not qyCobrancaContato.FieldByName('dtRetorno').IsNull) and (qyCobrancaContato.FieldByName('dtContato').AsDateTime > qyCobrancaContato.FieldByName('dtRetorno').AsDateTime) then AdicionaLinha(Result, ' - Data de contato não pode ser maior que a de retorno'); end; procedure TDmERP.GravarCobrancaContato; var strValidacao : String; bInserindo : Boolean; begin strValidacao := CobrancaContatoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyCobrancaContato.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyCobrancaContato); qyCobrancaContato.Post; fdConnERP.Commit; if bInserindo then Informacao('Contato de cobrança inserido com sucesso.') else Informacao('Contato de cobrança alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirCobrancaContato; begin if (qyCobrancaContato.Active) then begin if (qyCobranca.FieldByName('cdSituacao').AsInteger = 2) then Aviso('Este contato não pode ser excluído.' + #13 + 'Cobrança já finalizada.') else if Pergunta('Confirma a exclusão deste registro?') then begin qyCobrancaContato.Delete; Informacao('Contato de cobranca excluído com sucesso.'); end; end; end; function TDmERP.FatDiarioValido : String; begin Result := ''; if qyFatDiario.FieldByName('cdEmpresa').IsNull then AdicionaLinha(Result, ' - Empresa deve ser informada'); if qyFatDiario.FieldByName('vlFaturado').IsNull then AdicionaLinha(Result, ' - Valor faturado deve ser informado'); if qyFatDiario.FieldByName('dtMovimento').IsNull then AdicionaLinha(Result, ' - Data do movimento deve ser informada'); end; procedure TDmERP.GravarFatDiario; var strValidacao : String; bInserindo : Boolean; begin strValidacao := FatDiarioValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyFatDiario.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyFatDiario); qyFatDiario.Post; fdConnERP.Commit; if bInserindo then Informacao('Faturamento Diário inserido com sucesso.') else Informacao('Faturamento Diário alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirFatDiario; begin if (qyFatDiario.Active) then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyFatDiario.Delete; Informacao('Faturamento Diário excluído com sucesso.'); end; end; end; function TDmERP.NaturezaValida : String; begin Result := ''; if qyNatureza.FieldByName('cdNatureza').IsNull then AdicionaLinha(Result, ' - Código da Natureza deve ser informada'); if Trim(qyNatureza.FieldByName('deNatureza').AsString) = '' then AdicionaLinha(Result, ' - Descrição da Natureza deve ser informada'); if Trim(qyNatureza.FieldByName('deNaturezaFiscal').AsString) = '' then AdicionaLinha(Result, ' - Descrição Fiscal da Natureza deve ser informada'); if qyNatureza.FieldByName('flNaturezaTipo').IsNull then AdicionaLinha(Result, ' - Tipo da Natureza deve ser informada'); end; procedure TDmERP.GravarNatureza; var strValidacao : String; bInserindo : Boolean; begin strValidacao := NaturezaValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyNatureza.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyNatureza); qyNatureza.Post; fdConnERP.Commit; if bInserindo then Informacao('Natureza inserida com sucesso.') else Informacao('Natureza alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirNatureza; begin if (qyNatureza.Active) then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyNatureza.Delete; Informacao('Natureza excluída com sucesso.'); end; end; end; function TDmERP.TipoPatrimonioValido : String; begin Result := ''; if (Trim(qyPatrimonioTipo.FieldByName('dePatrimonioTipo').AsString) = '') then AdicionaLinha(Result, ' - Descrição do tipo de patrimônio deve ser informada'); end; procedure TDmERP.GravarTipoPatrimonio; var strValidacao : String; bInserindo : Boolean; begin strValidacao := TipoPatrimonioValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyPatrimonioTipo.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyPatrimonioTipo); qyPatrimonioTipo.Post; fdConnERP.Commit; if bInserindo then Informacao('Tipo de Patrimônio inserido com sucesso.') else Informacao('Tipo de Patrimônio alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirTipoPatrimonio; begin if qyPatrimonioTipo.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyPatrimonioTipo.Delete; Informacao('Tipo de Patrimônio excluído com sucesso.'); end; end; end; function TDmERP.PatrimonioValido : String; begin Result := ''; if (qyPatrimonio.FieldByName('cdPatrimonioTipo').IsNull) then AdicionaLinha(Result, ' - Tipo de patrimônio deve ser informado'); if (Trim(qyPatrimonio.FieldByName('nuPatrimonio').AsString) = '') then AdicionaLinha(Result, ' - Nº de patrimônio deve ser informado'); if (Trim(qyPatrimonio.FieldByName('dePatrimonio').AsString) = '') then AdicionaLinha(Result, ' - Descrição do patrimônio deve ser informada'); if (qyPatrimonio.FieldByName('cdSetor').IsNull) then AdicionaLinha(Result, ' - Setor do patrimônio deve ser informado'); end; procedure TDmERP.GravarPatrimonio; var strValidacao : String; bInserindo : Boolean; begin strValidacao := PatrimonioValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyPatrimonio.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyPatrimonio); qyPatrimonio.Post; fdConnERP.Commit; if bInserindo then Informacao('Patrimônio inserido com sucesso.') else Informacao('Patrimônio alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirPatrimonio; begin if qyPatrimonio.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyPatrimonio.Delete; Informacao('Patrimônio excluído com sucesso.'); end; end; end; function TDmERP.ClassifFiscalValida : String; begin Result := ''; if (Trim(qyClassifFiscal.FieldByName('nuClassifFiscal').AsString) = '') then AdicionaLinha(Result, ' - Nº da classificação fiscal deve ser informado'); end; procedure TDmERP.GravarClassifFiscal; var strValidacao : String; bInserindo : Boolean; begin strValidacao := ClassifFiscalValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyClassifFiscal.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyClassifFiscal); qyClassifFiscal.Post; fdConnERP.Commit; if bInserindo then Informacao('Classificação Fiscal inserida com sucesso.') else Informacao('Classificação Fiscal alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirClassifFiscal; begin if qyClassifFiscal.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyClassifFiscal.Delete; Informacao('Classificação Fiscal excluída com sucesso.'); end; end; end; function TDmERP.DocumentoTipoValido : String; begin Result := ''; if (Trim(qyDocumentoTipo.FieldByName('deDocumentoTipo').AsString) = '') then AdicionaLinha(Result, ' - Descrição do tipo de documento deve ser informada'); end; procedure TDmERP.GravarDocumentoTipo; var strValidacao : String; bInserindo : Boolean; begin strValidacao := DocumentoTipoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyDocumentoTipo.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyDocumentoTipo); qyDocumentoTipo.Post; fdConnERP.Commit; if bInserindo then Informacao('Tipo de Documento inserido com sucesso.') else Informacao('Tipo de Documento alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirDocumentoTipo; begin if qyDocumentoTipo.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyDocumentoTipo.Delete; Informacao('Tipo de Documento excluído com sucesso.'); end; end; end; function TDmERP.DespesaTipoValido : String; begin Result := ''; if (Trim(qyDespesaTipo.FieldByName('deDespesaTipo').AsString) = '') then AdicionaLinha(Result, ' - Descrição do tipo de despesa deve ser informada'); end; procedure TDmERP.GravarDespesaTipo; var strValidacao : String; bInserindo : Boolean; begin strValidacao := DespesaTipoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyDespesaTipo.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyDespesaTipo); qyDespesaTipo.Post; fdConnERP.Commit; if bInserindo then Informacao('Tipo de Despesa inserido com sucesso.') else Informacao('Tipo de Despesa alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirDespesaTipo; begin if qyDespesaTipo.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyDespesaTipo.Delete; Informacao('Tipo de Despesa excluído com sucesso.'); end; end; end; function TDmERP.VariavelValida : String; begin Result := ''; if (Trim(qyVariavel.FieldByName('deVariavel').AsString) = '') then AdicionaLinha(Result, ' - Descrição da variável deve ser informada'); end; procedure TDmERP.GravarVariavel; var strValidacao : String; bInserindo : Boolean; begin strValidacao := VariavelValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyVariavel.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyVariavel); qyVariavel.Post; fdConnERP.Commit; if bInserindo then Informacao('Variável inserida com sucesso.') else Informacao('Variável alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirVariavel; begin if qyVariavel.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyVariavel.Delete; Informacao('Variável excluída com sucesso.'); end; end; end; function TDmERP.VariavelItemValido : String; begin Result := ''; if (Trim(qyVariavelItens.FieldByName('deValor').AsString) = '') then AdicionaLinha(Result, ' - Valor do item da variável deve ser informado'); if (Trim(qyVariavelItens.FieldByName('deMascara').AsString) = '') then AdicionaLinha(Result, ' - Valor máscara do item da variável deve ser informado'); end; procedure TDmERP.GravarVariavelItem; var strValidacao : String; bInserindo : Boolean; begin strValidacao := VariavelItemValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyVariavelItens.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyVariavelItens); qyVariavelItens.Post; fdConnERP.Commit; if bInserindo then Informacao('Item de variável inserido com sucesso.') else Informacao('Item de variável alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirVariavelItem; begin if qyVariavelItens.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyVariavelItens.Delete; Informacao('Item de variável de excluído com sucesso.'); end; end; end; function TDmERP.ItemVinculoVariavelValido : String; var stDados : TStringList; begin Result := ''; stDados := TStringList.Create; if (Trim(qyItemVinculoVariavel.FieldByName('cdItem').AsString) = '') and (Trim(FscdItemVinculo) = '') then AdicionaLinha(Result, ' - Item deve ser informado'); if (qyItemVinculoVariavel.FieldByName('cdVariavel').IsNull) then AdicionaLinha(Result, ' - Variável deve ser informada'); if (Trim(Result) = '') and (qyItemVinculoVariavel.State = dsInsert) then begin stDados.Clear; ExecuteSimplesSql(fdConnERP, 'SELECT a.cdItem ' + ' FROM erp.itemVinculoVariavel a ' + ' WHERE a.cdItem = ' + QuotedStr(qyItemVinculoVariavel.FieldByName('cdItem').AsString) + ' AND a.cdVariavel = ' + qyItemVinculoVariavel.FieldByName('cdVariavel').AsString, 'cdItem', stDados ); if (stDados.Count > 0) and (Trim(stDados.Strings[0]) <> '') then AdicionaLinha(Result, ' - Variável já vinculada ao item ' + qyItemVinculoVariavel.FieldByName('cdItem').AsString); end; if Assigned(stDados) then FreeAndNil(stDados); end; procedure TDmERP.GravarItemVinculoVariavel; var strValidacao : String; bInserindo : Boolean; begin strValidacao := ItemVinculoVariavelValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyItemVinculoVariavel.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyItemVinculoVariavel); qyItemVinculoVariavel.Post; fdConnERP.Commit; if bInserindo then Informacao('Vínculo de variável ao item inserido com sucesso.') else Informacao('Vínculo de variável ao item alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirItemVinculoVariavel; begin if (qyItemVinculoVariavel.Active) and (not qyItemVinculoVariavel.IsEmpty) then begin if Pergunta('Confirma a exclusão deste registro?') then begin if qyItemVariavelItensBloq.Active then qyItemVariavelItensBloq.Close; qyItemVariavelItensBloq.MacroByName('filtro').Value := ' WHERE cdItem = ' + QuotedStr(qyItemVinculoVariavel.FieldByName('cdItem').AsString) + ' AND cdVariavel = ' + qyItemVinculoVariavel.FieldByName('cdVariavel').AsString; qyItemVariavelItensBloq.Open(); qyItemVariavelItensBloq.First; while not qyItemVariavelItensBloq.Eof do qyItemVariavelItensBloq.Delete; qyItemVinculoVariavel.Delete; Informacao('Vínculo de variável ao item excluído com sucesso.'); end; end; end; function TDmERP.PatrimonioManutencaoValida : String; var stDados : TStringList; sAux : String; begin Result := ''; if (qyPatrimonioManut.FieldByName('cdPatrimonio').IsNull) then AdicionaLinha(Result, ' - Patrimônio deve ser informado') else begin sAux := ''; if qyPatrimonioManut.State <> dsInsert then sAux := ' AND cdPatrimonioManutencao <> ' + qyPatrimonioManut.FieldByName('cdPatrimonioManutencao').AsString; stDados := TStringList.Create; ExecuteSimplesSql(fdConnERP, 'SELECT cdPatrimonioManutencao ' + ' FROM erp.patrimonioManutencao ' + ' WHERE cdPatrimonio = ' + qyPatrimonioManut.FieldByName('cdPatrimonio').AsString + ' AND cdSituacao IN (1,2) ' + //Em aberto | Em Progresso sAux, 'cdPatrimonioManutencao', stDados ); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then AdicionaLinha(Result, ' - Já existe uma manutenção cadastrada para este patrimônio que se encontra em aberto ou em progresso'); if Assigned(stDados) then FreeAndNil(stDados); end; if (qyPatrimonioManut.FieldByName('dtManutencao').IsNull) then AdicionaLinha(Result, ' - Data de manutenção deve ser informada'); if (qyPatrimonioManut.FieldByName('dtAvisarEm').IsNull) then AdicionaLinha(Result, ' - Data de aviso deve ser informada'); if (not qyPatrimonioManut.FieldByName('dtManutencao').IsNull) and (not qyPatrimonioManut.FieldByName('dtAvisarEm').IsNull) and ( qyPatrimonioManut.FieldByName('dtAvisarEm').AsDateTime > qyPatrimonioManut.FieldByName('dtManutencao').AsDateTime ) then AdicionaLinha(Result, ' - Data de aviso não pode ser maior que a de manutenção'); if (Trim(qyPatrimonioManut.FieldByName('deResponsavel').AsString) = '') then AdicionaLinha(Result, ' - Responsável deve ser informado'); if (Trim(qyPatrimonioManut.FieldByName('deManutencao').AsString) = '') then AdicionaLinha(Result, ' - Descrição da manutenção deve ser informada'); end; procedure TDmERP.GravarPatrimonioManutencao; var strValidacao : String; bInserindo : Boolean; begin strValidacao := PatrimonioManutencaoValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyPatrimonioManut.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyPatrimonioManut); qyPatrimonioManut.Post; fdConnERP.Commit; if bInserindo then Informacao('Manutenção de patrimônio inserida com sucesso.') else Informacao('Manutenção de patrimônio alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirPatrimonioManutencao; begin if qyPatrimonioManut.Active then begin if qyPatrimonioManut.FieldByName('cdSituacao').AsInteger <> 1 then Aviso('Manutenção de patrimônio não pode ser excluída. Situação diferente de "Em Aberto".') else if Pergunta('Confirma a exclusão deste registro?') then begin qyPatrimonioManut.Delete; Informacao('Manutenção de patrimônio excluída com sucesso.'); end; end; end; function TDmERP.BorderoValido : String; var stDados : TStringList; sAux : String; begin Result := ''; if (qyBordero.FieldByName('cdMotorista').IsNull) then AdicionaLinha(Result, ' - Motorista deve ser informado'); if (qyBordero.FieldByName('cdVeiculo').IsNull) then AdicionaLinha(Result, ' - Veículo deve ser informado'); if (qyBordero.FieldByName('dtSaida').IsNull) then AdicionaLinha(Result, ' - Data de saída deve ser informada'); if (qyBordero.FieldByName('dtRetorno').IsNull) then AdicionaLinha(Result, ' - Data de retorno deve ser informada'); if (not qyBordero.FieldByName('dtSaida').IsNull) and (not qyBordero.FieldByName('dtRetorno').IsNull) and ( qyBordero.FieldByName('dtSaida').AsDateTime > qyBordero.FieldByName('dtRetorno').AsDateTime ) then AdicionaLinha(Result, ' - Data de retorno não pode ser maior que a de saída'); if (qyBordero.FieldByName('nuKmInicial').AsInteger > 0) and (qyBordero.FieldByName('nuKmFinal').AsInteger > 0) and ( qyBordero.FieldByName('nuKmInicial').AsInteger > qyBordero.FieldByName('nuKmFinal').AsInteger ) then AdicionaLinha(Result, ' - Km inicial não pode ser maior que a final'); sAux := ''; if qyBordero.State <> dsInsert then sAux := ' AND cdBordero <> ' + qyBordero.FieldByName('cdBordero').AsString; stDados := TStringList.Create; if (not qyBordero.FieldByName('dtSaida').IsNull) then begin if (qyBordero.FieldByName('cdMotorista').AsInteger > 0) then begin stDados.Clear; ExecuteSimplesSql(fdConnERP, 'SELECT cdBordero ' + ' FROM erp.bordero ' + ' WHERE cdMotorista = ' + qyBordero.FieldByName('cdMotorista').AsString + ' AND dtSaida = ' + QuotedStr(qyBordero.FieldByName('dtSaida').AsString) + sAux, 'cdBordero', stDados ); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then AdicionaLinha(Result, ' - Já existe um bordero cadastrado para este motorista com data de saída em ' + qyBordero.FieldByName('dtSaida').AsString ); end; if (qyBordero.FieldByName('cdVeiculo').AsInteger > 0) then begin stDados.Clear; ExecuteSimplesSql(fdConnERP, 'SELECT cdBordero ' + ' FROM erp.bordero ' + ' WHERE cdVeiculo = ' + qyBordero.FieldByName('cdVeiculo').AsString + ' AND dtSaida = ' + QuotedStr(qyBordero.FieldByName('dtSaida').AsString) + sAux, 'cdBordero', stDados ); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then AdicionaLinha(Result, ' - Já existe um bordero cadastrado para este veículo com data de saída em ' + qyBordero.FieldByName('dtSaida').AsString ); end; end; if Assigned(stDados) then FreeAndNil(stDados); end; procedure TDmERP.GravarBordero; var strValidacao : String; bInserindo : Boolean; begin strValidacao := BorderoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyBordero.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyBordero); qyBordero.Post; fdConnERP.Commit; if bInserindo then Informacao('Bordero inserido com sucesso.') else Informacao('Bordero alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirBordero; begin if qyBordero.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyBordero.Delete; Informacao('Bordero excluído com sucesso.'); end; end; end; function TDmERP.DocumentoValido : String; begin Result := ''; if (qyDocumento.FieldByName('cdEmpresa').IsNull) then AdicionaLinha(Result, ' - Empresa deve ser informada'); if (qyDocumento.FieldByName('cdDocumentoTipo').IsNull) then AdicionaLinha(Result, ' - Tipo de documento deve ser informado'); if (qyDocumento.FieldByName('dtCompetencia').IsNull) then AdicionaLinha(Result, ' - Competência deve ser informada'); end; procedure TDmERP.GravarDocumento; var strValidacao : String; bInserindo : Boolean; begin strValidacao := DocumentoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyDocumento.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyDocumento); qyDocumento.Post; fdConnERP.Commit; if bInserindo then Informacao('Documento inserido com sucesso.') else Informacao('Documento alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirDocumento; begin if qyDocumento.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyDocumento.Delete; Informacao('Documento excluído com sucesso.'); end; end; end; function TDmERP.RepresentanteValido : String; begin Result := ''; if (Trim(qyRepresentante.FieldByName('deCpfCnpj').AsString) <> '') and (not (ValidaCpfCnpj(qyRepresentante.FieldByName('deCpfCnpj').AsString))) then begin if (qyRepresentante.FieldByName('flFisJur').AsString = 'J') then AdicionaLinha(Result, ' - CNPJ inválido') else AdicionaLinha(Result, ' - CPF inválido'); end; if (qyRepresentante.FieldByName('flFisJur').AsString = 'J') then begin if (Trim(qyRepresentante.FieldByName('deCpfCnpj').AsString) = '') then AdicionaLinha(Result, ' - Para pessoa jurídica, o CNPJ deve ser informado'); if (Trim(qyRepresentante.FieldByName('deRazaoSocial').AsString) = '') then AdicionaLinha(Result, ' - Para pessoa jurídica, a razão social deve ser informada'); end; end; procedure TDmERP.GravarRepresentante; var strValidacao : String; bInserindo : Boolean; begin strValidacao := RepresentanteValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyRepresentante.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyRepresentante); qyRepresentante.Post; fdConnERP.Commit; if bInserindo then Informacao('Representante inserido com sucesso.') else Informacao('Representante alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirRepresentante; begin if qyRepresentante.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyRepresentante.Delete; Informacao('Representante excluído com sucesso.'); end; end; end; function TDmERP.BancoValido : String; begin Result := ''; if Trim(qyBanco.FieldByName('cdBanco').AsString) = '' then AdicionaLinha(Result, ' - Código do banco deve ser informado') else if Length(qyBanco.FieldByName('cdBanco').AsString) <> 3 then AdicionaLinha(Result, ' - Código do banco deve ter 3 dígitos'); if Trim(qyBanco.FieldByName('deBanco').AsString) = '' then AdicionaLinha(Result, ' - Descrição do banco deve ser informada'); end; procedure TDmERP.GravarBanco; var strValidacao : String; bInserindo : Boolean; begin strValidacao := BancoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyBanco.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyBanco); qyBanco.Post; fdConnERP.Commit; if bInserindo then Informacao('Banco inserido com sucesso.') else Informacao('Banco alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirBanco; begin if qyBanco.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyBanco.Delete; Informacao('Banco excluído com sucesso.'); end; end; end; function TDmERP.AgenciaValida : String; var stDados : TStringList; sSql : String; begin stDados := TStringList.Create; Result := ''; if Trim(qyAgencia.FieldByName('cdBanco').AsString) = '' then AdicionaLinha(Result, ' - Código do banco deve ser informado'); if qyAgencia.FieldByName('nuAgencia').IsNull then AdicionaLinha(Result, ' - Nº da agência deve ser informado'); if (Trim(Result) = '') then begin sSql := 'SELECT deAgencia ' + ' FROM erp.agencia ' + ' WHERE nuAgencia = ' + QuotedStr(qyAgencia.FieldByName('nuAgencia').AsString) + ' AND cdBanco = ' + QuotedStr(qyAgencia.FieldByName('cdBanco').AsString); if (qyAgencia.FieldByName('cdAgencia').AsInteger > 0) then sSql := sSql + ' AND cdAgencia <> ' + qyAgencia.FieldByName('cdAgencia').AsString; stDados.Clear; ExecuteSimplesSql(fdConnERP, sSql, 'deAgencia', stDados); if (stDados.Count > 0) and (Trim(stDados.Strings[0]) <> '') then AdicionaLinha(Result, ' - Agência já cadastrada para o banco informado'); end; if Trim(qyAgencia.FieldByName('deAgencia').AsString) = '' then AdicionaLinha(Result, ' - Descrição da agência deve ser informada'); if Assigned(stDados) then FreeAndNil(stDados); end; procedure TDmERP.GravarAgencia; var strValidacao : String; bInserindo : Boolean; begin strValidacao := AgenciaValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyAgencia.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyAgencia); qyAgencia.Post; fdConnERP.Commit; if bInserindo then Informacao('Agência inserida com sucesso.') else Informacao('Agência alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirAgencia; begin if qyAgencia.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyAgencia.Delete; Informacao('Agência excluída com sucesso.'); end; end; end; function TDmERP.ContaValida : String; var stDados : TStringList; sSql : String; begin stDados := TStringList.Create; Result := ''; if qyConta.FieldByName('cdAgencia').IsNull then AdicionaLinha(Result, ' - Código da agência deve ser informado'); if qyConta.FieldByName('nuConta').IsNull then AdicionaLinha(Result, ' - Código da conta deve ser informado'); if (Trim(Result) = '') then begin sSql := 'SELECT deConta ' + ' FROM erp.conta ' + ' WHERE nuConta = ' + qyConta.FieldByName('nuConta').AsString + ' AND cdAgencia = ' + QuotedStr(qyConta.FieldByName('cdAgencia').AsString); if (qyConta.FieldByName('cdConta').AsInteger > 0) then sSql := sSql + ' AND cdConta <> ' + qyConta.FieldByName('cdConta').AsString; stDados.Clear; ExecuteSimplesSql(fdConnERP, sSql, 'deConta', stDados); if (stDados.Count > 0) and (Trim(stDados.Strings[0]) <> '') then AdicionaLinha(Result, ' - Conta já cadastrada para a agência informada'); end; if Trim(qyConta.FieldByName('deConta').AsString) = '' then AdicionaLinha(Result, ' - Descrição da conta deve ser informada'); if Assigned(stDados) then FreeAndNil(stDados); end; procedure TDmERP.GravarConta; var strValidacao : String; bInserindo : Boolean; begin strValidacao := ContaValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyConta.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyConta); qyConta.Post; fdConnERP.Commit; if bInserindo then Informacao('Conta inserida com sucesso.') else Informacao('Conta alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirConta; begin if qyConta.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyConta.Delete; Informacao('Conta excluída com sucesso.'); end; end; end; function TDmERP.CobrancaTipoValida : String; begin Result := ''; if Trim(qyCobrancaTipo.FieldByName('deCobrancaTipo').AsString) = '' then AdicionaLinha(Result, ' - Descrição do tipo de cobrança deve ser informada'); if Trim(qyCobrancaTipo.FieldByName('deCobrancaTipoSigla').AsString) = '' then AdicionaLinha(Result, ' - Sigla do tipo de cobrança deve ser informada'); end; procedure TDmERP.GravarCobrancaTipo; var strValidacao : String; bInserindo : Boolean; begin strValidacao := CobrancaTipoValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyCobrancaTipo.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyCobrancaTipo); qyCobrancaTipo.Post; fdConnERP.Commit; if bInserindo then Informacao('Tipo de Cobrança inserido com sucesso.') else Informacao('Tipo de Cobrança alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirCobrancaTipo; begin if qyCobrancaTipo.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyCobrancaTipo.Delete; Informacao('Tipo de Cobrança excluído com sucesso.'); end; end; end; function TDmERP.ReciboAvulsoValido : String; begin Result := ''; if qyReciboAvulso.FieldByName('cdEmpresa').IsNull then AdicionaLinha(Result, ' - Empresa deve ser informada'); if (qyReciboAvulso.FieldByName('vlReciboAvulso').IsNull) or (qyReciboAvulso.FieldByName('vlReciboAvulso').AsFloat = 0) then AdicionaLinha(Result, ' - Valor do recibo deve ser informado'); if Trim(qyReciboAvulso.FieldByName('nmRecebedor').AsString) = '' then AdicionaLinha(Result, ' - Nome do recebedor deve ser informado'); end; procedure TDmERP.GravarReciboAvulso; var strValidacao : String; bInserindo : Boolean; begin strValidacao := ''; //ReciboAvulsoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyReciboAvulso.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyReciboAvulso); qyReciboAvulso.Post; fdConnERP.Commit; { if bInserindo then Informacao('Recibo avulso inserido com sucesso.') else Informacao('Recibo avulso alterado com sucesso.'); } except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirReciboAvulso; begin if qyReciboAvulso.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyReciboAvulso.Delete; Informacao('Recibo avulso excluído com sucesso.'); end; end; end; function TDmERP.EscalaValida : String; begin Result := ''; if Trim(qyEscala.FieldByName('deEscala').AsString) = '' then AdicionaLinha(Result, ' - Descrição da escala deve ser informada'); end; procedure TDmERP.GravarEscala; var strValidacao : String; bInserindo : Boolean; begin strValidacao := EscalaValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyEscala.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyEscala); qyEscala.Post; fdConnERP.Commit; if bInserindo then Informacao('Escala inserida com sucesso.') else Informacao('Escala alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirEscala; begin if qyEscala.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyEscalaItem.First; while not qyEscalaItem.Eof do qyEscalaItem.Delete; qyEscala.Delete; Informacao('Escala excluída com sucesso.'); end; end; end; function TDmERP.EscalaItemValido : String; begin Result := ''; if Trim(qyEscalaItem.FieldByName('deEscalaItem').AsString) = '' then AdicionaLinha(Result, ' - Descrição do item da escala deve ser informado'); end; procedure TDmERP.GravarEscalaItem; var strValidacao : String; bInserindo : Boolean; begin strValidacao := EscalaItemValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyEscalaItem.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyEscalaItem); qyEscalaItem.Post; fdConnERP.Commit; if bInserindo then Informacao('Item da escala inserido com sucesso.') else Informacao('Item da escala alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirEscalaItem; begin if qyEscalaItem.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyEscalaItem.Delete; Informacao('Item da escala excluído com sucesso.'); end; end; end; function TDmERP.CargoValido : String; begin Result := ''; if Trim(qyCargo.FieldByName('deCargo').AsString) = '' then AdicionaLinha(Result, ' - Descrição do cargo deve ser informada'); end; procedure TDmERP.GravarCargo; var strValidacao : String; bInserindo : Boolean; begin strValidacao := CargoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyCargo.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyCargo); qyCargo.Post; fdConnERP.Commit; if bInserindo then Informacao('Cargo inserido com sucesso.') else Informacao('Cargo alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirCargo; begin if qyCargo.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyCargo.Delete; Informacao('Cargo excluído com sucesso.'); end; end; end; function TDmERP.ColaboradorValido : String; var stDados : TStringList; sSql : String; begin Result := ''; stDados := TStringList.Create; // if qyColaborador.FieldByName('cdCodigoFolha').IsNull then // AdicionaLinha(Result, ' - Código da folha deve ser informado'); if (qyColaborador.FieldByName('cdEmpresa').AsInteger > 0) and (qyColaborador.FieldByName('cdCodigoFolha').AsInteger > 0) then begin sSql := 'SELECT cdCodigoFolha ' + ' FROM erp.colaborador ' + ' WHERE cdEmpresa = ' + qyColaborador.FieldByName('cdEmpresa').AsString + ' AND cdCodigoFolha = ' + qyColaborador.FieldByName('cdCodigoFolha').AsString; if (qyColaborador.State = dsEdit) then sSql := sSql + ' AND cdColaborador <> ' + qyColaborador.FieldByName('cdColaborador').AsString; ExecuteSimplesSql(fdConnERP, sSql, 'cdCodigoFolha', stDados); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then AdicionaLinha(Result, ' - Código da folha já informado para outro cadastro'); end; if Trim(qyColaborador.FieldByName('nmColaborador').AsString) = '' then AdicionaLinha(Result, ' - Nome do colaborador deve ser informado'); if qyColaborador.FieldByName('cdEmpresa').IsNull then AdicionaLinha(Result, ' - Empresa deve ser informada'); if qyColaborador.FieldByName('cdColabSituacao').IsNull then AdicionaLinha(Result, ' - Situação deve ser informada'); if (qyColaborador.FieldByName('flUsaValeTransp').AsString = 'S') and ((qyColaborador.FieldByName('vlValeTransp').IsNull) or (qyColaborador.FieldByName('vlValeTransp').AsCurrency = 0)) then AdicionaLinha(Result, ' - Valor do vale transporte deve ser informado'); if (Trim(qyColaborador.FieldByName('deCpf').AsString) <> '') and (not (ValidaCpfCnpj(qyColaborador.FieldByName('deCpf').AsString))) then AdicionaLinha(Result, ' - CPF inválido'); if (Trim(qyColaborador.FieldByName('nuTituloEleitor').AsString) <> '') and (not (ValidaTituloEleitor(qyColaborador.FieldByName('nuTituloEleitor').AsString))) then AdicionaLinha(Result, ' - Título de eleitor inválido'); if (Trim(qyColaborador.FieldByName('nuPis').AsString) <> '') and (not (ValidaPIS(qyColaborador.FieldByName('nuPis').AsString))) then AdicionaLinha(Result, ' - PIS inválido'); if Assigned(stDados) then FreeAndNil(stDados); end; procedure TDmERP.GravarColaborador; var strValidacao : String; bInserindo : Boolean; begin strValidacao := ColaboradorValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyColaborador.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyColaborador); qyColaborador.Post; fdConnERP.Commit; if bInserindo then Informacao('Colaborador inserido com sucesso.') else Informacao('Colaborador alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirColaborador; var sMsg : String; function ExisteHistorico(const qyDados : TFDQuery) : Boolean; begin if qyDados.Active then qyDados.Close; qyDados.MacroByName('filtro').Value := ' WHERE cdColaborador = ' + qyColaborador.FieldByName('cdColaborador').AsString; qyDados.Open(); Result := not qyDados.IsEmpty; end; begin if qyColaborador.Active then begin sMsg := ''; if ExisteHistorico(qyColabSituacaoHst) then AdicionaLinha(sMsg, ' - Situação'); if ExisteHistorico(qyColabSetorHst) then AdicionaLinha(sMsg, ' - Setor'); if ExisteHistorico(qyColabEscalaHst) then AdicionaLinha(sMsg, ' - Escala'); if ExisteHistorico(qyColabCargoHst) then AdicionaLinha(sMsg, ' - Cargo'); if ExisteHistorico(qyColabSalarioHst) then AdicionaLinha(sMsg, ' - Salário'); if Trim(sMsg) <> '' then begin sMsg := 'Colaborador não pode ser excluído, pois possui os seguintes históricos: ' + #13#13 + sMsg; Aviso(sMsg); end else if Pergunta('Confirma a exclusão deste registro?') then begin qyColaborador.Delete; Informacao('Colaborador excluído com sucesso.'); end; end; end; function TDmERP.ColabDependenteValido : String; begin Result := ''; if Trim(qyColabDependentes.FieldByName('nmDependente').AsString) = '' then AdicionaLinha(Result, ' - Nome do dependente deve ser informado'); if qyColabDependentes.FieldByName('cdGrauParentesco').IsNull then AdicionaLinha(Result, ' - Grau de parentesco deve ser informado'); end; procedure TDmERP.GravarColabDependente; var strValidacao : String; bInserindo : Boolean; begin strValidacao := ColabDependenteValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyColabDependentes.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyColabDependentes); qyColabDependentes.Post; fdConnERP.Commit; if bInserindo then Informacao('Dependente inserido com sucesso.') else Informacao('Dependente alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirColabDependente; begin if qyColabDependentes.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyColabDependentes.Delete; Informacao('Dependente excluído com sucesso.'); end; end; end; function TDmERP.PedidoValido : String; var stDados : TStringList; begin Result := ''; stDados := TStringList.Create; if StrToIntDef(qyPedido.FieldByName('cdPedidoTipo').AsString, 0) = 0 then AdicionaLinha(Result, ' - Tipo do Pedido deve ser informado'); if StrToIntDef(qyPedido.FieldByName('cdPedidoSituacao').AsString, 0) = 0 then AdicionaLinha(Result, ' - Situação do Pedido deve ser informada'); if qyPedido.FieldByName('dtEmissao').IsNull then AdicionaLinha(Result, ' - Data de emissão deve ser informada'); if StrToIntDef(qyPedido.FieldByName('cdCliente').AsString, 0) = 0 then AdicionaLinha(Result, ' - Cliente deve ser informado'); if StrToIntDef(qyPedido.FieldByName('cdEmpresa').AsString, 0) = 0 then AdicionaLinha(Result, ' - Empresa deve ser informada'); if qyPedido.FieldByName('dtEntrega').IsNull then AdicionaLinha(Result, ' - Data de entrega deve ser informada'); if StrToIntDef(qyPedido.FieldByName('cdNatureza').AsString, 0) = 0 then AdicionaLinha(Result, ' - Natureza deve ser informada'); if Trim(qyPedido.FieldByName('cdTipoFrete').AsString) = '' then AdicionaLinha(Result, ' - Tipo de frete deve ser informado'); if (not qyPedido.FieldByName('dtEmissao').IsNull) and (not qyPedido.FieldByName('dtEntrega').IsNull) and (qyPedido.FieldByName('dtEmissao').AsDateTime > qyPedido.FieldByName('dtEntrega').AsDateTime)then AdicionaLinha(Result, ' - Data de emissão não pode ser maior que a data de entrega'); { if qyUnidadeMedida.State = dsInsert then begin ExecuteSimplesSql(fdConnERP, 'SELECT a.cdUnidadeMedida ' + ' FROM erp.unidadeMedida a ' + ' WHERE a.cdUnidadeMedida = ' + QuotedStr(qyUnidadeMedida.FieldByName('cdUnidadeMedida').AsString), 'cdUnidadeMedida', stDados ); if (stDados.Count > 0) and (Trim(stDados.Strings[0]) <> '') then AdicionaLinha(Result, ' - Código já informado para outro cadastro'); end; if Trim(qyUnidadeMedida.FieldByName('deUnidadeMedida').AsString) = '' then AdicionaLinha(Result, ' - Descrição deve ser informada'); } if Assigned(stDados) then FreeAndNil(stDados); end; procedure TDmERP.GravarPedido; var strValidacao : String; bInserindo : Boolean; begin strValidacao := PedidoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyPedido.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyPedido); qyPedido.Post; fdConnERP.Commit; if bInserindo then Informacao('Pedido inserido com sucesso.') else Informacao('Pedido alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirPedido; begin if qyPedido.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyPedido.Delete; Informacao('Pedido excluído com sucesso.'); end; end; end; function TDmERP.UnidadeMedidaValida : String; var stDados : TStringList; begin Result := ''; stDados := TStringList.Create; if Trim(qyUnidadeMedida.FieldByName('cdUnidadeMedida').AsString) = '' then AdicionaLinha(Result, ' - Código deve ser informado') else if qyUnidadeMedida.State = dsInsert then begin ExecuteSimplesSql(fdConnERP, 'SELECT a.cdUnidadeMedida ' + ' FROM erp.unidadeMedida a ' + ' WHERE a.cdUnidadeMedida = ' + QuotedStr(qyUnidadeMedida.FieldByName('cdUnidadeMedida').AsString), 'cdUnidadeMedida', stDados ); if (stDados.Count > 0) and (Trim(stDados.Strings[0]) <> '') then AdicionaLinha(Result, ' - Código já informado para outro cadastro'); end; if Trim(qyUnidadeMedida.FieldByName('deUnidadeMedida').AsString) = '' then AdicionaLinha(Result, ' - Descrição deve ser informada'); if Assigned(stDados) then FreeAndNil(stDados); end; procedure TDmERP.GravarUnidadeMedida; var strValidacao : String; bInserindo : Boolean; begin strValidacao := UnidadeMedidaValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyUnidadeMedida.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyUnidadeMedida); qyUnidadeMedida.Post; fdConnERP.Commit; if bInserindo then Informacao('Unidade de medida inserida com sucesso.') else Informacao('Unidade de medida alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirUnidadeMedida; begin if qyUnidadeMedida.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyUnidadeMedida.Delete; Informacao('Unidade de Medida excluída com sucesso.'); end; end; end; function TDmERP.ItemGrupoValido : String; begin Result := ''; if Trim(qyItemGrupo.FieldByName('deItemGrupo').AsString) = '' then AdicionaLinha(Result, ' - Descrição deve ser informada'); end; procedure TDmERP.GravarItemGrupo; var strValidacao : String; bInserindo : Boolean; begin strValidacao := ItemGrupoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyItemGrupo.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyItemGrupo); qyItemGrupo.Post; fdConnERP.Commit; if bInserindo then Informacao('Grupo de item inserido com sucesso.') else Informacao('Grupo de item alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirItemGrupo; var stDados : TStringList; begin if qyItemGrupo.Active then begin stDados := TStringList.Create; ExecuteSimplesSql(fdConnERP, 'SELECT a.cdItemSubGrupo ' + ' FROM erp.itemSubGrupo a ' + ' WHERE a.cdItemGrupo = ' + qyItemGrupo.FieldByName('cdItemGrupo').AsString, 'cdItemSubGrupo', stDados ); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then Aviso('Este grupo possui subgrupos cadastrados e não pode ser excluído.') else if Pergunta('Confirma a exclusão deste registro?') then begin qyItemGrupo.Delete; Informacao('Grupo de item excluído com sucesso.'); end; if Assigned(stDados) then FreeAndNil(stDados); end; end; function TDmERP.ItemSubGrupoValido : String; begin Result := ''; if qyItemSubGrupo.FieldByName('cdItemGrupo').IsNull then AdicionaLinha(Result, ' - Código do grupo deve ser informado'); if qyItemSubGrupo.FieldByName('cdItemSubGrupo').IsNull then AdicionaLinha(Result, ' - Código do subgrupo deve ser informado'); if Trim(qyItemSubGrupo.FieldByName('deItemSubGrupo').AsString) = '' then AdicionaLinha(Result, ' - Descrição deve ser informada'); end; procedure TDmERP.GravarItemSubGrupo; var strValidacao : String; bInserindo : Boolean; begin strValidacao := ItemSubGrupoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyItemSubGrupo.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyItemSubGrupo); qyItemSubGrupo.Post; fdConnERP.Commit; if bInserindo then Informacao('Subgrupo de item inserido com sucesso.') else Informacao('Subgrupo de item alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirItemSubGrupo; begin if qyItemSubGrupo.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyItemSubGrupo.Delete; Informacao('Subgrupo de item excluído com sucesso.'); end; end; end; function TDmERP.ItemFamiliaValida : String; begin Result := ''; if Trim(qyItemFamilia.FieldByName('deItemFamilia').AsString) = '' then AdicionaLinha(Result, ' - Descrição deve ser informada'); end; procedure TDmERP.GravarItemFamilia; var strValidacao : String; bInserindo : Boolean; begin strValidacao := ItemFamiliaValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyItemFamilia.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyItemFamilia); qyItemFamilia.Post; fdConnERP.Commit; if bInserindo then Informacao('Família de item inserida com sucesso.') else Informacao('Família de item alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirItemFamilia; begin if qyItemFamilia.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyItemFamilia.Delete; Informacao('Família de item excluída com sucesso.'); end; end; end; function TDmERP.ItemValido : String; var stDados : TStringList; begin Result := ''; stDados := TStringList.Create; if Trim(qyItem.FieldByName('cdItem').AsString) = '' then AdicionaLinha(Result, ' - Código do item deve ser informado') else if qyItem.State = dsInsert then begin ExecuteSimplesSql(fdConnERP, 'SELECT a.cdItem ' + ' FROM erp.item a ' + ' WHERE a.cdItem = ' + QuotedStr(qyItem.FieldByName('cdItem').AsString), 'cdItem', stDados ); if (stDados.Count > 0) and (Trim(stDados.Strings[0]) <> '') then AdicionaLinha(Result, ' - Código do item já informado para outro cadastro'); end; if Trim(qyItem.FieldByName('deItem').AsString) = '' then AdicionaLinha(Result, ' - Descrição do item deve ser informado'); if qyItem.FieldByName('cdItemTipo').IsNull then AdicionaLinha(Result, ' - Tipo de item deve ser informado'); if (qyItem.FieldByName('cdItemOrigem').IsNull) then AdicionaLinha(Result, ' - Origem de item deve ser informado'); if (qyItem.FieldByName('cdIcmsTipo').IsNull) then AdicionaLinha(Result, ' - Tipo de ICMS deve ser informado'); if (qyItem.FieldByName('cdIpiTipo').IsNull) then AdicionaLinha(Result, ' - Tipo de IPI deve ser informado'); if (qyItem.FieldByName('cdPisTipo').IsNull) then AdicionaLinha(Result, ' - Tipo de Pis deve ser informado'); if (qyItem.FieldByName('cdCofinsTipo').IsNull) then AdicionaLinha(Result, ' - Tipo de Cofins deve ser informado'); if Assigned(stDados) then FreeAndNil(stDados); end; procedure TDmERP.GravarItem; var strValidacao : String; bInserindo : Boolean; begin strValidacao := ItemValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyItem.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyItem); qyItem.Post; fdConnERP.Commit; if bInserindo then Informacao('Item inserido com sucesso.') else Informacao('Item alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirItem; begin if qyItem.Active then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyItem.Delete; Informacao('Item excluído com sucesso.'); end; end; end; procedure TDmERP.qyReciboAvulsoAfterScroll(DataSet: TDataSet); begin if (qyReciboAvulso.Active) and (not qyReciboAvulso.IsEmpty) then begin if Length(qyReciboAvulso.FieldByName('deCpfCnpj').AsString) = 14 then qyReciboAvulso.FieldByName('deCpfCnpj').EditMask := '99.999.999/9999-99;0;_' else qyReciboAvulso.FieldByName('deCpfCnpj').EditMask := '999.999.999-99;0;_'; end; end; procedure TDmERP.qyReciboAvulsoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyReciboAvulso, 'reciboAvulso', 'cdReciboAvulso', qyReciboAvulso.FieldByName('cdReciboAvulso').AsInteger); end; procedure TDmERP.qyReciboAvulsoNewRecord(DataSet: TDataSet); var dthrAtual : TDateTime; begin dthrAtual := DataHoraAtual(fdConnERP); qyReciboAvulso.FieldByName('dtReciboAvulso').AsDateTime := Trunc(dthrAtual); end; procedure TDmERP.qyRepresentanteAfterScroll(DataSet: TDataSet); begin if qyRepresentante.FieldByName('flFisJur').AsString = 'J' then qyRepresentante.FieldByName('deCpfCnpj').EditMask := '99.999.999/9999-99;0;_' else qyRepresentante.FieldByName('deCpfCnpj').EditMask := '999.999.999-99;0;_'; qyRepresentante.FieldByName('nuFone1').EditMask := '(99) 9999-99999;0;_'; qyRepresentante.FieldByName('nuFone2').EditMask := '(99) 9999-99999;0;_'; qyRepresentante.FieldByName('nuCelular').EditMask := '(99) 99999-9999;0;_'; qyRepresentante.FieldByName('nuFax').EditMask := '(99) 9999-99999;0;_'; qyRepresentante.FieldByName('nuCep').EditMask := '99999-999;0;_'; end; procedure TDmERP.qyRepresentanteBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyRepresentante, 'representante', 'cdRepresentante', qyRepresentante.FieldByName('cdRepresentante').AsInteger); end; procedure TDmERP.qyRepresentanteNewRecord(DataSet: TDataSet); begin qyRepresentante.FieldByName('flAtivo').AsString := 'S'; end; procedure TDmERP.qySetorBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qySetor, 'setor', 'cdSetor', qySetor.FieldByName('cdSetor').AsInteger); end; procedure TDmERP.qySetorNewRecord(DataSet: TDataSet); begin qySetor.FieldByName('flControlaBaixa').AsString := 'N'; qySetor.FieldByName('flEhSetorMontagem').AsString := 'N'; qySetor.FieldByName('flEhSetorEmbalagem').AsString := 'N'; qySetor.FieldByName('flEhSetorExpedicao').AsString := 'N'; end; procedure TDmERP.qyTelaBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyTela, 'tela', 'cdTela', qyTela.FieldByName('cdTela').AsInteger); end; procedure TDmERP.qyTelaNewRecord(DataSet: TDataSet); begin qyTela.FieldByName('flAtivo').AsString := 'S'; end; procedure TDmERP.qyTelasDisponiveisBeforeOpen(DataSet: TDataSet); begin qyTelasDisponiveis.ParamByName('cdUsuario').AsInteger := qyUsuario.FieldByName('cdUsuario').AsInteger; end; procedure TDmERP.qyTempoDWBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyTempoDW, 'dw_tempo', 'cdTempo', qyTempoDW.FieldByName('cdTempo').AsInteger); end; procedure TDmERP.qyTransportadoraAfterScroll(DataSet: TDataSet); begin if qyTransportadora.FieldByName('flFisJur').AsString = 'J' then qyTransportadora.FieldByName('deCpfCnpj').EditMask := '99.999.999/9999-99;0;_' else qyTransportadora.FieldByName('deCpfCnpj').EditMask := '999.999.999-99;0;_'; qyTransportadora.FieldByName('nuFone1').EditMask := '(99) 9999-99999;0;_'; qyTransportadora.FieldByName('nuFone2').EditMask := '(99) 9999-99999;0;_'; qyTransportadora.FieldByName('nuFax').EditMask := '(99) 9999-99999;0;_'; qyTransportadora.FieldByName('nuCep').EditMask := '99999-999;0;_'; end; procedure TDmERP.qyTransportadoraBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyTransportadora, 'transportadora', 'cdTransportadora', qyTransportadora.FieldByName('cdTransportadora').AsInteger); end; procedure TDmERP.qyTransportadoraNewRecord(DataSet: TDataSet); begin qyTransportadora.FieldByName('flAtivo').AsString := 'S'; qyTransportadora.FieldByName('flIsentoInscEst').AsString := 'S'; end; procedure TDmERP.qyUsuarioAfterScroll(DataSet: TDataSet); begin if qyUsuarioTela.Active then qyUsuarioTela.Close; qyUsuarioTela.Open(); if qyTelasDisponiveis.Active then qyTelasDisponiveis.Close; qyTelasDisponiveis.Open(); end; procedure TDmERP.qyUsuarioBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyUsuario, 'usuario', 'cdUsuario', qyUsuario.FieldByName('cdUsuario').AsInteger); end; procedure TDmERP.qyUsuarioMensagemBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyUsuarioMensagem, 'usuarioMensagem', 'cdUsuarioMensagem', qyUsuarioMensagem.FieldByName('cdUsuarioMensagem').AsInteger); end; procedure TDmERP.qyUsuarioNewRecord(DataSet: TDataSet); begin qyUsuario.FieldByName('flAtivo').AsString := 'S'; qyUsuario.FieldByName('deSenha').AsString := 'erp123'; end; procedure TDmERP.qyUsuarioPesqAfterClose(DataSet: TDataSet); begin qyUsuarioPesq.MacroByName('filtro').Clear; end; procedure TDmERP.qyUsuarioTelaBeforeOpen(DataSet: TDataSet); begin qyUsuarioTela.ParamByName('cdUsuario').AsInteger := qyUsuario.FieldByName('cdUsuario').AsInteger; end; procedure TDmERP.qyUsuarioTelaBeforePost(DataSet: TDataSet); begin GravarCamposAutomaticos(qyUsuarioTela); end; procedure TDmERP.qyVariavelAfterScroll(DataSet: TDataSet); begin if qyVariavelItens.Active then qyVariavelItens.Close; qyVariavelItens.Open(); end; procedure TDmERP.qyVariavelBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyVariavel, 'variavel', 'cdVariavel', qyVariavel.FieldByName('cdVariavel').AsInteger); end; procedure TDmERP.qyVariavelItensBeforeOpen(DataSet: TDataSet); begin if qyVariavel.Active then qyVariavelItens.ParamByName('cdVariavel').AsInteger := qyVariavel.FieldByName('cdVariavel').AsInteger; end; procedure TDmERP.qyVariavelItensBeforePost(DataSet: TDataSet); var stDados : TStringList; begin if (qyVariavelItens.State = dsInsert) and (qyVariavel.Active) then begin qyVariavelItens.FieldByName('cdVariavel').AsInteger := qyVariavel.FieldByName('cdVariavel').AsInteger; stDados := TStringList.Create; try ExecuteSimplesSql(fdConnERP, 'SELECT MAX(cdVariavelItem) AS ultCod ' + ' FROM erp.variavelItens ' + ' WHERE cdVariavel = ' + qyVariavel.FieldByName('cdVariavel').AsString, 'ultCod', stDados ); qyVariavelItens.FieldByName('cdVariavelItem').AsInteger := StrToIntDef(stDados.Strings[0], 0) + 1 finally if Assigned(stDados) then FreeAndNil(stDados); end; end; end; procedure TDmERP.qyVeiculoAfterScroll(DataSet: TDataSet); begin qyVeiculo.FieldByName('dePlaca').EditMask := 'LLL-9999;0;_'; end; procedure TDmERP.qyVeiculoBeforePost(DataSet: TDataSet); begin GerarCodigo(fdConnERP, qyVeiculo, 'veiculo', 'cdVeiculo', qyVeiculo.FieldByName('cdVeiculo').AsInteger); end; procedure TDmERP.DataModuleCreate(Sender: TObject); var stConfig : TStringList; begin if not (FileExists(ExtractFilePath(Application.ExeName) + 'ERP.ini')) then begin Erro('Arquivo de configuração não encontrado.'); Application.Terminate; end else begin stConfig := TStringList.Create; stConfig.LoadFromFile(ExtractFilePath(Application.ExeName) + 'ERP.ini'); if stConfig.Count <> FiNumLinhasConfigERP then begin Erro('Arquivo de configuração incorreto.'); Application.Terminate; end else begin fdConnERP.Connected := False; fdConnERP.Params.Clear; fdConnERP.LoginPrompt := False; fdConnERP.DriverName := stConfig.Values['DriverName']; fdConnERP.Params.Add(stConfig.Strings[1]); //DriverID fdConnERP.Params.Add(stConfig.Strings[2]); //Database fdConnERP.Params.Add(stConfig.Strings[3]); //Server fdConnERP.Params.Add(stConfig.Strings[4]); //Port fdConnERP.Params.Add(stConfig.Strings[5]); //User_Name fdConnERP.Params.Add(stConfig.Strings[6]); //Password try fdConnERP.Connected := True; FTelaInicial.FsEndServer := stConfig.Values['Server']; //Chamar form de login { for i := 0 to tvMenu.Items.Count - 1 do if tvMenu.Items.Item[i].Parent = nil then tvMenu.Items.Item[i].Expanded := True; } except on E: EFDDBEngineException do begin Erro(E.message); Application.Terminate; end; end; end; if Assigned(stConfig) then FreeAndNil(stConfig); end; end; procedure TDmERP.fdConnERPError(ASender, AInitiator: TObject; var AException: Exception); var oExc: EFDDBEngineException; begin if AException is EFDDBEngineException then begin oExc := EFDDBEngineException(AException); if oExc.Kind = ekRecordLocked then oExc.Message := 'O registro está ocupado. Tente novamente mais tarde.' else if (oExc.Kind = ekUKViolated) {and SameText(oExc[0].ObjName, 'UniqueKey_Orders')} then oExc.Message := 'Erro de chave primária. O código informado já existe'; end; end; procedure TDmERP.qyTelaPesqAfterClose(DataSet: TDataSet); begin qyTelaPesq.MacroByName('filtro').Clear; end; function TDmERP.ItemRelacionadoValido : String; var stDados : TStringList; sSql : String; begin sSql := ''; stDados := TStringList.Create; Result := ''; if Trim(qyIntIndItemRelacionado.FieldByName('cdItem').AsString) = '' then AdicionaLinha(Result, ' - Código do item'); if qyIntIndItemRelacionado.FieldByName('cdTamanho').IsNull then AdicionaLinha(Result, ' - Tamanho do item'); if (Trim(Result) = '') then begin stDados.Clear; sSql := 'SELECT cdItemRelacionado, cdItemBase, deTamanhoBase ' + ' FROM erp.intIndItemRelacionado ' + ' WHERE cdItem = ' + QuotedStr(Trim(qyIntIndItemRelacionado.FieldByName('cdItem').AsString)) + ' AND cdTamanho = ' + qyIntIndItemRelacionado.FieldByName('cdTamanho').AsString; if qyIntIndItemRelacionado.FieldByName('cdItemRelacionado').AsInteger > 0 then sSql := sSql + ' AND cdItemRelacionado <> ' + qyIntIndItemRelacionado.FieldByName('cdItemRelacionado').AsString; ExecuteSimplesSql(fdConnERP, sSql, 'cdItemRelacionado,cdItemBase,deTamanhoBase', stDados); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then AdicionaLinha(Result, ' - Item e tamanho já relacionados ao item base ' + stDados.Strings[1] + ', com tamanho base ' + stDados.Strings[2] + ' no cadastro de código ' + stDados.Strings[0] ); end; if Trim(qyIntIndItemRelacionado.FieldByName('cdItemBase').AsString) = '' then AdicionaLinha(Result, ' - Código do item base'); if qyIntIndItemRelacionado.FieldByName('cdTamanhoBase').IsNull then AdicionaLinha(Result, ' - Tamanho do item base'); if (Trim(Result) = '') then begin stDados.Clear; sSql := 'SELECT cdItemRelacionado ' + ' FROM erp.intIndItemRelacionado ' + ' WHERE cdItem = ' + QuotedStr(Trim(qyIntIndItemRelacionado.FieldByName('cdItem').AsString)) + ' AND cdTamanho = ' + qyIntIndItemRelacionado.FieldByName('cdTamanho').AsString + ' AND cdItemBase = ' + QuotedStr(Trim(qyIntIndItemRelacionado.FieldByName('cdItemBase').AsString)) + ' AND cdTamanhoBase = ' + qyIntIndItemRelacionado.FieldByName('cdTamanhoBase').AsString; if qyIntIndItemRelacionado.FieldByName('cdItemRelacionado').AsInteger > 0 then sSql := sSql + ' AND cdItemRelacionado <> ' + qyIntIndItemRelacionado.FieldByName('cdItemRelacionado').AsString; ExecuteSimplesSql(fdConnERP, sSql, 'cdItemRelacionado', stDados); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then AdicionaLinha(Result, ' - Item e tamanho já relacionados ao item e tamanho base ' + 'informados no cadastro de código ' + stDados.Strings[0] ); end; if Assigned(stDados) then FreeAndNil(stDados); end; procedure TDmERP.GravarItemRelacionado; var strValidacao : String; bInserindo : Boolean; begin strValidacao := ItemRelacionadoValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyIntIndItemRelacionado.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyIntIndItemRelacionado); qyIntIndItemRelacionado.Post; fdConnERP.Commit; if bInserindo then Informacao('Relacionamento de item inserido com sucesso.') else Informacao('Relacionamento de item alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirItemRelacionado; begin if (qyIntIndItemRelacionado.Active) then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyIntIndItemRelacionado.Delete; Informacao('Relacionamento de item excluído com sucesso.'); end; end; end; function TDmERP.CargaValida : String; begin Result := ''; if qyIntComCarga.FieldByName('cdCarga').IsNull then AdicionaLinha(Result, ' - Código da carga') else begin try DmIntegracao.fdConnInteg.Connected := True; DmIntegracao.qyCargaPesq.Open(); DmIntegracao.qyCargaPesq.First; if not DmIntegracao.qyCargaPesq.Locate('cdCarga', VarArrayOf([qyIntComCarga.FieldByName('cdCarga').AsInteger]), [] ) then AdicionaLinha(Result, ' - Código da carga inválido') else qyIntComCarga.FieldByName('deCarga').AsString := DmIntegracao.qyCargaPesq.FieldByName('deCarga').AsString; except on E: EFDDBEngineException do begin Erro(E.message); end; end; if DmIntegracao.qyCargaPesq.Active then DmIntegracao.qyCargaPesq.Close; DmIntegracao.fdConnInteg.Connected := False; end; end; procedure TDmERP.GravarCarga; var strValidacao : String; bInserindo : Boolean; begin strValidacao := CargaValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyIntComCarga.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyIntComCarga); qyIntComCarga.Post; fdConnERP.Commit; if bInserindo then Informacao('Carga inserida com sucesso.') else Informacao('Carga alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirCarga; begin if (qyIntComCarga.Active) then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyIntComCarga.Delete; Informacao('Carga excluída com sucesso.'); end; end; end; function TDmERP.CargaAlertaValida : String; begin Result := ''; if Trim(qyIntComCargaAlerta.FieldByName('deCargaAlerta').AsString) = '' then AdicionaLinha(Result, ' - Descrição do alerta da carga'); end; procedure TDmERP.GravarCargaAlerta; var strValidacao : String; bInserindo : Boolean; begin strValidacao := CargaAlertaValida; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyIntComCargaAlerta.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyIntComCargaAlerta); qyIntComCargaAlerta.Post; fdConnERP.Commit; if bInserindo then Informacao('Alerta de carga inserido com sucesso.') else Informacao('Alerta de carga alterado com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirCargaAlerta; begin if (qyIntComCargaAlerta.Active) then begin if Pergunta('Confirma a exclusão deste registro?') then begin qyIntComCargaAlerta.Delete; Informacao('Alerta de carga excluído com sucesso.'); end; end; end; function TDmERP.BaixaProducaoValida : TStringList; var sSql, sdeSetorAnt, scdSetorAnt, sEhSetAntMont : String; stDados : TStringList; function QtdeItemEstSetorAnt(const scdItem, scdTamanho : String; const bComEtiq : Boolean) : Integer; begin Result := 0; sSql := 'SELECT COUNT(cdIdQtde) AS qtdBaixa ' + ' FROM erp.intIndBaixaProducao ' + ' WHERE flEmEstoque = ''S'' ' + ' AND cdItem = ' + QuotedStr(scdItem) + ' AND cdTamanho = ' + QuotedStr(scdTamanho) + ' AND cdSetor = ' + scdSetorAnt; if (qyIntIndBaixaProducao.FieldByName('flEhSetorExpedicao').AsString = 'S') or (bComEtiq) then sSql := sSql + ' AND cdPedido IS NOT NULL'; stDados.Clear; ExecuteSimplesSql(fdConnERP, sSql, 'qtdBaixa', stDados ); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then Result := StrToIntDef(stDados.Strings[0], 0); end; function PedAgrupPertenceCarga(const snuPedido, snuCarga : String) : Boolean; var snuPedNovo : String; begin snuPedNovo := snuPedido; Result := False; while StrToIntDef(snuPedNovo, 0) > 0 do begin stDados.Clear; ExecuteSimplesSql(DmIntegracao.fdConnInteg, 'SELECT pa.pedido_novo ' + ' FROM pedAgrup pa ' + ' WHERE pa.pedido_ori = ' + snuPedNovo, 'pedido_novo', stDados ); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then begin snuPedNovo := Trim(stDados.Strings[0]); stDados.Clear; ExecuteSimplesSql(DmIntegracao.fdConnInteg, 'SELECT COALESCE(gp.codigo_grupoPed, 0) AS cdCarga ' + ' FROM grupoPed gp ' + ' WHERE COALESCE(gp.codigo_grupoPed, 0) = ' + snuCarga + ' AND gp.nro_pedido = ' + snuPedNovo, 'cdCarga', stDados ); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) and (Trim(stDados.Strings[0]) = snuCarga) then begin Result := True; snuPedNovo := '0'; end; end else snuPedNovo := '0'; end; end; begin stDados := TStringList.Create; Result := TStringList.Create; Result.Clear; if (qyIntIndBaixaProducao.FieldByName('cdSetor').AsInteger > 0) and (qyIntIndBaixaProducao.FieldByName('cdPedido').AsInteger > 0) and (qyIntIndBaixaProducao.FieldByName('cdSeqPed').AsInteger > 0) and (qyIntIndBaixaProducao.FieldByName('cdIdQtdeSeqPed').AsInteger > 0) then begin stDados.Clear; ExecuteSimplesSql(fdConnERP, 'SELECT cdSetor ' + ' FROM erp.intIndBaixaProducao ' + ' WHERE cdSetor = ' + qyIntIndBaixaProducao.FieldByName('cdSetor').AsString + ' AND cdPedido = ' + qyIntIndBaixaProducao.FieldByName('cdPedido').AsString + ' AND cdSeqPed = ' + qyIntIndBaixaProducao.FieldByName('cdSeqPed').AsString + ' AND cdIdQtdeSeqPed = ' + qyIntIndBaixaProducao.FieldByName('cdIdQtdeSeqPed').AsString, 'cdSetor', stDados ); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then Result.Add(' - Etiqueta já movimentada') end; if Result.Count = 0 then begin if (qyIntIndBaixaProducao.FieldByName('cdEmpresa').IsNull) or (qyIntIndBaixaProducao.FieldByName('cdEmpresa').AsInteger = 0) then Result.Add(' - Código da empresa'); if (qyIntIndBaixaProducao.FieldByName('cdSetor').IsNull) or (qyIntIndBaixaProducao.FieldByName('cdSetor').AsInteger = 0) then Result.Add(' - Código do setor'); if (Trim(qyIntIndBaixaProducao.FieldByName('cdItem').AsString) = '') then Result.Add(' - Código do item'); if (qyIntIndBaixaProducao.FieldByName('cdTamanho').IsNull) then Result.Add(' - Código do tamanho'); if (qyIntIndBaixaProducao.FieldByName('cdIdQtde').IsNull) then Result.Add(' - ID da quantidade'); if (qyIntIndBaixaProducao.FieldByName('cdSetorAnterior').AsInteger > 0) and (qyIntIndBaixaProducao.FieldByName('cdIdQtdeAnterior').IsNull) and (not( (qyIntIndBaixaProducao.FieldByName('flEhSetorEmbalagem').AsString = 'S') and ( (qyIntIndBaixaProducao.FieldByName('flEhRevenda').AsString = 'S') or (qyIntIndBaixaProducao.FieldByName('flEhAcessorio').AsString = 'S') ) ) ) then Result.Add(' - Item ' + qyIntIndBaixaProducao.FieldByName('cdItem').AsString + ' no tamanho ' + qyIntIndBaixaProducao.FieldByName('deTamanho').AsString + ' não existe no estoque do setor "' + qyIntIndBaixaProducao.FieldByName('deSetorAnt').AsString + '".' + #13 + 'Verifique com o responsável deste setor.' ); if Result.Count = 0 then begin //------------------------------------------------------------------------------ //Início validações campos do pedido if (qyIntIndBaixaProducao.FieldByName('cdPedido').AsInteger > 0) then begin if (qyIntIndBaixaProducao.FieldByName('cdPedido').IsNull) then Result.Add(' - Código do Pedido'); if (qyIntIndBaixaProducao.FieldByName('cdSeqPed').IsNull) then Result.Add(' - Sequência do pedido'); if (qyIntIndBaixaProducao.FieldByName('cdIdQtdeSeqPed').IsNull) then Result.Add(' - ID da quantidade'); if (qyIntIndBaixaProducao.FieldByName('cdPedido').AsInteger > 0) and (qyIntIndBaixaProducao.FieldByName('cdSeqPed').AsInteger > 0) then begin try DmIntegracao.fdConnInteg.Connected := True; DmIntegracao.qyPedido.MacroByName('filtro').Value := ' WHERE nuPedido = ' + qyIntIndBaixaProducao.FieldByName('cdPedido').AsString + ' AND seq = ' + qyIntIndBaixaProducao.FieldByName('cdSeqPed').AsString; DmIntegracao.qyPedido.Open; if DmIntegracao.qyPedido.IsEmpty then Result.Add(' - Item de pedido inválido') else begin if (qyIntIndBaixaProducao.FieldByName('flEhSetorExpedicao').AsString = 'S') and (qyIntIndBaixaProducao.FieldByName('cdCarga').AsInteger <> DmIntegracao.qyPedido.FieldByName('cdCarga').AsInteger ) then begin if not PedAgrupPertenceCarga(qyIntIndBaixaProducao.FieldByName('cdPedido').AsString, qyIntIndBaixaProducao.FieldByName('cdCarga').AsString ) then Result.Add(' - Etiqueta não pertence a carga da movimentação'); end; end; except on E: EFDDBEngineException do begin Erro(E.message); end; end; if DmIntegracao.qyPedido.Active then DmIntegracao.qyPedido.Close; DmIntegracao.fdConnInteg.Connected := False; end; end; //Fim validações campos do pedido //------------------------------------------------------------------------------ if (Result.Count = 0) and (qyIntIndBaixaProducao.FieldByName('flMovEstSetorAnt').AsString = 'S') then begin stDados.Clear; ExecuteSimplesSql(fdConnERP, 'SELECT * ' + ' FROM ( ' + ' SELECT a.cdSetorAnterior, b.deSetor AS deSetorAnt, b.flEhSetorMontagem AS flEhSetAntMont ' + ' FROM erp.setor a ' + ' LEFT JOIN erp.setor b ON(b.cdSetor = a.cdSetorAnterior) ' + ' WHERE a.cdSetor = ' + qyIntIndBaixaProducao.FieldByName('cdSetor').AsString + ' ) t ', 'cdSetorAnterior,deSetorAnt,flEhSetAntMont', stDados ); if (stDados.Count > 0) and (StrToIntDef(stDados.Strings[0], 0) > 0) then begin scdSetorAnt := Trim(stDados.Strings[0]); sdeSetorAnt := Trim(stDados.Strings[1]); sEhSetAntMont := Trim(stDados.Strings[2]); if (QtdeItemEstSetorAnt(qyIntIndBaixaProducao.FieldByName('cdItem').AsString, qyIntIndBaixaProducao.FieldByName('cdTamanho').AsString, (qyIntIndBaixaProducao.FieldByName('cdPedido').AsInteger > 0) and (sEhSetAntMont = 'N') ) = 0 ) then begin if (sEhSetAntMont = 'S') and (Trim(qyIntIndBaixaProducao.FieldByName('cdItemBase').AsString) <> '') then begin if (QtdeItemEstSetorAnt(qyIntIndBaixaProducao.FieldByName('cdItemBase').AsString, qyIntIndBaixaProducao.FieldByName('cdTamanho').AsString, (qyIntIndBaixaProducao.FieldByName('cdPedido').AsInteger > 0) and (sEhSetAntMont = 'N') ) = 0 ) then Result.Add(' - Setor "' + sdeSetorAnt + '" ainda não movimentou este item ou a quantidade está zerada.' + #13 + ' Avise o responsável para executar a movimentação.' ); end else if ( (qyIntIndBaixaProducao.FieldByName('flEhRevenda').AsString = 'N') and (qyIntIndBaixaProducao.FieldByName('flEhAcessorio').AsString = 'N') ) or ( ( (qyIntIndBaixaProducao.FieldByName('flEhRevenda').AsString = 'S') or (qyIntIndBaixaProducao.FieldByName('flEhAcessorio').AsString = 'S') ) and (qyIntIndBaixaProducao.FieldByName('flEhSetorExpedicao').AsString = 'S') ) then Result.Add(' - Setor "' + sdeSetorAnt + '" ainda não movimentou este item ou a quantidade está zerada.' + #13 + ' Avise o responsável para executar a movimentação.' ); end; end; end; end; end; if Assigned(stDados) then FreeAndNil(stDados); end; procedure TDmERP.GravarBaixaProducao; begin fdConnERP.StartTransaction; try qyIntIndBaixaProducao.Post; fdConnERP.Commit; except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; procedure TDmERP.ExcluirBaixaProducao; var stDados : TStringList; sSql, scdItem, scdTamanho : String; begin if qyIntIndBaixaProducao.Active then begin stDados := TStringList.Create; sSql := 'SELECT flEmEstoque ' + ' FROM erp.intIndBaixaProducao ' + ' WHERE cdItem = ' + QuotedStr(qyIntIndBaixaProducao.FieldByName('cdItem').AsString) + ' AND cdTamanho = ' + qyIntIndBaixaProducao.FieldByName('cdTamanho').AsString + ' AND cdIdQtde = ' + qyIntIndBaixaProducao.FieldByName('cdIdQtde').AsString + ' AND cdSetor = ' + qyIntIndBaixaProducao.FieldByName('cdSetor').AsString; ExecuteSimplesSql(fdConnERP, sSql, 'flEmEstoque', stDados); if (stDados.Count > 0) and (Trim(stDados.Strings[0]) = 'N') and (qyIntIndBaixaProducao.FieldByName('flEhSetorExpedicao').AsString = 'N') then Informacao('Item já baixado para outros setores.') else if Pergunta('Confirma a exclusão deste registro?') then begin if (qyIntIndBaixaProducao.FieldByName('cdSetorAnterior').AsInteger > 0) and (qyIntIndBaixaProducao.FieldByName('cdIdQtdeAnterior').AsInteger > 0) then begin scdItem := qyIntIndBaixaProducao.FieldByName('cdItem').AsString; scdTamanho := qyIntIndBaixaProducao.FieldByName('cdTamanho').AsString; if (qyIntIndBaixaProducao.FieldByName('cdItemBase').AsString <> '') then begin scdItem := qyIntIndBaixaProducao.FieldByName('cdItemBase').AsString; scdTamanho := qyIntIndBaixaProducao.FieldByName('cdTamanhoBase').AsString; end; sSql := 'UPDATE erp.intIndBaixaProducao a ' + ' SET flEmEstoque = ''S'' ' + ' WHERE a.cdItem = ' + QuotedStr(scdItem) + ' AND a.cdTamanho = ' + scdTamanho + ' AND a.cdSetor = ' + qyIntIndBaixaProducao.FieldByName('cdSetorAnterior').AsString + ' AND a.cdIdQtde = ' + qyIntIndBaixaProducao.FieldByName('cdIdQtdeAnterior').AsString; ExecuteInstrucaoSql(DmERP.fdConnERP, sSql); end; qyIntIndBaixaProducao.Delete; Informacao('Movimento de produção excluído com sucesso.'); end; if Assigned(stDados) then FreeAndNil(stDados); end; end; function TDmERP.MaterialMovValido(const qyMov : TFDQuery) : String; var stDados : TStringList; begin stDados := TStringList.Create; Result := ''; if (Trim(qyMov.FieldByName('flTipoMovimento').AsString) = '') then AdicionaLinha(Result, ' - Tipo'); if qyMov.FieldByName('cdSituacaoMovimento').IsNull then AdicionaLinha(Result, ' - Situação'); if (Trim(qyMov.FieldByName('cdMaterial').AsString) = '') then AdicionaLinha(Result, ' - Material'); if Trim(qyMov.FieldByName('cdUnidadeMedida').AsString) = '' then AdicionaLinha(Result, ' - Unidade de Medida deve ser informada'); if qyMov.FieldByName('nuQtde').IsNull then AdicionaLinha(Result, ' - Quantidade'); if (qyMov.FieldByName('flTipoMovimento').AsString = 'E') and (qyMov.FieldByName('cdSituacaoMovimento').AsInteger = 2) and (qyMov.FieldByName('vlUnitario').IsNull) then AdicionaLinha(Result, ' - Valor Unitário'); if (qyMov.FieldByName('flTipoMovimento').AsString = 'E') and (qyMov.FieldByName('cdFornecedor').IsNull) then AdicionaLinha(Result, ' - Fornecedor'); if (qyMov.FieldByName('flTipoMovimento').AsString = 'S') and (qyMov.FieldByName('cdMaterialSolicitacao').IsNull) then AdicionaLinha(Result, ' - Nº da Solicitação'); if (qyMov.State = dsEdit) then begin if (qyMov.FieldByName('flTipoMovimento').AsString = 'E') then begin stDados.Clear; ExecuteSimplesSql(fdConnERP, 'SELECT cdMaterial,nuQtde,cdFornecedor,cdSituacaoMovimento ' + ' FROM erp.intIndMaterialMovimento ' + ' WHERE cdMaterialMovimento = ' + qyMov.FieldByName('cdMaterialMovimento').AsString, 'cdMaterial,nuQtde,cdFornecedor,cdSituacaoMovimento', stDados ); if (stDados.Count > 0) then begin { if (qyMov.FieldByName('cdSituacaoMovimento').AsInteger <> 1) then begin if (Trim(stDados.Strings[0]) <> '') and (Trim(stDados.Strings[0]) <> qyMov.FieldByName('cdMaterial').AsString) then AdicionaLinha(Result, ' - Não é permitido alterar o material de um movimento de entrada que não se encontra na ' + 'situação "Cadastrado"' ); if (StrToFloatDef(stDados.Strings[1], 0) > 0) and (StrToFloatDef(stDados.Strings[1], 0) <> qyMov.FieldByName('nuQtde').AsFloat) then AdicionaLinha(Result, ' - Não é permitido alterar a quantidade de um movimento de entrada que não se encontra na ' + 'situação "Cadastrado"' ); if (StrToIntDef(stDados.Strings[2], 0) > 0) and (StrToIntDef(stDados.Strings[2], 0) <> qyMov.FieldByName('cdFornecedor').AsInteger) then AdicionaLinha(Result, ' - Não é permitido alterar o fornecedor de um movimento de entrada que não se encontra na ' + 'situação "Cadastrado"' ); end; } if {(StrToIntDef(stDados.Strings[3], 0) = 2) and} (qyMov.FieldByName('flTipoMovimento').AsString = 'E') then begin if qyIntIndMatEstoqueConsulta.Active then qyIntIndMatEstoqueConsulta.Close; qyIntIndMatEstoqueConsulta.MacroByName('filtro').Clear; qyIntIndMatEstoqueConsulta.MacroByName('filtro').Value := ' WHERE cdMaterial = ' + QuotedStr(qyMov.FieldByName('cdMaterial').AsString); qyIntIndMatEstoqueConsulta.ParamByName('cdMatMovEnt').AsInteger := qyMov.FieldByName('cdMaterialMovimento').AsInteger; qyIntIndMatEstoqueConsulta.Open(); if (qyIntIndMatEstoqueConsulta.FieldByName('nuQtdeEst').AsFloat + qyMov.FieldByName('nuQtde').AsFloat < 0 ) then AdicionaLinha(Result, ' - Entrada de material não pode ser alterada, pois o estoque deste material irá ficar negativo.' ); end; end; end; end; if Assigned(stDados) then FreeAndNil(stDados); end; procedure TDmERP.GravarMaterialMov(const qyMov : TFDQuery; const bExibirMsg : Boolean); var strValidacao : String; bInserindo : Boolean; begin strValidacao := MaterialMovValido(qyMov); if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyMov.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyMov); qyMov.Post; fdConnERP.Commit; if bExibirMsg then begin if bInserindo then Informacao('Movimentação de material inserida com sucesso.') else Informacao('Movimentação alterada com sucesso.'); end; except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirMaterialMov(const qyMov : TFDQuery); var bExcluir : Boolean; begin bExcluir := True; if (qyMov.Active) then begin if (qyMov.FieldByName('flTipoMovimento').AsString = 'E') and (qyMov.FieldByName('cdSituacaoMovimento').AsInteger <> 1) then begin Aviso('Esta entrada de material não pode ser excluída pois não se encontra na situação cadastrada.'); bExcluir := False; end else if (qyMov.FieldByName('flTipoMovimento').AsString = 'E') then begin if qyIntIndMatEstoqueConsulta.Active then qyIntIndMatEstoqueConsulta.Close; qyIntIndMatEstoqueConsulta.MacroByName('filtro').Clear; qyIntIndMatEstoqueConsulta.MacroByName('filtro').Value := ' WHERE cdMaterial = ' + QuotedStr(qyMov.FieldByName('cdMaterial').AsString); qyIntIndMatEstoqueConsulta.ParamByName('cdMatMovEnt').AsInteger := qyMov.FieldByName('cdMaterialMovimento').AsInteger; qyIntIndMatEstoqueConsulta.Open(); if qyIntIndMatEstoqueConsulta.FieldByName('nuQtdeEst').AsFloat < 0 then begin Aviso('Esta entrada de material não pode ser excluída, pois o estoque deste material irá ficar negativo.'); bExcluir := False; end; end; if (bExcluir) and (Pergunta('Confirma a exclusão deste registro?')) then begin qyMov.Delete; Informacao('Movimentação de material excluída com sucesso.'); end; end; end; function TDmERP.MaterialSolicValido : String; begin Result := ''; if (qyIntIndMaterialSolic.FieldByName('flTipoSolicitacao').AsString = 'I') and (qyIntIndMaterialSolic.FieldByName('cdSolicitante').IsNull) then AdicionaLinha(Result, ' - Solicitante'); if (qyIntIndMaterialSolic.FieldByName('flTipoSolicitacao').AsString = 'E') and (Trim(qyIntIndMaterialSolic.FieldByName('nmSolicitante').AsString) = '') then AdicionaLinha(Result, ' - Nome Solicitante'); end; procedure TDmERP.GravarMaterialSolic; var strValidacao : String; bInserindo : Boolean; begin strValidacao := MaterialSolicValido; if Trim(strValidacao) <> '' then Aviso('As seguintes informações devem ser verificadas:' + #13#13 + strValidacao) else begin bInserindo := qyIntIndMaterialSolic.State = dsInsert; fdConnERP.StartTransaction; try GravarCamposAutomaticos(qyIntIndMaterialSolic); qyIntIndMaterialSolic.Post; fdConnERP.Commit; if bInserindo then Informacao('Solicitação de material inserida com sucesso.') else Informacao('Solicitação de material alterada com sucesso.'); except on E: EFDDBEngineException do begin fdConnERP.Rollback; // do something here raise; end; end; end; end; procedure TDmERP.ExcluirMaterialSolic; begin if (qyIntIndMaterialSolic.Active) then begin if Pergunta('Confirma a exclusão deste registro?') then begin ExecuteInstrucaoSql(fdConnERP, 'DELETE FROM erp.intIndMaterialMovimento ' + ' WHERE cdMaterialSolicitacao = ' + qyIntIndMaterialSolic.FieldByName('cdMaterialSolicitacao').AsString ); qyIntIndMaterialSolic.Delete; Informacao('Solicitação de material excluída com sucesso.'); end; end; end; end.
unit Helpers; interface uses IdHashMessageDigest, idHash, VCL.Forms, classesArbeitsmittel, Classes; type TSuchEintrag = record SpaltenName: string; AnzeigeName: string; constructor Create(Spalte, Anzeige: string); end; type TFormStatus = (fsBearbeiten, fsGesperrt, fsNeu, fsLeer); function getMD5Hash(input: string): string; function getRandomString(strLength: integer): string; implementation { THelper } function getMD5Hash(input: string): string; var md5hasher: TIdHashMessageDigest5; begin md5hasher := TIdHashMessageDigest5.Create; try result := md5hasher.HashStringAsHex(input); finally md5hasher.Free; end; end; function getRandomString(strLength: integer): string; var temp: integer; begin randomize; repeat temp := random(255); if temp in [33 .. 126] then result := result + Chr(temp); until length(result) = strLength; end; { TSuchEintrag } constructor TSuchEintrag.Create(Spalte, Anzeige: string); begin self.SpaltenName := Spalte; self.AnzeigeName := Anzeige; end; end.
{** * @Author: Du xinming * @Contact: QQ<36511179>; Email<lndxm1979@163.com> * @Version: 0.0 * @Date: 2018.10.15 * @Thanks: * Liu weimin QQ<287413288> * Zhang gaofeng QQ<6117036> * @Brief: * TTCPIOHandle * 1. 提供所有重叠操作接口; * 2. 封装IOCP * TTCPIOContext * 1. 封装通信套接字 * 2. 管理通信套接字上的所有重叠操作。包括重叠读、重叠写以及重叠断开连接等等 * TTCPIOManager * 1. 管理所有重叠操作对应的IO缓冲 * 2. 管理所有的通信套接字 * 3. 管理监听套接字 * 4. 提供用户接口 * @Remarks: * 这是一个世界,一个高速运转的世界。 * 每个人即是参与者,也是管理者。 * 当你来到这个世界的时候,你要向大家问好,这是基本礼节,告诉这个世界的所有人,我来了。 * 不过,也许别人并没有理会你,但是没关系,当他需要你的时候他自然会去找你的。 * 当你准备离开的时候,别忘了向大家告别,这也是基本礼节。告诉这个世界的所有人,我走了。 * 不过,你得留下点什么,也许是遗憾,也许是承载你愿望的继任者。 * 什么?就这么走了,有点不甘心啊,我还没充当管理者角色呢!! * 别急,走的时候多看一眼,如果就剩你一个人,机会来了,你现在就是管理者,你的任务就是停止这个世界。 * 似乎有点失望,我告诉你,你不是刽子手,你是在给它重生的机会。 * @Modifications: *} unit org.tcpip.tcp; interface uses WinApi.Windows, WinApi.Winsock2, System.SysUtils, System.Classes, System.Math, AnsiStrings, org.tcpip, org.algorithms, org.algorithms.heap, org.algorithms.queue, org.algorithms.time, // dxm 2018.12.17 org.algorithms.crc, org.utilities, org.utilities.buffer, org.utilities.iocp; type PTCPSocketProtocolHead = ^TTCPSocketProtocolHead; TTCPSocketProtocolHead = record Version: Byte; R1: array [0..2] of Byte; Options: DWORD; Length: Int64; LengthEx: Int64; R2: array [0..5] of Byte; CRC16: Word; end; TTCPServiceStatus = (tssNone, tssStarting, tssRunning, tssStopping, tssStoped); TIOOperationType = (otNode, otConnect, otRead, otWrite, otGraceful, otDisconnect, otNotify); TTCPIOManager = class; TTCPIOContext = class; PTCPIOBuffer = ^TTCPIOBuffer; TTCPIOBuffer = record lpOverlapped: OVERLAPPED; LastErrorCode: Integer; CompletionKey: ULONG_PTR; BytesTransferred: DWORD; Buffers: array of WSABUF; BufferCount: Integer; Flags: DWORD; Position: DWORD; // SequenceNumber: Integer; // 当同时在套接字s上执行多个IO操作时,用于标识IO顺序 OpType: TIOOperationType; // 该IO对应的操作类型,AcceptEx, WSASend, WSARecv等 Context: TTCPIOContext; // dxm 2018.12.14 [重构] end; TTCPIOHandle = class(TIOCP) protected FStatus: TTCPServiceStatus; //\\ procedure DoThreadException(dwNumOfBytes: DWORD; dwCompletionKey: ULONG_PTR; lpOverlapped: POverlapped; E: Exception); override; procedure ProcessCompletionPacket(dwNumOfBytes: DWORD; dwCompletionKey: ULONG_PTR; lpOverlapped: POverlapped); override; public function PostAccept(IOSocket: TSocket; IOBuffer: PTCPIOBuffer): Integer; function PostRecv(IOSocket: TSocket; IOBuffer: PTCPIOBuffer): Integer; function PostSend(IOSocket: TSocket; IOBuffer: PTCPIOBuffer): Integer; function PostDisconnect(IOSocket: TSocket; IOBuffer: PTCPIOBuffer): Integer; function PostConnect(IOSocket: TSocket; IOBuffer: PTCPIOBuffer): Integer; //\\ function PostNotify(IOBuffer: PTCPIOBuffer): Boolean; public constructor Create(AThreadCount: Integer); destructor Destroy; override; procedure DoThreadBegin; override; procedure DoThreadEnd; override; procedure Start; override; procedure Stop; override; //\\ procedure HardCloseSocket(s: TSocket); //\\ property Status: TTCPServiceStatus read FStatus; end; TTCPIOContextClass = class of TTCPIOContext; TTCPIOContext = class private function DoSequenceNumCompare(const Value1, Value2: Integer): Integer; procedure DoSendBufferNotify(const Buffer: TBuffer; Action: TActionType); protected FOwner: TTCPIOManager; FStatus: DWORD; FIOStatus: Int64; // dxm 2018.11.7 描述当前虚拟环路中的IO状态 FSendIOStatus: Int64; FSendBytes: Int64; FRecvBytes: Int64; FSendBusy: Int64; // 用于同步发送 FOutstandingIOs: TMiniHeap<Integer, PTCPIOBuffer>; // 缓存返回IO的最小堆 FSendBuffers: TFlexibleQueue<TBuffer>; // 缓存用户提交的待发送数据 FNextSequence: Integer; //\\ FRefCount: Integer; // dxm 2018.12.18 //\\ FSocket: TSocket; FRemoteIP: string; FRemotePort: Word; //\\ FHeadSize: DWORD; FHead: PTCPSocketProtocolHead; //\\ FBodyInFile: Boolean; FBodyFileName: string; FBodyFileHandle: THandle; FBodyUnfilledLength: Int64; //\\ FBodyExInFile: Boolean; FBodyExFileName: string; FBodyExFileHandle: THandle; FBodyExUnfilledLength: Int64; FBodyExToBeDeleted: Boolean; //\\ FCrc16: TCrc16; function HasError(IOStatus: Int64): Boolean; virtual; function HasReadIO(IOStatus: Int64): Boolean; virtual; function HasWriteIO(IOStatus: Int64): Boolean; virtual; function HasErrorOrReadIO(IOStatus: Int64): Boolean; virtual; function HasIO(IOStatus: Int64): Boolean; virtual; function HasRead(IOStatus: Int64): Boolean; virtual; function HasReadOrReadIO(IOStatus: Int64): Boolean; virtual; function HasWrite(IOStatus: Int64): Boolean; virtual; function HasWriteOrWriteIO(IOStatus: Int64): Boolean; virtual; function HasWriteOrIO(IOStatus: Int64): Boolean; virtual; //\\ function RecvProtocol: Int64; function RecvBuffer: Int64; virtual; function RecvDisconnect: Int64; function SendDisconnect: Int64; virtual; function SendBuffer: Integer; virtual; //\\ function GetTempFile: string; procedure WriteBodyToFile; procedure WriteBodyExToFile; procedure GetBodyFileHandle; procedure GetBodyExFileHandle; //\\ procedure TeaAndCigaretteAndMore(var Tea: Int64; var Cigarette: DWORD); virtual; abstract; procedure DoConnected; virtual; abstract; procedure DoRecved(IOBuffer: PTCPIOBuffer); virtual; procedure DoSent(IOBuffer: PTCPIOBuffer); virtual; procedure DoDisconnected(IOBuffer: PTCPIOBuffer); virtual; procedure DoNotify(IOBuffer: PTCPIOBuffer); virtual; abstract; //\\ procedure ParseProtocol; virtual; procedure FillProtocol(pHead: PTCPSocketProtocolHead); virtual; procedure ParseAndProcessBody; virtual; procedure ParseAndProcessBodyEx; virtual; procedure NotifyBodyExProgress; virtual; abstract; //\\ function SendToPeer(Body: PAnsiChar; Length: DWORD; Options: DWORD): Integer; overload; function SendToPeer(Body: PAnsiChar; Length: DWORD; BodyEx: PAnsiChar; LengthEx: DWORD; Options: DWORD): Integer; overload; function SendToPeer(Body: PAnsiChar; Length: DWORD; BodyEx: TStream; LengthEx: DWORD; Options: DWORD): Integer; overload; function SendToPeer(Body: PAnsiChar; Length: DWORD; FilePath: string; Options: DWORD): Integer; overload; function SendToPeer(Body: TStream; Length: DWORD; Options: DWORD): Integer; overload; function SendToPeer(Body: TStream; Length: DWORD; BodyEx: PAnsiChar; LengthEx: DWORD; Options: DWORD): Integer; overload; function SendToPeer(Body: TStream; Length: DWORD; BodyEx: TStream; LengthEx: DWORD; Options: DWORD): Integer; overload; function SendToPeer(Body: TStream; Length: DWORD; FilePath: string; Options: DWORD): Integer; overload; public constructor Create(AOwner: TTCPIOManager); virtual; destructor Destroy; override; //\\ procedure HardCloseSocket; procedure Set80000000Error; function StatusString: string; function IsClientIOContext: Boolean; function IsServerIOContext: Boolean; //\\ property Socket: TSocket read FSocket; property RemotePort: Word read FRemotePort; property RemoteIP: string read FRemoteIP; end; TTCPConnectedNotify = procedure (Sender: TObject; Context: TTCPIOContext) of object; TTCPRecvedNotify = procedure (Sender: TObject; Context: TTCPIOContext) of object; TTCPSentNotify = procedure (Sender: TObject; Context: TTCPIOContext) of object; TTCPDisConnectingNotify = procedure (Sender: TObject; Context: TTCPIOContext) of object; TTCPIOManager = class private //\\ 用户事件 FLogNotify: TLogNotify; FConnectedNotify: TTCPConnectedNotify; FRecvedNotify: TTCPRecvedNotify; FSentNotify: TTCPSentNotify; FDisconnectingNotify: TTCPDisConnectingNotify; FLogLevel: TLogLevel; // 默认为llNormal,如果指定不能小于llError FTempDirectory: string; // 对Body和BodyEx,如果接收内容超过FMultiIOBufferCount*FBufferSize, // 则直接写入临时文件,该成员指明临时文件目录 FBuffersInUsed: Integer; // 统计用 procedure SetLogNotify(const Value: TLogNotify); procedure SetLogLevel(const Value: TLogLevel); procedure SetTempDirectory(const Value: string); protected FHeadSize: DWORD; FBufferSize: UInt64; // 内存池中每个Buffer的大小,必须为页的整数倍 FBufferPool: TBufferPool; // 内存池,按页的整数倍分配 FMultiIOBufferCount: Integer; // 一次提交Buffer的最大个数 FIOBuffers: TFlexibleQueue<PTCPIOBuffer>; // 管理IO缓冲 FIOHandle: TTCPIOHandle; FTimeWheel: TTimeWheel<TTCPIOContext>; // dxm 2018.12.17 procedure SetMultiIOBufferCount(const Value: Integer); virtual; //\\ dxm 2018.11.6 //\\ 关闭时释放IOBuffer和IOContext procedure DoIOBufferNotify(const IOBuffer: PTCPIOBuffer; Action: TActionType); procedure DoIOContextNotify(const IOContext: TTCPIOContext; Action: TActionType); //\\ function AllocateIOBuffer: PTCPIOBuffer; procedure ReleaseIOBuffer(IOBuffer: PTCPIOBuffer); //\\ function DoAcceptEx(IOBuffer: PTCPIOBuffer): Boolean; virtual; abstract; function DoConnectEx(IOBuffer: PTCPIOBuffer): Boolean; virtual; public constructor Create; destructor Destroy; override; //\\ function DequeueIOBuffer: PTCPIOBuffer; procedure EnqueueIOBuffer(IOBuffer: PTCPIOBuffer); function DequeueFreeContext(IOType: DWORD): TTCPIOContext; virtual; abstract; procedure EnqueueFreeContext(AContext: TTCPIOContext); virtual; procedure RegisterIOContextClass(IOType: DWORD; AClass: TTCPIOContextClass); virtual; abstract; //\\ procedure DoWaitTIMEWAIT(IOContext: TTCPIOContext); virtual; abstract; procedure DoWaitNotify(IOContext: TTCPIOContext); virtual; abstract; procedure DoWaitFirstData(IOContext: TTCPIOContext); virtual; //\\ function ListenAddr(LocalIP: string; LocalPort: Word): TSocket; function PostSingleAccept(IOSocket: TSocket): Integer; // 返回表示错误码,其中0或WSA_IO_PENDING表示投递成功 function PostMultiAccept(IOSocket: TSocket; Count: Integer): Integer; // 返回值表示成功投递的预连接数量 //\\ function PrepareSingleIOContext(IOContext: TTCPIOContext): Boolean; function PrepareMultiIOContext(AClass: TTCPIOContextClass; Count: Integer): Integer; //\\ procedure Start; virtual; procedure Stop; virtual; procedure WriteLog(LogLevel: TLogLevel; LogContent: string); //\\ property IOHandle: TTCPIOHandle read FIOHandle; property HeadSize: DWORD read FHeadSize write FHeadSize; property BufferPool: TBufferPool read FBufferPool; property BufferSize: UInt64 read FBufferSize; property MultiIOBufferCount: Integer read FMultiIOBufferCount write SetMultiIOBufferCount; property TempDirectory: string read FTempDirectory write SetTempDirectory; property LogLevel: TLogLevel read FLogLevel write SetLogLevel; property BuffersInUsed: Integer read FBuffersInUsed; property TimeWheel: TTimeWheel<TTCPIOContext> read FTimeWheel; //\\ property OnLog: TLogNotify read FLogNotify write SetLogNotify; property OnConnected: TTCPConnectedNotify read FConnectedNotify write FConnectedNotify; property OnRecved: TTCPRecvedNotify read FRecvedNotify write FRecvedNotify; property OnSent: TTCPSentNotify read FSentNotify write FSentNotify; property OnDisconnecting: TTCPDisConnectingNotify read FDisconnectingNotify write FDisconnectingNotify; end; const IO_OPTION_EMPTY: DWORD = $00000000; IO_OPTION_ONCEMORE: DWORD = $00000001; IO_OPTION_NOTIFY_BODYEX_PROGRESS: DWORD = $00000002; IO_OPERATION_TYPE_DESC: array [TIOOperationType] of string = ( '空闲', '连接', '接收', '发送', '接收GRACEFUL', '断开', '通知' ); {======================================================== 1. Status(状态) 00000000,00000000,00000000,00000000 [$00000000][闲置] 00000000,00000000,00000000,00000001 [$00000001][连接中] 00000000,00000000,00000000,00000010 [$00000002][已连接] 00000000,00000000,00000000,00000100 [$00000004][协议头读取] 00000000,00000000,00000000,00001000 [$00000008][Body已读取] 00000000,00000000,00000000,00010000 [$00000010][BodyEx已读取] 00000000,00000000,00000000,00100000 [$00000020][Graceful IO 已返回] 00000000,00000000,00000000,01000000 [$00000040][DisconnectEx IO 已返回] ........,........,........,........ 00100000,00000000,00000000,00000000 [$20000000][客户端套接字:1; 服务端套接字:0] 01000000,00000000,00000000,00000000 [$40000000][套接字已被关闭] [仅用于服务端关闭时设置,几乎不参与程序逻辑] 10000000,00000000,00000000,00000000 [$80000000][出错] 2. IOStatus(64位) 10000000,00000000,........,00000001 [$8000,0000,0000,0001] [READ IO 0] [第0位到第58位表示虚拟环路中的一个读IO, 共59个] 10000000,00000000,........,00000010 ........,........,........,........ 10000100,00000000,........,00000000 [$8400,0000,0000,0000] [READ IO 58] 10001000,00000000,........,00000000 [$8800,0000,0000,0000] [WRITE IO] 10010000,00000000,........,00000000 [$9000,0000,0000,0000] [IO ERROR] 10100000,00000000,........,00000000 [$A000,0000,0000,0000] [WRITE ] 11000000,00000000,........,00000000 [$C000,0000,0000,0000] [READ] 10000000,00000000,........,00000000 [] [保留] ========================================================} IO_STATUS_EMPTY: Int64 = -$8000000000000000; // 1000,0000,...,0000; IO_STATUS_INIT: Int64 = -$7000000000000000; // 1001,0000,...,0000;$9000000000000000 IO_STATUS_NOERROR: Int64 = -$7000000000000000; //[and]1001,0000,...,0000;$9000000000000000 IO_STATUS_HAS_READ: Int64 = -$4000000000000000; IO_STATUS_HAS_READ_IO: Int64 = -$7800000000000001; //[and]1000,0111,...,1111;$87FFFFFFFFFFFFFF IO_STATUS_HAS_READ_OR_READ_IO: Int64 = -$3800000000000001; //[and]1100,0111,...,1111;$C7FFFFFFFFFFFFFF IO_STATUS_HAS_WRITE: Int64 = -$6000000000000000; IO_STATUS_HAS_WRITE_IO: Int64 = -$7800000000000000; IO_STATUS_HAS_WRITE_OR_WRITE_IO: Int64 = -$5800000000000000; //[and]1010,1000,...,0000;$A800000000000000 IO_STATUS_HAS_IO: Int64 = -$7000000000000001; IO_STATUS_HAS_WRITE_OR_IO: Int64 = -$5000000000000001; //[and]1010,1111,...,1111;$AFFFFFFFFFFFFFFF IO_STATUS_ADD_WRITE_WRITE_IO: Int64 = -$5800000000000000; //[ or]1010,1000,...,0000;$A800000000000000 IO_STATUS_DEL_WRITE: Int64 = -$2000000000000001; //[and]1101,1111,...,1111;$DFFFFFFFFFFFFFFF IO_STATUS_DEL_WRITE_WRITE_IO: Int64 = -$2800000000000001; //[and]1101,0111,...,1111;$D7FFFFFFFFFFFFFF IO_STATUS_DEL_WRITE_WRITE_IO_ADD_ERROR: Int64 = -$3800000000000001; //[and]1100,0111,...,1111;$C7FFFFFFFFFFFFFF IO_STATUS_DEL_WRITE_IO: Int64 = -$0800000000000001; //[and]1111,0111,...,1111;$F7FFFFFFFFFFFFFF IO_STATUS_DEL_WRITE_IO_ADD_ERROR: Int64 = -$1800000000000001; IO_STATUS_ADD_READ: Int64 = -$4000000000000000; //[and]1100,0000,...,0000;$C000000000000000 IO_STATUS_DEL_READ: Int64 = -$4000000000000001; //[and]1011,1111,...,1111;$BFFFFFFFFFFFFFFF IO_STATUS_READ_CAPACITY = 59; // 增加IO位 [or] IO_STATUS_ADD_READ_IO: array [0..IO_STATUS_READ_CAPACITY-1] of Int64 = ( -$7FFFFFFFFFFFFFFF, -$7FFFFFFFFFFFFFFE, -$7FFFFFFFFFFFFFFC, -$7FFFFFFFFFFFFFF8, -$7FFFFFFFFFFFFFF0, -$7FFFFFFFFFFFFFE0, -$7FFFFFFFFFFFFFC0, -$7FFFFFFFFFFFFF80, -$7FFFFFFFFFFFFF00, -$7FFFFFFFFFFFFE00, -$7FFFFFFFFFFFFC00, -$7FFFFFFFFFFFF800, -$7FFFFFFFFFFFF000, -$7FFFFFFFFFFFE000, -$7FFFFFFFFFFFC000, -$7FFFFFFFFFFF8000, -$7FFFFFFFFFFF0000, -$7FFFFFFFFFFE0000, -$7FFFFFFFFFFC0000, -$7FFFFFFFFFF80000, -$7FFFFFFFFFF00000, -$7FFFFFFFFFE00000, -$7FFFFFFFFFC00000, -$7FFFFFFFFF800000, -$7FFFFFFFFF000000, -$7FFFFFFFFE000000, -$7FFFFFFFFC000000, -$7FFFFFFFF8000000, -$7FFFFFFFF0000000, -$7FFFFFFFE0000000, -$7FFFFFFFC0000000, -$7FFFFFFF80000000, -$7FFFFFFF00000000, -$7FFFFFFE00000000, -$7FFFFFFC00000000, -$7FFFFFF800000000, -$7FFFFFF000000000, -$7FFFFFE000000000, -$7FFFFFC000000000, -$7FFFFF8000000000, -$7FFFFF0000000000, -$7FFFFE0000000000, -$7FFFFC0000000000, -$7FFFF80000000000, -$7FFFF00000000000, -$7FFFE00000000000, -$7FFFC00000000000, -$7FFF800000000000, -$7FFF000000000000, -$7FFE000000000000, -$7FFC000000000000, -$7FF8000000000000, -$7FF0000000000000, -$7FE0000000000000, -$7FC0000000000000, -$7F80000000000000, -$7F00000000000000, -$7E00000000000000, -$7C00000000000000 ); // 去除IO位 [and] IO_STATUS_DEL_READ_IO: array [0..IO_STATUS_READ_CAPACITY-1] of Int64 = ( // 1111,...,1110; $FFFFFFFFFFFFFFFE // 1111,...,1101; $FFFFFFFFFFFFFFFD // 1111,...,1011; $FFFFFFFFFFFFFFFB // 1111,...,0111; $FFFFFFFFFFFFFFF7 -$0000000000000002, -$0000000000000003, -$0000000000000005, -$0000000000000009, -$0000000000000011, -$0000000000000021, -$0000000000000041, -$0000000000000081, -$0000000000000101, -$0000000000000201, -$0000000000000401, -$0000000000000801, -$0000000000001001, -$0000000000002001, -$0000000000004001, -$0000000000008001, -$0000000000010001, -$0000000000020001, -$0000000000040001, -$0000000000080001, -$0000000000100001, -$0000000000200001, -$0000000000400001, -$0000000000800001, -$0000000001000001, -$0000000002000001, -$0000000004000001, -$0000000008000001, -$0000000010000001, -$0000000020000001, -$0000000040000001, -$0000000080000001, -$0000000100000001, -$0000000200000001, -$0000000400000001, -$0000000800000001, -$0000001000000001, -$0000002000000001, -$0000004000000001, -$0000008000000001, -$0000010000000001, -$0000020000000001, -$0000040000000001, -$0000080000000001, -$0000100000000001, -$0000200000000001, -$0000400000000001, -$0000800000000001, -$0001000000000001, -$0002000000000001, -$0004000000000001, -$0008000000000001, -$0010000000000001, -$0020000000000001, -$0040000000000001, -$0080000000000001, -$0100000000000001, -$0200000000000001, -$0400000000000001 ); // 去除IO位并增加错误位 [and] IO_STATUS_DEL_READ_IO_ADD_ERROR: array [0..IO_STATUS_READ_CAPACITY-1] of Int64 = ( -$1000000000000002, -$1000000000000003, -$1000000000000005, -$1000000000000009, -$1000000000000011, -$1000000000000021, -$1000000000000041, -$1000000000000081, -$1000000000000101, -$1000000000000201, -$1000000000000401, -$1000000000000801, -$1000000000001001, -$1000000000002001, -$1000000000004001, -$1000000000008001, -$1000000000010001, -$1000000000020001, -$1000000000040001, -$1000000000080001, -$1000000000100001, -$1000000000200001, -$1000000000400001, -$1000000000800001, -$1000000001000001, -$1000000002000001, -$1000000004000001, -$1000000008000001, -$1000000010000001, -$1000000020000001, -$1000000040000001, -$1000000080000001, -$1000000100000001, -$1000000200000001, -$1000000400000001, -$1000000800000001, -$1000001000000001, -$1000002000000001, -$1000004000000001, -$1000008000000001, -$1000010000000001, -$1000020000000001, -$1000040000000001, -$1000080000000001, -$1000100000000001, -$1000200000000001, -$1000400000000001, -$1000800000000001, -$1001000000000001, -$1002000000000001, -$1004000000000001, -$1008000000000001, -$1010000000000001, -$1020000000000001, -$1040000000000001, -$1080000000000001, -$1100000000000001, -$1200000000000001, -$1400000000000001 ); implementation { TTCPIOHandle } constructor TTCPIOHandle.Create(AThreadCount: Integer); begin inherited; FStatus := tssNone; end; destructor TTCPIOHandle.Destroy; begin inherited; end; procedure TTCPIOHandle.DoThreadBegin; var Msg: string; begin Msg := Format('[%d]Start thread OK', [GetCurrentThreadId()]); WriteLog(llNormal, Msg); inherited; end; procedure TTCPIOHandle.DoThreadEnd; var Msg: string; begin inherited; Msg := Format('[%d]Stop thread OK', [GetCurrentThreadId()]); WriteLog(llNormal, Msg); end; procedure TTCPIOHandle.DoThreadException(dwNumOfBytes: DWORD; dwCompletionKey: ULONG_PTR; lpOverlapped: POverlapped; E: Exception); var ErrDesc: string; IOBuffer: PTCPIOBuffer; begin inherited; IOBuffer := PTCPIOBuffer(lpOverlapped); ErrDesc := Format('[%d][%d]<%s.DoThreadException> dwNumOfBytes=%d, dwCompletionKey=%d, Internal=%d, InternalHigh=%d, LastErrorCode=%d, OpType=%s, Status=%s, ExceptionMsg=%s', [ IOBuffer^.Context.FSocket, GetCurrentThreadId(), ClassName, dwNumOfBytes, dwCompletionKey, IOBuffer^.lpOverlapped.Internal, IOBuffer^.lpOverlapped.InternalHigh, IOBuffer^.LastErrorCode, IO_OPERATION_TYPE_DESC[IOBuffer^.OpType], IOBuffer^.Context.StatusString(), E.Message]); WriteLog(llFatal, ErrDesc); end; procedure TTCPIOHandle.HardCloseSocket(s: TSocket); var Linger: TLinger; ErrDesc: string; begin Linger.l_onoff := 1; Linger.l_linger := 0; if (setsockopt(s, SOL_SOCKET, SO_LINGER, @Linger, SizeOf(Linger)) = SOCKET_ERROR) then begin ErrDesc := Format('[%d][%d]<%s.HardCloseSocket.setsockopt> LastErrorCode=%d', [ s, GetCurrentThreadId(), ClassName, WSAGetLastError()]); WriteLog(llFatal, ErrDesc); end; closesocket(s); end; function TTCPIOHandle.PostAccept(IOSocket: TSocket; IOBuffer: PTCPIOBuffer): Integer; var ErrDesc: string; begin Result := 0; if IOBuffer^.Context.FSocket = INVALID_SOCKET then begin // dxm 2018.11.2 // WSAEMFILE [10024] 没有可用套接字资源 [致命] // WSAENOBUFS [10055] 没有可用内存以创建套接字对象 [致命] // 上述2个错误显然是[致命]错误 IOBuffer^.Context.FSocket := WSASocket( AF_INET, SOCK_STREAM, IPPROTO_TCP, nil, 0, WSA_FLAG_OVERLAPPED); if IOBuffer^.Context.FSocket = INVALID_SOCKET then begin Result := WSAGetLastError(); // 输出日志 ErrDesc := Format('[][%d]<%s.PostAccept.WSASocket> LastErrorCode=%d', [ GetCurrentThreadId(), ClassName, Result]); WriteLog(llFatal, ErrDesc); Exit; end; end; // dxm 2018.11.1 // 发起重叠建立连接操作 // 当连接建立完成时,会带回已传输字节数,完成Key以及OVERLAPPED结构体 // 当然,在关联监听套接字时并未指定完成Key // dxm 2018.11.2 // ERROR_IO_PENDING [997] 重叠IO初始化成功,稍后通知完成 [------][调用时][正常] // WSAECONNRESET [10054] 对端提交连接请求后,随即又终止了该请求 [通知时][------][正常][可重用][说明一旦收到连接请求,后续对端即使取消,本地也只是标记而已] // 对端强制关闭了已建立的连接。例如,程序崩溃、主机重启、掉线;或者是对端执行了硬关闭 // 当出现这种情况是,正在执行中的操作返回WSAENETRESET[10052]错误,而后续操作则返回WSAECONNRESET // 可见本函数不应该有错误,如果出现了错误则说明个人理解问题或其它未知的错误,暂且定为[致命][不可重用] if not org.tcpip.lpfnAcceptEx( IOSocket, IOBuffer^.Context.FSocket, IOBuffer^.Buffers[0].buf, {data + local address + remote address} 0, //为0时不接收连接数据 Sizeof(TSockAddrIn) + 16, Sizeof(TSockAddrIn) + 16, IOBuffer^.BytesTransferred, // @IOBuffer^.lpOverlapped) then begin Result := WSAGetLastError(); if Result <> WSA_IO_PENDING then begin // 输出日志 ErrDesc := Format('[%d][%d]<%s.PostAccept.AcceptEx> LastErrorCode=%d', [ IOBuffer^.Context.FSocket, GetCurrentThreadId(), ClassName, Result]); WriteLog(llFatal, ErrDesc); end; end; end; function TTCPIOHandle.PostConnect(IOSocket: TSocket; IOBuffer: PTCPIOBuffer): Integer; var ErrDesc: string; SrvAddr: TSockAddr; begin Result := 0; // dxm 2018.11.1 // 发起重叠建立连接操作 // 当连接建立完成时,会带回已传输字节数,完成Key以及OVERLAPPED结构体 // 当然,在关联监听套接字时并未指定完成Key // dxm 2018.11.2 // ERROR_IO_PENDING [997] 重叠IO初始化成功,稍后通知完成 [------][调用时][正常] // WSAECONNRESET [10054] 对端提交连接请求后,随即又终止了该请求 [通知时][------][正常][可重用][说明一旦收到连接请求,后续对端即使取消,本地也只是标记而已] // 可见本函数不应该有错误,如果出现了错误则说明个人理解问题或其它未知的错误,暂且定为[致命][不可重用] IOBuffer^.Context.FStatus := IOBuffer^.Context.FStatus or $00000001; ZeroMemory(@SrvAddr, SizeOf(TSockAddrIn)); TSockAddrIn(SrvAddr).sin_family := AF_INET; TSockAddrIn(SrvAddr).sin_addr.S_addr := inet_addr(PAnsiChar(Ansistring(IOBuffer.Context.FRemoteIP))); TSockAddrIn(SrvAddr).sin_port := htons(IOBuffer.Context.FRemotePort); // dxm 2018.11.15 // WSAETIMEDOUT [10060] 连接超时 [通知时][------][错误][分析:服务端投递的预连接太少,需动态设置预投递上限] if not org.tcpip.lpfnConnectEx( IOSocket, @SrvAddr, SizeOf(TSockAddrIn), nil, {data} 0, //为0时不发送连接数据 IOBuffer^.BytesTransferred, // @IOBuffer^.lpOverlapped ) then begin Result := WSAGetLastError(); if Result <> WSA_IO_PENDING then begin // 输出日志 ErrDesc := Format('[%d][%d]<%s.PostConnect.ConnectEx> LastErrorCode=%d, Status=%s', [ IOBuffer^.Context.FSocket, GetCurrentThreadId(), ClassName, Result, IOBuffer^.Context.StatusString()]); WriteLog(llFatal, ErrDesc); end; end; end; function TTCPIOHandle.PostDisconnect(IOSocket: TSocket; IOBuffer: PTCPIOBuffer): Integer; var ErrDesc: string; begin Result := 0; if not org.tcpip.lpfnDisconnectEx( IOSocket, @IOBuffer^.lpOverlapped, IOBuffer^.Flags, 0) then begin Result := WSAGetLastError(); if Result <> WSA_IO_PENDING then begin // 输出日志 ErrDesc := Format('[%d][%d]<%s.PostDisconnect.DisconnectEx> LastErrorCode=%d, Status=%s', [ IOSocket, GetCurrentThreadId(), ClassName, Result, IOBuffer^.Context.StatusString()]); WriteLog(llFatal, ErrDesc); end; end; end; function TTCPIOHandle.PostNotify(IOBuffer: PTCPIOBuffer): Boolean; var dwRet: DWORD; ErrDesc: string; begin Result := PostQueuedCompletionStatus(0, 0, @IOBuffer^.lpOverlapped); if not Result then begin dwRet := GetLastError(); ErrDesc := Format('[%d][%d]<%s.PostNotify.PostQueuedCompletionStatus> LastErrorCode=%d, Status=%s', [ IOBuffer^.Context.FSocket, GetCurrentThreadId(), ClassName, dwRet, IOBuffer^.Context.StatusString()]); WriteLog(llFatal, ErrDesc); end; end; function TTCPIOHandle.PostRecv(IOSocket: TSocket; IOBuffer: PTCPIOBuffer): Integer; var ErrDesc: string; begin Result := 0; // dxm 2018.12.06 // WSAECONNRESET [10054] [通知时][调用时][不可重用] // WSAENOTCONN [10057] [][][] if (WinApi.Winsock2.WSARecv( IOSocket, @IOBuffer^.Buffers[0], IOBuffer^.BufferCount, IOBuffer^.BytesTransferred, IOBuffer^.Flags, @IOBuffer^.lpOverlapped, nil) = SOCKET_ERROR) then begin Result := WSAGetLastError(); if Result <> WSA_IO_PENDING then begin ErrDesc := Format('[%d][%d]<%s.PostRecv.WSARecv> LastErrorCode=%d, Status=%s', [ IOSocket, GetCurrentThreadId(), ClassName, Result, IOBuffer^.Context.StatusString()]); WriteLog(llFatal, ErrDesc); end; end; end; function TTCPIOHandle.PostSend(IOSocket: TSocket; IOBuffer: PTCPIOBuffer): Integer; var ErrDesc: string; begin Result := 0; if (WinApi.Winsock2.WSASend( IOSocket, @IOBuffer^.Buffers[0], IOBuffer^.BufferCount, IOBuffer^.BytesTransferred, IOBuffer^.Flags, @IOBuffer^.lpOverlapped, nil) = SOCKET_ERROR) then begin Result := WSAGetLastError(); if Result <> WSA_IO_PENDING then begin ErrDesc := Format('[%d][%d]<%s.PostSend.WSASend> LastErrorCode=%d, Status=%s', [ IOSocket, GetCurrentThreadId(), ClassName, Result, IOBuffer^.Context.StatusString()]); WriteLog(llFatal, ErrDesc); end; end; end; procedure TTCPIOHandle.ProcessCompletionPacket(dwNumOfBytes: DWORD; dwCompletionKey: ULONG_PTR; lpOverlapped: POverlapped); var bRet: Boolean; IOBuffer: PTCPIOBuffer; IOContext: TTCPIOContext; {$IfDef DEBUG} Msg: string; {$Endif} begin // dxm 2018.11.2 // IOCP端只要出队了一个不为nil的lpOverlapped,就会调用此函数进行处理: //---------------------------------- // 1. IOBuffer^.OpType = otConnect // 此封包是针对监听套接字的,可能的IO错误有: // <1>. ERROR_IO_PENDING [997] 重叠IO初始化成功,稍后通知完成 [------][调用时][正常] // <2>. WSAECONNRESET [10054] 对端提交连接请求后,随即又终止了该请求 [通知时][------][正常][可重用][说明一旦收到连接请求,后续对端即使取消,本地也只是标记而已] // 1>. 如果IO正常,即lpOverlapped^.Internal=0,表示成功建立连接,后续交由DoAcceptEx处理 // 2>. 如果IO异常,即lpOverlapped^.Internal=WSAECONNRESET,表示对端提交连接请求后,随即又终止了该请求,也交由DoAcceptEx处理 //---------------------------------- // 2. IOBuffer^.OpType = otRead // 此封包是针对通信套接字的重叠读IO,可能的IO错误有: // <1>. WSAECONNABORTED [10053] 由于超时或其他错误导致虚拟环路终止 [通知时][调用时][错误][不可重用][软件导致连接终止,可能是数据传输超时或协议错误] // <2>. WSAECONNRESET [10054] 对端重置了虚拟环路 [通知时][调用时][错误][不可重用][对端程序停止、主机重启、网络丢失、对端执行了硬关闭] // <3>. WSAENETRESET [10052] 与keep-alive有关等等 [] // <4>. WSAETIMEDOUT [10060] 由于网络错误或对端响应失败导致连接被丢弃 [通知时][------][错误][不可重用] // <5>. WSAEWOULDBLOCK [10035] Windows NT 正在处理的重叠IO请求太多 [------][调用时][正常][稍后] // <6>. WSA_IO_PENDING [997] 重叠IO已成功初始化,稍后通知完成 [------][调用时][正常][稍后] // <7>. WSA_OPERATION_ABORTED 由于套接字被关闭而导致重叠IO被取消 [通知时][------][错误][----] // 1>. 如果调用WSARecv时返回<1>,<2>错误,如果系统上有当前套接字的IO请求存在,个人认为其会以同样的错误码返回IO完成封包, // 但是,在调用WSARecv时返回<1>,<2>错误后,如果立即关闭(closesocket)套接字,该套接字上的其它IO请求是返回同样的错误码还是错误<7>? // 如果是第一种情况,则等待全部IO请求返回后关闭套接字 // 如果是第二种情况,需进行验证 // 2>. 个人认为错误<4>应该在IO通知时才能获取,感觉应该同1>的第一种情况 // 3>. 当关闭套接字后,系统会取消该套接字上的Pending IO和Outstanding IO,这些IO最终都会以错误<7>返回, // 由于当前套接字上未返回的IO数量记录在Context中,因此,为了能够正确地回收为这些IO分配的应用程序资源, // 任何时候关闭套接字都必须等待上下文中的IO计数归零后在回收上下文资源 // // 对1>,2>,3>情况出队的完成封包都必须交给上下文对象进行处理,依次将这些IOBuffer归还应用程序; // 对1>,2>情况当IO计数归零后应将上下文状态设置为FStatus := FStatus or $80000000以便回收函数(EnqueueContext)将出错的套接字关闭; // 对3>情况,由于套接字已被主动关闭,故不需为上下文增加$80000000位。 //----------------------------------------- // 3. IOBuffer^.OpType = otWrite // 此封包是针对通信套接字的重叠写IO,其处理方式同otRead // ---------------------------------------- // 4. IOBuffer^.OpType = otDisConnect IOBuffer := PTCPIOBuffer(lpOverlapped); IOBuffer^.CompletionKey := dwCompletionKey; IOContext := IOBuffer^.Context; if IOBuffer^.OpType <> otNotify then begin bRet := WSAGetOverlappedResult( IOContext.FSocket, @IOBuffer^.lpOverlapped, IOBuffer^.BytesTransferred, False, IOBuffer^.Flags); if not bRet then IOBuffer^.LastErrorCode := WSAGetLastError(); end; {$IfDef DEBUG} Msg := Format('[%d][%d]<%s.ProcessCompletionPacket> dwNumBytes=%d, dwKey=%d, LastErrorCode=%d, SequenceNumber=%d, OpType=%s, Status=%s, IOStatus=%x', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, dwNumOfBytes, dwCompletionKey, IOBuffer^.LastErrorCode, IOBuffer^.SequenceNumber, IO_OPERATION_TYPE_DESC[IOBuffer^.OpType], IOContext.StatusString(), IOContext.FIOStatus]); WriteLog(llDebug, Msg); {$Endif} IOBuffer^.BytesTransferred := dwNumOfBytes; case IOBuffer^.OpType of otConnect: begin if IOContext.FStatus and $20000000 = $00000000 then begin if IOContext.FOwner.DoAcceptEx(IOBuffer) then IOContext.DoConnected(); end else begin if IOContext.FOwner.DoConnectEx(IOBuffer) then IOContext.DoConnected(); end; end; otRead, otGraceful: IOContext.DoRecved(IOBuffer); otWrite: IOContext.DoSent(IOBuffer); otDisconnect: IOContext.DoDisconnected(IOBuffer); otNotify: IOContext.DoNotify(IOBuffer); end; end; procedure TTCPIOHandle.Start; var iRet: Integer; wsaData: TWsaData; begin FStatus := tssStarting; iRet := WSAStartup(MakeWord(2, 2), wsaData); if iRet <> 0 then raise Exception.CreateFmt('[%d]<%s.Start.WSAStartup> failed with error: %d', [GetCurrentThreadId(), ClassName, iRet]); iRet := LoadWinsockEx(); if iRet = 0 then raise Exception.CreateFmt('[%d]<%s.Start.LoadWinsockEx> failed', [GetCurrentThreadId(), ClassName]); //启动线程池 inherited; FStatus := tssRunning; end; procedure TTCPIOHandle.Stop; begin FStatus := tssStopping; WSACleanup(); inherited; FStatus := tssStoped; end; { TTCPIOContext } constructor TTCPIOContext.Create(AOwner: TTCPIOManager); begin FOwner := AOwner; //\\ // FStatus := 延迟到派生类赋值。[不同的派生类FStatus的初始值可能不同] FIOStatus := IO_STATUS_INIT; FSendIOStatus := IO_STATUS_INIT; FSendBytes := 0; FRecvBytes := 0; FSendBusy := 0; FNextSequence := 0; FRefCount := 0; FOutstandingIOs := TMiniHeap<Integer, PTCPIOBuffer>.Create(128); FOutstandingIOs.OnKeyCompare := DoSequenceNumCompare; FSendBuffers := TFlexibleQueue<TBuffer>.Create(128); FSendBuffers.OnItemNotify := DoSendBufferNotify; //\\ FSocket := INVALID_SOCKET; FRemoteIP := ''; FRemotePort := 0; //\\ FHeadSize := FOwner.HeadSize; FHead := AllocMem(FHeadSize); //\\ FBodyInFile := False; FBodyFileName := ''; FBodyFileHandle := INVALID_HANDLE_VALUE; FBodyUnfilledLength := 0; //\\ FBodyExInFile := False; FBodyExFileName := ''; FBodyExFileHandle := INVALID_HANDLE_VALUE; FBodyExUnfilledLength := 0; FBodyExToBeDeleted := False; //\\ FCrc16 := TCrc16.Create(); end; destructor TTCPIOContext.Destroy; begin FOutstandingIOs.Free(); FSendBuffers.Free(); FreeMem(FHead, FHeadSize); FCrc16.Free(); inherited; end; procedure TTCPIOContext.DoDisconnected(IOBuffer: PTCPIOBuffer); var IOIndex: Integer; IOStatus: Int64; ErrDesc: string; begin // dxm 2018.11.3 // 如果IO正常,则通信套接字可重用,否则不可重用 IOIndex := IOBuffer^.SequenceNumber mod IO_STATUS_READ_CAPACITY; if IOBuffer^.LastErrorCode <> 0 then begin ErrDesc := Format('[%d][%d]<%s.DoDisconnected> IO内部错误 LastErrorCode=%d, SequenceNumber=%d, Status=%s, IOStatus=%x', [ FSocket, GetCurrentThreadId(), ClassName, IOBuffer^.LastErrorCode, IOBuffer^.SequenceNumber, StatusString(), FIOStatus]); FOwner.WriteLog(llError, ErrDesc); FOwner.EnqueueIOBuffer(IOBuffer); Set80000000Error(); IOStatus := InterlockedAnd64(FIOStatus, IO_STATUS_DEL_READ_IO_ADD_ERROR[IOIndex]); IOStatus := IOStatus and IO_STATUS_DEL_READ_IO[IOIndex]; end else begin FStatus := FStatus or $00000040; FOwner.EnqueueIOBuffer(IOBuffer); //{$IfDef DEBUG} // ErrDesc := Format('[%d][%d]<%s.DoDisconnected>[BEFORE DEL READ IO %d][FIOStatues] FIOStatus=%x', // [ FSocket, // GetCurrentThreadId(), // ClassName, // IOIndex, // FIOStatus]); // FOwner.WriteLog(llDebug, ErrDesc); //{$Endif} IOStatus := InterlockedAnd64(FIOStatus, IO_STATUS_DEL_READ_IO[IOIndex]); //{$IfDef DEBUG} // ErrDesc := Format('[%d][%d]<%s.DoDisconnected>[AFTER DEL READ IO %d][FIOStatues] FIOStatus=%x', // [ FSocket, // GetCurrentThreadId(), // ClassName, // IOIndex, // FIOStatus]); // FOwner.WriteLog(llDebug, ErrDesc); //{$Endif} IOStatus := IOStatus and IO_STATUS_DEL_READ_IO[IOIndex]; //{$IfDef DEBUG} // ErrDesc := Format('[%d][%d]<%s.DoDisconnected>[LOCAL][IOStatues] IOStatus=%x', // [ FSocket, // GetCurrentThreadId(), // ClassName, // IOStatus]); // FOwner.WriteLog(llDebug, ErrDesc); //{$Endif} // dxm 2018.11.28 // 注释了这些代码 // 该断开连接IO返回后不管是否有错误,只要没有[READ]即可归还了, // 只是如果有[ERROR]则不可重用,否则可重用 // if HasError(IOStatus) then begin // if not (HasReadOrReadIO(IOStatus) or HasWriteOrWriteIO(IOStatus)) then begin // FOwner.EnqueueFreeContext(Self); // end; // end // else begin // if not HasReadOrReadIO(IOStatus) then begin // FOwner.EnqueueFreeContext(Self); // end; // end; end; if not (HasReadOrReadIO(IOStatus) or HasWriteOrWriteIO(IOStatus)) then begin FOwner.EnqueueFreeContext(Self); end; end; procedure TTCPIOContext.DoRecved(IOBuffer: PTCPIOBuffer); var IOIndex: Integer; Status: DWORD; IOStatus: Int64; ErrDesc: string; begin IOIndex := IOBuffer^.SequenceNumber mod IO_STATUS_READ_CAPACITY; if (IOBuffer^.LastErrorCode <> 0) or ((IOBuffer^.OpType = otGraceful) and (IOBuffer^.BytesTransferred > 0)) or ((IOBuffer^.OpType = otRead) and (IOBuffer^.BytesTransferred = 0)) then begin ErrDesc := Format('[%d][%d]<%s.DoRecved> IO内部错误 [%s:%d] LastErrorCode=%d, OpType=%s, BytesTransferred=%d, SequenceNumber=%d, Status=%s, IOStatus=%x', [ FSocket, GetCurrentThreadId(), ClassName, FRemoteIP, FRemotePort, IOBuffer^.LastErrorCode, IO_OPERATION_TYPE_DESC[IOBuffer^.OpType], IOBuffer^.BytesTransferred, IOBuffer^.SequenceNumber, StatusString(), FIOStatus]); FOwner.WriteLog(llError, ErrDesc); FOwner.EnqueueIOBuffer(IOBuffer); Set80000000Error(); IOStatus := InterlockedAnd64(FIOStatus, IO_STATUS_DEL_READ_IO_ADD_ERROR[IOIndex]); IOStatus := IOStatus and IO_STATUS_DEL_READ_IO[IOIndex]; if not (HasReadOrReadIO(IOStatus) or HasWriteOrWriteIO(IOStatus)) then begin FOwner.EnqueueFreeContext(Self); end; end else begin if IOBuffer^.OpType = otGraceful then begin // 对端优雅关闭 FStatus := FStatus or $00000020; FOwner.EnqueueIOBuffer(IOBuffer); end else begin InterlockedAdd64(FRecvBytes, IOBuffer^.BytesTransferred); FOutstandingIOs.Push(IOBuffer^.SequenceNumber, IOBuffer); end; IOStatus := InterlockedAnd64(FIOStatus, IO_STATUS_DEL_READ_IO[IOIndex]); IOStatus := IOStatus and IO_STATUS_DEL_READ_IO[IOIndex]; if HasError(IOStatus) then begin if not (HasReadOrReadIO(IOStatus) or HasWriteOrWriteIO(IOStatus)) then begin FOwner.EnqueueFreeContext(Self); end; end else begin if not HasReadOrReadIO(IOStatus) then begin Status := FStatus; TeaAndCigaretteAndMore(IOStatus, Status); if Status and $80000040 = $00000040 then begin if not HasWriteIO(IOStatus) then FOwner.EnqueueFreeContext(Self); end else if HasError(IOStatus) or (Status and $80000000 = $80000000) then begin if not HasWriteOrIO(IOStatus) then begin FOwner.EnqueueFreeContext(Self); end; end else begin // nothing? end; end; end; end; end; procedure TTCPIOContext.DoSendBufferNotify(const Buffer: TBuffer; Action: TActionType); begin if Action = atDelete then Buffer.Free(); end; procedure TTCPIOContext.DoSent(IOBuffer: PTCPIOBuffer); var iRet: Integer; // Status: DWORD; // dxm 2018.12.11 IOStatus: Int64; BytesTransferred: Int64; LastErrorCode: Integer; SendBusy: Int64; ErrDesc: string; begin BytesTransferred := IOBuffer^.BytesTransferred; LastErrorCode := IOBuffer^.LastErrorCode; FSendBytes := FSendBytes + BytesTransferred; if LastErrorCode <> 0 then begin // [IO异常] ErrDesc := Format('[%d][%d]<%s.DoSent> IO内部错误 LastErrorCode=%d, OpType=%s, BytesTransferred=%d, SequenceNumber=%d, Status=%s, IOStatus=%x', [ FSocket, GetCurrentThreadId(), ClassName, IOBuffer^.LastErrorCode, IO_OPERATION_TYPE_DESC[IOBuffer^.OpType], IOBuffer^.BytesTransferred, IOBuffer^.SequenceNumber, StatusString(), FIOStatus]); FOwner.WriteLog(llError, ErrDesc); FOwner.EnqueueIOBuffer(IOBuffer); Set80000000Error(); IOStatus := InterlockedAnd64(FIOStatus, IO_STATUS_DEL_WRITE_IO_ADD_ERROR); IOStatus := IOStatus and IO_STATUS_DEL_WRITE_IO; end else begin FOwner.EnqueueIOBuffer(IOBuffer); SendBusy := InterlockedAdd64(FSendBusy, -BytesTransferred); if SendBusy > 0 then begin iRet := SendBuffer(); IOStatus := FSendIOStatus; if (iRet <> 0) and (iRet <> WSA_IO_PENDING) then begin ErrDesc := Format('[%d][%d]<%s.DoSent.SendBuffer> LastErrorCode=%d, Status=%s, IOStatus=%x', [ FSocket, GetCurrentThreadId(), ClassName, iRet, StatusString(), FIOStatus]); FOwner.WriteLog(llNormal, ErrDesc); end; end else begin IOStatus := InterlockedAnd64(FIOStatus, IO_STATUS_DEL_WRITE_IO); IOStatus := IOStatus and IO_STATUS_DEL_WRITE_IO; end; end; if HasError(IOStatus) or (FStatus and $80000040 = $00000040) then begin if not (HasReadOrReadIO(IOStatus) or HasWriteOrWriteIO(IOStatus)) then FOwner.EnqueueFreeContext(Self); end; end; procedure TTCPIOContext.FillProtocol(pHead: PTCPSocketProtocolHead); begin pHead^.R1[0] := 68; // D pHead^.R1[1] := 89; // Y pHead^.R1[2] := 70; // F pHead^.R2[0] := 90; // Z pHead^.R2[1] := 81; // Q // Crc16 := FCrc16.Compute(FHead, SizeOf(TTCPSocketProtocolHead) - SizeOf(Word), FCrc16.Init); pHead^.CRC16 := FCrc16.Compute(pHead, SizeOf(TTCPSocketProtocolHead) - SizeOf(Word), FCrc16.Init); pHead^.CRC16 := pHead^.CRC16 xor FCrc16.XorOut; end; procedure TTCPIOContext.GetBodyExFileHandle; var iRet: Integer; ErrDesc: string; begin if FBodyExInFile then begin // 由Peer指定的保存地址 if FBodyExFileName <> '' then begin if FileExists(FBodyExFileName) then FBodyExFileHandle := FileOpen(FBodyExFileName, fmOpenWrite or fmShareExclusive) else FBodyExFileHandle := FileCreate(FBodyExFileName, fmShareExclusive, 0); if FBodyExFileHandle <> INVALID_HANDLE_VALUE then begin FileSeek(FBodyExFileHandle, FHead^.LengthEx, 0); SetEndOfFile(FBodyExFileHandle); FileSeek(FBodyExFileHandle, 0, 0); FBodyExUnfilledLength := FHead^.LengthEx; end else begin iRet := GetLastError(); ErrDesc := Format('[%d][%d]<%s.GetBodyExFileHandle.FileOpen or FileCreate> LastErrorCode=%d', [ FSocket, GetCurrentThreadId(), ClassName, iRet]); FOwner.WriteLog(llError, ErrDesc); Set80000000Error(); end; end else begin ErrDesc := Format('[%d][%d]<%s.GetBodyExFileHandle> BodyExFileName=""', [ FSocket, GetCurrentThreadId(), ClassName]); FOwner.WriteLog(llError, ErrDesc); Set80000000Error(); end; end else if FHead^.LengthEx + FHeadSize + FHead^.Length > FRecvBytes + FOwner.MultiIOBufferCount * FOwner.BufferSize then begin FBodyExInFile := True; FBodyExFileName := GetTempFile(); FBodyExFileHandle := FileCreate(FBodyExFileName, fmShareExclusive, 0); if FBodyExFileHandle <> INVALID_HANDLE_VALUE then begin FileSeek(FBodyExFileHandle, FHead^.LengthEx, 0); SetEndOfFile(FBodyExFileHandle); FileSeek(FBodyExFileHandle, 0, 0); FBodyExUnfilledLength := FHead^.LengthEx; FBodyExToBeDeleted := True; end else begin iRet := GetLastError(); ErrDesc := Format('[%d][%d]<%s.GetBodyExFileHandle.FileOpen or FileCreate> LastErrorCode=%d', [ FSocket, GetCurrentThreadId(), ClassName, iRet]); FOwner.WriteLog(llError, ErrDesc); Set80000000Error(); end; end; end; procedure TTCPIOContext.GetBodyFileHandle; var iRet: Integer; ErrDesc: string; begin if FHead^.Length + FHeadSize > FRecvBytes + FOwner.MultiIOBufferCount * FOwner.BufferSize then begin FBodyInFile := True; FBodyFileName := GetTempFile(); FBodyFileHandle := FileCreate(FBodyFileName, fmShareExclusive, 0); if FBodyFileHandle <> INVALID_HANDLE_VALUE then begin FileSeek(FBodyFileHandle, FHead^.LengthEx, 0); SetEndOfFile(FBodyFileHandle); FileSeek(FBodyFileHandle, 0, 0); FBodyUnfilledLength := FHead^.Length; end else begin iRet := GetLastError(); ErrDesc := Format('[%d][%d]<%s.GetBodyFileHandle.FileCreate> LastErrorCode=%d', [ FSocket, GetCurrentThreadId(), ClassName, iRet]); FOwner.WriteLog(llError, ErrDesc); Set80000000Error(); end; end; end; function TTCPIOContext.GetTempFile: string; begin end; procedure TTCPIOContext.HardCloseSocket; begin FStatus := FStatus or $C0000000; FOwner.FIOHandle.HardCloseSocket(FSocket); FSocket := INVALID_SOCKET; end; function TTCPIOContext.HasError(IOStatus: Int64): Boolean; begin Result := IOStatus and IO_STATUS_NOERROR <> IO_STATUS_NOERROR; end; function TTCPIOContext.HasErrorOrReadIO(IOStatus: Int64): Boolean; begin Result := HasError(IOStatus) or HasReadIO(IOStatus); end; function TTCPIOContext.HasIO(IOStatus: Int64): Boolean; begin Result := IOStatus and IO_STATUS_HAS_IO <> IO_STATUS_EMPTY; end; function TTCPIOContext.HasRead(IOStatus: Int64): Boolean; begin Result := IOStatus and IO_STATUS_HAS_READ <> IO_STATUS_EMPTY; end; function TTCPIOContext.HasReadIO(IOStatus: Int64): Boolean; begin Result := IOStatus and IO_STATUS_HAS_READ_IO <> IO_STATUS_EMPTY; end; function TTCPIOContext.HasReadOrReadIO(IOStatus: Int64): Boolean; begin Result := IOStatus and IO_STATUS_HAS_READ_OR_READ_IO <> IO_STATUS_EMPTY; end; function TTCPIOContext.HasWrite(IOStatus: Int64): Boolean; begin Result := IOStatus and IO_STATUS_HAS_WRITE <> IO_STATUS_EMPTY; end; function TTCPIOContext.HasWriteIO(IOStatus: Int64): Boolean; begin Result := IOStatus and IO_STATUS_HAS_WRITE_IO <> IO_STATUS_EMPTY; end; function TTCPIOContext.HasWriteOrIO(IOStatus: Int64): Boolean; begin Result := IOStatus and IO_STATUS_HAS_WRITE_OR_IO <> IO_STATUS_EMPTY; end; function TTCPIOContext.HasWriteOrWriteIO(IOStatus: Int64): Boolean; begin Result := IOStatus and IO_STATUS_HAS_WRITE_OR_WRITE_IO <> IO_STATUS_EMPTY; end; function TTCPIOContext.IsClientIOContext: Boolean; begin Result := FStatus and $20000000 = $20000000; end; function TTCPIOContext.IsServerIOContext: Boolean; begin Result := FStatus and $20000000 = $00000000; end; procedure TTCPIOContext.ParseAndProcessBody; begin end; procedure TTCPIOContext.ParseAndProcessBodyEx; begin end; procedure TTCPIOContext.ParseProtocol; var IOBuffer: PTCPIOBuffer; PC: PAnsiChar; buf: PAnsiChar; Length: DWORD; Unfilled: DWORD; ErrDesc: string; Crc16: Word; begin // 初始化Protocol结构体 Unfilled := FHeadSize; PC := PAnsiChar(FHead); while Unfilled > 0 do begin FOutstandingIOs.Pop(IOBuffer); buf := IOBuffer^.Buffers[0].buf; Inc(buf, IOBuffer^.Position); Length := IOBuffer^.BytesTransferred - IOBuffer^.Position; if Length <= Unfilled then begin Move(buf^, PC^, Length); Inc(PC, Length); Dec(Unfilled, Length); FOwner.EnqueueIOBuffer(IOBuffer); end else begin Move(buf^, PC^, Unfilled); IOBuffer^.Position := IOBuffer^.Position + Unfilled; // dxm 2018.11.13 忘了将此种情况下的Unfilled归零,从而导致了死循环 Unfilled := 0; FOutstandingIOs.Push(IOBuffer^.SequenceNumber, IOBuffer); end; end; if FHead^.Version <> VERSION then begin ErrDesc := Format('[%d][%d]<%s.ParseProtocol> 客户端版本不符, [%s:%d], [%d:%d]', [ FSocket, GetCurrentThreadId(), ClassName, FRemoteIP, FRemotePort, FHead^.Version, VERSION]); FOwner.WriteLog(llError, ErrDesc); Set80000000Error(); end; // pHead^.R1[0] := 68; // pHead^.R1[1] := 89; // pHead^.R1[2] := 70; // // pHead^.R2[0] := 90; // pHead^.R2[1] := 81; if (FHead^.R1[0] <> 68) or (FHead^.R1[1] <> 89) or (FHead^.R1[2] <> 70) or (FHead^.R2[0] <> 90) or (FHead^.R2[1] <> 81) then begin ErrDesc := Format('[%d][%d]<%s.ParseProtocol> 客户端不匹配, [%s:%d]', [ FSocket, GetCurrentThreadId(), ClassName, FRemoteIP, FRemotePort]); FOwner.WriteLog(llError, ErrDesc); Set80000000Error(); end; Crc16 := FCrc16.Compute(FHead, SizeOf(TTCPSocketProtocolHead) - SizeOf(Word), FCrc16.Init); Crc16 := Crc16 xor FCrc16.XorOut; if Crc16 <> FHead^.CRC16 then begin ErrDesc := Format('[%d][%d]<%s.ParseProtocol> Crc16不匹配, [%s:%d], [%d~%d]', [ FSocket, GetCurrentThreadId(), ClassName, FRemoteIP, FRemotePort, FHead^.CRC16, Crc16]); FOwner.WriteLog(llError, ErrDesc); Set80000000Error(); end; end; function TTCPIOContext.RecvBuffer: Int64; var I: Integer; iRet: Integer; ErrDesc: string; IOCount: Integer; IOBuffer: PTCPIOBuffer; IOIndex: Integer; buf: PAnsiChar; begin IOCount := Ceil((FHeadSize + FHead^.Length + FHead^.LengthEx - FRecvBytes) / FOwner.FBufferSize); IOCount := IfThen(IOCount > FOwner.FMultiIOBufferCount, FOwner.FMultiIOBufferCount, IOCount); InterlockedOr64(FIOStatus, IO_STATUS_ADD_READ); for I := 0 to IOCount - 1 do begin IOBuffer := FOwner.DequeueIOBuffer(); IOBuffer^.Context := Self; buf := FOwner.FBufferPool.AllocateBuffer(); IOBuffer^.Buffers[0].buf := buf; IOBuffer^.Buffers[0].len := FOwner.FBufferSize; IOBuffer^.BufferCount := 1; IOBuffer^.OpType := otRead; if I = IOCount - 1 then IOBuffer^.Flags := 0 else IOBuffer^.Flags := MSG_WAITALL; IOBuffer^.SequenceNumber := FNextSequence; Inc(FNextSequence); IOIndex := IOBuffer^.SequenceNumber mod IO_STATUS_READ_CAPACITY; InterlockedOr64(FIOStatus, IO_STATUS_ADD_READ_IO[IOIndex]); iRet := FOwner.IOHandle.PostRecv(FSocket, IOBuffer); if (iRet <> 0) and (iRet <> WSA_IO_PENDING) then begin // 输出日志 ErrDesc := Format('[%d][%d]<%s.RecvBuffer.PostRecv> LastErrorCode=%d, Status=%s', [ FSocket, GetCurrentThreadId(), ClassName, iRet, StatusString()]); FOwner.WriteLog(llError, ErrDesc); // 归还当前IOBuffer FOwner.EnqueueIOBuffer(IOBuffer); Set80000000Error(); InterlockedAnd64(FIOStatus, IO_STATUS_DEL_READ_IO_ADD_ERROR[IOIndex]); Break; end; end; Result := InterlockedAnd64(FIOStatus, IO_STATUS_DEL_READ); Result := Result and IO_STATUS_DEL_READ; end; function TTCPIOContext.RecvDisconnect: Int64; var iRet: Integer; IOBuffer: PTCPIOBuffer; IOIndex: Integer; buf: PAnsiChar; ErrDesc: string; begin // 投递读IO以等待客户端优雅关闭 IOBuffer := FOwner.DequeueIOBuffer(); IOBuffer^.Context := Self; buf := FOwner.FBufferPool.AllocateBuffer(); IOBuffer^.Buffers[0].buf := buf; IOBuffer^.Buffers[0].len := FOwner.FBufferSize; IOBuffer^.BufferCount := 1; IOBuffer^.OpType := {otRead}otGraceful; IOBuffer^.SequenceNumber := FNextSequence; Inc(FNextSequence); InterlockedOr64(FIOStatus, IO_STATUS_ADD_READ); IOIndex := IOBuffer^.SequenceNumber mod IO_STATUS_READ_CAPACITY; InterlockedOr64(FIOStatus, IO_STATUS_ADD_READ_IO[IOIndex]); iRet := FOwner.IOHandle.PostRecv(FSocket, IOBuffer); if (iRet <> 0) and (iRet <> WSA_IO_PENDING) then begin // 失败,套接字应丢弃 // 输出日志 ErrDesc := Format('[%d][%d]<%s.RecvDisconnect.PostRecv> LastErrorCode=%d, Status=%s', [ FSocket, GetCurrentThreadId(), ClassName, iRet, StatusString()]); FOwner.WriteLog(llNormal, ErrDesc); // 归还IOBuffer FOwner.EnqueueIOBuffer(IOBuffer); Set80000000Error(); InterlockedAnd64(FIOStatus, IO_STATUS_DEL_READ_IO_ADD_ERROR[IOIndex]); end; Result := InterlockedAnd64(FIOStatus, IO_STATUS_DEL_READ); Result := Result and IO_STATUS_DEL_READ; end; function TTCPIOContext.RecvProtocol: Int64; var iRet: Integer; IOBuffer: PTCPIOBuffer; IOIndex: Integer; buf: PAnsiChar; ErrDesc: string; begin IOBuffer := FOwner.DequeueIOBuffer(); IOBuffer^.Context := Self; buf := FOwner.FBufferPool.AllocateBuffer(); IOBuffer^.Buffers[0].buf := buf; IOBuffer^.Buffers[0].len := FOwner.FBufferSize; IOBuffer^.BufferCount := 1; IOBuffer^.OpType := otRead; IOBuffer^.SequenceNumber := FNextSequence; Inc(FNextSequence); FIOStatus := FIOStatus or IO_STATUS_ADD_READ; IOIndex := IOBuffer^.SequenceNumber mod IO_STATUS_READ_CAPACITY; FIOStatus := FIOStatus or IO_STATUS_ADD_READ_IO[IOIndex]; iRet := FOwner.IOHandle.PostRecv(FSocket, IOBuffer); if (iRet <> 0) and (iRet <> WSA_IO_PENDING) then begin // 失败,套接字应丢弃 // 输出日志 ErrDesc := Format('[%d][%d]<%s.RecvProtocol.PostRecv> LastErrorCode=%d, Status=%s', [ FSocket, GetCurrentThreadId(), ClassName, iRet, StatusString()]); FOwner.WriteLog(llNormal, ErrDesc); FOwner.EnqueueIOBuffer(IOBuffer); Set80000000Error(); InterlockedAnd64(FIOStatus, IO_STATUS_DEL_READ_IO_ADD_ERROR[IOIndex]); end; Result := InterlockedAnd64(FIOStatus, IO_STATUS_DEL_READ); Result := Result and IO_STATUS_DEL_READ; end; function TTCPIOContext.SendBuffer: Integer; var I: Integer; len: DWORD; IOBuffer: PTCPIOBuffer; ibuf: TBuffer; buf: PAnsiChar; ErrDesc: string; begin I := 0; len := 0; IOBuffer := FOwner.DequeueIOBuffer(); while (FSendBuffers.Count > 0) and (I < FOwner.FMultiIOBufferCount) do begin buf := FOwner.FBufferPool.AllocateBuffer(); IOBuffer^.Buffers[I].buf := buf; IOBuffer^.Buffers[I].len := FOwner.FBufferSize; ibuf := FSendBuffers.GetValue(0); len := len + ibuf.GetBuffer(IOBuffer^.Buffers[I].buf + len, IOBuffer^.Buffers[I].len - len); while len < IOBuffer^.Buffers[I].len do begin ibuf := FSendBuffers.Dequeue(); ibuf.Free(); if FSendBuffers.Count > 0 then begin ibuf := FSendBuffers.GetValue(0); len := len + ibuf.GetBuffer(IOBuffer^.Buffers[I].buf + len, IOBuffer^.Buffers[I].len - len); end else break; end; IOBuffer^.Buffers[I].len := len; len := 0; Inc(I); end; IOBuffer^.BufferCount := I; IOBuffer^.Context := Self; IOBuffer^.Flags := 0; IOBuffer^.OpType := otWrite; InterlockedOr64(FIOStatus, IO_STATUS_ADD_WRITE_WRITE_IO); Result := FOwner.IOHandle.PostSend(FSocket, IOBuffer); if (Result <> 0) and (Result <> WSA_IO_PENDING) then begin // 输出日志 ErrDesc := Format('[%d][%d]<%s.SendBuffer.PostSend> LastErrorCode=%d, Status=%s', [ FSocket, GetCurrentThreadId(), ClassName, Result, StatusString()]); FOwner.WriteLog(llNormal, ErrDesc); // 归还当前IOBuffer FOwner.EnqueueIOBuffer(IOBuffer); Set80000000Error(); FSendIOStatus := InterlockedAnd64(FIOStatus, IO_STATUS_DEL_WRITE_WRITE_IO_ADD_ERROR); // dxm 2018.11.28 FSendIOStatus := FSendIOStatus and IO_STATUS_DEL_WRITE_WRITE_IO; end else begin FSendIOStatus := InterlockedAnd64(FIOStatus, IO_STATUS_DEL_WRITE); // dxm 2018.11.28 FSendIOStatus := FSendIOStatus and IO_STATUS_DEL_WRITE; end; if HasError(FSendIOStatus) or (FStatus and $80000040 = $00000040) then begin if not (HasReadOrReadIO(FSendIOStatus) or HasWriteOrWriteIO(FSendIOStatus)) then begin FOwner.EnqueueFreeContext(Self); end; end; end; function TTCPIOContext.SendDisconnect: Int64; var iRet: Integer; IOBuffer: PTCPIOBuffer; IOIndex: Integer; buf: PAnsiChar; ErrDesc: string; begin IOBuffer := FOwner.DequeueIOBuffer(); IOBuffer^.Context := Self; buf := FOwner.FBufferPool.AllocateBuffer(); IOBuffer^.Buffers[0].buf := buf; IOBuffer^.Buffers[0].len := FOwner.FBufferSize; IOBuffer^.BufferCount := 1; IOBuffer^.OpType := otDisconnect; // dxm 2018.11.10 居然忘了设置这个位,又是2小时过去了... IOBuffer^.Flags := TF_REUSE_SOCKET; IOBuffer^.SequenceNumber := FNextSequence; Inc(FNextSequence); InterlockedOr64(FIOStatus, IO_STATUS_ADD_READ); IOIndex := IOBuffer^.SequenceNumber mod IO_STATUS_READ_CAPACITY; InterlockedOr64(FIOStatus, IO_STATUS_ADD_READ_IO[IOIndex]); iRet := FOwner.IOHandle.PostDisconnect(FSocket, IOBuffer); if iRet <> WSA_IO_PENDING then begin ErrDesc := Format('[%d][%d]<%s.SendDisconnect.PostDisconnect> LastErrorCode=%d, Status=%s', [ FSocket, GetCurrentThreadId(), ClassName, iRet, StatusString()]); FOwner.WriteLog(llNormal, ErrDesc); FOwner.EnqueueIOBuffer(IOBuffer); Set80000000Error(); InterlockedAnd64(FIOStatus, IO_STATUS_DEL_READ_IO_ADD_ERROR[IOIndex]); end; // dxm 2018.11.10 14:20 由于将InterlockedAnd64写成InterlockedAdd64,直接废掉半天,教训啊!!! Result := InterlockedAnd64(FIOStatus, IO_STATUS_DEL_READ); Result := Result and IO_STATUS_DEL_READ; end; function TTCPIOContext.SendToPeer(Body: PAnsiChar; Length: DWORD; BodyEx: TStream; LengthEx, Options: DWORD): Integer; var AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; ByteBuf: TByteBuffer; StreamBuf: TStreamBuffer; SendBusy: Int64; begin Result := 0; AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := LengthEx; FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); FSendBuffers.Lock(); try ByteBuf := TByteBuffer.Create(); ByteBuf.SetBuffer(pHead, FHeadSize); FSendBuffers.EnqueueEx(ByteBuf); ByteBuf := TByteBuffer.Create(); ByteBuf.SetBuffer(Body, Length); FSendBuffers.EnqueueEx(ByteBuf); StreamBuf := TStreamBuffer.Create(); StreamBuf.SetBuffer(BodyEx); FSendBuffers.EnqueueEx(StreamBuf); finally FSendBuffers.Unlock(); end; SendBusy := InterlockedAdd64(FSendBusy, FHeadSize + Length + LengthEx); if SendBusy - FHeadSize - Length = 0 then Result:= SendBuffer(); end; function TTCPIOContext.SendToPeer(Body: PAnsiChar; Length: DWORD; FilePath: string; Options: DWORD): Integer; var AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; ByteBuf: TByteBuffer; FileHandle: THandle; FileLength: Int64; FileBuf: TFileBuffer; SendBusy: Int64; begin Result := 0; FileHandle := FileOpen(FilePath, fmOpenRead or fmShareDenyWrite); if FileHandle <> INVALID_HANDLE_VALUE then begin FileLength := FileSeek(FileHandle, 0, 2); AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := FileLength; FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); FSendBuffers.Lock(); try ByteBuf := TByteBuffer.Create(); ByteBuf.SetBuffer(pHead, FHeadSize); FSendBuffers.EnqueueEx(ByteBuf); ByteBuf := TByteBuffer.Create(); ByteBuf.SetBuffer(Body, Length); FSendBuffers.EnqueueEx(ByteBuf); FileBuf := TFileBuffer.Create(); FileBuf.SetBuffer(FileHandle, FileLength); FSendBuffers.EnqueueEx(FileBuf); finally FSendBuffers.Unlock(); end; SendBusy := InterlockedAdd64(FSendBusy, FHeadSize + Length + FileLength); if SendBusy - FHeadSize - Length - FileLength = 0 then Result:= SendBuffer(); end else begin FreeMem(Body, Length); Result := GetLastError(); end; end; function TTCPIOContext.SendToPeer(Body: PAnsiChar; Length, Options: DWORD): Integer; var AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; buf: TByteBuffer; SendBusy: Int64; begin Result := 0; AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := 0; FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); FSendBuffers.Lock(); try buf := TByteBuffer.Create(); buf.SetBuffer(pHead, FHeadSize); FSendBuffers.EnqueueEx(buf); buf := TByteBuffer.Create(); buf.SetBuffer(Body, Length); FSendBuffers.EnqueueEx(buf); finally FSendBuffers.Unlock(); end; SendBusy := InterlockedAdd64(FSendBusy, FHeadSize + Length); if SendBusy - FHeadSize - Length = 0 then Result:= SendBuffer(); end; function TTCPIOContext.SendToPeer(Body: PAnsiChar; Length: DWORD; BodyEx: PAnsiChar; LengthEx, Options: DWORD): Integer; var AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; buf: TByteBuffer; SendBusy: Int64; begin Result := 0; AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := LengthEx; FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); FSendBuffers.Lock(); try buf := TByteBuffer.Create(); buf.SetBuffer(pHead, FHeadSize); FSendBuffers.EnqueueEx(buf); buf := TByteBuffer.Create(); buf.SetBuffer(Body, Length); FSendBuffers.EnqueueEx(buf); buf := TByteBuffer.Create(); buf.SetBuffer(BodyEx, LengthEx); FSendBuffers.EnqueueEx(buf); finally FSendBuffers.Unlock(); end; SendBusy := InterlockedAdd64(FSendBusy, FHeadSize + Length + LengthEx); if SendBusy - FHeadSize - Length = 0 then Result:= SendBuffer(); end; function TTCPIOContext.SendToPeer(Body: TStream; Length: DWORD; BodyEx: TStream; LengthEx, Options: DWORD): Integer; var AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; ByteBuf: TByteBuffer; StreamBuf: TStreamBuffer; SendBusy: Int64; begin Result := 0; AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := LengthEx; FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); FSendBuffers.Lock(); try ByteBuf := TByteBuffer.Create(); ByteBuf.SetBuffer(pHead, FHeadSize); FSendBuffers.EnqueueEx(ByteBuf); StreamBuf := TStreamBuffer.Create(); StreamBuf.SetBuffer(Body); FSendBuffers.EnqueueEx(StreamBuf); StreamBuf := TStreamBuffer.Create(); StreamBuf.SetBuffer(BodyEx); FSendBuffers.EnqueueEx(StreamBuf); finally FSendBuffers.Unlock(); end; SendBusy := InterlockedAdd64(FSendBusy, FHeadSize + Length + LengthEx); if SendBusy - FHeadSize - Length = 0 then Result:= SendBuffer(); end; function TTCPIOContext.SendToPeer(Body: TStream; Length: DWORD; FilePath: string; Options: DWORD): Integer; var AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; ByteBuf: TByteBuffer; StreamBuf: TStreamBuffer; FileHandle: THandle; FileLength: Int64; FileBuf: TFileBuffer; SendBusy: Int64; begin Result := 0; FileHandle := FileOpen(FilePath, fmOpenRead or fmShareDenyWrite); if FileHandle <> INVALID_HANDLE_VALUE then begin FileLength := FileSeek(FileHandle, 0, 2); AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := FileLength; FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); FSendBuffers.Lock(); try ByteBuf := TByteBuffer.Create(); ByteBuf.SetBuffer(pHead, FHeadSize); FSendBuffers.EnqueueEx(ByteBuf); StreamBuf := TStreamBuffer.Create(); StreamBuf.SetBuffer(Body); FSendBuffers.EnqueueEx(StreamBuf); FileBuf := TFileBuffer.Create(); FileBuf.SetBuffer(FileHandle, FileLength); FSendBuffers.EnqueueEx(FileBuf); finally FSendBuffers.Unlock(); end; SendBusy := InterlockedAdd64(FSendBusy, FHeadSize + Length + FileLength); if SendBusy - FHeadSize - Length - FileLength = 0 then Result:= SendBuffer(); end else begin Body.Free(); Result := GetLastError(); end; end; function TTCPIOContext.SendToPeer(Body: TStream; Length, Options: DWORD): Integer; var AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; ByteBuf: TByteBuffer; StreamBuf: TStreamBuffer; SendBusy: Int64; begin Result := 0; AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := 0; FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); FSendBuffers.Lock(); try ByteBuf := TByteBuffer.Create(); ByteBuf.SetBuffer(pHead, FHeadSize); FSendBuffers.EnqueueEx(ByteBuf); StreamBuf := TStreamBuffer.Create(); StreamBuf.SetBuffer(Body); FSendBuffers.EnqueueEx(StreamBuf); finally FSendBuffers.Unlock(); end; SendBusy := InterlockedAdd64(FSendBusy, FHeadSize + Length); if SendBusy - FHeadSize - Length = 0 then Result:= SendBuffer(); end; function TTCPIOContext.SendToPeer(Body: TStream; Length: DWORD; BodyEx: PAnsiChar; LengthEx, Options: DWORD): Integer; var AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; ByteBuf: TByteBuffer; StreamBuf: TStreamBuffer; SendBusy: Int64; begin Result := 0; AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := LengthEx; FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); FSendBuffers.Lock(); try ByteBuf := TByteBuffer.Create(); ByteBuf.SetBuffer(pHead, FHeadSize); FSendBuffers.EnqueueEx(ByteBuf); StreamBuf := TStreamBuffer.Create(); StreamBuf.SetBuffer(Body); FSendBuffers.EnqueueEx(StreamBuf); ByteBuf := TByteBuffer.Create(); ByteBuf.SetBuffer(BodyEx, LengthEx); FSendBuffers.EnqueueEx(ByteBuf); finally FSendBuffers.Unlock(); end; SendBusy := InterlockedAdd64(FSendBusy, FHeadSize + Length + LengthEx); if SendBusy - FHeadSize - Length = 0 then Result:= SendBuffer(); end; function TTCPIOContext.DoSequenceNumCompare(const Value1, Value2: Integer): Integer; begin Result := Value1 - Value2; end; procedure TTCPIOContext.Set80000000Error; begin FStatus := FStatus or $80000000; end; function TTCPIOContext.StatusString: string; begin //00000000,00000000,00000000,00000000 [$00000000][闲置] //00000000,00000000,00000000,00000001 [$00000001][连接中] //00000000,00000000,00000000,00000010 [$00000002][已连接] //00000000,00000000,00000000,00000100 [$00000004][协议头读取] //00000000,00000000,00000000,00001000 [$00000008][Body已读取] //00000000,00000000,00000000,00010000 [$00000010][BodyEx已读取] //00000000,00000000,00000000,00100000 [$00000020][Graceful IO 已返回] //00000000,00000000,00000000,01000000 [$00000040][DisconnectEx IO 已返回] //........,........,........,........ //00100000,00000000,00000000,00000000 [$20000000][1:客户端通信套接字][0:服务端通信套接字] //01000000,00000000,00000000,00000000 [$40000000][套接字已被关闭] //10000000,00000000,00000000,00000000 [$80000000][出错] // Result := ''; if FStatus and $00000001 = $00000001 then Result := Result + '[连接中]'; if FStatus and $00000002 = $00000002 then Result := Result + '[已连接]'; if FStatus and $00000004 = $00000004 then Result := Result + '[协议头已读取]'; if FStatus and $00000008 = $00000008 then Result := Result + '[Body已读取]'; if FStatus and $00000010 = $00000010 then Result := Result + '[BodyEx已读取]'; if FStatus and $00000020 = $00000020 then Result := Result + '[Graceful IO 已返回]'; if FStatus and $00000040 = $00000040 then Result := Result + '[DisconnectEx IO 已返回]'; if FStatus and $20000000 = $20000000 then Result := Result + '[客户端套接字]' else Result := Result + '[服务端套接字]'; if FStatus and $40000000 = $40000000 then Result := Result + '[套接字已被关闭]'; if FStatus and $80000000 = $80000000 then Result := Result + '[套接字上有错误]'; if Result = '' then Result := '[闲置]'; end; procedure TTCPIOContext.WriteBodyExToFile; var IOBuffer: PTCPIOBuffer; PC: PAnsiChar; Length: DWORD; begin while (FBodyExUnfilledLength > 0) and FOutstandingIOs.Pop(IOBuffer) do begin PC := IOBuffer^.Buffers[0].buf; Inc(PC, IOBuffer^.Position); Length := IOBuffer^.BytesTransferred - IOBuffer^.Position; if Length <= FBodyExUnfilledLength then begin FileWrite(FBodyExFileHandle, PC^, Length); Dec(FBodyExUnfilledLength, Length); FOwner.EnqueueIOBuffer(IOBuffer); end // dxm 2018.11.16 // [old: 无此分支] else begin FileWrite(FBodyExFileHandle, PC^, FBodyExUnfilledLength); IOBuffer^.Position := IOBuffer^.Position + FBodyExUnfilledLength; FBodyExUnfilledLength := 0; FOwner.EnqueueIOBuffer(IOBuffer); end; end; if FBodyExUnfilledLength = 0 then begin FileClose(FBodyExFileHandle); FBodyExFileHandle := INVALID_HANDLE_VALUE; end; end; procedure TTCPIOContext.WriteBodyToFile; var IOBuffer: PTCPIOBuffer; PC: PAnsiChar; Length: DWORD; begin while (FBodyUnfilledLength > 0) and FOutstandingIOs.Pop(IOBuffer) do begin PC := IOBuffer^.Buffers[0].buf; Inc(PC, IOBuffer^.Position); Length := IOBuffer^.BytesTransferred - IOBuffer^.Position; if Length <= FBodyUnfilledLength then begin FileWrite(FBodyFileHandle, PC^, Length); Dec(FBodyUnfilledLength, Length); FOwner.EnqueueIOBuffer(IOBuffer); end else begin FileWrite(FBodyFileHandle, PC^, FBodyUnfilledLength); // dxm 2018.11.16 // 可能一个buffer=protocol+body+part of bodyex [old: IOBuffer^.Position := FBodyUnfilledLength;] IOBuffer^.Position := IOBuffer^.Position + FBodyUnfilledLength; FBodyUnfilledLength := 0; FOutstandingIOs.Push(IOBuffer^.SequenceNumber, IOBuffer); end; end; if FBodyUnfilledLength = 0 then begin FileClose(FBodyFileHandle); FBodyFileHandle := INVALID_HANDLE_VALUE; end; end; { TTCPIOManager } function TTCPIOManager.AllocateIOBuffer: PTCPIOBuffer; begin Result := AllocMem(SizeOf(TTCPIOBuffer)); end; constructor TTCPIOManager.Create; begin FLogNotify := nil; FConnectedNotify := nil; FRecvedNotify := nil; FSentNotify := nil; FDisconnectingNotify := nil; //\\ FLogLevel := llNormal; FTempDirectory := ''; FBuffersInUsed := 0; //\\ FHeadSize := SizeOf(TTCPSocketProtocolHead); // 默认值。切记当修改了协议头后一定要修改中这个属性 FBufferSize := GetPageSize(); FMultiIOBufferCount := MULTI_IO_BUFFER_COUNT; //\\ FTimeWheel := TTimeWheel<TTCPIOContext>.Create(); // 延迟到派生类的Start函数中创建并初始化 // FBufferPool := TBufferPool.Create(); // FBufferPool.Initialize(); // FIOBuffers := TFlexibleQueue<PTCPIOBuffer>.Create(64); // FIOBuffers.OnItemNotify := DoIOBufferNotify; FIOHandle := TTCPIOHandle.Create(2 * GetNumberOfProcessors()); end; function TTCPIOManager.DequeueIOBuffer: PTCPIOBuffer; begin InterlockedIncrement(FBuffersInUsed); Result := FIOBuffers.Dequeue(); if Result = nil then begin Result := AllocateIOBuffer(); ZeroMemory(@Result^.lpOverlapped, SizeOf(OVERLAPPED)); //\\ dxm 2018.12.04 SetLength(Result^.Buffers, FMultiIOBufferCount); //\\ Result^.LastErrorCode := 0; Result^.CompletionKey := 0; Result^.BytesTransferred := 0; Result^.BufferCount := 0; Result^.Flags := 0; Result^.Position := 0; Result^.SequenceNumber := 0; Result^.OpType := otNode; Result^.Context := nil; end; end; destructor TTCPIOManager.Destroy; begin FIOHandle.Free(); FTimeWheel.Free(); inherited; end; function TTCPIOManager.DoConnectEx(IOBuffer: PTCPIOBuffer): Boolean; var iRet: Integer; ErrDesc: string; IOContext: TTCPIOContext; begin // dxm 2018.11.1 // 1. 判断IO是否出错 // 2. 初始化套接字上下文 // 3. 关联通信套接字与IO完成端口 // dxm 2018.11.13 // 当ConnectEx重叠IO通知到达时: // 1. WSAECONNREFUSED [10061] 通常是对端服务器未启动 [通知时][调用时][正常][可重用] // 2. WSAENETUNREACH [10051] 网络不可达,通常是路由无法探知远端 [通知时][调用时][正常][可重用] // 3. WSAETIMEDOUT [10060] 连接超时 [通知时][------][正常][可重用][分析:服务端投递的预连接太少,需动态设置预投递上限] Result := True; IOContext := IOBuffer^.Context; if IOBuffer^.LastErrorCode = 0 then begin {$region [IO 正常]} // dxm 2018.11.13 // 激活套接字之前的属性 // 本函数不应该错误,否则要么是参数设置有问题,要么是理解偏差 // 如果出错暂时定为 [致命][不可重用 ] iRet := setsockopt(IOContext.FSocket, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, nil, 0); if iRet <> SOCKET_ERROR then begin IOContext.FStatus := IOContext.FStatus or $00000002; // [连接中][已连接] end else begin //if iRet = SOCKET_ERROR then begin // [更新套接字属性失败] Result := False; IOContext.Set80000000Error(); iRet := WSAGetLastError(); ErrDesc := Format('[%d][%d]<%s.DoConnectEx.setsockopt> LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, iRet, IOContext.StatusString()]); WriteLog(llFatal, ErrDesc); end; {$endregion} end else begin // dxm 2018.11.13 // 当ConnectEx重叠IO通知到达时: // 1. WSAECONNREFUSED [10061] 通常是对端服务器未启动 [通知时][调用时][正常][可重用] // 2. WSAENETUNREACH [10051] 网络不可达,通常是路由无法探知远端 [通知时][调用时][正常][可重用] // 3. WSAETIMEDOUT [10060] 连接超时 [通知时][------][正常][可重用] Result := False; iRet := IOBuffer^.LastErrorCode; if (iRet <> WSAECONNREFUSED) or (iRet <> WSAENETUNREACH) or (iRet <> WSAETIMEDOUT) then IOContext.Set80000000Error(); ErrDesc := Format('[%d][%d]<%s.DoConnectEx> IO内部错误: LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, iRet, IOContext.StatusString()]); WriteLog(llError, ErrDesc); end; EnqueueIOBuffer(IOBuffer); if not Result then EnqueueFreeContext(IOContext); end; procedure TTCPIOManager.DoIOBufferNotify(const IOBuffer: PTCPIOBuffer; Action: TActionType); begin if Action = atDelete then ReleaseIOBuffer(IOBuffer); end; procedure TTCPIOManager.DoIOContextNotify(const IOContext: TTCPIOContext; Action: TActionType); begin if Action = atDelete then IOContext.Free(); end; procedure TTCPIOManager.DoWaitFirstData(IOContext: TTCPIOContext); var iRet: Integer; RefCount: Integer; OptSeconds: Integer; OptLen: Integer; IOStatus: Int64; ErrDesc: string; begin RefCount := InterlockedDecrement(IOContext.FRefCount); if (RefCount = 0) and (IOContext.FSocket <> INVALID_SOCKET) then begin OptSeconds := 0; OptLen := SizeOf(OptSeconds); iRet := getsockopt(IOContext.FSocket, SOL_SOCKET, SO_CONNECT_TIME, @OptSeconds, OptLen); if iRet <> 0 then begin // IOContext.HardCloseSocket(); end else begin IOStatus := InterlockedAdd64(IOContext.FIOStatus, 0); if (IOContext.FStatus and $8000007F = $00000003) and // 1000,0000,...,0111,1111 (IOContext.HasReadIO(IOStatus)) and (IOContext.FNextSequence = 1) and (OptSeconds >= MAX_FIRSTDATA_TIME - 1) then begin ErrDesc := Format('[%d][%d]<%s.DoWaitFirstData> [%s:%d] time=%ds', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, IOContext.FRemoteIP, IOContext.FRemotePort, OptSeconds]); WriteLog(llWarning, ErrDesc); IOContext.HardCloseSocket(); end; end; end; end; procedure TTCPIOManager.EnqueueFreeContext(AContext: TTCPIOContext); var IOBuffer: PTCPIOBuffer; {$IfDef DEBUG} Msg: string; {$Endif} begin {$IfDef DEBUG} Msg := Format('[%d][%d]<%s.EnqueueFreeContext> be to enqueue a free context, Status=%s, IOStatux=%x', [ AContext.FSocket, GetCurrentThreadId(), ClassName, AContext.StatusString(), AContext.FIOStatus]); WriteLog(llDebug, Msg); {$Endif} AContext.FSendBytes := 0; AContext.FRecvBytes := 0; AContext.FNextSequence := 0; AContext.FIOStatus := IO_STATUS_INIT; AContext.FSendIOStatus := IO_STATUS_INIT; AContext.FSendBusy := 0; while AContext.FOutstandingIOs.Pop(IOBuffer) do EnqueueIOBuffer(IOBuffer); AContext.FSendBuffers.Clear(); if AContext.FBodyInFile then begin if AContext.FBodyFileHandle <> INVALID_HANDLE_VALUE then begin FileClose(AContext.FBodyFileHandle); AContext.FBodyFileHandle := INVALID_HANDLE_VALUE; end; DeleteFile(AContext.FBodyFileName); AContext.FBodyInFile := False; end; if AContext.FBodyExInFile then begin if AContext.FBodyExToBeDeleted or (AContext.FStatus and $80000000 = $80000000) then begin if AContext.FBodyExFileHandle <> INVALID_HANDLE_VALUE then begin FileClose(AContext.FBodyExFileHandle); AContext.FBodyExFileHandle := INVALID_HANDLE_VALUE; end; DeleteFile(AContext.FBodyExFileName); end; AContext.FBodyExInFile := False; AContext.FBodyExToBeDeleted := False; end; end; procedure TTCPIOManager.EnqueueIOBuffer(IOBuffer: PTCPIOBuffer); var I: Integer; begin InterlockedDecrement(FBuffersInUsed); // dxm 2018.11.5 // 1.将IOBuffer携带的内存块归还FBufferPool // 2.IOBuffer各成员初始化为默认值 // 3.将IOBuffer归还FIOBuffers for I := 0 to IOBuffer^.BufferCount - 1 do begin if IOBuffer^.Buffers[I].buf <> nil then begin FBufferPool.ReleaseBuffer(IOBuffer^.Buffers[I].buf); IOBuffer^.Buffers[I].buf := nil; IOBuffer^.Buffers[I].len := 0; end; end; IOBuffer^.BufferCount := 0; IOBuffer^.Context := nil; IOBuffer^.LastErrorCode := 0; IOBuffer^.CompletionKey := 0; IOBuffer^.BytesTransferred := 0; IOBuffer^.Position := 0; IOBuffer^.SequenceNumber := 0; IOBuffer^.Flags := 0; IOBuffer^.OpType := otNode; ZeroMemory(@IOBuffer^.lpOverlapped, SizeOf(IOBuffer^.lpOverlapped)); FIOBuffers.Enqueue(IOBuffer); end; function TTCPIOManager.ListenAddr(LocalIP: string; LocalPort: Word): TSocket; var iRet: Integer; dwRet: DWORD; ErrDesc: string; ServerAddr: TSockAddrIn; begin // 创建一个阻塞,重叠模式监听套接字 Result := WSASocket(PF_INET, SOCK_STREAM, IPPROTO_TCP, nil, 0, WSA_FLAG_OVERLAPPED); if Result = INVALID_SOCKET then begin iRet := WSAGetLastError(); ErrDesc := Format('[%d]<%s.ListenAddr.WSASocket> failed with error: %d', [ GetCurrentThreadId(), ClassName, iRet]); WriteLog(llFatal, ErrDesc); Exit; end; // set SO_REUSEADDR option FillChar(ServerAddr, SizeOf(ServerAddr), #0); ServerAddr.sin_family := AF_INET; if (LocalIP = '') or (LocalIP = '0.0.0.0') then ServerAddr.sin_addr.S_addr := htonl(INADDR_ANY) else ServerAddr.sin_addr.S_addr := inet_addr(PAnsiChar(AnsiString(LocalIP))); ServerAddr.sin_port := htons(LocalPort); // 关联本地地址 if bind(Result, TSockAddr(ServerAddr), SizeOf(ServerAddr)) = SOCKET_ERROR then begin iRet := WSAGetLastError(); CloseSocket(Result); Result := INVALID_SOCKET; ErrDesc := Format('[%d]<%s.ListenAddr.bind> failed with error: %d', [ GetCurrentThreadId(), ClassName, iRet]); WriteLog(llFatal, ErrDesc); Exit; end; // 关联完成端口 dwRet := FIOHandle.AssociateDeviceWithCompletionPort(Result, 0); if dwRet <> 0 then begin closesocket(Result); Result := INVALID_SOCKET; ErrDesc := Format('[%d]<%s.ListenAddr.AssociateDeviceWithCompletionPort> failed with error: %d', [ GetCurrentThreadId(), ClassName, dwRet]); WriteLog(llFatal, ErrDesc); Exit; end; // 启动监听 if listen(Result, 1024) = SOCKET_ERROR then begin iRet := WSAGetLastError(); closesocket(Result); Result := INVALID_SOCKET; ErrDesc := Format('[%d]<%s.ListenAddr.listen> failed with error: %d', [ GetCurrentThreadId(), ClassName, iRet]); WriteLog(llFatal, ErrDesc); end; end; function TTCPIOManager.PostMultiAccept(IOSocket: TSocket; Count: Integer): Integer; var iRet: Integer; ErrDesc: string; begin Result := 0; while Count > 0 do begin iRet := PostSingleAccept(IOSocket); if (iRet = 0) or (iRet = WSA_IO_PENDING) then begin Inc(Result); end else begin ErrDesc := Format('[%d][%d]<%s.PostMultiAccept.PostSingleAccept> LastErrorCode=%d', [ IOSocket, GetCurrentThreadId(), ClassName, iRet]); WriteLog(llNormal, ErrDesc); end; Dec(Count); end; end; function TTCPIOManager.PostSingleAccept(IOSocket: TSocket): Integer; var IOContext: TTCPIOContext; IOBuffer: PTCPIOBuffer; buf: PAnsiChar; ErrDesc: string; begin // dxm 2018.11.5 // 如果投递预连接失败,IOBuffer和IOContext可直接回收 IOContext := DequeueFreeContext($00000000); IOContext.FStatus := IOContext.FStatus or $00000001; // [连接中] IOBuffer := DequeueIOBuffer(); buf := FBufferPool.AllocateBuffer(); IOBuffer^.Buffers[0].buf := buf; IOBuffer^.Buffers[0].len := FBufferSize; IOBuffer^.BufferCount := 1; IOBuffer^.Context := IOContext; IOBuffer^.OpType := otConnect; Result := FIOHandle.PostAccept(IOSocket, IOBuffer); // dxm 2018.11.6 // if (IOContext.FSocket = INVALID_SOCKET) or (IOContext.FStatus and $80000000 = $80000000) then begin // --> if (Result <> 0) and (Result <> WSA_IO_PENDING) then begin // 原则是Post系列函数,只做本质工作,其它事情交由调用方处理 if (Result <> 0) and (Result <> WSA_IO_PENDING) then begin if IOContext.FSocket <> INVALID_SOCKET then IOContext.Set80000000Error(); ErrDesc := Format('[%d][%d]<%s.PostSingleAccept.PostAccept> LastErrorCode=%d', [ IOSocket, GetCurrentThreadId(), ClassName, Result]); WriteLog(llNormal, ErrDesc); // 回收IOBuffer EnqueueIOBuffer(IOBuffer); // 回收通信上下文 EnqueueFreeContext(IOContext); end; end; function TTCPIOManager.PrepareMultiIOContext(AClass: TTCPIOContextClass; Count: Integer): Integer; var bRet: Boolean; ErrDesc: string; IOContext: TTCPIOContext; begin Result := 0; while Count > 0 do begin IOContext := AClass.Create(Self); bRet := PrepareSingleIOContext(IOContext); if bRet then begin Inc(Result); end else begin ErrDesc := Format('[%d]<%s.PostMultiAccept.PrepareSingleIOContext> failed', [ GetCurrentThreadId(), ClassName]); WriteLog(llNormal, ErrDesc); end; Dec(Count); EnqueueFreeContext(IOContext); end; end; function TTCPIOManager.PrepareSingleIOContext(IOContext: TTCPIOContext): Boolean; var TempAddr: TSockAddrIn; iRet: Integer; dwRet: DWORD; OptVal: Integer; ErrDesc: string; begin // dxm 2018.11.13 // 传入ConnectEx的通信套接字必须是绑定,非连接的。为此,在使用其进行通信之前,要先绑定,并关联到IOCP Result := True; if IOContext.FSocket = INVALID_SOCKET then begin // dxm 2018.11.2 // WSAEMFILE 没有可用套接字资源 [致命] // WSAENOBUFS 没有可用内存以创建套接字对象 [致命] // 上述2个错误显然是[致命]错误 IOContext.FSocket := WSASocket( AF_INET, SOCK_STREAM, IPPROTO_TCP, nil, 0, WSA_FLAG_OVERLAPPED); if IOContext.FSocket = INVALID_SOCKET then begin Result := False; iRet := WSAGetLastError(); // 输出日志 ErrDesc := Format('[][%d]<%s.PrepareSingleIOContext.WSASocket> LastErrorCode=%d', [ GetCurrentThreadId(), ClassName, iRet]); WriteLog(llFatal, ErrDesc); Exit; end; OptVal := 1; iRet := setsockopt(IOContext.FSocket, SOL_SOCKET, SO_REUSEADDR, @OptVal, SizeOf(OptVal)); if iRet = SOCKET_ERROR then begin Result := False; iRet := WSAGetLastError(); // 输出日志 ErrDesc := Format('[][%d]<%s.PrepareSingleIOContext.setsockopt> LastErrorCode=%d', [ GetCurrentThreadId(), ClassName, iRet]); WriteLog(llFatal, ErrDesc); IOContext.Set80000000Error(); Exit; end; ZeroMemory(@TempAddr, SizeOf(TSockAddrIn)); TempAddr.sin_family := AF_INET; TempAddr.sin_addr.S_addr := htonl(INADDR_ANY); TempAddr.sin_port := htons(Word(0)); // 关联本地地址 if bind(IOContext.FSocket, TSockAddr(TempAddr), SizeOf(TempAddr)) = SOCKET_ERROR then begin Result := False; iRet := WSAGetLastError(); // 输出日志 ErrDesc := Format('[%d][%d]<%s.PrepareSingleIOContext.bind> LastErrorCode=%d', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, iRet]); WriteLog(llFatal, ErrDesc); IOContext.Set80000000Error(); Exit; end; end; dwRet := FIOHandle.AssociateDeviceWithCompletionPort(IOContext.FSocket, 0); if dwRet <> 0 then begin Result := False; ErrDesc := Format('[%d][%d]<%s.PrepareSingleIOContext.AssociateDeviceWithCompletionPort> LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, dwRet, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); IOContext.Set80000000Error(); end; end; procedure TTCPIOManager.ReleaseIOBuffer(IOBuffer: PTCPIOBuffer); begin FreeMem(IOBuffer, SizeOf(TTCPIOBuffer)); end; procedure TTCPIOManager.SetLogLevel(const Value: TLogLevel); begin FLogLevel := Value; FIOHandle.LogLevel := Value; end; procedure TTCPIOManager.SetLogNotify(const Value: TLogNotify); begin FLogNotify := Value; FIOHandle.OnLogNotify := Value; end; procedure TTCPIOManager.SetMultiIOBufferCount(const Value: Integer); var AValue: Integer; begin AValue := Value; if Value > IO_STATUS_READ_CAPACITY then AValue := IO_STATUS_READ_CAPACITY; if Value = 0 then AValue := MULTI_IO_BUFFER_COUNT; FMultiIOBufferCount := AValue; end; procedure TTCPIOManager.SetTempDirectory(const Value: string); begin FTempDirectory := Value; end; procedure TTCPIOManager.Start; begin FTimeWheel.Start(); FIOHandle.Start(); end; procedure TTCPIOManager.Stop; begin end; procedure TTCPIOManager.WriteLog(LogLevel: TLogLevel; LogContent: string); begin if Assigned(FLogNotify) then begin LogContent := '[' + LOG_LEVLE_DESC[LogLevel] + ']' + LogContent; FLogNotify(nil, LogLevel, LogContent); end; end; end.
unit rhlMurmur3; interface uses rhlCore; type { TrhlMurmur3 } TrhlMurmur3 = class(TrhlHashWithKey) private const CKEY: DWord = $C58F1A7B; var m_h: DWord; m_key: DWord; protected procedure UpdateBytes(const ABuffer; ASize: LongWord); override; function GetKey: TBytes; override; procedure SetKey(AValue: TBytes); override; public constructor Create; override; procedure Init; override; procedure Final(var ADigest); override; end; implementation { TrhlMurmur3 } procedure TrhlMurmur3.UpdateBytes(const ABuffer; ASize: LongWord); const c: array[1..5] of DWord = ( $CC9E2D51, $1B873593, $E6546B64, $85EBCA6B, $C2B2AE35); var ci: Integer; k: DWord; a_data: array[0..0] of Byte absolute ABuffer; len: DWord; begin m_h := m_key; ci := 0; len := ASize; while (len >= 4) do begin k := (a_data[ci+0]) or (a_data[ci+1] shl 8) or (a_data[ci+2] shl 16) or (a_data[ci+3] shl 24); k := RolDWord(k * C[1], 15) * C[2]; m_h := RolDWord(m_h xor k, 13) * 5 + C[3]; Inc(ci, 4); Dec(len, 4); end; case (len) of 3: k := (a_data[ci + 2] shl 16) or (a_data[ci + 1] shl 8) or a_data[ci]; 2: k := (a_data[ci + 1] shl 8) or a_data[ci]; 1: k := a_data[ci]; end; if len >= 1 then m_h := m_h xor RolDWord(k * C[1], 15) * C[2]; m_h := m_h xor ASize; m_h := m_h xor (m_h shr 16); m_h := m_h * C[4]; m_h := m_h xor (m_h shr 13); m_h := m_h * C[5]; m_h := m_h xor (m_h shr 16); end; function TrhlMurmur3.GetKey: TBytes; begin SetLength(Result, SizeOf(m_key)); Move(m_key, Result[0], SizeOf(m_key)); end; procedure TrhlMurmur3.SetKey(AValue: TBytes); begin if Length(AValue) = SizeOf(m_key) then Move(AValue[0], m_key, SizeOf(m_key)); end; constructor TrhlMurmur3.Create; begin HashSize := 4; BlockSize := 4; m_key := CKEY; end; procedure TrhlMurmur3.Init; begin inherited Init; m_h := m_key; end; procedure TrhlMurmur3.Final(var ADigest); begin Move(m_h, ADigest, 4); end; end.
unit uclsClasses; interface uses IdSMTP, IdSSLOpenSSL, IdMessage, IdText, IdAttachmentFile, IdExplicitTLSClientServerBase, System.StrUtils, System.Classes; type IEnviarEmail = interface ['{DAB06D13-6455-4EAB-9424-EFD1A2C2E7A2}'] procedure Enviar(AAssunto, ADestino, AAnexo: String; ACorpo: TStrings); end; TEnviarEmail = class(TInterfacedObject, IEnviarEmail) private public procedure Enviar(AAssunto, ADestino, AAnexo: String; ACorpo: TStrings); end; TCEP = class(TPersistent) private FCEP : String; FLogradouro : String; FComplemento : String; FBairro : string; FLocalidade : string; FUF : String; FUnidade : String; FIBGE : String; FGIA : String; published property CEP : String read FCEP write FCEP; property Logradouro : String read FLogradouro; property Complemento : String read FComplemento; property Bairro : String read FBairro; property Localidade : string read FLocalidade; property UF : String read FUF; property Unidade : String read FUnidade; property IBGE : String read FIBGE; property GIA : String read FGIA; end; TClient = class(TPersistent) private FNome : String; FIdentidade : String; FCPF : String; FEmail : String; FTelefone : String; FCEP : TCEP; published property Nome : String read FNome write FNome; property Identidade : String read FIdentidade write FIdentidade; property CPF : String read FCPF write FCPF; property Email : String read FEmail write FEmail; property Telefone : String read FTelefone write FTelefone; property CEP : TCEP read FCEP write FCEP; end; implementation uses System.SysUtils, Vcl.Dialogs; { TEnviarEmail } procedure TEnviarEmail.Enviar(AAssunto, ADestino, AAnexo: String; ACorpo: TStrings); var IdSSLIOHandlerSocket: TIdSSLIOHandlerSocketOpenSSL; IdSMTP: TIdSMTP; IdMessage: TIdMessage; IdText: TIdText; sAnexo: string; begin // instanciação dos objetos IdSSLIOHandlerSocket := TIdSSLIOHandlerSocketOpenSSL.Create(nil); IdSMTP := TIdSMTP.Create(nil); IdMessage := TIdMessage.Create(nil); try // Configuração do protocolo SSL (TIdSSLIOHandlerSocketOpenSSL) IdSSLIOHandlerSocket.SSLOptions.Method := sslvSSLv23; IdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient; // Configuração do servidor SMTP (TIdSMTP) IdSMTP.IOHandler := IdSSLIOHandlerSocket; IdSMTP.UseTLS := utUseImplicitTLS; IdSMTP.AuthType := satDefault; IdSMTP.Port := 465; IdSMTP.Host := 'smtp.gmail.com'; IdSMTP.Username := 'email@gmail.com'; IdSMTP.Password := 'senha'; IdMessage.From.Address := 'brenno@gmail.com'; IdMessage.From.Name := 'Brenno Pimenta'; IdMessage.ReplyTo.EMailAddresses := IdMessage.From.Address; IdMessage.Recipients.Add.Text := ADestino; IdMessage.Subject := AAssunto; IdMessage.Encoding := meMIME; IdText := TIdText.Create(IdMessage.MessageParts); IdText.Body.Add('Cadastro em Anexo'); IdText.ContentType := 'text/plain; charset=iso-8859-1'; if FileExists(AAnexo) then begin TIdAttachmentFile.Create(IdMessage.MessageParts, AAnexo); end; try IdSMTP.Connect; IdSMTP.Authenticate; except on E:Exception do begin MessageDlg('Erro na conexão ou autenticação: ' + E.Message, mtWarning, [mbOK], 0); Exit; end; end; try IdSMTP.Send(IdMessage); MessageDlg('Mensagem enviada com sucesso!', mtInformation, [mbOK], 0); except On E:Exception do begin MessageDlg('Erro ao enviar a mensagem: ' + E.Message, mtWarning, [mbOK], 0); end; end; finally IdSMTP.Disconnect; UnLoadOpenSSLLibrary; FreeAndNil(IdMessage); FreeAndNil(IdSSLIOHandlerSocket); FreeAndNil(IdSMTP); end; end; end.
unit Unit1; interface uses System.SysUtils, System.Classes, Vcl.Imaging.JPeg, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, //GLS GLScene, GLObjects, GLCadencer, GLTexture, GLWin32Viewer, GLCrossPlatform, GLCoordinates, GLBaseClasses; type TForm1 = class(TForm) Timer1: TTimer; GLSceneViewer1: TGLSceneViewer; GLScene1: TGLScene; GLCamera1: TGLCamera; DummyCube1: TGLDummyCube; Cube1: TGLCube; GLLightSource1: TGLLightSource; GLMemoryViewer1: TGLMemoryViewer; GLCadencer1: TGLCadencer; Panel1: TPanel; Label1: TLabel; Label2: TLabel; RB1to1: TRadioButton; RB1to2: TRadioButton; RB1to10: TRadioButton; CheckBox1: TCheckBox; LabelFPS: TLabel; procedure Timer1Timer(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure CheckBox1Click(Sender: TObject); procedure GLSceneViewer1AfterRender(Sender: TObject); procedure FormCreate(Sender: TObject); procedure RB1to1Click(Sender: TObject); private { Private declarations } textureFramerateRatio, n: Integer; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses GLContext, OpenGLAdapter; procedure TForm1.FormCreate(Sender: TObject); begin textureFramerateRatio := 1; n := 0; end; procedure TForm1.RB1to1Click(Sender: TObject); begin textureFramerateRatio := (Sender as TRadioButton).Tag; end; procedure TForm1.CheckBox1Click(Sender: TObject); begin if CheckBox1.Checked then GLSceneViewer1.VSync := vsmSync else GLSceneViewer1.VSync := vsmNoSync; end; procedure TForm1.GLSceneViewer1AfterRender(Sender: TObject); begin if not GLSceneViewer1.Buffer.RenderingContext.GL.W_ARB_pbuffer then begin ShowMessage('WGL_ARB_pbuffer not supported...'#13#10#13#10 + 'Get newer graphics hardware or try updating your drivers!'); GLSceneViewer1.AfterRender := nil; Exit; end; Inc(n); try if n >= textureFramerateRatio then begin // render to the viewer GLMemoryViewer1.Render; // copy result to the textures GLMemoryViewer1.CopyToTexture(Cube1.Material.Texture); n := 0; end; except // pbuffer not supported... catchall for exotic ICDs... GLSceneViewer1.AfterRender := nil; raise; end; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin DummyCube1.TurnAngle := newTime * 60; end; procedure TForm1.Timer1Timer(Sender: TObject); begin LabelFPS.Caption := Format('GLScene Memory Viewer'+' - %.1f FPS', [GLSceneViewer1.FramesPerSecond]); GLSceneViewer1.ResetPerformanceMonitor; end; end.
{*********************************************} { TeeBI Software Library } { TDataProviderNeeds Editor } { Copyright (c) 2015-2016 by Steema Software } { All Rights Reserved } {*********************************************} unit VCLBI.Editor.Needs; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BI.Algorithm, Vcl.ComCtrls, BI.DataItem, Vcl.StdCtrls, Vcl.ExtCtrls; type TProviderNeedsEditor = class(TForm) PageNeeds: TPageControl; PanelBottom: TPanel; BApply: TButton; PanelOk: TPanel; BOk: TButton; BCancel: TButton; procedure BApplyClick(Sender: TObject); private { Private declarations } FOptions : TCustomForm; INeeds : TDataProviderNeeds; procedure ChangedCombo(Sender:TObject); procedure ChangedItems(Sender:TObject); public { Public declarations } class function Embed(const AOwner:TComponent; const AParent: TWinControl; const ANeeds:TDataProviderNeeds; const ASource:TDataItem):TProviderNeedsEditor; static; procedure EnableApply; procedure RefreshNeeds(const ANeeds:TDataProviderNeeds; const ASource:TDataItem); property Needs:TDataProviderNeeds read INeeds; property Options:TCustomForm read FOptions; end; TDataProviderClass=class of TDataProvider; TRegisteredProvider=record public ProviderClass : TDataProviderClass; EditorClass : TCustomFormClass; end; TRegisteredProviders=Array of TRegisteredProvider; TRegisteredProvidersHelper=record helper for TRegisteredProviders public function Count:Integer; inline; function EditorOf(const AOwner:TComponent; const AProvider:TDataProvider):TCustomForm; function IndexOf(const AClass:TDataProviderClass):Integer; class procedure RegisterProvider(const AClass:TDataProviderClass; const AEditor:TCustomFormClass); static; procedure UnRegisterProvider(const AClass:TDataProviderClass); end; var RegisteredProviders : TRegisteredProviders=nil; implementation
unit LUX.Audio.SDIF.Frames; interface //#################################################################### ■ uses System.Classes, LUX.Audio.SDIF; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 TFrame1TYP = class; TFrameASTI = class; TFrame1ASO = class; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TFrame1TYP TFrame1TYP = class( TFrameSDIF ) private protected _Text :TArray<AnsiChar>; public ///// メソッド class function ReadCreate( const F_:TFileStream; const H_:TFrameHeaderSDIF; const P_:TFileSDIF ) :TFrameSDIF; override; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TFrameASTI TFrameASTI = class( TFrameSDIF ) private protected public ///// メソッド class function ReadCreate( const F_:TFileStream; const H_:TFrameHeaderSDIF; const P_:TFileSDIF ) :TFrameSDIF; override; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TFrame1ASO TFrame1ASO = class( TFrameSDIF ) private protected ///// アクセス function GetClss :String; function GetDura :Single; function GetTimeMax :Single; public ///// プロパティ property Clss :String read GetClss ; property Dura :Single read GetDura ; property TimeMax :Single read GetTimeMax; ///// メソッド class function Select( const Clss_:String ) :CFrameSDIF; reintroduce; virtual; class function ReadCreate( const F_:TFileStream; const H_:TFrameHeaderSDIF; const P_:TFileSDIF ) :TFrameSDIF; override; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ uses System.SysUtils, LUX.Audio.SDIF.Matrixs, LUX.Audio.SDIF.Frames.ASO1; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TFrame1TYP //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public /////////////////////////////////////////////////////////////////////// メソッド class function TFrame1TYP.ReadCreate( const F_:TFileStream; const H_:TFrameHeaderSDIF; const P_:TFileSDIF ) :TFrameSDIF; begin Result := Create( P_ ); with TFrame1TYP( Result ) do begin SetLength( _Text, H_.Size - 16 ); F_.Read( _Text[0], H_.Size - 16 ); end; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TFrameASTI //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public /////////////////////////////////////////////////////////////////////// メソッド class function TFrameASTI.ReadCreate( const F_:TFileStream; const H_:TFrameHeaderSDIF; const P_:TFileSDIF ) :TFrameSDIF; var P :TFrameSDIF; N :Integer; begin P := TFrameSDIF.Create; for N := 1 to H_.MatrixCount do TMatrixSDIF.ReadCreate( F_, P ); Result := Create( P_ ); for N := 1 to P.ChildsN do P.Head.Paren := TMatrixSDIF( Result ); P.Free; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TFrame1ASO //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TFrame1ASO.GetClss :String; begin Result := TMatrixChar( FindMatrix( 'clss' ) ).Lines[ 0 ]; end; function TFrame1ASO.GetDura :Single; begin Result := TMatrixFlo4( FindMatrix( 'dura' ) ).Values[ 0, 0 ]; end; function TFrame1ASO.GetTimeMax :Single; begin Result := Time + Dura; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public /////////////////////////////////////////////////////////////////////// メソッド class function TFrame1ASO.Select( const Clss_:String ) :CFrameSDIF; begin if SameText( Clss_, 'Tran' ) then Result := TFrameTran else if SameText( Clss_, 'TmSt' ) then Result := TFrameTmSt else if SameText( Clss_, 'Frmt' ) then Result := TFrameFrmt else if SameText( Clss_, 'BpGa' ) then Result := TFrameBpGa else if SameText( Clss_, 'Rflt' ) then Result := TFrameRflt else if SameText( Clss_, 'Clip' ) then Result := TFrameClip else if SameText( Clss_, 'Gsim' ) then Result := TFrameGsim else if SameText( Clss_, 'Frze' ) then Result := TFrameFrze else if SameText( Clss_, 'Revs' ) then Result := TFrameRevs else if SameText( Clss_, 'Imag' ) then Result := TFrameImag else if SameText( Clss_, 'Brkp' ) then Result := TFrameBrkp else if SameText( Clss_, 'Surf' ) then Result := TFrameSurf else if SameText( Clss_, 'Band' ) then Result := TFrameBand else if SameText( Clss_, 'Noiz' ) then Result := TFrameNoiz else Result := nil; Assert( Assigned( Result ), Clss_ + ':未対応のクラス型です。' ); end; class function TFrame1ASO.ReadCreate( const F_:TFileStream; const H_:TFrameHeaderSDIF; const P_:TFileSDIF ) :TFrameSDIF; var P :TFrame1ASO; N :Integer; begin P := TFrame1ASO.Create; for N := 1 to H_.MatrixCount do TMatrixSDIF.ReadCreate( F_, P ); Result := Select( P.Clss ).Create( P_ ); for N := 1 to P.ChildsN do P.Head.Paren := TMatrixSDIF( Result ); P.Free; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 //############################################################################## □ initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化 finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化 end. //######################################################################### ■
unit WiseLogger; interface uses SysUtils, DateUtils; type TWiseLogger = class private name: string; // The name of the logger, e.g. 'dome-agent' path: string; // The name of the log-file f: TextFile; // Handle to the file function makeFullPath: string; public procedure log(s: string); constructor Create(name: string); end; implementation (* We use lazy opening of the log-file, only when a log-line is actually written. Every time a log line is written we check if the date changed in the meanwhile and update the fullpath accordingly. *) const topLogDir: string = 'c:\Logs'; function TWiseLogger.makeFullPath; var x: TdateTime; day, month, year: integer; begin x := Now; if HourOfTheDay(x) >= 12 then x := IncDay(x, 1); day := DayOfTheMonth(x); month := MonthOfTheYear(x); year := YearOf(x); Result := topLogDir + '\' + Format('%d-%02d-%02d', [year, month, day]) + '\' + Self.name + '.txt'; end; constructor TWiseLogger.Create(name: string); begin Self.name := name; Self.path := ''; end; procedure TWiseLogger.log(s: string); var currpath: string; begin currpath := makeFullPath; if (currpath <> Self.path) then begin Self.path := currpath; if not ForceDirectories(ExtractFileDir(Self.path)) then exit; AssignFile(Self.f, Self.path); if FileExists(Self.path) then Append(Self.f) else Rewrite(Self.f); end; Writeln(Self.f, FormatDateTime('ddddd hh:nn:ss.zzz', Now) + ': ' + s); Flush(Self.f); end; end.
UNIT windows; INTERFACE USES Dos,Crt; PROCEDURE OpenWindow(x1,y1,x2,y2: byte; Fgnd,Bkgnd: byte; VAR Error : ShortInt ); (* Creates a blank Window with the given coordinates, and saves the contents *) (* of the underlying region on the heap. If an Error occurs in attempting to *) (* open the Window, Error is set to TRUE; otherwise, FALSE is returned. *) procedure CloseWindow; IMPLEMENTATION CONST MaxWindows = 10; (* maximum # on-screen windows *) FrameFgnd = red; (* frame colors *) FrameBkgnd = lightgray; { error conditions } NoError = 0; TooManyWindows = 1; OutOfHeap = 2; BadDimensions = 3; TYPE IntPtr = ^integer; WindowType = record xL,yL,xR,yR : integer; (* coordinates of corners *) BufrPtr : IntPtr; (* pointer to buffer location *) CursorX,CursorY : integer; (* cursor position before opening *) ScreenAttr : byte; (* text attributes before opening *) end; VAR WindowStack : array [0..MaxWindows] of WindowType; MaxCols,MaxRows : byte; (* # rows & columns for initial video mode *) NumWindows : 0..MaxWindows; (* # windows currently open *) VidStart : word; (* location for video memory *) Regs : registers; ExitSave : POINTER; PROCEDURE Beep; (* This procedure is called if the request to open a window causes an error *) begin Sound(200); Delay(100); Sound(350); Delay(100); Sound(100); Delay(100); Nosound end (* procedure Beep *); PROCEDURE DrawFrame (x1,y1,x2,y2: byte); (* Draws a rectangular frame on the screen with upper left hand corner *) (* at x1,y1, lower right hand corner at x2,y2. *) VAR k : integer; CurrentAttr : byte; begin (* DrawFrame *) CurrentAttr := TextAttr; (* save the current text attributes *) TextAttr := FrameFgnd + 16*FrameBkgnd; (* change attributes for frame *) GotoXY(x1,y1); Write(chr(201)); for k := (x1 + 1) to (x2 - 1) do Write(chr(205)); Write(chr(187)); for k := (y1 + 1) to (y2 - 1) do begin GotoXY(x1,k); Write(chr(186)); GotoXY(x2,k); Write(chr(186)); end; GotoXY(x1,y2); Write(chr(200)); for k := (x1 + 1) to (x2 - 1) do Write(chr(205)); Write(chr(188)); TextAttr := CurrentAttr (* restore previous text attributes *) end (* DrawFrame *); PROCEDURE SaveRegion (x1,y1,x2,y2 : byte; VAR StartAddr : IntPtr ); (* Saves the contents of the screen rectangle with coordinates x1,y1,x2,y2 *) (* on the heap starting at address StartAddr. *) VAR TempPtr,LinePtr : IntPtr; k,LineLength : integer; begin LineLength := (x2 - x1 + 1) * 2; (* # bytes per line in rectangle *) (* allocate space on heap *) GetMem (StartAddr,LineLength * (y2 - y1 + 1)); TempPtr := StartAddr; (* TempPtr points to copy destination on heap *) for k := y1 to y2 do begin (* Make LinePtr point to screen position x=x1, y=k *) LinePtr := Ptr(VidStart, (k-1)*MaxCols*2 + (x1-1)*2); (* Move the line from screen to heap *) Move (LinePtr^,TempPtr^,LineLength); (* Increment the screen IntPtr *) TempPtr := Ptr(seg(TempPtr^),ofs(TempPtr^) + LineLength); end end (* procedure SaveRegion *); PROCEDURE RecallRegion (x1,y1,x2,y2 : integer; HpPtr : IntPtr); (* Moves the contents of a previously saved region from the heap back *) (* to the screen. *) VAR TempPtr,LinePtr : IntPtr; k,LineLength : integer; begin LineLength := (x2 - x1 + 1) * 2; (* # bytes per line in rectangle *) TempPtr := HpPtr; (* TempPtr gives the source location for copy *) for k := y1 to y2 do begin (* Make LinePtr point to screen position x=x1, y=k *) LinePtr := Ptr(VidStart, (k-1)*MaxCols*2 + (x1-1)*2); move (TempPtr^,LinePtr^,LineLength); TempPtr := Ptr(seg(TempPtr^),ofs(TempPtr^) + LineLength); end; end (* procedure RecallRegion *); PROCEDURE OpenWindow(x1,y1,x2,y2: byte; Fgnd,Bkgnd: byte; VAR Error : ShortInt ); (* Creates a blank Window with the given coordinates, and saves the contents *) (* of the underlying region on the heap. If an Error occurs in attempting to *) (* open the Window, Error is set to TRUE; otherwise, FALSE is returned. *) VAR Pntr : IntPtr; begin if (NumWindows = 0) then begin (* determine current screen parameters *) MaxCols := Lo(WindMax) + 1; (* add 1, since numbering begins with 0 *) MaxRows := Hi(WindMax) + 1; with WindowStack[0] do (* WindowStack[0] is the entire screen *) begin xL := 0; yL := 0; xR := MaxCols + 1; yR := MaxRows + 1 end end; (* check for possible error conditions *) Error := 0; IF (NumWindows = MaxWindows) THEN (* too many windows? *) Error := 1; (* out of heap? *) IF (MaxAvail < longint((x2 - x1 + 1)*(y2 - y1 + 1)*2)) THEN Error := 2; (* wrong dimensions? *) IF NOT ( (x1 in [1..MaxCols-2]) and (x2 in [3..MaxCols]) and (x2-x1>1) and (y1 in [1..MaxRows-2]) and (y2 in [3..MaxRows]) and (y2-y1>1) ) THEN Error := 3; IF Error > 0 THEN Beep ELSE BEGIN (* successful request *) SaveRegion (x1,y1,x2,y2,Pntr); Error := 0; NumWindows := NumWindows + 1; with WindowStack[NumWindows] do begin xL := x1; yL := y1; xR := x2; yR := y2; BufrPtr := Pntr; CursorX := WhereX; CursorY := Wherey; ScreenAttr := TextAttr end; Window (1,1,MaxCols,MaxRows); (* make the whole screen a window *) DrawFrame (x1,y1,x2,y2); Window (x1+1,y1+1,x2-1,y2-1); (* create the requested window *) TextColor(Fgnd); TextBackground(Bkgnd); ClrScr end (* else clause *) end (* procedure OpenWindow *); PROCEDURE CloseWindow; VAR x,y : integer; begin if NumWindows > 0 then begin with WindowStack[NumWindows] do begin RecallRegion (xL,yL,xR,yR,BufrPtr); (* restore underlying text *) FreeMem (BufrPtr,(xR - xL + 1)*(yR - yL + 1)*2); (* free heap space *) x := CursorX; y := CursorY; (* prepare to restore cursor position *) TextAttr := ScreenAttr (* restore screen attributes *) end; (* activate the underlying Window *) NumWindows := NumWindows - 1; with WindowStack[NumWindows] do Window (xL+1,yL+1,xR-1,yR-1); GotoXY (x,y) (* restore the cursor position *) end (* if NumWindows > 0 *) end (* procedure CloseWindow *); {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} {$F+} procedure TerminateClean; {$F-} { This should automatically get called no matter how we exit } { I added this - Art } BEGIN WHILE NumWindows > 0 DO CloseWindow; ExitProc := ExitSave; END; {TerminateClean} {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} begin (* Windows initialization *) NumWindows := 0; Regs.AH := 15; (* prepare for DOS interrupt *) Intr($10,Regs); (* determine current video mode *) case Regs.AL of 0..3 : VidStart := $B800; (* start of video memory *) 7 : VidStart := $B000; end; (* case statement *) ExitSave := ExitProc; ExitProc := @TerminateClean; end (* Windows initialization *). 
unit Ukey; // SpyroTAS is licensed under WTFPL // keyboard and controller related stuff interface uses Utas, Windows; const // from PlayStation spec actually pad_Select = $0001; pad_L3 = $0002; pad_R3 = $0004; pad_Start = $0008; pad_Up = $0010; pad_Right = $0020; pad_Down = $0040; pad_Left = $0080; pad_L2 = $0100; pad_R2 = $0200; pad_L1 = $0400; pad_R1 = $0800; pad_Triangle = $1000; pad_Circle = $2000; pad_Cross = $4000; pad_Square = $8000; const // arbitrary sequence to refer buttons PadButton: array[0..15] of Integer = (pad_Up, pad_Right, pad_Down, pad_Left, pad_Triangle, pad_Circle, pad_Cross, pad_Square, pad_L1, pad_L2, pad_R1, pad_R2, pad_Start, pad_Select, pad_L3, pad_R3); const // for ini ButtonNames: array[0..15] of string = ('pad_up', 'pad_right', 'pad_down', 'pad_left', 'pad_triangle', 'pad_circle', 'pad_cross', 'pad_square', 'pad_l1', 'pad_l2', 'pad_r1', 'pad_r2', 'pad_start', 'pad_select', 'pad_l3', 'pad_r3'); const // controller defaults DefaultButtons: array[0..2, 0..15] of Byte = ((VK_UP, VK_RIGHT, VK_DOWN, VK_LEFT, VK_END, VK_NUMPAD0, VK_RCONTROL, VK_RSHIFT, VK_DELETE, VK_INSERT, VK_NEXT, VK_PRIOR, VK_SPACE, 191, 0, 0), (Ord('W'), Ord('D'), Ord('S'), Ord('A'), Ord('T'), Ord('H'), Ord('G'), Ord('F'), Ord('E'), Ord('Q'), Ord('R'), Ord('Y'), Ord('C'), Ord('X'), Ord('Z'), Ord('V')), (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); const // hotkey sequence HotkeySave = 0; HotkeyLoad = 1; HotkeyPrevious = 2; HotkeyCurrent = 3; HotkeySwap = 4; HotkeyFast = 5; HotkeyFrame = 6; HotkeyExit = 7; HotkeyWarp = 8; HotkeyAuto = 9; EmulatorHotkeySavestate = 10; EmulatorHotkeyLoadstate = 11; HotkeysLast = EmulatorHotkeyLoadstate; // must point to previous! type THotkey = 0..HotkeysLast; const // for ini HotkeyNames: array[0..HotkeysLast] of string = ('hot_save', 'hot_load', 'hot_prev', 'hot_last', 'hot_swap', 'hot_fast', 'hot_advance', 'hot_exit', 'hot_warp', 'hot_auto', 'emu_save', 'emu_load'); const HotkeyExitDefault = VK_F10; // explicit DefaultHotkeys: array[0..HotkeysLast] of Byte = (VK_APPS, VK_RETURN, VK_BACK, VK_DIVIDE, VK_TAB, VK_ADD, VK_SUBTRACT, HotkeyExitDefault, VK_MULTIPLY, VK_DECIMAL, VK_F1, VK_F3); const // keycode names VkKeyNames: array[0..255] of string = ('', 'Left Mouse', 'Right Mouse', '[CANCEL]', 'Middle Mouse', 'X-1 Mouse', 'X-2 Mouse', '(7)', 'Backspasce', 'Tab', '(10)', '(11)', 'Clear (Num 5)', 'Enter', '(14)', '(15)', '(16)', '(17)', '(18)', 'Pause Break', 'Caps Lock', '[KANA]', '(22)', '[JUNJA]', '[FINAL]', '[KANJI]', '(26)', '', '[CONVERT]', '[NONCONVERT]', '[ACCEPT]', '[MODECHANGE]', 'Space', 'Page Up', 'Page Down', 'End', 'Home', 'Left', 'Up', 'Right', 'Down', '[SELECT]', '[PRINT]', '[EXECUTE]', 'Print Screen', 'Insert', 'Delete', '[HELP]', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '(58)', '(59)', '(60)', '(61)', '(62)', '(63)', '(64)', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'Left Windows', 'Right Windows', 'Application (menu)', '(94)', '[SLEEP]', 'Num 0', 'Num 1', 'Num 2', 'Num 3', 'Num 4', 'Num 5', 'Num 6', 'Num 7', 'Num 8', 'Num 9', 'Num Multiply', 'Num Add', '[SEPARATOR]', 'Num Substract', 'Num Dot', 'Num Divide', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'F13', 'F14', 'F15', 'F16', 'F17', 'F18', 'F19', 'F20', 'F21', 'F22', 'F23', 'F24', '(136)', '(137)', '(138)', '(139)', '(140)', '(141)', '(142)', '(143)', 'Num Lock', 'Scroll Lock', '[FJ_JISHO]', '[FJ_MASSHOU]', '[FJ_TOUROKU]', '[FJ_LOYA]', '[ROYA]', '(151)', '(152)', '(153)', '(154)', '(155)', '(156)', '(157)', '(158)', '(159)', 'Left Shift', 'Right Shift', 'Left Control', 'Right Control', 'Left Alt', 'Right Alt', '[BROWSER_BACK]', '[BROWSER_FORWARD]', '[BROWSER_REFRESH]', '[BROWSER_STOP]', '[BROWSER_SEARCH]', '[BROWSER_FAVORITES]', '[BROWSER_HOME]', '[VOLUME_MUTE]', '[VOLUME_DOWN]', '[VOLUME_UP]', '[MEDIA_NEXT_TRACK]', '[MEDIA_PREV_TRACK]', '[MEDIA_STOP]', '[MEDIA_PLAY_PAUSE]', '[LAUNCH_MAIL]', '[MEDIA_SELECT]', '[LAUNCH_APP1]', '[LAUNCH_APP2]', '(184)', '(185)', ' ; :', ' = +', ' , <', ' - _', ' . >', ' / ?', ' ` ~', '[ABNT_C1]', '[ABNT_C2]', '(195)', '(196)', '(197)', '(198)', '(199)', '(200)', '(201)', '(202)', '(203)', '(204)', '(205)', '(206)', '(207)', '(208)', '(209)', '(210)', '(211)', '(212)', '(213)', '(214)', '(215)', '(216)', '(217)', '(218)', ' [ {', ' \ |', ' ] }', ' '' "', '[OEM_8]', '(224)', '[OEM_AX]', ' \ /', '[ICO_HELP]', '[ICO_00]', '[PROCESSKEY]', '[ICO_CLEAR]', '[PACKET]', '(232)', '[OEM_RESET]', '[OEM_JUMP]', '[OEM_PA1]', '[OEM_PA2]', '[OEM_PA3]', '[OEM_WSCTRL]', '[OEM_CUSEL]', '[OEM_ATTN]', '[OEM_FINISH]', '[OEM_COPY]', '[OEM_AUTO]', '[OEM_ENLW]', '[OEM_BACKTAB]', '[ATTN]', '[CRSEL]', '[EXSEL]', '[EREOF]', '[PLAY]', '[ZOOM]', '[NONAME]', '[PA1]', '[OEM_CLEAR]', '0xFF'); var GlobalKeysForPad: Integer = 0; IsPadRouted: Boolean = False; procedure PressKeyDown(KeyCode: Byte); procedure ReleaseAllPressedKeys(); function IsKeyJustPressed(KeyCode: Byte): Boolean; procedure MakeKeyDown(KeyCode: Byte); procedure MakeKeyUp(KeyCode: Byte); procedure ReadFromKeys(var Keys: Integer; Mask: Integer = 0); procedure PressThoseKeys(Keys: Integer); function JustPressedKeys(): Integer; function IsKeyCatched(KeyCode: Byte): Boolean; procedure CatchKeysNow(); procedure ClearCatchedKeys(); procedure ClearJustPressed(); function IsHotkeyPressed(Hotkey: THotkey; JustPress: Boolean): Boolean; procedure AssignHotkey(Hotkey: THotkey; KeyCode: Byte); function GetAssignedHotkey(Hotkey: THotkey): Byte; procedure AssignButton(Port, Button: Integer; KeyCode: Byte); function GetAssignedButton(Port, Button: Integer): Byte; implementation uses Messages; var KeyMonitorQueue: array[0..255] of Integer; // to know which to release KeyMonitorQueueCounter: Integer = 0; JustPressArray: array[0..255] of Boolean; // to test for exact press moment PressedKeys: array[0..255] of Boolean; // that catched AssignedHotkeys: array[0..HotkeysLast] of Byte; // all hotkeys AssignedButtons: array[0..2, 0..15] of Byte; // virtual, 1 and 2 controllers // press and store key: procedure PressKeyDown(KeyCode: Byte); begin Inc(KeyMonitorQueueCounter); KeyMonitorQueue[KeyMonitorQueueCounter] := KeyCode; // store MakeKeyDown(KeyCode); // push key end; // pull up all PressKeyDown'ed: procedure ReleaseAllPressedKeys(); begin while KeyMonitorQueueCounter > 0 do begin MakeKeyUp(KeyMonitorQueue[KeyMonitorQueueCounter]); // release every key Dec(KeyMonitorQueueCounter); end; end; // check against press event, not hold function IsKeyJustPressed(KeyCode: Byte): Boolean; begin Result := False; if KeyCode = AssignedHotkeys[HotkeyExit] then // don't touch exit key Exit; if not JustPressArray[KeyCode] then // was released begin if 0 <> GetAsyncKeyState(KeyCode) then // but pressed now begin JustPressArray[KeyCode] := True; // will be down Result := True; end; end else // was hold begin if 0 = GetAsyncKeyState(KeyCode) then // but released now JustPressArray[KeyCode] := False; // will be up end; end; // simulate key down event procedure MakeKeyDown(KeyCode: Byte); var ScanCode: Integer; begin if IsRunDLL then // no events when standalone Exit; ScanCode := MapVirtualKey(KeyCode, 0); // might be need if EmulatorWindow <> 0 then begin // actually when there's no window, no events should be sent at all, hmm PostMessage(EmulatorWindow, WM_KEYDOWN, KeyCode, 1 or Integer(ScanCode shl 16)); PostMessage(EmulatorWindow, WM_KEYDOWN, KeyCode, 1 or Integer(ScanCode shl 16) or Integer(1 shl 24)); end; // abuse every method keybd_event(KeyCode, ScanCode, 0, 0); keybd_event(KeyCode, ScanCode, KEYEVENTF_EXTENDEDKEY, 0); end; // simulate key up event, everything alike MakeKeyDown: procedure MakeKeyUp(KeyCode: Byte); var ScanCode: Integer; begin if IsRunDLL then Exit; ScanCode := MapVirtualKey(KeyCode, 0); if EmulatorWindow <> 0 then begin PostMessage(EmulatorWindow, WM_KEYUP, KeyCode, 1 or Integer(ScanCode shl 16) or Integer(3 shl 30)); PostMessage(EmulatorWindow, WM_KEYUP, KeyCode, 1 or Integer(ScanCode shl 16) or Integer(3 shl 30) or Integer(1 shl 24)); end; keybd_event(KeyCode, ScanCode, KEYEVENTF_KEYUP, 0); keybd_event(KeyCode, ScanCode, KEYEVENTF_KEYUP or KEYEVENTF_EXTENDEDKEY, 0); end; // updates history keys with current pressed, supporting semi-keys mask: procedure ReadFromKeys(var Keys: Integer; Mask: Integer = 0); var Index: Integer; begin for Index := 0 to 15 do // checking virtual if PressedKeys[AssignedButtons[0, Index]] and (((Mask and PadButton[Index]) = 0) or AutofireButton[Index]) then Keys := Keys or PadButton[Index]; end; // do press all keys from history: procedure PressThoseKeys(Keys: Integer); var Index: Integer; begin GlobalKeysForPad := Keys; if IsPadRouted then Exit; for Index := 0 to 15 do // first controller if (Keys and PadButton[Index]) <> 0 then PressKeyDown(AssignedButtons[1, Index]); Keys := Keys shr 16; // second for Index := 0 to 15 do if (Keys and PadButton[Index]) <> 0 then PressKeyDown(AssignedButtons[2, Index]); end; // get only just-pressed virtuals as history keys: function JustPressedKeys(): Integer; var Index: Integer; begin Result := 0; // no by default for Index := 0 to 15 do if IsKeyJustPressed(AssignedButtons[0, Index]) then Result := Result or PadButton[Index]; // combine end; // getter for array: function IsKeyCatched(KeyCode: Byte): Boolean; begin Result := PressedKeys[KeyCode]; end; // poll keyboard and update array: procedure CatchKeysNow(); var Index: Integer; begin for Index := 1 to 255 do // gather pressed keys if (Index <> AssignedHotkeys[HotkeyExit]) and (0 <> GetAsyncKeyState(Index)) then PressedKeys[Index] := True; // ignoring exit hotkey end; // refresh array of pressed: procedure ClearCatchedKeys(); var Index: Integer; begin for Index := 0 to 255 do // can be done my ZeroMemory, hmm PressedKeys[Index] := False; end; // refresh just-press array: procedure ClearJustPressed(); var Index: Integer; begin for Index := 0 to 255 do JustPressArray[Index] := False; end; // checker for hotkeys: function IsHotkeyPressed(Hotkey: THotkey; JustPress: Boolean): Boolean; begin if JustPress then Result := IsKeyJustPressed(AssignedHotkeys[Hotkey]) else Result := IsKeyCatched(AssignedHotkeys[Hotkey]); end; // setter for hotkeys: procedure AssignHotkey(Hotkey: THotkey; KeyCode: Byte); begin if KeyCode = VK_ESCAPE then KeyCode := 0; AssignedHotkeys[Hotkey] := KeyCode; if (Hotkey = HotkeyExit) and (KeyCode = 0) then AssignedHotkeys[Hotkey] := HotkeyExitDefault; end; // getter for hotkeys: function GetAssignedHotkey(Hotkey: THotkey): Byte; begin Result := AssignedHotkeys[Hotkey]; end; // setter for controllers: procedure AssignButton(Port, Button: Integer; KeyCode: Byte); begin if KeyCode = VK_ESCAPE then KeyCode := 0; AssignedButtons[Port][Button] := KeyCode; end; // getter for controllers: function GetAssignedButton(Port, Button: Integer): Byte; begin Result := AssignedButtons[Port][Button]; end; end. // EOF
{----------------------------------------------------------------------------- Unit Name: fEditSetting Author: Original code by Lachlan Gemmell (http://lachlan.gemmell.com/), maintained and improved by Erwien Saputra. Purpose: Encapsulates all interaction with the Registry. History: 12/27/04 - Received the file from Lachlan. 01/02/05 - Updated to work with new ISettingCollection. A lot of updates. Refactored the logic and creates several helper classes. 03/01/05 - Added buttons. 04/08/05 - Updated this form, giving this form the ability to persist its setting. This form uses my new setting framework. 06/18/05 - Updated SetTopPanelHeight and GetTopPanelHeight. -----------------------------------------------------------------------------} unit fEditSetting; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls, TreeViewController, DelphiSettingRegistry, Buttons, ImgList, ValueNamesProvider, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls, ActnList, Menus, SettingPersistent; type TEditSettingProperties = class; IEditSetting = interface ['{D8825E5B-D312-4277-9605-0DC278F65D7B}'] function GetLeftSettingPath : string; function GetRightSettingPath : string; function GetLeftSettingName : string; function GetRightSettingName : string; procedure SetLeftSettingPath (const APath : string); procedure SetRightSettingPath (const APath : string); procedure SetLeftSettingName (const ASettingName : string); procedure SetRightSettingName (const ASettingName : string); procedure Execute; property LeftSettingPath : string read GetLeftSettingPath write SetLeftSettingPath; property LeftSettingName : string read GetLeftSettingName write SetLeftSettingName; property RightSettingPath : string read GetRightSettingPath write SetRightSettingPath; property RightSettingName : string read GetRightSettingName write SetRightSettingName; end; TfrmEditSetting = class(TForm, IEditSetting) pnlTop: TPanel; Splitter1: TSplitter; pnlValuesLeft: TPanel; pnlValuesRight: TPanel; pnlLeft: TPanel; spTree: TSplitter; pnlRight: TPanel; tvLeft: TTreeView; tvRight: TTreeView; lblLeft: TLabel; lblRight: TLabel; lbLeftValues: TListBox; lbRightValues: TListBox; pnlBottom: TPanel; pnlButton: TPanel; btnClose: TButton; imgTree: TImageList; memValueLeft: TMemo; memValueRight: TMemo; actKeyValue: TActionList; actLeftCopyKeyTo: TAction; actLeftDeleteKey: TAction; actLeftCopyNameTo: TAction; actLeftDeleteName: TAction; actLeftClearValue: TAction; actRightCopyKeyTo: TAction; actRightCopyNameTo: TAction; actRightDeleteName: TAction; actRightClearValue: TAction; spValues: TSplitter; popLeftTree: TPopupMenu; actRightDeleteKey: TAction; LeftCopyKeyTo: TMenuItem; LeftDeleteKey: TMenuItem; PoRightTree: TPopupMenu; MenuItem6: TMenuItem; MenuItem7: TMenuItem; popLeftValue: TPopupMenu; MenuItem13: TMenuItem; MenuItem14: TMenuItem; MenuItem15: TMenuItem; popRightValues: TPopupMenu; MenuItem28: TMenuItem; MenuItem29: TMenuItem; MenuItem30: TMenuItem; popLeftMemo: TPopupMenu; MenuItem35: TMenuItem; popRightMemo: TPopupMenu; MenuItem50: TMenuItem; atbLeftNames: TActionToolBar; atbRightNames: TActionToolBar; acmKeyValue: TActionManager; imgKeyValues: TImageList; atbLeftKey: TActionToolBar; atbRightKey: TActionToolBar; procedure ValueNamesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure TreeViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure popLeftValuePopup(Sender: TObject); procedure actRightClearValueExecute(Sender: TObject); procedure actRightDeleteNameExecute(Sender: TObject); procedure actRightDeleteKeyExecute(Sender: TObject); procedure actLeftClearValueExecute(Sender: TObject); procedure actLeftDeleteNameExecute(Sender: TObject); procedure actLeftDeleteKeyExecute(Sender: TObject); procedure FormResize(Sender: TObject); procedure TreeMenuPopup(Sender: TObject); procedure actLeftCopyNameToExecute(Sender: TObject); procedure actRightCopyNameToExecute(Sender: TObject); procedure actRightCopyKeyToExecute(Sender: TObject); procedure actLeftCopyKeyToExecute(Sender: TObject); procedure lbLeftValuesClick(Sender: TObject); procedure tvLeftGetSelectedIndex(Sender: TObject; Node: TTreeNode); procedure tvLeftGetImageIndex(Sender: TObject; Node: TTreeNode); procedure spTreeCanResize(Sender: TObject; var NewSize: Integer; var Accept: Boolean); procedure spTreeMoved(Sender: TObject); private { Private declarations } FLeftSettingName : string; FLeftRegistry : IDelphiSettingRegistry; FLeftController : ITreeViewController; FLeftValueNamesProvider : IValueNamesProvider; FRightSettingName : string; FRightRegistry : IDelphiSettingRegistry; FRightController : ITreeViewController; FRightValueNamesProvider : IValueNamesProvider; FSynchronizer : IDelphiSettingSynchronizer; FLeftReadOnly: Boolean; FRightReadOnly: Boolean; FSettingProperties : TEditSettingProperties; function GetLeftSettingPath : string; function GetRightSettingPath : string; function GetLeftSettingName : string; function GetRightSettingName : string; procedure SetLeftSettingPath (const APath : string); procedure SetRightSettingPath (const APath : string); procedure SetLeftSettingName (const ASettingName : string); procedure SetRightSettingName (const ASettingName : string); procedure Execute; procedure BuildListBoxes (const ListA, ListB : TStrings); procedure UpdateListBox (const Intf : IInterface); procedure DisplayValue (const Intf : IInterface); procedure SyncListBox (const ANewSelection, ATopIndex : integer); procedure CopyValue (const SourceListBox : TListBox; const SourceProvider, TargetProvider : IValueNamesProvider); procedure DeleteCurrentKey (const DelphiRegistry : IDelphiSettingRegistry; const TreeView : TTreeView); procedure DeleteSelectedValue (const Provider : IValueNamesProvider; const SelectedItem, TopItem : integer); procedure ClearSelectedValue(const Provider: IValueNamesProvider; const SelectedItem, TopItem: integer); public { Public declarations } constructor Create (AOwner : TComponent); override; destructor Destroy; override; end; TEditSettingProperties = class (TFormSetting) private function GetLeftPanelWidth: integer; function GetTopPanelHeight: integer; procedure SetPanelWidth(const Value: integer); procedure SetTopPanelHeight(const Value: integer); published property TopPanelHeight : integer read GetTopPanelHeight write SetTopPanelHeight; property LeftPanelWidth : integer read GetLeftPanelWidth write SetPanelWidth; end; implementation uses IntfObserver, dmGlyphs; const //Captions for the menus. COPY_KEY_CAPTION = 'Copy "%0:s" To "%1:s"'; DELETE_KEY_CAPTION = 'Delete Key "%s"'; COPY_NAME_CAPTION = 'Copy "%s" To "%s"'; DELETE_NAME_CAPTION = 'Delete Name "%s"'; CLEAR_VALUE = 'Clear Value'; READ_ONLY_SUFFIX = ' (Read Only)'; CAPTION_COLOR : array [false..true] of TColor = (clWindowText, clRed); {$R *.dfm} { TForm1 } constructor TfrmEditSetting.Create (AOwner : TComponent); begin inherited; //Create the DelphiSettingRegistry and Disable the observer pattern here. FLeftRegistry := TDelphiSettingRegistry.Create; (FLeftRegistry as ISubject).Enabled := false; //Create the treeview controller, bind the DelphiSettingRegistry and the //TreeView. FLeftController := CreateTreeViewController; FLeftController.BindDelphiSettingRegistry(FLeftRegistry); FLeftController.BindTreeView (tvLeft); //Create the ValueNamesProvider. It is bound with the DelphiSettingRegistry. //Attach the events. FLeftValueNamesProvider := GetValueNamesProvider (FLeftRegistry); FLeftValueNamesProvider.OnValueNamesChanged := UpdateListBox; FLeftValueNamesProvider.OnAsStringChanged := DisplayValue; (FLeftRegistry as ISubject).Enabled := true; //Create the DelphiSettingRegistry and Disable the observer pattern here. FRightRegistry := TDelphiSettingRegistry.Create; (FRightRegistry as ISubject).Enabled := false; //Create the treeview controller, bind the DelphiSettingRegistry and the //TreeView. FRightController := CreateTreeViewController; FRightController.BindTreeView (tvRight); FRightController.BindDelphiSettingRegistry (FRightRegistry); //Create the ValueNamesProvider. It is bound with the DelphiSettingRegistry. //Attach the events. FRightValueNamesProvider := GetValueNamesProvider (FRightRegistry); FRightValueNamesProvider.OnValueNamesChanged := UpdateListBox; FRightValueNamesProvider.OnAsStringChanged := DisplayValue; (FRightRegistry as ISubject).Enabled := true; //Create the synchronizer. FSynchronizer := GetDelphiSettingSynchronizer; self.atbLeftNames.Orientation := boRightToLeft; self.atbLeftKey.Orientation := boRightToLeft; FSettingProperties := TEditSettingProperties.Create (self); SettingPersistent.GetIniPersistentManager.LoadSetting (FSettingProperties); end; function TfrmEditSetting.GetLeftSettingPath: string; begin Result := FLeftRegistry.SettingPath; end; function TfrmEditSetting.GetRightSettingPath: string; begin Result := FRightRegistry.SettingPath; end; //Set the left setting path. It opens the FLeftRegistryProvider, setup the //controller, add the treeview controller to the synchronizer. procedure TfrmEditSetting.SetLeftSettingPath(const APath: string); begin //Open the DelphiSettingRegistry, build the nodes based on the new path. FLeftRegistry.OpenSetting (APath); FLeftController.BuildNode (nil); //Add the controller to the synchronizer. FSynchronizer.AddTreeViewController (FLeftController); //Let the ValueNamesProvider knows what is the setting path of the //DelphiSettingRegistry. This value is necessary to get the relative path for //the ValueNamesProvider. FLeftValueNamesProvider.SetSettingPath (FLeftRegistry.SettingPath); //If the Path does not contain CustomSetting string, this path is the path to //the original Delphi IDE key. Disables the menus. FLeftReadOnly := Pos ('CustomSettings', APath) = 0; //Disables the menus when the custom setting is read-only. if FLeftReadOnly = true then begin self.actLeftDeleteKey.Enabled := false; self.actLeftDeleteName.Enabled := false; self.actLeftClearValue.Enabled := false; self.actRightCopyKeyTo.Enabled := false; self.actRightCopyNameTo.Enabled := false; SetLeftSettingName (FLeftSettingName); end; end; //Set the right pane. It opens the FRightRegistryProvider, setup the //controller, add the treeview controller to the synchronizer. procedure TfrmEditSetting.SetRightSettingPath(const APath: string); begin FRightRegistry.OpenSetting (APath); FRightController.BuildNode (nil); FSynchronizer.AddTreeViewController (FRightController); //Let the ValueNamesProvider knows what is the setting path of the //DelphiSettingRegistry. This value is necessary to get the relative path for //the ValueNamesProvider. FRightValueNamesProvider.SetSettingPath (FRightRegistry.SettingPath); //If the Path does not contain CustomSetting string, this path is the path to //the original Delphi IDE key. Disables the menus. FRightReadOnly := Pos ('CustomSettings', APath) = 0; if FRightReadOnly = true then begin self.actRightDeleteKey.Enabled := false; self.actRightDeleteName.Enabled := false; self.actRightClearValue.Enabled := false; self.actLeftCopyKeyTo.Enabled := false; self.actLeftCopyNameTo.Enabled := false; SetRightSettingName (FRightSettingName); lblRight.Caption := lblRight.Caption + ' (Read Only)'; end; end; procedure TfrmEditSetting.Execute; begin ShowModal; end; function TfrmEditSetting.GetLeftSettingName: string; begin Result := FLeftSettingName; end; function TfrmEditSetting.GetRightSettingName: string; begin Result := FRightSettingName; end; //UI stuff. Assign the name Delphi Setting Registry on the left pane. procedure TfrmEditSetting.SetLeftSettingName(const ASettingName: string); begin FLeftSettingName := ASettingName; if FLeftReadOnly = true then FLeftSettingName := ASettingName + READ_ONLY_SUFFIX; lblLeft.Caption := FLeftSettingName; lblLeft.Font.Color := CAPTION_COLOR [FLeftReadOnly]; end; //UI stuff. Assign the name Delphi Setting Registry on the right pane. procedure TfrmEditSetting.SetRightSettingName(const ASettingName: string); begin FRightSettingName := ASettingName; if FRightReadOnly = true then FRightSettingName := ASettingName + READ_ONLY_SUFFIX; lblRight.Caption := FRightSettingName; lblRight.Font.Color := CAPTION_COLOR [FRightReadOnly]; end; //This event is shared with spTree and spValues. pnlLeft is controlled by spTree //while pnlValuesLeft is controller by spValues. This event handler synchronizes //these two panels, that both will always be at the same size. procedure TfrmEditSetting.spTreeMoved(Sender: TObject); var ControlledPanel, OtherPanel : TPanel; begin //Get the other panel that is not controlled by the Sender. if (Sender = spTree) then begin ControlledPanel := pnlLeft; OtherPanel := pnlValuesLeft; end else begin ControlledPanel := pnlValuesLeft; OtherPanel := pnlLeft; end; //Synchronizes both panel. OtherPanel.Width := ControlledPanel.Width; end; procedure TfrmEditSetting.spTreeCanResize(Sender: TObject; var NewSize: Integer; var Accept: Boolean); begin Accept := (NewSize > 30); end; //Load the closed folder image if an item is drawn. procedure TfrmEditSetting.tvLeftGetImageIndex(Sender: TObject; Node: TTreeNode); begin Node.ImageIndex := 0; end; //Load the open folder image if an item is selected. procedure TfrmEditSetting.tvLeftGetSelectedIndex(Sender: TObject; Node: TTreeNode); begin Node.SelectedIndex := 1; end; //This method synchronizes the ListBox values. It compares two TStrings line by //line, and if two lines are not identical, that means there is a gap. If a gap //if found, this method will synchronizes the listbox by inserting an empty //string. The end result, two string list that each line will have same values //or the counterpart is blank. //If one TStrings is empty, it will remain empty. It won't be filled with blank //lines. //Both string must not be auto sorted. procedure TfrmEditSetting.BuildListBoxes(const ListA, ListB: TStrings); var CompareResult, LoopA, LoopB : integer; StrA, StrB : string; begin LoopA := 0; LoopB := 0; //Iterates both TStrings. while (LoopA < ListA.Count) and (LoopB < ListB.Count) do begin //Get the string for the first TString if LoopA < ListA.Count then StrA := ListA [LoopA] else StrA := EmptyStr; //Get the string for the second TString if LoopB < ListB.Count then StrB := ListB [LoopB] else StrB := EmptyStr; //Compare both strings. if the result is not identical, insert blank line //to at the location of the string that has greater value. CompareResult := CompareText (StrA, StrB); if (CompareResult > 0) then ListA.Insert (LoopA, EmptyStr) else if (CompareResult < 0) then ListB.Insert (LoopB, EmptyStr); Inc (LoopA); Inc (LoopB); end; //If both lines do not have same count, that means at the end of one TStrings, //there is no more text that can be compared. Add blank lines to the TStrings //that has less line items. while (ListA.Count <> ListB.Count) and ((ListA.Count <> 0) and (ListB.Count <> 0)) do if ListA.Count < ListB.Count then ListA.Append (EmptyStr) else ListB.Append (EmptyStr); end; //Event handler for ValueNamesProvider.OnValueNamesChanged. If the provider //is changed, this method will populate the listbox. This event handler is //shared by FLeftValueNamesProvider and FRightValueNamesProvider. procedure TfrmEditSetting.UpdateListBox(const Intf: IInterface); var NamesProvider, OtherProvider : IValueNamesProvider; StrActive, strOther : TStrings; begin //Get the left and the right provider, based on Intf parameter. NamesProvider := (Intf as IValueNamesProvider); if (NamesProvider = FLeftValueNamesProvider) then begin StrActive := lbLeftValues.Items; StrOther := lbRightValues.Items; OtherProvider := FRightValueNamesProvider; end else begin StrActive := lbRightValues.Items; StrOther := lbLeftValues.Items; OtherProvider := FLeftValueNamesProvider; end; if OtherProvider = nil then Exit; StrActive.BeginUpdate; StrOther.BeginUpdate; try //If the LeftProvider and the RightProvider have identical RelativePath, //this means that both providers have that key and are synchronized. Refresh //the ListBoxes for both ListBoxes and then synchronize the list boxes. if NamesProvider.RelativePath = OtherProvider.RelativePath then begin StrActive.Assign (NamesProvider.ValueNames); StrOther.Assign (OtherProvider.ValueNames); BuildListBoxes (StrActive, StrOther); end else begin //If the LeftProvider and the RightProvider does not point to the same //relative path, assign it to one and clear the other list box. This can //be one of two things, the "Other" provider does not have the key, or //both provider are not synchronized yet. StrActive.Assign (NamesProvider.ValueNames); StrOther.Clear; end; finally StrActive.EndUpdate; StrOther.EndUpdate; end; end; //Event handler for ValueNamesProvider.OnAsStringChanged. If the names have //values it will be displayed in the memo. If the left and the right are not //match, it will be displayed in green. This event handler is shared by //FLeftValueNamesProvider and FRightValueNamesProvider. procedure TfrmEditSetting.DisplayValue(const Intf: IInterface); var NamesProvider : IValueNamesProvider; Color : TColor; begin NamesProvider := Intf as IValueNamesProvider; //Find out which TMemo it should update. if NamesProvider = FLeftValueNamesProvider then memValueLeft.Lines.Text := NamesProvider.AsString else memValueRight.Lines.Text := NamesProvider.AsString; //If both TMemos have same value, set the color to normal, otherwise make it //green. if SameText (memValueLeft.Text, memValueRight.Text) then Color := clWindowText else Color := clGreen; memValueLeft.Font.Color := Color; memValueRight.Font.Color := Color; end; //Event handler when the list box is clicked. It will synchronizes both list //boxes. This event handler is shared by lbLeftValues and lbRightValues. procedure TfrmEditSetting.lbLeftValuesClick(Sender: TObject); var ListBox : TListBox; begin ListBox := (Sender as TListBox); SyncListBox (ListBox.ItemIndex, ListBox.TopIndex); end; //This method synchronizes the list box selection. procedure TfrmEditSetting.SyncListBox(const ANewSelection, ATopIndex: integer); procedure SetSelection (ListBox : TListBox; const NamesProvider : IValueNamesProvider); var ClickEvent : TNotifyEvent; SelectedName : string; begin //Disable the event handler, otherwise it might trapped into infinite loop. ClickEvent := ListBox.OnClick; ListBox.OnClick := nil; SelectedName := EmptyStr; //Set the ItemIndex and get the name. The name can be an empty string. Empty //string means that the selected name does not exist in the NameProvider. if ListBox.Items.Count > ANewSelection then begin ListBox.ItemIndex := ANewSelection; SelectedName := ListBox.Items [ANewSelection]; end; //Synchronizes the TopIndex. This will synchonizes not only the selection //but also the item positions. if ListBox.Items.Count > ATopIndex then ListBox.TopIndex := ATopIndex; //Update the NameProvider.SelectedIndex. Remember, if SelectedName is an //empty string, the selected index is -1. The value name does not exist. NamesProvider.SelectedIndex := NamesProvider.GetNameIndex (SelectedName); //Restore the event handler. ListBox.OnClick := ClickEvent; end; begin SetSelection (lbLeftValues, FLeftValueNamesProvider); SetSelection (lbRightValues, FRightValueNamesProvider); end; //Copy value copies a value name from the SourceProvider to the TargetProvider. //ListBox parameter is needed, after copying the name/value, the ListBoxes need //to be synchronized. //If the Name exist on both SourceProvider, the value will be copied. procedure TfrmEditSetting.CopyValue(const SourceListBox: TListBox; const SourceProvider, TargetProvider: IValueNamesProvider); var TopIndex, SelectedIndex : integer; begin TopIndex := SourceListBox.TopIndex; SelectedIndex := SourceListBox.ItemIndex; TargetProvider.CopySelectedValue (SourceProvider); SyncListBox (SelectedIndex, TopIndex); end; //Delete a key. There is no check whether the treeview is read-only or not. procedure TfrmEditSetting.DeleteCurrentKey( const DelphiRegistry: IDelphiSettingRegistry; const TreeView : TTreeView); const CONFIRM_DELETE_KEY = 'Are you sure you want to delete "%s"?'; var Node : TTreeNode; KeyName : string; begin Node := TreeView.Selected; KeyName := Node.Text; if (MessageDlg (Format (CONFIRM_DELETE_KEY, [KeyName]), mtConfirmation, [mbYes, mbNo], 0) = mrNo) then Exit; //Delete the current key. DelphiRegistry.DeleteCurrentKey; //The Treeview Controller does not rebuild the nodes when a node is deleted. //It is better to delete the node rather than clears the treeview and rebuild //everything. Node.Delete; end; //Delete selected value name, and synchronize the list box selection and top //position. procedure TfrmEditSetting.DeleteSelectedValue( const Provider: IValueNamesProvider; const SelectedItem, TopItem : integer); begin Provider.DeleteSelectedValue; if (SelectedItem < lbLeftValues.Items.Count) then begin lbLeftValues.Selected [SelectedItem] := true; lbLeftValues.TopIndex := TopItem; end; if (SelectedItem < lbRightValues.Items.Count) then begin lbRightValues.Selected [SelectedItem] := true; lbRightValues.TopIndex := TopItem; end; end; //Clear the selected value. procedure TfrmEditSetting.ClearSelectedValue( const Provider: IValueNamesProvider; const SelectedItem, TopItem : integer); begin Provider.ClearSelectedValue; if (SelectedItem < lbLeftValues.Items.Count) then begin lbLeftValues.Selected [SelectedItem] := true; lbLeftValues.TopIndex := TopItem; end; if (SelectedItem < lbRightValues.Items.Count) then begin lbRightValues.Selected [SelectedItem] := true; lbRightValues.TopIndex := TopItem; end; end; procedure TfrmEditSetting.actLeftCopyKeyToExecute(Sender: TObject); begin //Add Key. DelphiRegistrySetting will add the missing registry key, then it //will notify the changes and at the same time setting the newly created key //as the current key. TreeViewController as the observer will fail to find //related Node, as the key was just created. It then creates the node. //The OnChange event will get refired as side effect. FRightRegistry.AddKey (FLeftValueNamesProvider.RelativePath); end; procedure TfrmEditSetting.actRightCopyKeyToExecute(Sender: TObject); begin //Look at comment at the actLeftCopyKeyToExecute event handler. FLeftRegistry.AddKey (FRightValueNamesProvider.RelativePath); end; procedure TfrmEditSetting.actLeftDeleteKeyExecute(Sender: TObject); begin DeleteCurrentKey (FLeftRegistry, tvLeft); end; procedure TfrmEditSetting.actRightDeleteKeyExecute(Sender: TObject); begin DeleteCurrentKey (FRightRegistry, tvRight); end; procedure TfrmEditSetting.actRightCopyNameToExecute(Sender: TObject); begin CopyValue (lbRightValues, FRightValueNamesProvider, FLeftValueNamesProvider); end; procedure TfrmEditSetting.actLeftCopyNameToExecute(Sender: TObject); begin CopyValue (lbLeftValues, FLeftValueNamesProvider, FRightValueNamesProvider); end; procedure TfrmEditSetting.actLeftDeleteNameExecute(Sender: TObject); begin DeleteSelectedValue (FLeftValueNamesProvider, lbLeftValues.ItemIndex, lbLeftValues.TopIndex); end; procedure TfrmEditSetting.actRightDeleteNameExecute(Sender: TObject); begin DeleteSelectedValue (FRightValueNamesProvider, lbRightValues.ItemIndex, lbRightValues.TopIndex); end; procedure TfrmEditSetting.actLeftClearValueExecute(Sender: TObject); begin ClearSelectedValue (FLeftValueNamesProvider, lbLeftValues.ItemIndex, lbLeftValues.TopIndex); end; procedure TfrmEditSetting.actRightClearValueExecute(Sender: TObject); begin ClearSelectedValue (FRightValueNamesProvider, lbRightValues.ItemIndex, lbRightValues.TopIndex); end; //This event handler is shared by popLeftTree and popRightTree. //This menu does not enable or disable the menus based on the read-only property //as the menus is already disabled on SetLeftSettingPath and SetRightSettingPath procedure TfrmEditSetting.TreeMenuPopup(Sender: TObject); begin if Sender = popLeftTree then begin actLeftCopyKeyTo.Caption := Format (COPY_KEY_CAPTION, [tvLeft.Selected.Text, FRightSettingName]); actLeftDeleteKey.Caption := Format (DELETE_KEY_CAPTION, [tvLeft.Selected.Text]); end else begin actRightCopyKeyTo.Caption := Format (COPY_KEY_CAPTION, [tvRight.Selected.Text, FLeftSettingName]); actRightDeleteKey.Caption := Format (DELETE_KEY_CAPTION, [tvRight.Selected.Text]); end; end; //This event handler is shared by popLeftValue and popRightValue. //This controls what menus will be visible and what is the text for those menus. procedure TfrmEditSetting.popLeftValuePopup(Sender: TObject); var IsValueSelected : boolean; ValueName : string; begin if Sender = popLeftValue then begin //The blank lines on the ListBox can be a blank line or a missing value name //If it is a missing value name, SelectedIndex will be -1. IsValueSelected := (FLeftValueNamesProvider.SelectedIndex <> -1); //Set captions for the menus here. if (IsValueSelected = true) then begin ValueName := FLeftValueNamesProvider.ValueNames [FLeftValueNamesProvider.SelectedIndex]; actLeftCopyNameTo.Caption := Format (COPY_NAME_CAPTION, [ValueName, FRightSettingName]); actLeftDeleteName.Caption := Format (DELETE_NAME_CAPTION, [ValueName]); end; //Set whether the menus should be disabled or enabled. actLeftCopyNameTo.Enabled := IsValueSelected and (FRightReadOnly = false); actLeftDeleteName.Enabled := IsValueSelected and (FLeftReadOnly = false); actLeftClearValue.Enabled := IsValueSelected and (FLeftReadOnly = false); end else begin IsValueSelected := (FRightValueNamesProvider.SelectedIndex <> -1); if (IsValueSelected = true) then begin ValueName := FRightValueNamesProvider.ValueNames [FRightValueNamesProvider.SelectedIndex]; actRightCopyNameTo.Caption := Format (COPY_NAME_CAPTION, [ValueName, FLeftSettingName]); actRightDeleteName.Caption := Format (DELETE_NAME_CAPTION, [ValueName]); end; actRightCopyNameTo.Enabled := IsValueSelected and (FLeftReadOnly = false); actRightDeleteName.Enabled := IsValueSelected and (FRightReadOnly = false); actRightClearValue.Enabled := IsValueSelected and (FRightReadOnly = false); end; end; procedure TfrmEditSetting.FormResize(Sender: TObject); begin pnlValuesLeft.Width := pnlLeft.Width; end; procedure TfrmEditSetting.TreeViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key <> VK_DELETE) then Exit; if (Sender = tvLeft) and (FLeftReadOnly = false) then DeleteCurrentKey (FLeftRegistry, tvLeft); if (Sender = tvRight) and (FRightReadOnly = false) then DeleteCurrentKey (FRightRegistry, tvRight); end; procedure TfrmEditSetting.ValueNamesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key <> VK_DELETE) then Exit; if (Sender = lbLeftValues) and (FLeftReadOnly = false) then DeleteSelectedValue (FLeftValueNamesProvider, lbLeftValues.ItemIndex, lbLeftValues.TopIndex); if (Sender = lbRightValues) and (FRightReadOnly = false) then DeleteSelectedValue (FRightValueNamesProvider, lbRightValues.ItemIndex, lbRightValues.TopIndex); end; destructor TfrmEditSetting.Destroy; begin if Assigned (FSettingProperties) then begin SettingPersistent.GetIniPersistentManager.SaveSetting (FSettingProperties); FreeAndNil (FSettingProperties); end; inherited; end; { TEditSettingProperties } function TEditSettingProperties.GetTopPanelHeight: integer; begin Result := (Form as TfrmEditSetting).pnlTop.Height; end; procedure TEditSettingProperties.SetTopPanelHeight(const Value: integer); begin (Form as TfrmEditSetting).pnlTop.Height := Value; end; function TEditSettingProperties.GetLeftPanelWidth: integer; begin Result := (Form as TfrmEditSetting).pnlLeft.Width; end; procedure TEditSettingProperties.SetPanelWidth(const Value: integer); begin (Form as TfrmEditSetting).pnlLeft.Width := Value; end; end.
unit ControlBarImpl1; interface uses Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls, ComServ, StdVCL, AXCtrls, DelCtrls_TLB, ExtCtrls; type TControlBarX = class(TActiveXControl, IControlBarX) private { Private declarations } FDelphiControl: TControlBar; FEvents: IControlBarXEvents; procedure CanResizeEvent(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); procedure ClickEvent(Sender: TObject); procedure ConstrainedResizeEvent(Sender: TObject; var MinWidth, MinHeight, MaxWidth, MaxHeight: Integer); procedure DblClickEvent(Sender: TObject); procedure PaintEvent(Sender: TObject); procedure ResizeEvent(Sender: TObject); protected { Protected declarations } procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override; procedure EventSinkChanged(const EventSink: IUnknown); override; procedure InitializeControl; override; function ClassNameIs(const Name: WideString): WordBool; safecall; function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall; function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall; function Get_AutoDrag: WordBool; safecall; function Get_AutoSize: WordBool; safecall; function Get_BevelInner: TxBevelCut; safecall; function Get_BevelKind: TxBevelKind; safecall; function Get_BevelOuter: TxBevelCut; safecall; function Get_BiDiMode: TxBiDiMode; safecall; function Get_Color: OLE_COLOR; safecall; function Get_Cursor: Smallint; safecall; function Get_DockSite: WordBool; safecall; function Get_DoubleBuffered: WordBool; safecall; function Get_DragCursor: Smallint; safecall; function Get_DragMode: TxDragMode; safecall; function Get_Enabled: WordBool; safecall; function Get_ParentColor: WordBool; safecall; function Get_ParentCtl3D: WordBool; safecall; function Get_ParentFont: WordBool; safecall; function Get_Picture: IPictureDisp; safecall; function Get_RowSnap: WordBool; safecall; function Get_Visible: WordBool; safecall; function GetControlsAlignment: TxAlignment; safecall; function IsRightToLeft: WordBool; safecall; function UseRightToLeftAlignment: WordBool; safecall; function UseRightToLeftReading: WordBool; safecall; function UseRightToLeftScrollBar: WordBool; safecall; procedure AboutBox; safecall; procedure FlipChildren(AllLevels: WordBool); safecall; procedure InitiateAction; safecall; procedure Set_AutoDrag(Value: WordBool); safecall; procedure Set_AutoSize(Value: WordBool); safecall; procedure Set_BevelInner(Value: TxBevelCut); safecall; procedure Set_BevelKind(Value: TxBevelKind); safecall; procedure Set_BevelOuter(Value: TxBevelCut); safecall; procedure Set_BiDiMode(Value: TxBiDiMode); safecall; procedure Set_Color(Value: OLE_COLOR); safecall; procedure Set_Cursor(Value: Smallint); safecall; procedure Set_DockSite(Value: WordBool); safecall; procedure Set_DoubleBuffered(Value: WordBool); safecall; procedure Set_DragCursor(Value: Smallint); safecall; procedure Set_DragMode(Value: TxDragMode); safecall; procedure Set_Enabled(Value: WordBool); safecall; procedure Set_ParentColor(Value: WordBool); safecall; procedure Set_ParentCtl3D(Value: WordBool); safecall; procedure Set_ParentFont(Value: WordBool); safecall; procedure Set_Picture(const Value: IPictureDisp); safecall; procedure Set_RowSnap(Value: WordBool); safecall; procedure Set_Visible(Value: WordBool); safecall; procedure StickControls; safecall; end; implementation uses ComObj, About8; { TControlBarX } procedure TControlBarX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); begin { Define property pages here. Property pages are defined by calling DefinePropertyPage with the class id of the page. For example, DefinePropertyPage(Class_ControlBarXPage); } end; procedure TControlBarX.EventSinkChanged(const EventSink: IUnknown); begin FEvents := EventSink as IControlBarXEvents; end; procedure TControlBarX.InitializeControl; begin FDelphiControl := Control as TControlBar; FDelphiControl.OnCanResize := CanResizeEvent; FDelphiControl.OnClick := ClickEvent; FDelphiControl.OnConstrainedResize := ConstrainedResizeEvent; FDelphiControl.OnDblClick := DblClickEvent; FDelphiControl.OnPaint := PaintEvent; FDelphiControl.OnResize := ResizeEvent; end; function TControlBarX.ClassNameIs(const Name: WideString): WordBool; begin Result := FDelphiControl.ClassNameIs(Name); end; function TControlBarX.DrawTextBiDiModeFlags(Flags: Integer): Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlags(Flags); end; function TControlBarX.DrawTextBiDiModeFlagsReadingOnly: Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly; end; function TControlBarX.Get_AutoDrag: WordBool; begin Result := FDelphiControl.AutoDrag; end; function TControlBarX.Get_AutoSize: WordBool; begin Result := FDelphiControl.AutoSize; end; function TControlBarX.Get_BevelInner: TxBevelCut; begin Result := Ord(FDelphiControl.BevelInner); end; function TControlBarX.Get_BevelKind: TxBevelKind; begin Result := Ord(FDelphiControl.BevelKind); end; function TControlBarX.Get_BevelOuter: TxBevelCut; begin Result := Ord(FDelphiControl.BevelOuter); end; function TControlBarX.Get_BiDiMode: TxBiDiMode; begin Result := Ord(FDelphiControl.BiDiMode); end; function TControlBarX.Get_Color: OLE_COLOR; begin Result := OLE_COLOR(FDelphiControl.Color); end; function TControlBarX.Get_Cursor: Smallint; begin Result := Smallint(FDelphiControl.Cursor); end; function TControlBarX.Get_DockSite: WordBool; begin Result := FDelphiControl.DockSite; end; function TControlBarX.Get_DoubleBuffered: WordBool; begin Result := FDelphiControl.DoubleBuffered; end; function TControlBarX.Get_DragCursor: Smallint; begin Result := Smallint(FDelphiControl.DragCursor); end; function TControlBarX.Get_DragMode: TxDragMode; begin Result := Ord(FDelphiControl.DragMode); end; function TControlBarX.Get_Enabled: WordBool; begin Result := FDelphiControl.Enabled; end; function TControlBarX.Get_ParentColor: WordBool; begin Result := FDelphiControl.ParentColor; end; function TControlBarX.Get_ParentCtl3D: WordBool; begin Result := FDelphiControl.ParentCtl3D; end; function TControlBarX.Get_ParentFont: WordBool; begin Result := FDelphiControl.ParentFont; end; function TControlBarX.Get_Picture: IPictureDisp; begin GetOlePicture(FDelphiControl.Picture, Result); end; function TControlBarX.Get_RowSnap: WordBool; begin Result := FDelphiControl.RowSnap; end; function TControlBarX.Get_Visible: WordBool; begin Result := FDelphiControl.Visible; end; function TControlBarX.GetControlsAlignment: TxAlignment; begin Result := TxAlignment(FDelphiControl.GetControlsAlignment); end; function TControlBarX.IsRightToLeft: WordBool; begin Result := FDelphiControl.IsRightToLeft; end; function TControlBarX.UseRightToLeftAlignment: WordBool; begin Result := FDelphiControl.UseRightToLeftAlignment; end; function TControlBarX.UseRightToLeftReading: WordBool; begin Result := FDelphiControl.UseRightToLeftReading; end; function TControlBarX.UseRightToLeftScrollBar: WordBool; begin Result := FDelphiControl.UseRightToLeftScrollBar; end; procedure TControlBarX.AboutBox; begin ShowControlBarXAbout; end; procedure TControlBarX.FlipChildren(AllLevels: WordBool); begin FDelphiControl.FlipChildren(AllLevels); end; procedure TControlBarX.InitiateAction; begin FDelphiControl.InitiateAction; end; procedure TControlBarX.Set_AutoDrag(Value: WordBool); begin FDelphiControl.AutoDrag := Value; end; procedure TControlBarX.Set_AutoSize(Value: WordBool); begin FDelphiControl.AutoSize := Value; end; procedure TControlBarX.Set_BevelInner(Value: TxBevelCut); begin FDelphiControl.BevelInner := TBevelCut(Value); end; procedure TControlBarX.Set_BevelKind(Value: TxBevelKind); begin FDelphiControl.BevelKind := TBevelKind(Value); end; procedure TControlBarX.Set_BevelOuter(Value: TxBevelCut); begin FDelphiControl.BevelOuter := TBevelCut(Value); end; procedure TControlBarX.Set_BiDiMode(Value: TxBiDiMode); begin FDelphiControl.BiDiMode := TBiDiMode(Value); end; procedure TControlBarX.Set_Color(Value: OLE_COLOR); begin FDelphiControl.Color := TColor(Value); end; procedure TControlBarX.Set_Cursor(Value: Smallint); begin FDelphiControl.Cursor := TCursor(Value); end; procedure TControlBarX.Set_DockSite(Value: WordBool); begin FDelphiControl.DockSite := Value; end; procedure TControlBarX.Set_DoubleBuffered(Value: WordBool); begin FDelphiControl.DoubleBuffered := Value; end; procedure TControlBarX.Set_DragCursor(Value: Smallint); begin FDelphiControl.DragCursor := TCursor(Value); end; procedure TControlBarX.Set_DragMode(Value: TxDragMode); begin FDelphiControl.DragMode := TDragMode(Value); end; procedure TControlBarX.Set_Enabled(Value: WordBool); begin FDelphiControl.Enabled := Value; end; procedure TControlBarX.Set_ParentColor(Value: WordBool); begin FDelphiControl.ParentColor := Value; end; procedure TControlBarX.Set_ParentCtl3D(Value: WordBool); begin FDelphiControl.ParentCtl3D := Value; end; procedure TControlBarX.Set_ParentFont(Value: WordBool); begin FDelphiControl.ParentFont := Value; end; procedure TControlBarX.Set_Picture(const Value: IPictureDisp); begin SetOlePicture(FDelphiControl.Picture, Value); end; procedure TControlBarX.Set_RowSnap(Value: WordBool); begin FDelphiControl.RowSnap := Value; end; procedure TControlBarX.Set_Visible(Value: WordBool); begin FDelphiControl.Visible := Value; end; procedure TControlBarX.StickControls; begin FDelphiControl.StickControls; end; procedure TControlBarX.CanResizeEvent(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); var TempNewWidth: Integer; TempNewHeight: Integer; TempResize: WordBool; begin TempNewWidth := Integer(NewWidth); TempNewHeight := Integer(NewHeight); TempResize := WordBool(Resize); if FEvents <> nil then FEvents.OnCanResize(TempNewWidth, TempNewHeight, TempResize); NewWidth := Integer(TempNewWidth); NewHeight := Integer(TempNewHeight); Resize := Boolean(TempResize); end; procedure TControlBarX.ClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnClick; end; procedure TControlBarX.ConstrainedResizeEvent(Sender: TObject; var MinWidth, MinHeight, MaxWidth, MaxHeight: Integer); var TempMinWidth: Integer; TempMinHeight: Integer; TempMaxWidth: Integer; TempMaxHeight: Integer; begin TempMinWidth := Integer(MinWidth); TempMinHeight := Integer(MinHeight); TempMaxWidth := Integer(MaxWidth); TempMaxHeight := Integer(MaxHeight); if FEvents <> nil then FEvents.OnConstrainedResize(TempMinWidth, TempMinHeight, TempMaxWidth, TempMaxHeight); MinWidth := Integer(TempMinWidth); MinHeight := Integer(TempMinHeight); MaxWidth := Integer(TempMaxWidth); MaxHeight := Integer(TempMaxHeight); end; procedure TControlBarX.DblClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnDblClick; end; procedure TControlBarX.PaintEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnPaint; end; procedure TControlBarX.ResizeEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnResize; end; initialization TActiveXControlFactory.Create( ComServer, TControlBarX, TControlBar, Class_ControlBarX, 8, '{695CDB10-02E5-11D2-B20D-00C04FA368D4}', OLEMISC_SIMPLEFRAME or OLEMISC_ACTSLIKELABEL, tmApartment); end.
unit testTreeView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls; type TtestTreeViewForm = class(TForm) tv1: TTreeView; edt1: TEdit; btn1: TButton; procedure edt1Change(Sender: TObject); procedure FormCreate(Sender: TObject); procedure tv1AdvancedCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean); procedure btn1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var testTreeViewForm: TtestTreeViewForm; implementation uses UPointerTestFrm; {$R *.dfm} function GetNextPart(var str: string; Sep1: char = char(9); Sep2: char = ','; Position: integer = 1): string; var intPos: integer; begin intPos := pos(Sep1, str); if (intPos = 0) and (Sep2 <> '') then intPos := pos(Sep2, str); if intPos > 0 then begin result := Copy(str, 1, intPos - 1); Delete(str, 1, intPos); end else begin result := str; str := ''; end; if (intPos > 0) and (Position > 1) then result := GetNextPart(str, Sep1, Sep2, Position - 1); end; procedure TtestTreeViewForm.edt1Change(Sender: TObject); var i: integer; IntSearch, IntTmp: integer; strTmp: string; begin IntSearch := strtointdef(edt1.text, 0); if IntSearch <> 0 then begin for i := 0 to tv1.Items.Count - 1 do begin strTmp := tv1.Items.Item[i].Text; strTmp := getnextpart(strTmp, ' '); IntTmp := strtointdef(strTmp, 0); if IntSearch = IntTmp then begin tv1.Select(tv1.Items.item[i]); end; end; end; end; procedure TtestTreeViewForm.FormCreate(Sender: TObject); begin tv1.FullExpand; end; procedure TtestTreeViewForm.tv1AdvancedCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean); begin if TTreeView(sender).Selected = Node then Sender.Canvas.Brush.Color := clblue; end; procedure TtestTreeViewForm.btn1Click(Sender: TObject); begin PointerTestForm := TPointerTestForm.Create(Self); PointerTestForm.show; end; end.
unit WriterThread; interface uses Windows, Classes, Math, SysUtils, ltr34api, Dialogs, ltrapi, Config; type TWriter = class(TThread) private procedure WriteConfigInfo(path : string); public path:string; frequency:string; Files : array of TextFile; skipAmount: integer; History: THistory; stop:boolean; debugFile:TextFile; Config:TConfig; constructor Create(ipath: string; ifrequency: string; iskipAmount: integer; SuspendCreate : Boolean; ConfigRef : TConfig); destructor Free(); procedure Save(); procedure CreateFiles(); procedure CloseFiles(); procedure DebugWrite(Value: Double); end; implementation constructor TWriter.Create(ipath: string; ifrequency: string; iskipAmount: integer; SuspendCreate : Boolean; ConfigRef : TConfig); begin path:=ipath; frequency:=ifrequency; skipAmount:=iskipAmount; Config := ConfigRef; SetLength(Files, ChannelsAmount); Inherited Create(SuspendCreate); CreateFiles(); end; procedure TWriter.DebugWrite(Value: Double); begin writeln(debugFile, FloatToStr(Value)); end; procedure TWriter.WriteConfigInfo(path : string); var configFile:TextFile; begin System.Assign(configFile, path); ReWrite(configFile); writeln(configFile, path); writeln(configFile, 'Продолжительность записи: ' + Config.ProcessTime); writeln(configFile, 'Пишется каждое ' + Config.SkippedNumbers + '-е число.'); writeln(configFile, ''); writeln(configFile, '[Режим]'); writeln(configFile, 'Калибровка: ' + Config.Calibration); writeln(configFile, 'Бесконечная запись: ' + Config.UnlimWriting); writeln(configFile, 'Показывать сигнал: ' + Config.ShowSignal); writeln(configFile, ''); writeln(configFile, '[АЦП]'); writeln(configFile, 'Диапазон: ' + Config.ACPrange); writeln(configFile, 'Режим отсечки постоянной: ' + Config.ACPmode); writeln(configFile, 'Частота работы АЦП: ' + Config.ACPfreq); writeln(configFile, 'Разрядность данных: ' + Config.ACPbits); writeln(configFile, ''); writeln(configFile, '[Оптим.]'); writeln(configFile, 'Ширина оптимального положения: ' + Config.OptWide + '% амплитуды'); writeln(configFile, ''); writeln(configFile, '[Сбросы]'); writeln(configFile, '1-й датчик: ' + Config.ResetVt1 + ' Вольт'); writeln(configFile, '2-й датчик: ' + Config.ResetVt2 + ' Вольт'); writeln(configFile, ''); writeln(configFile, '[Порог]'); writeln(configFile, 'Рабочая точка движется медленнее, чем ' + Config.WorkpointSpeedLimit + '% амплитуды за блок'); writeln(configFile, ''); writeln(configFile, '[Множитель]'); writeln(configFile, '1-й датчик х ' + Config.Mult1); writeln(configFile, '2-й датчик х ' + Config.Mult2); writeln(configFile, ''); writeln(configFile, '[Низкочастот.]'); writeln(configFile, 'Считается средним по ' + Config.BlocksForLowfreqCalculation + ' блокам данных.'); writeln(configFile, 'Время записи 1 блока: ' + Config.TimeToWriteBlock + ' мс.'); CloseFile(configFile); end; procedure TWriter.Save; var ch,i,skipInd, size, skips: Integer; buffer: string; sum:double; begin size := Length(History[0])-1; skips :=Trunc(size/skipAmount); EnterCriticalSection(HistorySection); for ch:=0 to DevicesAmount-1 do begin for i := 0 to skips-1 do begin sum:=0; for skipInd:= 0 to skipAmount-1 do begin sum := sum+History[ch, i*skipAmount + skipInd]; end; if (skipAmount>1)then sum:=Floor(outputMultiplicators[ch]*(sum/skipAmount)) else sum:=Floor(outputMultiplicators[ch]*sum); buffer:=buffer + FloatToStr(sum) + LineBreak; end; writeln(Files[ch], buffer); end; LeaveCriticalSection(HistorySection); end; destructor TWriter.Free(); begin CloseFiles(); Inherited Free(); end; procedure TWriter.CreateFiles; var TimeMark, P: string; i,deviceN,fileIndex: integer; begin TimeSeparator := '-'; TimeMark := DateToStr(Now) + TimeSeparator + TimeToStr(Now); TimeMark := StringReplace(TimeMark, '/', TimeSeparator, [rfReplaceAll]); TimeMark := StringReplace(TimeMark, ' ', TimeSeparator, [rfReplaceAll]); P:= path +'\EU2.' + frequency + '.' + TimeMark; System.MkDir(P); for deviceN := 0 to DevicesAmount-1 do begin for i := 0 to ChannelsPerDevice-1 do begin fileIndex := i+deviceN*(ChannelsPerDevice); System.Assign(Files[fileIndex], P + '\Device'+ InttoStr(deviceN) +'-Cn' + InttoStr(i) + '.txt'); ReWrite(Files[fileIndex]); end; end; System.Assign(debugFile, P + '\Device0-DAC.txt'); ReWrite(debugFile); WriteConfigInfo(P + '\Config.txt'); end; procedure TWriter.CloseFiles; var i:integer; begin CloseFile(debugFile); for i := 0 to DevicesAmount-1 do CloseFile(Files[i]); end; end.
// **************************************************************************** // * mxWebUpdate Component for Delphi 5,6,7 // **************************************************************************** // * CopyRight 2002-2005, Bitvadász Kft. All Rights Reserved. // **************************************************************************** // * This component can be freely used and distributed in commercial and // * private environments, provied this notice is not modified in any way. // **************************************************************************** // * Feel free to contact me if you have any questions, comments or suggestions // * at support@maxcomponents.net // **************************************************************************** // * Web page: www.maxcomponents.net // **************************************************************************** // * Description: // * // * TmxWebUpdate helps you to add automatic update support to your application. // * It retrieves information from the web, if a newer version available, it // * can download a file via HTTP and run the update. // * // **************************************************************************** Unit mxWebUpdateInfo; Interface Uses Windows, Forms, ImgList, Controls, StdCtrls, Graphics, ExtCtrls, Classes, OleCtrls, SHDocVw; Type Tfrm_ShowInfoUpdate = Class( TForm ) Panel_Bottom: TPanel; Panel2: TPanel; chk_FutureUpdate: TCheckBox; btn_OK: TButton; btn_Cancel: TButton; Panel1: TPanel; WebBrowser: TWebBrowser; Procedure Panel_BottomResize( Sender: TObject ); Private Public End; //************************************************************************** //* I M P L E M E N T A T I O N //************************************************************************** Implementation Uses Sysutils; {$R *.DFM} Procedure Tfrm_ShowInfoUpdate.Panel_BottomResize( Sender: TObject ); Begin btn_OK.Left := ( Panel_Bottom.Width - ( btn_OK.Width + btn_Cancel.Width + 6 ) ) Div 2; btn_Cancel.Left := btn_OK.Left + btn_OK.Width + 3; End; End.
unit ncaFrmPopupUnidade; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ncaFrmPopUpEdit, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, DB, cxDBData, nxdb, dxBarExtItems, dxBar, cxClasses, Menus, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridCustomView, cxGrid, ExtCtrls, uParentedPanel, cxDBEdit, cxContainer, cxTextEdit, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, cxPCdxBarPopupMenu, cxPC, StdCtrls, cxButtons, uNexTransResourceStrings_PT; type TFrmPopupUnidade = class(TFrmPopUpEdit) private { Private declarations } public procedure Inicializar(aPopUp : TcxDBPopupEdit; aTabGeral:tDataset); override; { Public declarations } end; var FrmPopupUnidade: TFrmPopupUnidade; implementation {$R *.dfm} { TFrmCategoria } procedure TFrmPopupUnidade.Inicializar(aPopUp: TcxDBPopupEdit; aTabGeral: tDataset); begin fNomeTabelaPrincipal := 'produto'; // do not localize fNomeCampoTabelaPrincipal := 'unid'; // do not localize fNomeTabelaValores := 'unidade'; // do not localize fNomeCampoTabelaValores := 'descricao'; // do not localize fDescricao := SncaFrmPopupUnidade_Unidade; fCannotDeleteText := SncaFrmPopupUnidade_NãoéPossívelA; fCannotEditText := SncaFrmPopupUnidade_EstaUnidadeJá; inherited; end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC Oracle Call Interface } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.OracleCli; interface uses FireDAC.Stan.Intf; {----------------------------------------------------------------------------} { ORATYPES.H } {----------------------------------------------------------------------------} type // Generic Oracle Types sword = Integer; eword = Integer; uword = Cardinal; sb8 = Int64; ub8 = UInt64; sb4 = Integer; ub4 = Cardinal; sb2 = SmallInt; ub2 = Word; sb1 = ShortInt; ub1 = Byte; dvoid = Pointer; pOCIText = PByte; pUb1 = ^ub1; pSb1 = ^sb1; pUb2 = ^ub2; pSb2 = ^sb2; pUb4 = ^ub4; pSb4 = ^sb4; ppUb1 = ^pUb1; ppUb4 = ^pUb4; TUB1Array = array[0..$FFFF] of ub1; PUB1Array = ^TUB1Array; TSB2Array = array[0..$FFFF] of sb2; PSB2Array = ^TSB2Array; TUB2Array = array[0..$FFFF] of ub2; PUB2Array = ^TUB2Array; TUB4Array = array[0..$FFFF] of ub4; PUB4Array = ^TUB4Array; TBoolArray = array[0..$FFFF] of Boolean; PBoolArray = ^TBoolArray; const MAXUB4 = High(ub4); MAXSB4 = High(sb4); MINUB4MAXVAL = MAXUB4; UB4MAXVAL = MAXUB4; type TOraDate = packed record century, year, month, day, hour, minute, second: ub1; end; POraDate = ^TOraDate; {----------------------------------------------------------------------------} { OCI.H } {----------------------------------------------------------------------------} //-----------------------Handle Definitions---------------------------------- pOCIHandle = pointer; ppOCIHandle = ^pOCIHandle; pOCIEnv = pOCIHandle; pOCIServer = pOCIHandle; pOCIError = pOCIHandle; pOCISvcCtx = pOCIHandle; pOCIStmt = pOCIHandle; pOCIDefine = pOCIHandle; pOCISession = pOCIHandle; pOCITrans = pOCIHandle; pOCIBind = pOCIHandle; pOCIDescribe = pOCIHandle; pOCIDirPathCtx = pOCIHandle; pOCIDirPathColArray = pOCIHandle; pOCIDirPathStream = pOCIHandle; pOCIAdmin = pOCIHandle; pOCISubscription = pOCIHandle; //-----------------------Descriptor Definitions------------------------------ pOCIDescriptor = pOCIHandle; pOCISnapshot = pOCIDescriptor; pOCILobLocator = pOCIDescriptor; pOCIParam = pOCIDescriptor; pOCIRowid = pOCIDescriptor; pOCIComplexObjectComp = pOCIDescriptor; pOCIAQEnqOptions = pOCIDescriptor; pOCIAQDeqOptions = pOCIDescriptor; pOCIAQMsgProperties = pOCIDescriptor; pOCIAQAgent = pOCIDescriptor; pOCIDirPathDesc = pOCIDescriptor; pOCIDateTime = pOCIDescriptor; pOCIInterval = pOCIDescriptor; const //-----------------------------Handle Types---------------------------------- OCI_HTYPE_FIRST = 1; OCI_HTYPE_ENV = 1; OCI_HTYPE_ERROR = 2; OCI_HTYPE_SVCCTX = 3; OCI_HTYPE_STMT = 4; OCI_HTYPE_BIND = 5; OCI_HTYPE_DEFINE = 6; OCI_HTYPE_DESCRIBE = 7; OCI_HTYPE_SERVER = 8; OCI_HTYPE_SESSION = 9; OCI_HTYPE_TRANS = 10; OCI_HTYPE_COMPLEXOBJECT = 11; OCI_HTYPE_SECURITY = 12; OCI_HTYPE_SUBSCRIPTION = 13; // subscription handle OCI_HTYPE_DIRPATH_CTX = 14; // direct path context OCI_HTYPE_DIRPATH_COLUMN_ARRAY = 15; // direct path column array OCI_HTYPE_DIRPATH_STREAM = 16; // direct path stream OCI_HTYPE_PROC = 17; // process handle // post 8.1 OCI_HTYPE_DIRPATH_FN_CTX = 18; // direct path function context OCI_HTYPE_DIRPATH_FN_COL_ARRAY = 19; // dp object column array OCI_HTYPE_XADSESSION = 20; // access driver session OCI_HTYPE_XADTABLE = 21; // access driver table OCI_HTYPE_XADFIELD = 22; // access driver field OCI_HTYPE_XADGRANULE = 23; // access driver granule OCI_HTYPE_XADRECORD = 24; // access driver record OCI_HTYPE_XADIO = 25; // access driver I/O OCI_HTYPE_CPOOL = 26; // connection pool handle OCI_HTYPE_SPOOL = 27; // session pool handle // post 10.2 OCI_HTYPE_ADMIN = 28; // admin handle OCI_HTYPE_EVENT = 29; // HA event handle OCI_HTYPE_LAST = 29; //-------------------------Descriptor Types---------------------------------- OCI_DTYPE_FIRST = 50; OCI_DTYPE_LOB = 50; OCI_DTYPE_SNAP = 51; OCI_DTYPE_RSET = 52; OCI_DTYPE_PARAM = 53; OCI_DTYPE_ROWID = 54; OCI_DTYPE_COMPLEXOBJECTCOMP = 55; OCI_DTYPE_FILE = 56; OCI_DTYPE_AQENQ_OPTIONS = 57; OCI_DTYPE_AQDEQ_OPTIONS = 58; OCI_DTYPE_AQMSG_PROPERTIES = 59; OCI_DTYPE_AQAGENT = 60; OCI_DTYPE_LOCATOR = 61; // LOB locator // >= 9.0 OCI_DTYPE_INTERVAL_YM = 62; // Interval year month OCI_DTYPE_INTERVAL_DS = 63; // Interval day second OCI_DTYPE_AQNFY_DESCRIPTOR = 64; // AQ notify descriptor // >= 8.1 OCI_DTYPE_DATE = 65; // Date OCI_DTYPE_TIME = 66; // Time OCI_DTYPE_TIME_TZ = 67; // Time with timezone OCI_DTYPE_TIMESTAMP = 68; // Timestamp OCI_DTYPE_TIMESTAMP_TZ = 69; // Timestamp with timezone OCI_DTYPE_TIMESTAMP_LTZ = 70; // Timestamp with local tz OCI_DTYPE_UCB = 71; // user callback descriptor OCI_DTYPE_SRVDN = 72; // server DN list descriptor OCI_DTYPE_SIGNATURE = 73; // signature OCI_DTYPE_RESERVED_1 = 74; // reserved for internal use OCI_DTYPE_AQLIS_OPTIONS = 75; // AQ listen options OCI_DTYPE_AQLIS_MSG_PROPERTIES = 76; // AQ listen msg props OCI_DTYPE_CHDES = 77; // Top level change notification desc OCI_DTYPE_TABLE_CHDES = 78; // Table change descriptor OCI_DTYPE_ROW_CHDES = 79; // Row change descriptor OCI_DTYPE_CQDES = 80; // Query change descriptor OCI_DTYPE_LOB_REGION = 81; // LOB Share region descriptor OCI_DTYPE_RESERVED_82 = 82; // reserved OCI_DTYPE_LAST = 82; // last value of a descriptor type // --------------------------------LOB types --------------------------------- OCI_TEMP_BLOB = 1; // LOB type - BLOB OCI_TEMP_CLOB = 2; // LOB type - CLOB OCI_TEMP_NCLOB = 3; //-------------------------Object Ptr Types---------------------------------- OCI_OTYPE_NAME = 1; // object name OCI_OTYPE_REF = 2; // REF to TDO OCI_OTYPE_PTR = 3; // PTR to TDO // -------------------------Attributes Types---------------------------------- OCI_ATTR_FNCODE = 1; // the OCI function code OCI_ATTR_OBJECT = 2; // is the environment initialized in object mode OCI_ATTR_NONBLOCKING_MODE = 3; // non blocking mode OCI_ATTR_SQLCODE = 4; // the SQL verb OCI_ATTR_ENV = 5; // the environment handle OCI_ATTR_SERVER = 6; // the server handle OCI_ATTR_SESSION = 7; // the user session handle OCI_ATTR_TRANS = 8; // the transaction handle OCI_ATTR_ROW_COUNT = 9; // the rows processed so far OCI_ATTR_SQLFNCODE = 10; // the SQL verb of the statement OCI_ATTR_PREFETCH_ROWS = 11; // sets the number of rows to prefetch OCI_ATTR_NESTED_PREFETCH_ROWS = 12; // the prefetch rows of nested table OCI_ATTR_PREFETCH_MEMORY = 13; // memory limit for rows fetched OCI_ATTR_NESTED_PREFETCH_MEMORY = 14; // memory limit for nested rows OCI_ATTR_CHAR_COUNT = 15; // this specifies the bind and define size in characters OCI_ATTR_PDSCL = 16; // packed decimal scale OCI_ATTR_FSPRECISION = OCI_ATTR_PDSCL; // fs prec for datetime data types OCI_ATTR_PDPRC = 17; // packed decimal format OCI_ATTR_LFPRECISION = OCI_ATTR_PDPRC; // fs prec for datetime data types OCI_ATTR_PARAM_COUNT = 18; // number of column in the select list OCI_ATTR_ROWID = 19; // the rowid OCI_ATTR_CHARSET = 20; // the character set value OCI_ATTR_NCHAR = 21; // NCHAR type OCI_ATTR_USERNAME = 22; // username attribute OCI_ATTR_PASSWORD = 23; // password attribute OCI_ATTR_STMT_TYPE = 24; // statement type OCI_ATTR_INTERNAL_NAME = 25; // user friendly global name OCI_ATTR_EXTERNAL_NAME = 26; // the internal name for global txn OCI_ATTR_XID = 27; // XOPEN defined global transaction id OCI_ATTR_TRANS_LOCK = 28; // OCI_ATTR_TRANS_NAME = 29; // string to identify a global transaction OCI_ATTR_HEAPALLOC = 30; // memory allocated on the heap OCI_ATTR_CHARSET_ID = 31; // Character Set ID OCI_ATTR_CHARSET_FORM = 32; // Character Set Form OCI_ATTR_MAXDATA_SIZE = 33; // Maximumsize of data on the server OCI_ATTR_CACHE_OPT_SIZE = 34; // object cache optimal size OCI_ATTR_CACHE_MAX_SIZE = 35; // object cache maximum size percentage OCI_ATTR_PINOPTION = 36; // object cache default pin option OCI_ATTR_ALLOC_DURATION = 37; // object cache default allocation duration OCI_ATTR_PIN_DURATION = 38; // object cache default pin duration OCI_ATTR_FDO = 39; // Format Descriptor object attribute OCI_ATTR_POSTPROCESSING_CALLBACK = 40; // Callback to process outbind data OCI_ATTR_POSTPROCESSING_CONTEXT = 41; // Callback context to process outbind data OCI_ATTR_ROWS_RETURNED = 42; // Number of rows returned in current iter - for Bind handles OCI_ATTR_FOCBK = 43; // Failover Callback attribute OCI_ATTR_IN_V8_MODE = 44; // is the server/service context in V8 mode OCI_ATTR_LOBEMPTY = 45; // empty lob ? OCI_ATTR_SESSLANG = 46; // session language handle OCI_ATTR_VISIBILITY = 47; // visibility OCI_ATTR_RELATIVE_MSGID = 48; // relative message id OCI_ATTR_SEQUENCE_DEVIATION = 49; // sequence deviation OCI_ATTR_CONSUMER_NAME = 50; // consumer name OCI_ATTR_DEQ_MODE = 51; // dequeue mode OCI_ATTR_NAVIGATION = 52; // navigation OCI_ATTR_WAIT = 53; // wait OCI_ATTR_DEQ_MSGID = 54; // dequeue message id OCI_ATTR_PRIORITY = 55; // priority OCI_ATTR_DELAY = 56; // delay OCI_ATTR_EXPIRATION = 57; // expiration OCI_ATTR_CORRELATION = 58; // correlation id OCI_ATTR_ATTEMPTS = 59; // # of attempts OCI_ATTR_RECIPIENT_LIST = 60; // recipient list OCI_ATTR_EXCEPTION_QUEUE = 61; // exception queue name OCI_ATTR_ENQ_TIME = 62; // enqueue time (only OCIAttrGet) OCI_ATTR_MSG_STATE = 63; // message state (only OCIAttrGet) // NOTE: 64-66 used below OCI_ATTR_AGENT_NAME = 64; // agent name OCI_ATTR_AGENT_ADDRESS = 65; // agent address OCI_ATTR_AGENT_PROTOCOL = 66; // agent protocol OCI_ATTR_SENDER_ID = 68; // sender id OCI_ATTR_ORIGINAL_MSGID = 69; // original message id OCI_ATTR_QUEUE_NAME = 70; // queue name OCI_ATTR_NFY_MSGID = 71; // message id OCI_ATTR_MSG_PROP = 72; // message properties OCI_ATTR_NUM_DML_ERRORS = 73; // num of errs in array DML OCI_ATTR_DML_ROW_OFFSET = 74; // row offset in the array OCI_ATTR_DATEFORMAT = 75; // default date format string OCI_ATTR_BUF_ADDR = 76; // buffer address OCI_ATTR_BUF_SIZE = 77; // buffer size OCI_ATTR_NUM_ROWS = 81; // number of rows in column array // NOTE that OCI_ATTR_NUM_COLS is a column // array attribute too. OCI_ATTR_COL_COUNT = 82; // columns of column array processed so far. OCI_ATTR_STREAM_OFFSET = 83; // str off of last row processed OCI_ATTR_SHARED_HEAPALLOC = 84; // Shared Heap Allocation Size OCI_ATTR_SERVER_GROUP = 85; // server group name OCI_ATTR_MIGSESSION = 86; // migratable session attribute OCI_ATTR_NOCACHE = 87; // Temporary LOBs OCI_ATTR_MEMPOOL_SIZE = 88; // Pool Size OCI_ATTR_MEMPOOL_INSTNAME = 89; // Instance name OCI_ATTR_MEMPOOL_APPNAME = 90; // Application name OCI_ATTR_MEMPOOL_HOMENAME = 91; // Home Directory name OCI_ATTR_MEMPOOL_MODEL = 92; // Pool Model (proc,thrd,both) OCI_ATTR_MODES = 93; // Modes OCI_ATTR_SUBSCR_NAME = 94; // name of subscription OCI_ATTR_SUBSCR_CALLBACK = 95; // associated callback OCI_ATTR_SUBSCR_CTX = 96; // associated callback context OCI_ATTR_SUBSCR_PAYLOAD = 97; // associated payload OCI_ATTR_SUBSCR_NAMESPACE = 98; // associated namespace OCI_ATTR_PROXY_CREDENTIALS = 99; // Proxy user credentials OCI_ATTR_INITIAL_CLIENT_ROLES = 100; // Initial client role list OCI_ATTR_UNK = 101; // unknown attribute OCI_ATTR_NUM_COLS = 102; // number of columns OCI_ATTR_LIST_COLUMNS = 103; // parameter of the column list OCI_ATTR_RDBA = 104; // DBA of the segment header OCI_ATTR_CLUSTERED = 105; // whether the table is clustered OCI_ATTR_PARTITIONED = 106; // whether the table is partitioned OCI_ATTR_INDEX_ONLY = 107; // whether the table is index only OCI_ATTR_LIST_ARGUMENTS = 108; // parameter of the argument list OCI_ATTR_LIST_SUBPROGRAMS = 109; // parameter of the subprogram list OCI_ATTR_REF_TDO = 110; // REF to the type descriptor OCI_ATTR_LINK = 111; // the database link name OCI_ATTR_MIN = 112; // minimum value OCI_ATTR_MAX = 113; // maximum value OCI_ATTR_INCR = 114; // increment value OCI_ATTR_CACHE = 115; // number of sequence numbers cached OCI_ATTR_ORDER = 116; // whether the sequence is ordered OCI_ATTR_HW_MARK = 117; // high-water mark OCI_ATTR_TYPE_SCHEMA = 118; // type's schema name OCI_ATTR_TIMESTAMP = 119; // timestamp of the object OCI_ATTR_NUM_ATTRS = 120; // number of sttributes OCI_ATTR_NUM_PARAMS = 121; // number of parameters OCI_ATTR_OBJID = 122; // object id for a table or view OCI_ATTR_PTYPE = 123; // type of info described by OCI_ATTR_PARAM = 124; // parameter descriptor OCI_ATTR_OVERLOAD_ID = 125; // overload ID for funcs and procs OCI_ATTR_TABLESPACE = 126; // table name space OCI_ATTR_TDO = 127; // TDO of a type OCI_ATTR_LTYPE = 128; // list type OCI_ATTR_PARSE_ERROR_OFFSET =129; // Parse Error offset OCI_ATTR_IS_TEMPORARY = 130; // whether table is temporary OCI_ATTR_IS_TYPED = 131; // whether table is typed OCI_ATTR_DURATION = 132; // duration of temporary table OCI_ATTR_IS_INVOKER_RIGHTS = 133; // is invoker rights OCI_ATTR_OBJ_NAME = 134; // top level schema obj name OCI_ATTR_OBJ_SCHEMA = 135; // schema name OCI_ATTR_OBJ_ID = 136; // top level schema object id OCI_ATTR_TRANS_TIMEOUT = 142; // transaction timeout OCI_ATTR_SERVER_STATUS = 143; // state of the server handle OCI_ATTR_STATEMENT = 144; // statement txt in stmt hdl OCI_ATTR_NO_CACHE = 145; // statement should not be executed in cache OCI_ATTR_DEQCOND = 146; // dequeue condition OCI_ATTR_RESERVED_2 = 147; // reserved OCI_ATTR_SUBSCR_RECPT = 148; // recepient of subscription OCI_ATTR_SUBSCR_RECPTPROTO = 149; // protocol for recepient OCI_ATTR_LDAP_HOST = 153; // LDAP host to connect to OCI_ATTR_LDAP_PORT = 154; // LDAP port to connect to OCI_ATTR_BIND_DN = 155; // bind DN OCI_ATTR_LDAP_CRED = 156; // credentials to connect to LDAP OCI_ATTR_WALL_LOC = 157; // client wallet location OCI_ATTR_LDAP_AUTH = 158; // LDAP authentication method OCI_ATTR_LDAP_CTX = 159; // LDAP adminstration context DN OCI_ATTR_SERVER_DNS = 160; // list of registration server DNs OCI_ATTR_DN_COUNT = 161; // the number of server DNs OCI_ATTR_SERVER_DN = 162; // server DN attribute OCI_ATTR_MAXCHAR_SIZE = 163; // max char size of data OCI_ATTR_CURRENT_POSITION = 164; // for scrollable result sets // Added to get attributes for ref cursor to statement handle OCI_ATTR_RESERVED_3 = 165; // reserved OCI_ATTR_RESERVED_4 = 166; // reserved OCI_ATTR_DIGEST_ALGO = 168; // digest algorithm OCI_ATTR_CERTIFICATE = 169; // certificate OCI_ATTR_SIGNATURE_ALGO = 170; // signature algorithm OCI_ATTR_CANONICAL_ALGO = 171; // canonicalization algo. OCI_ATTR_PRIVATE_KEY = 172; // private key OCI_ATTR_DIGEST_VALUE = 173; // digest value OCI_ATTR_SIGNATURE_VAL = 174; // signature value OCI_ATTR_SIGNATURE = 175; // signature // attributes for setting OCI stmt caching specifics in svchp OCI_ATTR_STMTCACHESIZE = 176; // size of the stm cache // ------------------------ Connection Pool Attributes ----------------------- OCI_ATTR_CONN_NOWAIT = 178; OCI_ATTR_CONN_BUSY_COUNT = 179; OCI_ATTR_CONN_OPEN_COUNT = 180; OCI_ATTR_CONN_TIMEOUT = 181; OCI_ATTR_STMT_STATE = 182; OCI_ATTR_CONN_MIN = 183; OCI_ATTR_CONN_MAX = 184; OCI_ATTR_CONN_INCR = 185; // For value 187, see DirPathAPI attribute section in this file OCI_ATTR_NUM_OPEN_STMTS = 188; // open stmts in session OCI_ATTR_DESCRIBE_NATIVE = 189; // get native info via desc OCI_ATTR_BIND_COUNT = 190; // number of bind postions OCI_ATTR_HANDLE_POSITION = 191; // pos of bind/define handle OCI_ATTR_RESERVED_5 = 192; // reserverd OCI_ATTR_SERVER_BUSY = 193; // call in progress on server // For value 194, see DirPathAPI attribute section in this file // notification presentation for recipient OCI_ATTR_SUBSCR_RECPTPRES = 195; OCI_ATTR_TRANSFORMATION = 196; // AQ message transformation OCI_ATTR_ROWS_FETCHED = 197; // rows fetched in last call // --------------------------- Snapshot attributes --------------------------- OCI_ATTR_SCN_BASE = 198; // snapshot base OCI_ATTR_SCN_WRAP = 199; // snapshot wrap // --------------------------- Miscellanous attributes ----------------------- OCI_ATTR_RESERVED_6 = 200; // reserved */ OCI_ATTR_READONLY_TXN = 201; // txn is readonly OCI_ATTR_RESERVED_7 = 202; // reserved OCI_ATTR_ERRONEOUS_COLUMN = 203; // position of erroneous col OCI_ATTR_RESERVED_8 = 204; // reserved OCI_ATTR_ASM_VOL_SPRT = 205; // ASM volume supported? // For value 206, see DirPathAPI attribute section in this file OCI_ATTR_INST_TYPE = 207; // oracle instance type // USED attribute 208 for OCI_ATTR_SPOOL_STMTCACHESIZE OCI_ATTR_ENV_UTF16 = 209; // is env in utf16 mode? OCI_ATTR_ENV_CHARSET_ID = 31; // = OCI_ATTR_CHARSET_ID - charset id in env OCI_ATTR_ENV_NCHARSET_ID = 262; // = OCI_ATTR_NCHARSET_ID - ncharset id in env OCI_ATTR_RESERVED_9 = 210; // reserved OCI_ATTR_RESERVED_10 = 211; // reserved // For values 212 and 213, see DirPathAPI attribute section in this file OCI_ATTR_RESERVED_12 = 214; // reserved OCI_ATTR_RESERVED_13 = 215; // reserved OCI_ATTR_IS_EXTERNAL = 216; // whether table is external // -------------------------- Statement Handle Attributes ------------------ OCI_ATTR_RESERVED_15 = 217; // reserved OCI_ATTR_STMT_IS_RETURNING = 218; // stmt has returning clause OCI_ATTR_RESERVED_16 = 219; // reserved OCI_ATTR_RESERVED_17 = 220; // reserved OCI_ATTR_RESERVED_18 = 221; // reserved // --------------------------- session attributes --------------------------- OCI_ATTR_RESERVED_19 = 222; // reserved OCI_ATTR_RESERVED_20 = 223; // reserved OCI_ATTR_CURRENT_SCHEMA = 224; // Current Schema OCI_ATTR_RESERVED_21 = 415; // reserved OCI_ATTR_LAST_LOGON_TIME_UTC=463; // Last Successful Logon Time // ------------------------- notification subscription ---------------------- OCI_ATTR_SUBSCR_QOSFLAGS = 225; // QOS flags OCI_ATTR_SUBSCR_PAYLOADCBK = 226; // Payload callback OCI_ATTR_SUBSCR_TIMEOUT = 227; // Timeout OCI_ATTR_SUBSCR_NAMESPACE_CTX=228; // Namespace context OCI_ATTR_SUBSCR_CQ_QOSFLAGS =229; // change notification (CQ) specific QOS flags OCI_ATTR_SUBSCR_CQ_REGID = 230; // change notification registration id OCI_ATTR_SUBSCR_NTFN_GROUPING_CLASS = 231; // ntfn grouping class OCI_ATTR_SUBSCR_NTFN_GROUPING_VALUE = 232; // ntfn grouping value OCI_ATTR_SUBSCR_NTFN_GROUPING_TYPE = 233; // ntfn grouping type OCI_ATTR_SUBSCR_NTFN_GROUPING_START_TIME = 234; // ntfn grp start time OCI_ATTR_SUBSCR_NTFN_GROUPING_REPEAT_COUNT =235; // ntfn grp rep count OCI_ATTR_AQ_NTFN_GROUPING_MSGID_ARRAY = 236; // aq grp msgid array OCI_ATTR_AQ_NTFN_GROUPING_COUNT = 237; // ntfns recd in grp // ----------------------- row callback attributes ------------------------- OCI_ATTR_BIND_ROWCBK = 301; // bind row callback OCI_ATTR_BIND_ROWCTX = 302; // ctx for bind row callback OCI_ATTR_SKIP_BUFFER = 303; // skip buffer in array ops // ----------------------- XStream API attributes -------------------------- OCI_ATTR_XSTREAM_ACK_INTERVAL = 350; // XStream ack interval OCI_ATTR_XSTREAM_IDLE_TIMEOUT = 351; // XStream idle timeout //----- Db Change Notification (CQ) statement handle attributes------------ OCI_ATTR_CQ_QUERYID = 304; // ------------- DB Change Notification reg handle attributes --------------- OCI_ATTR_CHNF_TABLENAMES = 401; // out: array of table names OCI_ATTR_CHNF_ROWIDS = 402; // in: rowids needed OCI_ATTR_CHNF_OPERATIONS = 403; // in: notification operation filter OCI_ATTR_CHNF_CHANGELAG = 404; // txn lag between notifications // DB Change: Notification Descriptor attributes ----------------------- OCI_ATTR_CHDES_DBNAME = 405; // source database OCI_ATTR_CHDES_NFYTYPE = 406; // notification type flags OCI_ATTR_CHDES_XID = 407; // XID of the transaction OCI_ATTR_CHDES_TABLE_CHANGES = 408; // array of table chg descriptors OCI_ATTR_CHDES_TABLE_NAME = 409; // table name OCI_ATTR_CHDES_TABLE_OPFLAGS = 410; // table operation flags OCI_ATTR_CHDES_TABLE_ROW_CHANGES = 411; // array of changed rows OCI_ATTR_CHDES_ROW_ROWID = 412; // rowid of changed row OCI_ATTR_CHDES_ROW_OPFLAGS = 413; // row operation flags // Statement handle attribute for db change notification OCI_ATTR_CHNF_REGHANDLE = 414; // IN: subscription handle OCI_ATTR_NETWORK_FILE_DESC = 415; // network file descriptor // client name for single session proxy OCI_ATTR_PROXY_CLIENT = 416; // 415 is already taken - see OCI_ATTR_RESERVED_21 // TDE attributes on the Table OCI_ATTR_TABLE_ENC = 417; // does table have any encrypt columns OCI_ATTR_TABLE_ENC_ALG = 418; // Table encryption Algorithm OCI_ATTR_TABLE_ENC_ALG_ID = 419; // Internal Id of encryption Algorithm // -------- Attributes related to Statement cache callback ----------------- OCI_ATTR_STMTCACHE_CBKCTX = 420; // opaque context on stmt OCI_ATTR_STMTCACHE_CBK = 421; // callback fn for stmtcache // ---------------- Query change descriptor attributes ----------------------- OCI_ATTR_CQDES_OPERATION = 422; OCI_ATTR_CQDES_TABLE_CHANGES = 423; OCI_ATTR_CQDES_QUERYID = 424; OCI_ATTR_CHDES_QUERIES = 425; // Top level change desc array of queries // --------- Attributes added to support server side session pool ---------- OCI_ATTR_CONNECTION_CLASS = 425; OCI_ATTR_PURITY = 426; OCI_ATTR_PURITY_DEFAULT = $00; OCI_ATTR_PURITY_NEW = $01; OCI_ATTR_PURITY_SELF = $02; // -------- Attributes for Network Session Time Out-------------------------- // >= 11.2 OCI_ATTR_SEND_TIMEOUT = 435; // NS send timeout in MSec OCI_ATTR_RECEIVE_TIMEOUT = 436; // NS receive timeout in MSec //--------- Attributes related to LOB prefetch------------------------------ OCI_ATTR_DEFAULT_LOBPREFETCH_SIZE = 438; // default prefetch size OCI_ATTR_LOBPREFETCH_SIZE = 439; // prefetch size OCI_ATTR_LOBPREFETCH_LENGTH = 440; // prefetch length & chunk //--------- Attributes related to LOB Deduplicate Regions ------------------ OCI_ATTR_LOB_REGION_PRIMARY = 442; // Primary LOB Locator OCI_ATTR_LOB_REGION_PRIMOFF = 443; // Offset into Primary LOB OCI_ATTR_LOB_REGION_OFFSET = 445; // Region Offset OCI_ATTR_LOB_REGION_LENGTH = 446; // Region Length Bytes/Chars OCI_ATTR_LOB_REGION_MIME = 447; // Region mime type //--------------------Attribute to fetch ROWID ------------------------------ OCI_ATTR_FETCH_ROWID = 448; // server attribute OCI_ATTR_RESERVED_37 = 449; //-------------------Attributes for OCI column security----------------------- OCI_ATTR_NO_COLUMN_AUTH_WARNING = 450; OCI_ATTR_XDS_POLICY_STATUS = 451; OCI_XDS_POLICY_NONE = 0; OCI_XDS_POLICY_ENABLED = 1; OCI_XDS_POLICY_UNKNOWN = 2; // --------------- ip address attribute in environment handle -------------- OCI_ATTR_SUBSCR_IPADDR = 452; // ip address to listen on // server attribute OCI_ATTR_RESERVED_40 = 453; OCI_ATTR_RESERVED_42 = 455; OCI_ATTR_RESERVED_43 = 456; // statement attribute OCI_ATTR_UB8_ROW_COUNT = 457; // ub8 value of row count // ------------- round trip callback attributes in the process handle ----- OCI_ATTR_RESERVED_458 = 458; // reserved OCI_ATTR_RESERVED_459 = 459; // reserved // invisible columns attributes OCI_ATTR_SHOW_INVISIBLE_COLUMNS = 460; // invisible columns support OCI_ATTR_INVISIBLE_COL = 461; // invisible columns support // support at most once transaction semantics OCI_ATTR_LTXID = 462; // logical transaction id // statement handle attribute OCI_ATTR_IMPLICIT_RESULT_COUNT = 463; OCI_ATTR_RESERVED_464 = 464; OCI_ATTR_RESERVED_465 = 465; OCI_ATTR_RESERVED_466 = 466; OCI_ATTR_RESERVED_467 = 467; // SQL translation profile session attribute OCI_ATTR_SQL_TRANSLATION_PROFILE = 468; // Per Iteration array DML rowcount attribute OCI_ATTR_DML_ROW_COUNT_ARRAY = 469; OCI_ATTR_RESERVED_470 = 470; // session handle attribute OCI_ATTR_MAX_OPEN_CURSORS = 471; { Can application failover and recover from this error? e.g. ORA-03113 is recoverable while ORA-942 (table or view does not exist) is not. } OCI_ATTR_ERROR_IS_RECOVERABLE = 472; // ONS specific private attribute OCI_ATTR_RESERVED_473 = 473; // Attribute to check if ILM Write Access Tracking is enabled or not OCI_ATTR_ILM_TRACK_WRITE = 474; // Notification subscription failure callback and context OCI_ATTR_SUBSCR_FAILURE_CBK = 477; OCI_ATTR_SUBSCR_FAILURE_CTX = 478; // Reserved OCI_ATTR_RESERVED_479 = 479; OCI_ATTR_RESERVED_480 = 480; OCI_ATTR_RESERVED_481 = 481; OCI_ATTR_RESERVED_482 = 482; { A SQL translation profile with FOREIGN_SQL_SYNTAX attribute is set in the database session. } OCI_ATTR_TRANS_PROFILE_FOREIGN = 483; // is a transaction active on the session? OCI_ATTR_TRANSACTION_IN_PROGRESS = 484; // add attribute for DBOP: DataBase OPeration OCI_ATTR_DBOP = 485; // FAN-HA private attribute OCI_ATTR_RESERVED_486 = 486; // reserved OCI_ATTR_RESERVED_487 = 487; OCI_ATTR_RESERVED_488 = 488; OCI_ATTR_VARTYPE_MAXLEN_COMPAT = 489; // Max Lifetime for session OCI_ATTR_SPOOL_MAX_LIFETIME_SESSION = 490; OCI_ATTR_RESERVED_491 = 491; OCI_ATTR_RESERVED_492 = 492; OCI_ATTR_RESERVED_493 = 493; OCI_ATTR_ITERS_PROCESSED = 494; OCI_ATTR_BREAK_ON_NET_TIMEOUT = 495; // Break on timeout //---------------------------- DB Change: Event types ------------------------ OCI_EVENT_NONE = $0; // None OCI_EVENT_STARTUP = $1; // Startup database OCI_EVENT_SHUTDOWN = $2; // Shutdown database OCI_EVENT_SHUTDOWN_ANY = $3; // Startup instance OCI_EVENT_DROP_DB = $4; // Drop database OCI_EVENT_DEREG = $5; // Subscription deregistered OCI_EVENT_OBJCHANGE = $6; // Object change notification OCI_EVENT_QUERYCHANGE = $7; // query result change //---------------------------- DB Change: Operation types -------------------- OCI_OPCODE_ALLROWS = $01; // all rows invalidated OCI_OPCODE_ALLOPS = $00; // interested in all operations OCI_OPCODE_INSERT = $02; // INSERT OCI_OPCODE_UPDATE = $04; // UPDATE OCI_OPCODE_DELETE = $08; // DELETE OCI_OPCODE_ALTER = $10; // ALTER OCI_OPCODE_DROP = $20; // DROP TABLE OCI_OPCODE_UNKNOWN = $40; // GENERIC/ UNKNOWN // ----------------------- ha event callback attributes -------------------- OCI_ATTR_EVTCBK = 304; // ha callback OCI_ATTR_EVTCTX = 305; // ctx for ha callback // ------------------ User memory attributes (all handles) ----------------- OCI_ATTR_USER_MEMORY = 306; // pointer to user memory // ------- unauthorised access and user action auditing banners ------------ OCI_ATTR_ACCESS_BANNER = 307; // access banner OCI_ATTR_AUDIT_BANNER = 308; // audit banner // ----------------- port no attribute in environment handle ------------- OCI_ATTR_SUBSCR_PORTNO = 390; // port no to listen //------------- Supported Values for protocol for recepient ----------------- OCI_SUBSCR_PROTO_OCI = 0; // oci OCI_SUBSCR_PROTO_MAIL = 1; // mail OCI_SUBSCR_PROTO_SERVER = 2; // server OCI_SUBSCR_PROTO_HTTP = 3; // http OCI_SUBSCR_PROTO_MAX = 4; // max current protocols //------------- Supported Values for presentation for recepient ------------- OCI_SUBSCR_PRES_DEFAULT = 0; // default OCI_SUBSCR_PRES_XML = 1; // xml OCI_SUBSCR_PRES_MAX = 2; // max current presentations //------------- Supported QOS values for notification registrations --------- OCI_SUBSCR_QOS_RELIABLE = $01; // reliable OCI_SUBSCR_QOS_PAYLOAD = $02; // payload delivery OCI_SUBSCR_QOS_REPLICATE = $04; // replicate to director // internal qos - 12c secure ntfns with client initiated connections OCI_SUBSCR_QOS_SECURE = $08; // secure payload delivery OCI_SUBSCR_QOS_PURGE_ON_NTFN = $10; // purge on first ntfn OCI_SUBSCR_QOS_MULTICBK = $20; // multi instance callback // 0x40 is used for a internal flag OCI_SUBSCR_QOS_HAREG = $80; // HA reg // non-durable registration. For now supported only with secure ntfns OCI_SUBSCR_QOS_NONDURABLE = $100; // non-durable reg OCI_SUBSCR_QOS_ASYNC_DEQ = $200; // Asyncronous Deq OCI_SUBSCR_QOS_AUTO_ACK = $400; // auto acknowledgement OCI_SUBSCR_QOS_TX_ACK = $800; // transacted acks // ----QOS flags specific to change notification/ continuous queries CQ ----- OCI_SUBSCR_CQ_QOS_QUERY = $01; // query level notification OCI_SUBSCR_CQ_QOS_BEST_EFFORT = $02; // best effort notification OCI_SUBSCR_CQ_QOS_CLQRYCACHE = $04; // client query caching //------------- Supported Values for notification grouping class ------------ OCI_SUBSCR_NTFN_GROUPING_CLASS_TIME = 1; // time //------------- Supported Values for notification grouping type ------------- OCI_SUBSCR_NTFN_GROUPING_TYPE_SUMMARY = 1; // summary OCI_SUBSCR_NTFN_GROUPING_TYPE_LAST = 2; // last //--------- Temporary attribute value for UCS2/UTF16 character set ID ------- OCI_US7ASCIIID = 1; // US7ASCII charset ID OCI_UTF8ID = 871; // UTF8 charset ID OCI_UCS2ID = 1000; // UCS2 charset ID OCI_UTF16ID = 1000; // UTF16 charset ID // -------------------------- Implicit Result types ------------------------ OCI_RESULT_TYPE_SELECT = 1; //---------------- Server Handle Attribute Values --------------------------- // OCI_ATTR_SERVER_STATUS OCI_SERVER_NOT_CONNECTED = $0; OCI_SERVER_NORMAL = $1; //------------------------- Supported Namespaces --------------------------- OCI_SUBSCR_NAMESPACE_ANONYMOUS = 0; // Anonymous Namespace OCI_SUBSCR_NAMESPACE_AQ = 1; // Advanced Queues OCI_SUBSCR_NAMESPACE_DBCHANGE = 2; // change notification OCI_SUBSCR_NAMESPACE_RESERVED1 = 3; OCI_SUBSCR_NAMESPACE_MAX = 4; // Max Name Space Number //-------------------------Credential Types---------------------------------- OCI_CRED_RDBMS = 1; // database username/password OCI_CRED_EXT = 2; // externally provided credentials OCI_CRED_PROXY = 3; // proxy authentication OCI_CRED_RESERVED_1 = 4; // reserved OCI_CRED_RESERVED_2 = 5; // reserved OCI_CRED_RESERVED_3 = 6; // reserved //------------------------Error Return Values-------------------------------- OCI_SUCCESS = 0; // maps to SQL_SUCCESS of SAG CLI OCI_SUCCESS_WITH_INFO = 1; // maps to SQL_SUCCESS_WITH_INFO OCI_RESERVED_FOR_INT_USE = 200; // reserved OCI_NO_DATA = 100; // maps to SQL_NO_DATA OCI_ERROR = -1; // maps to SQL_ERROR OCI_INVALID_HANDLE = -2; // maps to SQL_INVALID_HANDLE OCI_NEED_DATA = 99; // maps to SQL_NEED_DATA OCI_STILL_EXECUTING = -3123; // OCI would block error //--------------------- User Callback Return Values ------------------------- OCI_CONTINUE = -24200; // Continue with the body of the OCI function OCI_ROWCBK_DONE = -24201; // ------------------DateTime and Interval check Error codes------------------ // DateTime Error Codes used by OCIDateTimeCheck() */ OCI_DT_INVALID_DAY = $1; // Bad day OCI_DT_DAY_BELOW_VALID = $2; // Bad DAy Low/high bit (1=low) OCI_DT_INVALID_MONTH = $4; // Bad MOnth OCI_DT_MONTH_BELOW_VALID = $8; // Bad MOnth Low/high bit (1=low) OCI_DT_INVALID_YEAR = $10; // Bad YeaR OCI_DT_YEAR_BELOW_VALID = $20; // Bad YeaR Low/high bit (1=low) OCI_DT_INVALID_HOUR = $40; // Bad HouR OCI_DT_HOUR_BELOW_VALID = $80; // Bad HouR Low/high bit (1=low) OCI_DT_INVALID_MINUTE = $100; // Bad MiNute OCI_DT_MINUTE_BELOW_VALID = $200; // Bad MiNute Low/high bit (1=low) OCI_DT_INVALID_SECOND = $400; // Bad SeCond OCI_DT_SECOND_BELOW_VALID = $800; // Bad second Low/high bit (1=low) OCI_DT_DAY_MISSING_FROM_1582=$1000; // Day is one of those "missing" from 1582 OCI_DT_YEAR_ZERO = $2000; // Year may not equal zero OCI_DT_INVALID_TIMEZONE = $4000; // Bad Timezone OCI_DT_INVALID_FORMAT = $8000; // Bad date format input // Interval Error Codes used by OCIInterCheck() OCI_INTER_INVALID_DAY = $1; // Bad day OCI_INTER_DAY_BELOW_VALID = $2; // Bad DAy Low/high bit (1=low) OCI_INTER_INVALID_MONTH = $4; // Bad MOnth OCI_INTER_MONTH_BELOW_VALID = $8; // Bad MOnth Low/high bit (1=low) OCI_INTER_INVALID_YEAR = $10; // Bad YeaR OCI_INTER_YEAR_BELOW_VALID = $20; // Bad YeaR Low/high bit (1=low) OCI_INTER_INVALID_HOUR = $40; // Bad HouR OCI_INTER_HOUR_BELOW_VALID = $80; // Bad HouR Low/high bit (1=low) OCI_INTER_INVALID_MINUTE = $100; // Bad MiNute OCI_INTER_MINUTE_BELOW_VALID = $200; // Bad MiNute Low/high bit(1=low) OCI_INTER_INVALID_SECOND = $400; // Bad SeCond OCI_INTER_SECOND_BELOW_VALID = $800; // Bad second Low/high bit(1=low) OCI_INTER_INVALID_FRACSEC = $1000; // Bad Fractional second OCI_INTER_FRACSEC_BELOW_VALID = $2000; // Bad fractional second Low/High //------------------------Parsing Syntax Types------------------------------- OCI_V7_SYNTAX = 2; // V815 language - for backwards compatibility OCI_V8_SYNTAX = 3; // V815 language - for backwards compatibility OCI_NTV_SYNTAX = 1; // Use what so ever is the native lang of server OCI_FOREIGN_SYNTAX = UB4MAXVAL; // Foreign syntax - require translation //------------------------(Scrollable Cursor) Fetch Options------------------- { For non-scrollable cursor, the only valid (and default) orientation is OCI_FETCH_NEXT } OCI_FETCH_CURRENT = $00000001; // refetching current position OCI_FETCH_NEXT = $00000002; // next row OCI_FETCH_FIRST = $00000004; // first row of the result set OCI_FETCH_LAST = $00000008; // the last row of the result set OCI_FETCH_PRIOR = $00000010; // previous row relative to current OCI_FETCH_ABSOLUTE = $00000020; // absolute offset from first OCI_FETCH_RELATIVE = $00000040; // offset relative to current OCI_FETCH_RESERVED_1 = $00000080; // reserved OCI_FETCH_RESERVED_2 = $00000100; // reserved OCI_FETCH_RESERVED_3 = $00000200; // reserved OCI_FETCH_RESERVED_4 = $00000400; // reserved OCI_FETCH_RESERVED_5 = $00000800; // reserved OCI_FETCH_RESERVED_6 = $00001000; // reserved //------------------------Bind and Define Options---------------------------- OCI_SB2_IND_PTR = $00000001; // unused OCI_DATA_AT_EXEC = $00000002; // data at execute time OCI_DYNAMIC_FETCH = $00000002; // fetch dynamically OCI_PIECEWISE = $00000004; // piecewise DMLs or fetch OCI_DEFINE_RESERVED_1 = $00000008; // reserved OCI_BIND_RESERVED_2 = $00000010; // reserved OCI_DEFINE_RESERVED_2 = $00000020; // reserved OCI_BIND_SOFT = $00000040; // soft bind or define OCI_DEFINE_SOFT = $00000080; // soft bind or define OCI_BIND_RESERVED_3 = $00000100; // reserved OCI_IOV = $00000200; // For scatter gather bind/define //----------------------------- Various Modes ------------------------------ OCI_DEFAULT = $00000000; // the default value for parameters and attributes //-------------OCIInitialize Modes / OCICreateEnvironment Modes ------------- OCI_THREADED = $00000001; // appl. in threaded environment OCI_OBJECT = $00000002; // application in object environment OCI_EVENTS = $00000004; // >= 8.1.5 application is enabled for events OCI_RESERVED1 = $00000008; // reserved OCI_SHARED = $00000010; // >= 8.1.5 the application is in shared mode OCI_RESERVED2 = $00000020; // reserved // The following /TWO/ are only valid for OCICreateEnvironment call OCI_NO_UCB = $00000040; // No user callback called during ini OCI_NO_MUTEX = $00000080; // if not OCI_THREADED and < 8.1 // the environment handle will not be // protected by a mutex internally // >= 8.1 OCI_SHARED_EXT = $00000100; // Used for shared forms // $00000200 free OCI_ALWAYS_BLOCKING = $00000400; // all connections always blocking // $00000800 free OCI_USE_LDAP = $00001000; // allow LDAP connections OCI_REG_LDAPONLY = $00002000; // only register to LDAP OCI_UTF16 = $00004000; // mode for all UTF16 metadata OCI_AFC_PAD_ON = $00008000; // turn on AFC blank padding when rlenp present OCI_ENVCR_RESERVED3 = $00010000; // reserved OCI_NEW_LENGTH_SEMANTICS = $00020000; // adopt new length semantics // the new length semantics, always bytes, is used by OCIEnvNlsCreate OCI_NO_MUTEX_STMT = $00040000; // Do not mutex stmt handle OCI_MUTEX_ENV_ONLY = $00080000; // Mutex only the environment handle OCI_SUPPRESS_NLS_VALIDATION = $00100000; // suppress nls validation // nls validation suppression is on by default; use OCI_ENABLE_NLS_VALIDATION to disable it // >= 10.2 OCI_MUTEX_TRY = $00200000; // try and acquire mutex OCI_NCHAR_LITERAL_REPLACE_ON = $00400000; // nchar literal replace on OCI_NCHAR_LITERAL_REPLACE_OFF = $00800000; // nchar literal replace off// OCI_ENABLE_NLS_VALIDATION = $01000000; // enable nls validation OCI_ENVCR_RESERVED4 = $02000000; // reserved OCI_ENVCR_RESERVED5 = $04000000; // reserved OCI_ENVCR_RESERVED6 = $08000000; // reserved OCI_ENVCR_RESERVED7 = $10000000; // reserved // >= 12 // client initiated notification listener connections, applicable only for 12c queues and above OCI_SECURE_NOTIFICATION = $20000000; OCI_DISABLE_DIAG = $40000000; // disable diagnostics //----------------------- Execution Modes ----------------------------------- OCI_BATCH_MODE = $00000001; // batch the oci stmt for exec OCI_EXACT_FETCH = $00000002; // fetch exact rows specified // $00000004 available OCI_STMT_SCROLLABLE_READONLY = $00000008; // if result set is scrollable OCI_DESCRIBE_ONLY = $00000010; // only describe the statement OCI_COMMIT_ON_SUCCESS = $00000020; // commit, if successful exec OCI_NON_BLOCKING = $00000040; // non-blocking OCI_BATCH_ERRORS = $00000080; // batch errors in array dmls OCI_PARSE_ONLY = $00000100; // only parse the statement OCI_EXACT_FETCH_RESERVED_1 = $00000200; // reserved OCI_SHOW_DML_WARNINGS = $00000400; // return OCI_SUCCESS_WITH_INFO for delete/update w/no where clause OCI_EXEC_RESERVED_2 = $00000800; // reserved OCI_DESC_RESERVED_1 = $00001000; // reserved OCI_EXEC_RESERVED_3 = $00002000; // reserved OCI_EXEC_RESERVED_4 = $00004000; // reserved OCI_EXEC_RESERVED_5 = $00008000; // reserved OCI_EXEC_RESERVED_6 = $00010000; // reserved OCI_RESULT_CACHE = $00020000; // hint to use query caching OCI_NO_RESULT_CACHE = $00040000; // hint to bypass query caching OCI_EXEC_RESERVED_7 = $00080000; // reserved OCI_RETURN_ROW_COUNT_ARRAY = $00100000; // Per Iter DML Row Count mode //------------------------Authentication Modes------------------------------- OCI_MIGRATE = $00000001; // migratable auth context OCI_SYSDBA = $00000002; // for SYSDBA authorization OCI_SYSOPER = $00000004; // for SYSOPER authorization OCI_PRELIM_AUTH = $00000008; // for preliminary authorization OCIP_ICACHE = $00000010; // Private OCI cache mode OCI_AUTH_RESERVED_1 = $00000020; // reserved OCI_STMT_CACHE = $00000040; // enable OCI Stmt Caching OCI_STATELESS_CALL = $00000080; // stateless at call boundary OCI_STATELESS_TXN = $00000100; // stateless at txn boundary OCI_STATELESS_APP = $00000200; // stateless at user-specified pts OCI_AUTH_RESERVED_2 = $00000400; // reserved OCI_AUTH_RESERVED_3 = $00000800; // reserved OCI_AUTH_RESERVED_4 = $00001000; // reserved OCI_AUTH_RESERVED_5 = $00002000; // reserved OCI_SYSASM = $00008000; // for SYSASM authorization OCI_AUTH_RESERVED_6 = $00010000; // reserved OCI_SYSBKP = $00020000; // for SYSBACKUP authorization OCI_SYSDGD = $00040000; // for SYSDG authorization OCI_SYSKMT = $00080000; // for SYSKM authorization //---------------------OCIStmtPrepare2 Modes--------------------------------- OCI_PREP2_CACHE_SEARCHONLY = $0010; // ONly Search OCI_PREP2_GET_PLSQL_WARNINGS = $0020; // Get PL/SQL warnings OCI_PREP2_RESERVED_1 = $0040; // reserved OCI_PREP2_RESERVED_2 = $0080; // reserved OCI_PREP2_RESERVED_3 = $0100; // reserved OCI_PREP2_RESERVED_4 = $0200; // reserved OCI_PREP2_IMPL_RESULTS_CLIENT = $0400; // client for implicit results OCI_PREP2_RESERVED_5 = $0800; // reserved //---------------------OCIStmtRelease Modes---------------------------------- OCI_STRLS_CACHE_DELETE = $0010; // Delete from Cache //------------------------Piece Information---------------------------------- OCI_PARAM_IN = $01; // in parameter OCI_PARAM_OUT = $02; // out parameter //------------------------ Transaction Start Flags -------------------------- // NOTE: OCI_TRANS_JOIN and OCI_TRANS_NOMIGRATE not supported in 8.0.X OCI_TRANS_NEW = $00000001; // start a new local or global txn OCI_TRANS_JOIN = $00000002; // join an existing global txn OCI_TRANS_RESUME = $00000004; // resume the global txn branch OCI_TRANS_PROMOTE = $00000008; // promote the local txn to global OCI_TRANS_STARTMASK = $000000ff; // mask for start operation flags OCI_TRANS_READONLY = $00000100; // start a readonly txn OCI_TRANS_READWRITE = $00000200; // start a read-write txn OCI_TRANS_SERIALIZABLE = $00000400; // start a serializable txn OCI_TRANS_ISOLMASK = $0000ff00; // mask for start isolation flags OCI_TRANS_LOOSE = $00010000; // a loosely coupled branch OCI_TRANS_TIGHT = $00020000; // a tightly coupled branch OCI_TRANS_TYPEMASK = $000f0000; // mask for branch type flags OCI_TRANS_NOMIGRATE = $00100000; // non migratable transaction OCI_TRANS_SEPARABLE = $00200000; // separable transaction (8.1.6+) OCI_TRANS_OTSRESUME = $00400000; // OTS resuming a transaction OCI_TRANS_OTHRMASK = $fff00000; // mask for other start flags //------------------------ Transaction End Flags ---------------------------- OCI_TRANS_TWOPHASE = $01000000; // use two phase commit OCI_TRANS_WRITEBATCH = $00000001; // force cmt-redo for local txns OCI_TRANS_WRITEIMMED = $00000002; // no force cmt-redo OCI_TRANS_WRITEWAIT = $00000004; // no sync cmt-redo OCI_TRANS_WRITENOWAIT = $00000008; // sync cmt-redo for local txns //------------------------- AQ Constants ------------------------------------ // ------------------------- Visibility flags ------------------------------- OCI_ENQ_IMMEDIATE = 1; // enqueue is an independent transaction OCI_ENQ_ON_COMMIT = 2; // enqueue is part of current transaction // ----------------------- Dequeue mode flags ------------------------------- OCI_DEQ_BROWSE = 1; // read message without acquiring a lock OCI_DEQ_LOCKED = 2; // read and obtain write lock on message OCI_DEQ_REMOVE = 3; // read the message and delete it OCI_DEQ_REMOVE_NODATA = 4; // delete message w'o returning payload OCI_DEQ_GETSIG = 5; // get signature only // ----------------- Dequeue navigation flags ------------------------------- OCI_DEQ_FIRST_MSG = 1; // get first message at head of queue OCI_DEQ_NEXT_MSG = 3; // next message that is available OCI_DEQ_NEXT_TRANSACTION = 2; // get first message of next txn group OCI_DEQ_FIRST_MSG_MULTI_GROUP = 4; // start from first message and array deq across txn groups OCI_DEQ_MULT_TRANSACTION = 5; // array dequeue across txn groups OCI_DEQ_NEXT_MSG_MULTI_GROUP = OCI_DEQ_MULT_TRANSACTION; // array dequeue across txn groups // ----------------- Dequeue Option Reserved flags ------------------------- OCI_DEQ_RESERVED_1 = $000001; // --------------------- Message states ------------------------------------- OCI_MSG_WAITING = 1; // the message delay has not yet completed OCI_MSG_READY = 0; // the message is ready to be processed OCI_MSG_PROCESSED = 2; // the message has been processed OCI_MSG_EXPIRED = 3; // message has moved to exception queue // --------------------- Sequence deviation --------------------------------- OCI_ENQ_BEFORE = 2; // enqueue message before another message OCI_ENQ_TOP = 3; // enqueue message before all messages // ------------------------- Visibility flags ------------------------------- OCI_DEQ_IMMEDIATE = 1; // dequeue is an independent transaction OCI_DEQ_ON_COMMIT = 2; // dequeue is part of current transaction // ------------------------ Wait -------------------------------------------- OCI_DEQ_WAIT_FOREVER = -1; // wait forever if no message available OCI_NTFN_GROUPING_FOREVER = -1; // send grouping notifications forever OCI_DEQ_NO_WAIT = 0; // do not wait if no message is available OCI_FLOW_CONTROL_NO_TIMEOUT = -1; // streaming enqueue: no timeout for flow control // ------------------------ Delay ------------------------------------------- OCI_MSG_NO_DELAY = 0; // message is available immediately // ------------------------- Expiration ------------------------------------- OCI_MSG_NO_EXPIRATION = -1; // message will never expire OCI_MSG_PERSISTENT_OR_BUFFERED =3; OCI_MSG_BUFFERED = 2; OCI_MSG_PERSISTENT = 1; // ----------------------- Reserved/AQE pisdef flags ------------------------ OCI_AQ_RESERVED_1 = $0002; OCI_AQ_RESERVED_2 = $0004; OCI_AQ_RESERVED_3 = $0008; OCI_AQ_RESERVED_4 = $0010; OCI_AQ_STREAMING_FLAG = $02000000; // AQ JMS message types OCI_AQJMS_RAW_MSG = $00000001; // raw message OCI_AQJMS_TEXT_MSG = $00000002; // text message OCI_AQJMS_MAP_MSG = $00000004; // map message OCI_AQJMS_BYTE_MSG = $00000008; // byte message OCI_AQJMS_STREAM_MSG = $00000010; // stream message OCI_AQJMS_ADT_MSG = $00000020; // adt message // AQ JMS Message streaming flags OCI_AQMSG_FIRST_CHUNK = $00000001; // first chunk of message OCI_AQMSG_NEXT_CHUNK = $00000002; // next chunk of message OCI_AQMSG_LAST_CHUNK = $00000004; // last chunk of message // ------------------------------ Replay Info ------------------------------- OCI_AQ_LAST_ENQUEUED = 0; OCI_AQ_LAST_ACKNOWLEDGED = 1; //=======================Describe Handle Parameter Attributes =============== //=========================================================================== // Attributes common to Columns and Stored Procs OCI_ATTR_DATA_SIZE = 1; // maximum size of the data OCI_ATTR_DATA_TYPE = 2; // the SQL type of the column/argument OCI_ATTR_DISP_SIZE = 3; // the display size OCI_ATTR_NAME = 4; // the name of the column/argument OCI_ATTR_PRECISION = 5; // precision if number type OCI_ATTR_SCALE = 6; // scale if number type OCI_ATTR_IS_NULL = 7; // is it null ? OCI_ATTR_TYPE_NAME = 8; // name of the named data type or a package name for package private types OCI_ATTR_SCHEMA_NAME = 9; // the schema name OCI_ATTR_SUB_NAME = 10; // type name if package private type OCI_ATTR_POSITION = 11; // relative position of col/arg in the list of cols/args // complex object retrieval parameter attributes OCI_ATTR_COMPLEXOBJECTCOMP_TYPE = 50; OCI_ATTR_COMPLEXOBJECTCOMP_TYPE_LEVEL = 51; OCI_ATTR_COMPLEXOBJECT_LEVEL = 52; OCI_ATTR_COMPLEXOBJECT_COLL_OUTOFLINE = 53; // Only Columns OCI_ATTR_DISP_NAME = 100; // the display name OCI_ATTR_ENCC_SIZE = 101; // encrypted data size OCI_ATTR_COL_ENC = 102; // column is encrypted ? OCI_ATTR_COL_ENC_SALT = 103; // is encrypted column salted ? OCI_ATTR_COL_PROPERTIES = 104; // column properties // Flags coresponding to the column properties OCI_ATTR_COL_PROPERTY_IS_IDENTITY = $0000000000000001; OCI_ATTR_COL_PROPERTY_IS_GEN_ALWAYS = $0000000000000002; OCI_ATTR_COL_PROPERTY_IS_GEN_BY_DEF_ON_NULL = $0000000000000004; // Only Stored Procs OCI_ATTR_OVERLOAD = 210; // is this position overloaded OCI_ATTR_LEVEL = 211; // level for structured types OCI_ATTR_HAS_DEFAULT = 212; // has a default value OCI_ATTR_IOMODE = 213; // in, out inout OCI_ATTR_RADIX = 214; // returns a radix OCI_ATTR_NUM_ARGS = 215; // total number of arguments // only named type attributes OCI_ATTR_TYPECODE = 216; // object or collection OCI_ATTR_COLLECTION_TYPECODE = 217; // varray or nested table OCI_ATTR_VERSION = 218; // user assigned version OCI_ATTR_IS_INCOMPLETE_TYPE = 219; // is this an incomplete type OCI_ATTR_IS_SYSTEM_TYPE = 220; // a system type OCI_ATTR_IS_PREDEFINED_TYPE = 221; // a predefined type OCI_ATTR_IS_TRANSIENT_TYPE = 222; // a transient type OCI_ATTR_IS_SYSTEM_GENERATED_TYPE = 223; // system generated type OCI_ATTR_HAS_NESTED_TABLE = 224; // contains nested table attr OCI_ATTR_HAS_LOB = 225; // has a lob attribute OCI_ATTR_HAS_FILE = 226; // has a file attribute OCI_ATTR_COLLECTION_ELEMENT = 227; // has a collection attribute OCI_ATTR_NUM_TYPE_ATTRS = 228; // number of attribute types OCI_ATTR_LIST_TYPE_ATTRS = 229; // list of type attributes OCI_ATTR_NUM_TYPE_METHODS = 230; // number of type methods OCI_ATTR_LIST_TYPE_METHODS = 231; // list of type methods OCI_ATTR_MAP_METHOD = 232; // map method of type OCI_ATTR_ORDER_METHOD = 233; // order method of type // only collection element OCI_ATTR_NUM_ELEMS = 234; // number of elements // only type methods OCI_ATTR_ENCAPSULATION = 235; // encapsulation level OCI_ATTR_IS_SELFISH = 236; // method selfish OCI_ATTR_IS_VIRTUAL = 237; // virtual OCI_ATTR_IS_INLINE = 238; // inline OCI_ATTR_IS_CONSTANT = 239; // constant OCI_ATTR_HAS_RESULT = 240; // has result OCI_ATTR_IS_CONSTRUCTOR = 241; // constructor OCI_ATTR_IS_DESTRUCTOR = 242; // destructor OCI_ATTR_IS_OPERATOR = 243; // operator OCI_ATTR_IS_MAP = 244; // a map method OCI_ATTR_IS_ORDER = 245; // order method OCI_ATTR_IS_RNDS = 246; // read no data state method OCI_ATTR_IS_RNPS = 247; // read no process state OCI_ATTR_IS_WNDS = 248; // write no data state method OCI_ATTR_IS_WNPS = 249; // write no process state OCI_ATTR_DESC_PUBLIC = 250; // public object // Object Cache Enhancements : attributes for User Constructed Instances OCI_ATTR_CACHE_CLIENT_CONTEXT = 251; OCI_ATTR_UCI_CONSTRUCT = 252; OCI_ATTR_UCI_DESTRUCT = 253; OCI_ATTR_UCI_COPY = 254; OCI_ATTR_UCI_PICKLE = 255; OCI_ATTR_UCI_UNPICKLE = 256; OCI_ATTR_UCI_REFRESH = 257; // for type inheritance OCI_ATTR_IS_SUBTYPE = 258; OCI_ATTR_SUPERTYPE_SCHEMA_NAME = 259; OCI_ATTR_SUPERTYPE_NAME = 260; // for schemas OCI_ATTR_LIST_OBJECTS = 261; // list of objects in schema // for database OCI_ATTR_NCHARSET_ID = 262; // char set id OCI_ATTR_LIST_SCHEMAS = 263; // list of schemas OCI_ATTR_MAX_PROC_LEN = 264; // max procedure length OCI_ATTR_MAX_COLUMN_LEN = 265; // max column name length OCI_ATTR_CURSOR_COMMIT_BEHAVIOR = 266; // cursor commit behavior OCI_ATTR_MAX_CATALOG_NAMELEN = 267; // catalog namelength OCI_ATTR_CATALOG_LOCATION = 268; // catalog location OCI_ATTR_SAVEPOINT_SUPPORT = 269; // savepoint support OCI_ATTR_NOWAIT_SUPPORT = 270; // nowait support OCI_ATTR_AUTOCOMMIT_DDL = 271; // autocommit DDL OCI_ATTR_LOCKING_MODE = 272; // locking mode // for externally initialized context OCI_ATTR_APPCTX_SIZE = 273; // count of context to be init OCI_ATTR_APPCTX_LIST = 274; // count of context to be init OCI_ATTR_APPCTX_NAME = 275; // name of context to be init OCI_ATTR_APPCTX_ATTR = 276; // attr of context to be init OCI_ATTR_APPCTX_VALUE = 277; // value of context to be init // for client id propagation OCI_ATTR_CLIENT_IDENTIFIER = 278; // value of client id to set // for inheritance - part 2 OCI_ATTR_IS_FINAL_TYPE = 279; // is final type ? OCI_ATTR_IS_INSTANTIABLE_TYPE = 280; // is instantiable type ? OCI_ATTR_IS_FINAL_METHOD = 281; // is final method ? OCI_ATTR_IS_INSTANTIABLE_METHOD = 282; // is instantiable method ? OCI_ATTR_IS_OVERRIDING_METHOD = 283; // is overriding method ? // slot 284 available OCI_ATTR_CHAR_USED = 285; // char length semantics OCI_ATTR_CHAR_SIZE = 286; // char length // SQLJ support OCI_ATTR_IS_JAVA_TYPE = 287; // is java implemented type ? // N-Tier support OCI_ATTR_DISTINGUISHED_NAME = 300; // use DN as user name OCI_ATTR_KERBEROS_TICKET = 301; // Kerberos ticket as cred. // for multilanguage debugging OCI_ATTR_ORA_DEBUG_JDWP = 302; // ORA_DEBUG_JDWP attribute OCI_ATTR_RESERVED_14 = 303; // reserved // For values 303 - 307, see DirPathAPI attribute section in this file // ----------------------- Session Pool Attributes ------------------------- OCI_ATTR_SPOOL_TIMEOUT = 308; // session timeout OCI_ATTR_SPOOL_GETMODE = 309; // session get mode OCI_ATTR_SPOOL_BUSY_COUNT = 310; // busy session count OCI_ATTR_SPOOL_OPEN_COUNT = 311; // open session count OCI_ATTR_SPOOL_MIN = 312; // min session count OCI_ATTR_SPOOL_MAX = 313; // max session count OCI_ATTR_SPOOL_INCR = 314; // session increment count OCI_ATTR_SPOOL_STMTCACHESIZE = 208; // Stmt cache size of pool OCI_ATTR_SPOOL_AUTH = 460; // Auth handle on pool handle //---------------------------- For XML Types ------------------------------- // For table, view and column OCI_ATTR_IS_XMLTYPE = 315; // Is the type an XML type? OCI_ATTR_XMLSCHEMA_NAME = 316; // Name of XML Schema OCI_ATTR_XMLELEMENT_NAME = 317; // Name of XML Element OCI_ATTR_XMLSQLTYPSCH_NAME = 318; // SQL type's schema for XML Ele OCI_ATTR_XMLSQLTYPE_NAME = 319; // Name of SQL type for XML Ele OCI_ATTR_XMLTYPE_STORED_OBJ = 320; // XML type stored as object? OCI_ATTR_XMLTYPE_BINARY_XML = 422; // XML type stored as binary? //---------------------------- For Subtypes ------------------------------- // For type OCI_ATTR_HAS_SUBTYPES = 321; // Has subtypes? OCI_ATTR_NUM_SUBTYPES = 322; // Number of subtypes OCI_ATTR_LIST_SUBTYPES = 323; // List of subtypes // XML flag OCI_ATTR_XML_HRCHY_ENABLED = 324; // hierarchy enabled? // Method flag OCI_ATTR_IS_OVERRIDDEN_METHOD = 325; // Method is overridden? // For values 326 - 335, see DirPathAPI attribute section in this file //------------- Attributes for 10i Distributed Objects ---------------------- OCI_ATTR_OBJ_SUBS = 336; // obj col/tab substitutable // For values 337 - 338, see DirPathAPI attribute section in this file //---------- Attributes for 10i XADFIELD (NLS language, territory ----------- OCI_ATTR_XADFIELD_RESERVED_1 = 339; // reserved OCI_ATTR_XADFIELD_RESERVED_2 = 340; // reserved //------------- Kerberos Secure Client Identifier --------------------------- OCI_ATTR_KERBEROS_CID = 341; // Kerberos db service ticket //------------------------ Attributes for Rules objects --------------------- OCI_ATTR_CONDITION = 342; // rule condition OCI_ATTR_COMMENT = 343; // comment OCI_ATTR_VALUE = 344; // Anydata value OCI_ATTR_EVAL_CONTEXT_OWNER = 345; // eval context owner OCI_ATTR_EVAL_CONTEXT_NAME = 346; // eval context name OCI_ATTR_EVALUATION_FUNCTION = 347; // eval function name OCI_ATTR_VAR_TYPE = 348; // variable type OCI_ATTR_VAR_VALUE_FUNCTION = 349; // variable value function OCI_ATTR_VAR_METHOD_FUNCTION = 350; // variable method function OCI_ATTR_ACTION_CONTEXT = 351; // action context OCI_ATTR_LIST_TABLE_ALIASES = 352; // list of table aliases OCI_ATTR_LIST_VARIABLE_TYPES = 353; // list of variable types OCI_ATTR_TABLE_NAME = 356; // table name // For values 357 - 359, see DirPathAPI attribute section in this file OCI_ATTR_MESSAGE_CSCN = 360; // message cscn OCI_ATTR_MESSAGE_DSCN = 361; // message dscn //--------------------- Audit Session ID ------------------------------------ OCI_ATTR_AUDIT_SESSION_ID = 362; // Audit session ID //--------------------- Kerberos TGT Keys ----------------------------------- OCI_ATTR_KERBEROS_KEY = 363; // n-tier Kerberos cred key OCI_ATTR_KERBEROS_CID_KEY = 364; // SCID Kerberos cred key OCI_ATTR_TRANSACTION_NO = 365; // AQ enq txn number // ----------------------- Attributes for End To End Tracing ----------------- // >= 10.1 OCI_ATTR_MODULE = 366; // module for tracing OCI_ATTR_ACTION = 367; // action for tracing OCI_ATTR_CLIENT_INFO = 368; // client info OCI_ATTR_COLLECT_CALL_TIME = 369; // collect call time OCI_ATTR_CALL_TIME = 370; // extract call time OCI_ATTR_ECONTEXT_ID = 371; // execution-id context OCI_ATTR_ECONTEXT_SEQ = 372; // execution-id sequence num //------------------------------ Session attributes ------------------------- OCI_ATTR_SESSION_STATE = 373; // session state OCI_SESSION_STATELESS = 1; // valid states OCI_SESSION_STATEFUL = 2; OCI_ATTR_SESSION_STATETYPE = 374; // session state type OCI_SESSION_STATELESS_DEF = 0; // valid state types OCI_SESSION_STATELESS_CAL = 1; OCI_SESSION_STATELESS_TXN = 2; OCI_SESSION_STATELESS_APP = 3; OCI_ATTR_SESSION_STATE_CLEARED = 376; // session state cleared OCI_ATTR_SESSION_MIGRATED = 377; // did session migrate OCI_ATTR_SESSION_PRESERVE_STATE = 388; // preserve session state OCI_ATTR_DRIVER_NAME = 424; // Driver Name // -------------------------- Admin Handle Attributes ---------------------- // >= 10.2 OCI_ATTR_ADMIN_PFILE = 389; // client-side param file // -------------------------- HA Event Handle Attributes ------------------- OCI_ATTR_HOSTNAME = 390; // SYS_CONTEXT hostname OCI_ATTR_DBNAME = 391; // SYS_CONTEXT dbname OCI_ATTR_INSTNAME = 392; // SYS_CONTEXT instance name OCI_ATTR_SERVICENAME = 393; // SYS_CONTEXT service name OCI_ATTR_INSTSTARTTIME = 394; // v$instance instance start time OCI_ATTR_HA_TIMESTAMP = 395; // event time OCI_ATTR_RESERVED_22 = 396; // reserved OCI_ATTR_RESERVED_23 = 397; // reserved OCI_ATTR_RESERVED_24 = 398; // reserved OCI_ATTR_DBDOMAIN = 399; // db domain OCI_ATTR_RESERVED_27 = 425; // reserved OCI_ATTR_EVENTTYPE = 400; // event type // valid value for OCI_ATTR_EVENTTYPE OCI_EVENTTYPE_HA = 0; OCI_ATTR_HA_SOURCE = 401; // valid values for OCI_ATTR_HA_SOURCE OCI_HA_SOURCE_INSTANCE = 0; OCI_HA_SOURCE_DATABASE = 1; OCI_HA_SOURCE_NODE = 2; OCI_HA_SOURCE_SERVICE = 3; OCI_HA_SOURCE_SERVICE_MEMBER = 4; OCI_HA_SOURCE_ASM_INSTANCE = 5; OCI_HA_SOURCE_SERVICE_PRECONNECT = 6; OCI_ATTR_HA_STATUS = 402; // valid values for OCI_ATTR_HA_STATUS OCI_HA_STATUS_DOWN = 0; OCI_HA_STATUS_UP = 1; OCI_ATTR_HA_SRVFIRST = 403; OCI_ATTR_HA_SRVNEXT = 404; // ------------------------- Server Handle Attributes ----------------------- OCI_ATTR_TAF_ENABLED = 405; // Extra notification attributes OCI_ATTR_NFY_FLAGS = 406; OCI_ATTR_MSG_DELIVERY_MODE = 407; // msg delivery mode OCI_ATTR_DB_CHARSET_ID = 416; // database charset ID OCI_ATTR_DB_NCHARSET_ID = 417; // database ncharset ID OCI_ATTR_RESERVED_25 = 418; // reserved OCI_ATTR_FLOW_CONTROL_TIMEOUT = 423; // AQ: flow control timeout OCI_ATTR_ENV_NLS_LANGUAGE = 424; OCI_ATTR_ENV_NLS_TERRITORY = 425; //===================DirPathAPI attribute Section============================ //=========================================================================== //------------- Supported Values for Direct Path Stream Version ------------- OCI_DIRPATH_STREAM_VERSION_1 = 100; OCI_DIRPATH_STREAM_VERSION_2 = 200; OCI_DIRPATH_STREAM_VERSION_3 = 300; // default OCI_ATTR_DIRPATH_MODE = 78; // mode of direct path operation OCI_ATTR_DIRPATH_NOLOG = 79; // nologging option OCI_ATTR_DIRPATH_PARALLEL = 80; // parallel (temp seg) option // >= 8.1 OCI_ATTR_DIRPATH_SORTED_INDEX = 137; // index that data is sorted on // direct path index maint method (see oci8dp.h) OCI_ATTR_DIRPATH_INDEX_MAINT_METHOD= 138; // parallel load: db file, initial and next extent sizes OCI_ATTR_DIRPATH_FILE = 139; // DB file to load into OCI_ATTR_DIRPATH_STORAGE_INITIAL = 140; // initial extent size OCI_ATTR_DIRPATH_STORAGE_NEXT = 141; // next extent size // 8.2 dpapi support of FDTs OCI_ATTR_DIRPATH_EXPR_TYPE = 150; // expr type of OCI_ATTR_NAME OCI_ATTR_DIRPATH_INPUT = 151; // input in text or stream format OCI_DIRPATH_INPUT_TEXT = $01; OCI_DIRPATH_INPUT_STREAM = $02; OCI_DIRPATH_INPUT_UNKNOWN = $04; OCI_ATTR_DIRPATH_FN_CTX = 167; // fn ctx FDT attrs or args OCI_ATTR_DIRPATH_OID = 187; // loading into an OID col OCI_ATTR_DIRPATH_SID = 194; // loading into an SID col OCI_ATTR_DIRPATH_OBJ_CONSTR = 206; // obj type of subst obj tbl // Attr to allow setting of the stream version PRIOR to calling Prepare OCI_ATTR_DIRPATH_STREAM_VERSION = 212; // version of the stream// OCIP_ATTR_DIRPATH_VARRAY_INDEX = 213; // varray index column //------------- Supported Values for Direct Path Date cache ----------------- OCI_ATTR_DIRPATH_DCACHE_NUM = 303; // date cache entries OCI_ATTR_DIRPATH_DCACHE_SIZE = 304; // date cache limit OCI_ATTR_DIRPATH_DCACHE_MISSES = 305; // date cache misses OCI_ATTR_DIRPATH_DCACHE_HITS = 306; // date cache hits OCI_ATTR_DIRPATH_DCACHE_DISABLE = 307; { on set: disable datecache on overflow. on get: datecache disabled? could be due to overflow or others } //------------- Attributes for 10i Updates to the DirPath API --------------- OCI_ATTR_DIRPATH_RESERVED_7 = 326; // reserved OCI_ATTR_DIRPATH_RESERVED_8 = 327; // reserved OCI_ATTR_DIRPATH_CONVERT = 328; // stream conversion needed? OCI_ATTR_DIRPATH_BADROW = 329; // info about bad row OCI_ATTR_DIRPATH_BADROW_LENGTH = 330; // length of bad row info OCI_ATTR_DIRPATH_WRITE_ORDER = 331; // column fill order OCI_ATTR_DIRPATH_GRANULE_SIZE = 332; // granule size for unload OCI_ATTR_DIRPATH_GRANULE_OFFSET = 333; // offset to last granule OCI_ATTR_DIRPATH_RESERVED_1 = 334; // reserved OCI_ATTR_DIRPATH_RESERVED_2 = 335; // reserved //------ Attributes for 10i DirPathAPI conversion (NLS lang, terr, cs) ------ OCI_ATTR_DIRPATH_RESERVED_3 = 337; // reserved OCI_ATTR_DIRPATH_RESERVED_4 = 338; // reserved OCI_ATTR_DIRPATH_RESERVED_5 = 357; // reserved OCI_ATTR_DIRPATH_RESERVED_6 = 358; // reserved OCI_ATTR_DIRPATH_LOCK_WAIT = 359; // wait for lock in dpapi // values for OCI_ATTR_DIRPATH_MODE attribute OCI_DIRPATH_LOAD = 1; // direct path load operation OCI_DIRPATH_UNLOAD = 2; // direct path unload operation OCI_DIRPATH_CONVERT = 3; // direct path convert only operation // values for OCI_ATTR_DIRPATH_INDEX_MAINT_METHOD attribute OCI_DIRPATH_INDEX_MAINT_SINGLE_ROW = 1; OCI_DIRPATH_INDEX_MAINT_SKIP_UNUSABLE = 2; OCI_DIRPATH_INDEX_MAINT_SKIP_ALL = 3; // values for OCI_ATTR_STATE attribute of OCIDirPathCtx OCI_DIRPATH_NORMAL = 1; // can accept rows, last row complete OCI_DIRPATH_PARTIAL = 2; // last row was partial OCI_DIRPATH_NOT_PREPARED = 3; // direct path context is not prepared // values for cflg argument to OCIDirpathColArrayEntrySet OCI_DIRPATH_COL_COMPLETE = 0; // column data is complete OCI_DIRPATH_COL_NULL = 1; // column is null OCI_DIRPATH_COL_PARTIAL = 2; // column data is partial // values for action parameter to OCIDirPathDataSave OCI_DIRPATH_DATASAVE_SAVEONLY = 0; // data save point only OCI_DIRPATH_DATASAVE_FINISH = 1; // execute finishing logic //================ Describe Handle Parameter Attribute Values =============== //=========================================================================== // OCI_ATTR_CURSOR_COMMIT_BEHAVIOR OCI_CURSOR_OPEN = 0; OCI_CURSOR_CLOSED = 1; // OCI_ATTR_CATALOG_LOCATION OCI_CL_START = 0; OCI_CL_END = 1; // OCI_ATTR_SAVEPOINT_SUPPORT OCI_SP_SUPPORTED = 0; OCI_SP_UNSUPPORTED = 1; // OCI_ATTR_NOWAIT_SUPPORT OCI_NW_SUPPORTED = 0; OCI_NW_UNSUPPORTED = 1; // OCI_ATTR_AUTOCOMMIT_DDL OCI_AC_DDL = 0; OCI_NO_AC_DDL = 1; // OCI_ATTR_LOCKING_MODE OCI_LOCK_IMMEDIATE = 0; OCI_LOCK_DELAYED = 1; // ------------------- Instance type attribute values ----------------------- OCI_INSTANCE_TYPE_UNKNOWN = 0; OCI_INSTANCE_TYPE_RDBMS = 1; OCI_INSTANCE_TYPE_OSM = 2; OCI_INSTANCE_TYPE_PROXY = 3; OCI_INSTANCE_TYPE_IOS = 4; // ---------------- ASM Volume Device Support attribute values -------------- OCI_ASM_VOLUME_UNSUPPORTED = 0; OCI_ASM_VOLUME_SUPPORTED = 1; //---------------------------OCIPasswordChange------------------------------- OCI_AUTH = $08; // Change the password but do not login //------------------------Other Constants------------------------------------ OCI_MAX_FNS = 100; // max number of OCI Functions OCI_SQLSTATE_SIZE = 5; OCI_ERROR_MAXMSG_SIZE = 1024; // max size of an error message OCI_ERROR_MAXMSG_SIZE2 = 3072; // new len max size of an error message OCI_LOBMAXSIZE = MINUB4MAXVAL; // maximum lob data size OCI_ROWID_LEN = 23; OCI_LOB_CONTENTTYPE_MAXSIZE = 128; // max size of securefile contenttype OCI_LOB_CONTENTTYPE_MAXBYTESIZE = 128; OCI_MAX_ATTR_LEN = 1024; OCI_NLS_MAXBUFSZ = 100; // Max buffer size may need for OCINlsGetInfo //------------------------ Fail Over Events --------------------------------- OCI_FO_END = $00000001; OCI_FO_ABORT = $00000002; OCI_FO_REAUTH = $00000004; OCI_FO_BEGIN = $00000008; OCI_FO_ERROR = $00000010; //------------------------ Fail Over Callback Return Codes ------------------ OCI_FO_RETRY = 25410; //------------------------- Fail Over Types --------------------------------- OCI_FO_NONE = $00000001; OCI_FO_SESSION = $00000002; OCI_FO_SELECT = $00000004; OCI_FO_TXNAL = $00000008; //--------------------- OCI_ATTR_VARTYPE_MAXLEN_COMPAT values --------------- OCI_ATTR_MAXLEN_COMPAT_STANDARD = 1; OCI_ATTR_MAXLEN_COMPAT_EXTENDED = 2; //----------------------------Piece Definitions------------------------------ OCI_ONE_PIECE = 0; // one piece OCI_FIRST_PIECE = 1; // the first piece OCI_NEXT_PIECE = 2; // the next of many pieces OCI_LAST_PIECE = 3; // the last piece //--------------------------- FILE open modes ------------------------------- OCI_FILE_READONLY = 1; // readonly mode open for FILE types //--------------------------- LOB open modes -------------------------------- OCI_LOB_READONLY = 1; // readonly mode open for ILOB types OCI_LOB_READWRITE = 2; // read write mode open for ILOBs OCI_LOB_WRITEONLY = 3; // Writeonly mode open for ILOB types OCI_LOB_APPENDONLY = 4; // Appendonly mode open for ILOB types OCI_LOB_FULLOVERWRITE = 5; // Completely overwrite ILOB OCI_LOB_FULLREAD = 6; // Doing a Full Read of ILOB //----------------------- LOB Buffering Flush Flags ------------------------- OCI_LOB_BUFFER_FREE = 1; OCI_LOB_BUFFER_NOFREE = 2; //---------------------------LOB Option Types ------------------------------- OCI_LOB_OPT_COMPRESS = 1; // SECUREFILE Compress OCI_LOB_OPT_ENCRYPT = 2; // SECUREFILE Encrypt OCI_LOB_OPT_DEDUPLICATE = 4; // SECUREFILE Deduplicate OCI_LOB_OPT_ALLOCSIZE = 8; // SECUREFILE Allocation Size OCI_LOB_OPT_CONTENTTYPE = 16; // SECUREFILE Content Type OCI_LOB_OPT_MODTIME = 32; // SECUREFILE Modification Time //------------------------ LOB Option Values ------------------------------ // Compression OCI_LOB_COMPRESS_OFF = 0; // Compression off OCI_LOB_COMPRESS_ON = 1; // Compression on // Encryption OCI_LOB_ENCRYPT_OFF = 0; // Encryption Off OCI_LOB_ENCRYPT_ON = 2; // Encryption On // Deduplciate OCI_LOB_DEDUPLICATE_OFF = 0; // Deduplicate Off OCI_LOB_DEDUPLICATE_ON = 4; // Deduplicate Lobs //--------------------------- OCI Statement Types --------------------------- OCI_STMT_SELECT = 1; // select statement OCI_STMT_UPDATE = 2; // update statement OCI_STMT_DELETE = 3; // delete statement OCI_STMT_INSERT = 4; // Insert Statement OCI_STMT_CREATE = 5; // create statement OCI_STMT_DROP = 6; // drop statement OCI_STMT_ALTER = 7; // alter statement OCI_STMT_BEGIN = 8; // begin ... (pl/sql statement) OCI_STMT_DECLARE = 9; // declare .. (pl/sql statement) OCI_STMT_CALL = 10; // corresponds to kpu call OCI_STMT_EXPLAIN1 = 14; // explain (on 8.0) OCI_STMT_EXPLAIN2 = 15; // explain (on 8.1 and higher) //--------------------------- OCI Parameter Types --------------------------- OCI_PTYPE_UNK = 0; // unknown OCI_PTYPE_TABLE = 1; // table OCI_PTYPE_VIEW = 2; // view OCI_PTYPE_PROC = 3; // procedure OCI_PTYPE_FUNC = 4; // function OCI_PTYPE_PKG = 5; // package OCI_PTYPE_TYPE = 6; // user-defined type OCI_PTYPE_SYN = 7; // synonym OCI_PTYPE_SEQ = 8; // sequence OCI_PTYPE_COL = 9; // column OCI_PTYPE_ARG = 10; // argument OCI_PTYPE_LIST = 11; // list OCI_PTYPE_TYPE_ATTR = 12; // user-defined type's attribute OCI_PTYPE_TYPE_COLL = 13; // collection type's element OCI_PTYPE_TYPE_METHOD = 14; // user-defined type's method OCI_PTYPE_TYPE_ARG = 15; // user-defined type method's argument OCI_PTYPE_TYPE_RESULT = 16; // user-defined type method's result OCI_PTYPE_SCHEMA = 17; // schema OCI_PTYPE_DATABASE = 18; // database OCI_PTYPE_RULE = 19; // rule OCI_PTYPE_RULE_SET = 20; // rule set OCI_PTYPE_EVALUATION_CONTEXT = 21; // evaluation context OCI_PTYPE_TABLE_ALIAS = 22; // table alias OCI_PTYPE_VARIABLE_TYPE = 23; // variable type OCI_PTYPE_NAME_VALUE = 24; // name value pair //--------------------- NLS service type and constance ---------------------- OCI_NLS_CHARSET_ID = 93; // Character set id OCI_NLS_NCHARSET_ID = 94; // NCharacter set id // ............. more ................ // ------------------------- Database Startup Flags -------------------------- OCI_DBSTARTUPFLAG_FORCE = $00000001; // Abort running instance, start OCI_DBSTARTUPFLAG_RESTRICT = $00000002; // Restrict access to DBA // ------------------------- Database Shutdown Modes ------------------------- OCI_DBSHUTDOWN_TRANSACTIONAL = 1; // Wait for all the transactions OCI_DBSHUTDOWN_TRANSACTIONAL_LOCAL = 2; // Wait for local transactions OCI_DBSHUTDOWN_IMMEDIATE = 3; // Terminate and roll back OCI_DBSHUTDOWN_ABORT = 4; // Terminate and don't roll back OCI_DBSHUTDOWN_FINAL = 5; // Orderly shutdown {----------------------------------------------------------------------------} { ORO.H } {----------------------------------------------------------------------------} //--------------------------- OBJECT INDICATOR ------------------------------ type OCIInd = sb2; pOCIInd = ^OCIInd; const OCI_IND_NOTNULL = 0; // not NULL OCI_IND_NULL = -1; // NULL OCI_IND_BADNULL = -2; // BAD NULL OCI_IND_NOTNULLABLE = -3; // not NULLable //-------------------------- Object Cache ---------------------------------- OCI_ATTR_OBJECT_NEWNOTNULL = $10; OCI_ATTR_OBJECT_DETECTCHANGE = $20; OCI_ATTR_CACHE_ARRAYFLUSH = $40; //-------------------------- OBJECT Duration ------------------------------- type OCIDuration = ub2; const OCI_DURATION_INVALID = $FFFF; // Invalid duration OCI_DURATION_BEGIN = 10; // beginning sequence of duration OCI_DURATION_NULL = OCI_DURATION_BEGIN-1; // null duration OCI_DURATION_DEFAULT = OCI_DURATION_BEGIN-2; // default OCI_DURATION_USER_CALLBACK = OCI_DURATION_BEGIN-3; OCI_DURATION_NEXT = OCI_DURATION_BEGIN-4; // next special duration OCI_DURATION_SESSION = OCI_DURATION_BEGIN; // the end of user session OCI_DURATION_TRANS = OCI_DURATION_BEGIN+1; // the end of user transaction //--------------------------- Type parameter mode --------------------------- // Proc/Func param type OCI_TYPEPARAM_IN = 0; OCI_TYPEPARAM_OUT = 1; OCI_TYPEPARAM_INOUT = 2; OCI_TYPEPARAM_BYREF = 3; OCI_TYPEPARAM_OUTNCPY = 4; OCI_TYPEPARAM_INOUTNCPY = 5; {----------------------------------------------------------------------------} { ORL.H } {----------------------------------------------------------------------------} //------------------------ NUMBER/FLOAT/DECIMAL TYPE ------------------------ const OCI_NUMBER_SIZE = 22; type OCINumber = array [0 .. OCI_NUMBER_SIZE-1] of ub1; pOCINumber = ^OCINumber; //-------------------------- OCINumberToInt --------------------------------- const OCI_NUMBER_UNSIGNED = 0; OCI_NUMBER_SIGNED = 2; //------------------------- COLLECTION FUNCTIONS ---------------------------- type // OCIColl - generic collection type pOCIColl = pOCIHandle; // OCIArray - varray collection type pOCIArray = pOCIColl; // OCITable - nested table collection type pOCITable = pOCIColl; // OCIIter - collection iterator pOCIIter = pOCIHandle; {----------------------------------------------------------------------------} { XA.H } {----------------------------------------------------------------------------} //-------------- Transaction branch identification: XID and NULLXID --------- const MAXTXNAMELEN = 64; XIDDATASIZE = 128; // size in bytes MAXGTRIDSIZE = 64; // maximum size in bytes of gtrid MAXBQUALSIZE = 64; // maximum size in bytes of bqual NULLXID_ID = -1; type PXID = ^TXID; TXID = record formatID: sb4; // format identifier gtrid_length: sb4; // value from 1 through 64 bqual_length: sb4; // value from 1 through 64 data: array [0 .. XIDDATASIZE - 1] of ub1; end; { If call SQLConnection1.StartTransaction(rDesc) with following rDesc: rDesc.TransactionID := 100; rDesc.GlobalID := 100; then dbExpress driver will setup following XID: formatID = ..... gtrid_length := 3 bqual_length := 1; data := '100'#1 } {----------------------------------------------------------------------------} { OCIDFN.H } {----------------------------------------------------------------------------} const // OCI Data Types SQLT_CHR = 1 ; // (ORANET TYPE) character string SQLT_NUM = 2 ; // (ORANET TYPE) oracle numeric SQLT_INT = 3 ; // (ORANET TYPE) integer SQLT_FLT = 4 ; // (ORANET TYPE) Floating point number SQLT_STR = 5 ; // zero terminated string SQLT_VNU = 6 ; // NUM with preceding length byte SQLT_PDN = 7 ; // (ORANET TYPE) Packed Decimal Numeric SQLT_LNG = 8 ; // long SQLT_VCS = 9 ; // Variable character string SQLT_NON = 10 ; // Null/empty PCC Descriptor entry SQLT_RID = 11 ; // rowid SQLT_DAT = 12 ; // date in oracle format SQLT_VBI = 15 ; // binary in VCS format SQLT_BIN = 23 ; // binary data(DTYBIN) SQLT_LBI = 24 ; // long binary _SQLT_PLI = 29; SQLT_UIN = 68 ; // unsigned integer SQLT_SLS = 91 ; // Display sign leading separate SQLT_LVC = 94 ; // Longer longs (char) SQLT_LVB = 95 ; // Longer long binary SQLT_AFC = 96 ; // Ansi fixed char SQLT_AVC = 97 ; // Ansi Var char SQLT_CUR = 102; // cursor type SQLT_RDD = 104; // rowid descriptor SQLT_LAB = 105; // label type SQLT_OSL = 106; // oslabel type SQLT_NTY = 108; // named object type SQLT_REF = 110; // ref type SQLT_CLOB = 112; // character lob SQLT_BLOB = 113; // binary lob SQLT_BFILEE = 114; // binary file lob SQLT_CFILEE = 115; // character file lob SQLT_RSET = 116; // result set type SQLT_NCO = 122; // named collection type (varray or nested table) SQLT_VST = 155; // OCIString type SQLT_ODT = 156; // OCIDate type SQLT_REC = 250; SQLT_TAB = 251; SQLT_BOL = 252; // post 8.1 // datetimes and intervals SQLT_DATE = 184; // ANSI Date SQLT_TIME = 185; // TIME SQLT_TIME_TZ = 186; // TIME WITH TIME ZONE SQLT_TIMESTAMP = 187; // TIMESTAMP SQLT_TIMESTAMP_TZ = 188; // TIMESTAMP WITH TIME ZONE SQLT_INTERVAL_YM = 189; // INTERVAL YEAR TO MONTH SQLT_INTERVAL_DS = 190; // INTERVAL DAY TO SECOND SQLT_TIMESTAMP_LTZ = 232; // TIMESTAMP WITH LOCAL TZ SQLT_PNTY = 241; // pl/sql representation of named types // >= 10 // binary SQLT_IBFLOAT = 100; // binary float canonical SQLT_IBDOUBLE = 101; // binary double canonical // CHAR/NCHAR/VARCHAR2/NVARCHAR2/CLOB/NCLOB char set "form" information SQLCS_IMPLICIT = 1; // for CHAR, VARCHAR2, CLOB w/o a specified set SQLCS_NCHAR = 2; // for NCHAR, NCHAR VARYING, NCLOB SQLCS_EXPLICIT = 3; // for CHAR, etc, with "CHARACTER SET ..." syntax SQLCS_FLEXIBLE = 4; // for PL/SQL "flexible" parameters SQLCS_LIT_NULL = 5; // for typecheck of NULL and empty_clob() lits {----------------------------------------------------------------------------} { OCIAP.H } {----------------------------------------------------------------------------} type TOCIInitialize = function(mode: ub4; ctxp: pointer; malocfp: pointer; ralocfp: pointer; mfreefp: pointer): sword; cdecl; TOCIEnvInit = function(var envhpp: pOCIEnv; mode: ub4; xtramemsz: TFDsize_t; usrmempp: PPointer): sword; cdecl; TOCIEnvCreate = function(var envhpp: pOCIEnv; mode: ub4; ctxp: pointer; malocfp: pointer; ralocfp: pointer; mfreefp: pointer; xtramemsz: TFDsize_t; usrmempp: PPointer): sword; cdecl; TOCIEnvNlsCreate = function(var envhpp: pOCIEnv; mode: ub4; ctxp: pointer; malocfp: pointer; ralocfp: pointer; mfreefp: pointer; xtramemsz: TFDsize_t; usrmempp: PPointer; charset: ub2; ncharset: ub2): sword; cdecl; TOCIHandleAlloc = function(parenth: pOCIHandle; var hndlpp: pOCIHandle; atype: ub4; xtramem_sz: TFDsize_t; usrmempp: PPointer): sword; cdecl; TOCIServerAttach = function(srvhp: pOCIServer; errhp: pOCIError; dblink: pOCIText; dblink_len: sb4; mode: ub4): sword; cdecl; TOCIAttrSet = function(trgthndlp: pOCIHandle; trghndltyp: ub4; attributep: pointer; size: ub4; attrtype: ub4; errhp: pOCIError): sword; cdecl; TOCISessionBegin = function(svchp: pOCISvcCtx; errhp: pOCIError; usrhp: pOCISession; credt: ub4; mode: ub4): sword; cdecl; TOCISessionEnd = function(svchp: pOCISvcCtx; errhp: pOCIError; usrhp: pOCISession; mode: ub4): sword; cdecl; TOCIServerDetach = function(srvhp: pOCIServer; errhp: pOCIError; mode: ub4): sword; cdecl; TOCIHandleFree = function(hndlp: pointer; atype: ub4): sword; cdecl; TOCIErrorGet = function(hndlp: pointer; recordno: ub4; sqlstate: pOCIText; var errcodep: sb4; bufp: pOCIText; bufsiz: ub4; atype: ub4): sword; cdecl; TOCIStmtPrepare = function(stmtp: pOCIStmt; errhp: pOCIError; stmt: pOCIText; stmt_len: ub4; language: ub4; mode: ub4): sword; cdecl; TOCIStmtPrepare2 = function(svchp: pOCISvcCtx; var stmtp: pOCIStmt; errhp: pOCIError; stmt: pOCIText; stmt_len: ub4; key: pOCIText; key_len: ub4; language: ub4; mode: ub4): sword; cdecl; TOCIStmtExecute = function(svchp: pOCISvcCtx; stmtp: pOCIStmt; errhp: pOCIError; iters: ub4; rowoff: ub4; snap_in: pOCISnapshot; snap_out: pOCISnapshot; mode: ub4): sword; cdecl; TOCIStmtGetNextResult = function (stmtp: pOCIStmt; errhp: pOCIError; var result: Pointer; var rtype: ub4; mode: ub4): sword; cdecl; TOCIParamGet = function(hndlp: pointer; htype: ub4; errhp: pOCIError; var parmdpp: pointer; pos: ub4): sword; cdecl; TOCIAttrGet = function(trgthndlp: pOCIHandle; trghndltyp: ub4; attributep: pointer; sizep: pointer; attrtype: ub4; errhp: pOCIError):sword; cdecl; TOCIStmtFetch = function(stmtp: pOCIStmt; errhp: pOCIError; nrows: ub4; orientation: ub2; mode: ub4): sword; cdecl; TOCIStmtFetch2 = function(stmtp: pOCIStmt; errhp: pOCIError; nrows: ub4; orientation: ub2; scrollOffset: ub4; mode: ub4): sword; cdecl; TOCIDefineByPos = function(stmtp: pOCIStmt; var defnpp: pOCIDefine; errhp: pOCIError; position: ub4; valuep: pointer; value_sz: sb4; dty: ub2; indp: pointer; rlenp: pUb2; rcodep: pUb2; mode: ub4): sword; cdecl; TOCIDefineByPos2 = function(stmtp: pOCIStmt; var defnpp: pOCIDefine; errhp: pOCIError; position: ub4; valuep: pointer; value_sz: sb8; dty: ub2; indp: pointer; rlenp: pUb4; rcodep: pUb2; mode: ub4): sword; cdecl; TOCIDefineArrayOfStruct = function(defnpp: pOCIDefine; errhp: pOCIError; pvskip: ub4; indskip: ub4; rlskip: ub4; rcskip: ub4): sword; cdecl; TOCIRowidToChar = function (rowidDesc: pOCIRowid; outbfp: pOCIText; var outbflp: ub2; errhp: pOCIError): sword; cdecl; TOCIBindByPos = function(stmtp: pOCIStmt; var bindpp: pOCIBind; errhp: pOCIError; position: ub4; valuep: pointer; value_sz: sb4; dty: ub2; indp: pointer; alenp: pUb2; rcodep: pUb2; maxarr_len: ub4; curelep: pUb4; mode: ub4): sword; cdecl; TOCIBindByPos2 = function(stmtp: pOCIStmt; var bindpp: pOCIBind; errhp: pOCIError; position: ub4; valuep: pointer; value_sz: sb8; dty: ub2; indp: pointer; alenp: pUb4; rcodep: pUb2; maxarr_len: ub4; curelep: pUb4; mode: ub4): sword; cdecl; TOCIBindByName = function(stmtp: pOCIStmt; var bindpp: pOCIBind; errhp: pOCIError; placeholder: pOCIText; placeh_len: sb4; valuep: pointer; value_sz: sb4; dty: ub2; indp: pointer; alenp: pUb2; rcodep: pUb2; maxarr_len: ub4; curelep: pUb4; mode: ub4): sword; cdecl; TOCIBindByName2 = function(stmtp: pOCIStmt; var bindpp: pOCIBind; errhp: pOCIError; placeholder: pOCIText; placeh_len: sb4; valuep: pointer; value_sz: sb8; dty: ub2; indp: pointer; alenp: pUb4; rcodep: pUb2; maxarr_len: ub4; curelep: pUb4; mode: ub4): sword; cdecl; TOCIInCBFunc = function(ictxp: Pointer; bindp: pOCIBind; iter: ub4; index: ub4; var bufpp: Pointer; var alenp: Ub4; var piecep: Ub1; var indp: pSb2): sword; cdecl; TOCIOutCBFunc = function(octxp: Pointer; bindp: pOCIBind; iter: ub4; index: ub4; var bufpp: Pointer; var alenpp: pUb4; var piecep: ub1; var indpp: pSb2; var rcodepp: pUb2): sword; cdecl; TOCIBindDynamic = function(bindp: pOCIBind; errhp: pOCIError; ictxp: Pointer; icbfp: TOCIInCBFunc; octxp: Pointer; ocbfp: TOCIOutCBFunc): sword; cdecl; TOCITransStart = function(svchp: pOCISvcCtx; errhp: pOCIError; timeout: uword; flags: ub4): sword; cdecl; TOCITransRollback = function(svchp: pOCISvcCtx; errhp: pOCIError; flags: ub4): sword; cdecl; TOCITransCommit = function(svchp: pOCISvcCtx; errhp: pOCIError; flags: ub4): sword; cdecl; TOCITransDetach = function(svchp: pOCISvcCtx; errhp: pOCIError; flags: ub4): sword; cdecl; TOCITransPrepare = function(svchp: pOCISvcCtx; errhp: pOCIError; flags: ub4): sword; cdecl; TOCITransForget = function(svchp: pOCISvcCtx; errhp: pOCIError; flags: ub4): sword; cdecl; TOCIDescribeAny = function(svchp: pOCISvcCtx; errhp: pOCIError; objptr: pOCIText; objnm_len: ub4; objptr_typ: ub1; info_level: ub1; objtyp: ub1; dschp: pOCIDescribe): sword; cdecl; TOCIBreak = function(svchp: pOCISvcCtx; errhp: pOCIError): sword; cdecl; TOCIReset = function(svchp: pOCISvcCtx; errhp: pOCIError): sword; cdecl; TOCIDescriptorAlloc = function(parenth: pOCIEnv; var descpp: pOCIDescriptor; htype: ub4; xtramem_sz: integer; usrmempp: pointer): sword; cdecl; TOCIDescriptorFree = function(descp: pointer; htype: ub4): sword; cdecl; TOCILobAppend = function(svchp: pOCISvcCtx; errhp: pOCIError; dst_locp, src_locp: pOCILobLocator): sword; cdecl; TOCILobAssign = function(envhp: pOCIEnv; errhp: pOCIError; src_locp: pOCILobLocator; var dst_locpp: pOCILobLocator): sword; cdecl; TOCILobCharSetForm = function (envhp: pOCIEnv; errhp: pOCIError; locp: pOCILobLocator; var csfrm: ub1): sword; cdecl; TOCILobClose = function(svchp: pOCISvcCtx; errhp: pOCIError; locp: pOCILobLocator): sword; cdecl; TOCILobCopy = function(svchp: pOCISvcCtx; errhp: pOCIError; dst_locp: pOCILobLocator; src_locp: pOCILobLocator; amount: ub4; dst_offset: ub4; src_offset: ub4): sword; cdecl; TOCILobEnableBuffering = function(svchp: pOCISvcCtx; errhp: pOCIError; locp: pOCILobLocator): sword; cdecl; TOCILobDisableBuffering = function(svchp: pOCISvcCtx; errhp: pOCIError; locp: pOCILobLocator): sword; cdecl; TOCILobErase = function(svchp: pOCISvcCtx; errhp: pOCIError; locp: pOCILobLocator; var amount: ub4; offset: ub4): sword; cdecl; TOCILobFileExists = function(svchp: pOCISvcCtx; errhp: pOCIError; filep: pOCILobLocator; var flag: LongBool): sword; cdecl; TOCILobFileGetName = function(envhp: pOCIEnv; errhp: pOCIError; filep: pOCILobLocator; dir_alias: pOCIText; var d_length: ub2; filename: pOCIText; var f_length: ub2): sword; cdecl; TOCILobFileSetName = function(envhp: pOCIEnv; errhp: pOCIError; var filep: pOCILobLocator; dir_alias: pOCIText; d_length: ub2; filename: pOCIText; f_length: ub2): sword; cdecl; TOCILobFlushBuffer = function(svchp: pOCISvcCtx; errhp: pOCIError; locp: pOCILobLocator; flag: ub4): sword; cdecl; TOCILobGetLength = function (svchp: pOCISvcCtx; errhp: pOCIError; locp: pOCILobLocator; var lenp: ub4): sword; cdecl; TOCILobIsOpen = function(svchp: pOCISvcCtx; errhp: pOCIError; locp: pOCILobLocator; var flag: LongBool): sword; cdecl; TOCILobLoadFromFile = function (svchp: pOCISvcCtx; errhp: pOCIError; dst_locp: pOCILobLocator; src_locp: pOCILobLocator; amount: ub4; dst_offset: ub4; src_offset: ub4): sword; cdecl; TOCILobLocatorIsInit = function (envhp: pOCIEnv; errhp: pOCIError; locp: pOCILobLocator; var is_initialized: LongBool): sword; cdecl; TOCILobOpen = function (svchp: pOCISvcCtx; errhp: pOCIError; locp: pOCILobLocator; mode: ub1): sword; cdecl; TOCILobRead = function (svchp: pOCISvcCtx; errhp: pOCIError; locp: pOCILobLocator; var amtp: ub4; offset: ub4; bufp: Pointer; bufl: ub4; ctxp: Pointer; cbfp: Pointer; csid: ub2; csfrm: ub1): sword; cdecl; TOCILobTrim = function (svchp: pOCISvcCtx; errhp: pOCIError; locp: pOCILobLocator; newlen: ub4): sword; cdecl; TOCILobWrite = function(svchp: pOCISvcCtx; errhp: pOCIError; locp: pOCILobLocator; var amtp: ub4; offset: ub4; bufp: pointer; bufl: ub4; piece: ub1; ctxp: pointer; cbfp: pointer; csid: ub2; csfrm: ub1): sword; cdecl; TOCILobCreateTemporary = function(svchp: pOCISvcCtx; errhp: pOCIError; locp: pOCILobLocator; csid: ub2; csfrm: ub1; lobtype: ub1; cache: LongBool; duration: OCIDuration): sword; cdecl; TOCILobFreeTemporary = function(svchp: pOCISvcCtx; errhp: pOCIError; locp: pOCILobLocator): sword; cdecl; TOCILobIsTemporary = function(envhp: pOCIEnv; errhp: pOCIError; locp: pOCILobLocator; var is_temporary: LongBool): sword; cdecl; TOCIStmtGetPieceInfo = function(stmtp: pOCIStmt; errhp: pOCIError; var hndlpp: pointer; var typep: ub4; var in_outp: ub1; var iterp: ub4; var idxp: ub4; var piecep: ub1): sword; cdecl; TOCIStmtSetPieceInfo = function(handle: pointer; typep: ub4; errhp: pOCIError; buf: pointer; var alenp: ub4; piece: ub1; indp: pointer; var rcodep: ub2): sword; cdecl; TOCIPasswordChange = function(svchp: pOCISvcCtx; errhp: pOCIError; user_name: pOCIText; usernm_len: ub4; opasswd: pOCIText; opasswd_len: ub4; npasswd: pOCIText; npasswd_len: sb4; mode: ub4): sword; cdecl; TOCIServerVersion = function(hndlp: pOCIHandle; errhp: pOCIError; bufp: pOCIText; bufsz: ub4; hndltype: ub1): sword; cdecl; TOCIResultSetToStmt = function(rsetdp: pOCIHandle; errhp: pOCIError): sword; cdecl; TOCIDirPathAbort = function(dpctx: pOCIDirPathCtx; errhp: pOCIError): sword; cdecl; TOCIDirPathDataSave = function(dpctx: pOCIDirPathCtx; errhp: pOCIError; action: ub4): sword; cdecl; TOCIDirPathFinish = function(dpctx: pOCIDirPathCtx; errhp: pOCIError): sword; cdecl; TOCIDirPathFlushRow = function(dpctx: pOCIDirPathCtx; errhp: pOCIError): sword; cdecl; TOCIDirPathPrepare = function(dpctx: pOCIDirPathCtx; svchp: pOCISvcCtx; errhp: pOCIError): sword; cdecl; TOCIDirPathLoadStream = function(dpctx: pOCIDirPathCtx; dpstr: pOCIDirPathStream; errhp: pOCIError): sword; cdecl; TOCIDirPathColArrayEntryGet = function(dpca: pOCIDirPathColArray; errhp: pOCIError; rownum: ub4; colIdx: ub2; var cvalpp: pUb1; var clenp: ub4; var cflgp: ub1): sword; cdecl; TOCIDirPathColArrayEntrySet = function(dpca: pOCIDirPathColArray; errhp: pOCIError; rownum: ub4; colIdx: ub2; cvalp: pUb1; clen: ub4; cflg: ub1): sword; cdecl; TOCIDirPathColArrayRowGet = function(dpca: pOCIDirPathColArray; errhp: pOCIError; rownum: ub4; var cvalppp: ppUb1; var clenpp: pUb4; var cflgpp: pUb1): sword; cdecl; TOCIDirPathColArrayReset = function(dpca: pOCIDirPathColArray; errhp: pOCIError): sword; cdecl; TOCIDirPathColArrayToStream = function(dpca: pOCIDirPathColArray; dpctx: pOCIDirPathCtx; dpstr: pOCIDirPathStream; errhp: pOCIError; rowcnt: ub4; rowoff: ub4): sword; cdecl; TOCIDirPathStreamReset = function(dpstr: pOCIDirPathStream; errhp: pOCIError): sword; cdecl; TOCIDirPathStreamToStream = function(istr: pOCIDirPathStream; ostr: pOCIDirPathStream; dpctx: pOCIDirPathCtx; errhp: pOCIError; isoff: ub4; osoff: ub4): sword; cdecl; TOCILogon = function(envhp: pOCIEnv; errhp: pOCIError; var svchp: pOCISvcCtx; username: pOCIText; uname_len: ub4; password: pOCIText; passwd_len: ub4; dbname: pOCIText; dbname_len: ub4): sword; cdecl; TOCILogon2 = function(envhp: pOCIEnv; errhp: pOCIError; var svchp: pOCISvcCtx; username: pOCIText; uname_len: ub4; password: pOCIText; passwd_len: ub4; dbname: pOCIText; dbname_len: ub4; mode: ub4): sword; cdecl; TOCILogoff = function(svchp: pOCISvcCtx; errhp: pOCIError): sword; cdecl; TOCIDateTimeGetDate = function(envhp: pOCIEnv; errhp: pOCIError; datetime: pOCIDateTime; var year: sb2; var month: ub1; var day: ub1): sword; cdecl; TOCIDateTimeGetTime = function(envhp: pOCIEnv; errhp: pOCIError; datetime: pOCIDateTime; var hour: ub1; var min: ub1; var sec: ub1; var fsec: ub4): sword; cdecl; TOCIDateTimeConstruct = function(envhp: pOCIEnv; errhp: pOCIError; datetime: pOCIDateTime; year: sb2; month: ub1; day: ub1; hour: ub1; min: ub1; sec: ub1; fsec: ub4; timezone: pOCIText; timezone_length: ub4): sword; cdecl; TOCIDateTimeGetTimeZoneOffset = function(envhp: pOCIEnv; errhp: pOCIError; datetime: pOCIDateTime; var hour: sb1; var minute: sb1): sword; cdecl; TOCIDateTimeAssign = function(envhp: pOCIEnv; err: pOCIError; from: pOCIDateTime; to_: pOCIDateTime): sword; cdecl; TOCIPing = function(svchp: pOCISvcCtx; errhp: pOCIError; mode: ub4): sword; cdecl; TOCINlsCharSetNameToId = function(envhp: pOCIEnv; name: pOCIText): ub2; cdecl; TOCINlsCharSetIdToName = function(envhp: pOCIEnv; buf: pOCIText; buflen: TFDsize_t; id: ub2): sword; cdecl; TOCINlsEnvironmentVariableGet = function(valp: Pointer; size: TFDsize_t; item: ub2; charset: ub2; var rsize: TFDsize_t): sword; cdecl; TOCIClientVersion = function(var major_version, minor_version, update_num, patch_num, port_update_num: sword): sword; cdecl; TOCIIntervalAssign = function(envhp: pOCIEnv; err: pOCIError; from: pOCIInterval; to_: pOCIInterval): sword; cdecl; TOCIIntervalCheck = function (envhp: pOCIEnv; err: pOCIError; interval: pOCIInterval; var valid: ub4): sword; cdecl; TOCIIntervalSetYearMonth = function (envhp: pOCIEnv; err: pOCIError; yr, mnth: sb4; result: pOCIInterval): sword; cdecl; TOCIIntervalGetYearMonth = function (envhp: pOCIEnv; err: pOCIError; out yr, mnth: sb4; result: pOCIInterval): sword; cdecl; TOCIIntervalSetDaySecond = function (envhp: pOCIEnv; err: pOCIError; dy, hr, mm, ss, fsec: sb4; result: pOCIInterval): sword; cdecl; TOCIIntervalGetDaySecond = function (envhp: pOCIEnv; err: pOCIError; out dy, hr, mm, ss, fsec: sb4; result: pOCIInterval): sword; cdecl; TOCIDBStartup = function (svchp: pOCISvcCtx; errhp: pOCIError; admhp: pOCIAdmin; mode: ub4; flags: ub4): sword; cdecl; TOCIDBShutdown = function (svchp: pOCISvcCtx; errhp: pOCIError; admhp: pOCIAdmin; mode: ub4): sword; cdecl; TOCISubscriptionRegister = function (svchp: pOCISvcCtx; subscrhpp: ppOCIHandle; count: ub2; errhp: pOCIError; mode: ub4): sword; cdecl; TOCISubscriptionPost = function (svchp: pOCISvcCtx; subscrhpp: ppOCIHandle; count: ub2; errhp: pOCIError; mode: ub4): sword; cdecl; TOCISubscriptionUnRegister = function (svchp: pOCISvcCtx; subscrhp: pOCISubscription; errhp: pOCIError; mode: ub4): sword; cdecl; TOCISubscriptionDisable = function (subscrhp: pOCISubscription; errhp: pOCIError; mode: ub4): sword; cdecl; TOCISubscriptionEnable = function (subscrhp: pOCISubscription; errhp: pOCIError; mode: ub4): sword; cdecl; {----------------------------------------------------------------------------} { ORL.H } {----------------------------------------------------------------------------} TOCINumberToText = function(errhp: pOCIError; number: pOCINumber; fmt: pOCIText; fmt_length: ub4; nls_params: pOCIText; nls_p_length: ub4; var buf_size: ub4; buf: pOCIText): sword; cdecl; TOCICollSize = function (envhp: pOCIEnv; err: pOCIError; coll: pOCIColl; var size: sb4): sword; cdecl; TOCICollMax = function (env: pOCIEnv; coll: pOCIColl): sb4; cdecl; TOCICollGetElem = function (envhp: pOCIEnv; err: pOCIError; coll: pOCIColl; index: sb4; var exists: LongBool; var elem: Pointer; var elemind: Pointer): sword; cdecl; TOCICollAssignElem = function (envhp: pOCIEnv; err: pOCIError; index: sb4; elem: Pointer; elemind: Pointer; coll: pOCIColl): sword; cdecl; TOCICollAssign = function (envhp: pOCIEnv; err: pOCIError; rhs, lhs: pOCIColl): sword; cdecl; TOCICollAppend = function (envhp: pOCIEnv; err: pOCIError; elem: Pointer; elemind: Pointer; coll: pOCIColl): sword; cdecl; TOCICollTrim = function (envhp: pOCIEnv; err: pOCIError; trim_num: sb4; coll: pOCIColl): sword; cdecl; TOCICollIsLocator = function (envhp: pOCIEnv; err: pOCIError; coll: pOCIColl; var result: LongBool): sword; cdecl; TOCIIterCreate = function (envhp: pOCIEnv; err: pOCIError; coll: pOCIColl; var itr: pOCIIter): sword; cdecl; TOCIIterDelete = function (envhp: pOCIEnv; err: pOCIError; var itr: pOCIIter): sword; cdecl; TOCIIterInit = function (envhp: pOCIEnv; err: pOCIError; coll: pOCIColl; itr: pOCIIter): sword; cdecl; TOCIIterGetCurrent = function (envhp: pOCIEnv; err: pOCIError; itr: pOCIIter; var elem: Pointer; var elemind: Pointer): sword; cdecl; TOCIIterNext = function (envhp: pOCIEnv; err: pOCIError; itr: pOCIIter; var elem: Pointer; var elemind: Pointer; var eoc: LongBool): sword; cdecl; TOCIIterPrev = function (envhp: pOCIEnv; err: pOCIError; itr: pOCIIter; var elem: Pointer; var elemind: Pointer; var boc: LongBool): sword; cdecl; implementation end.
unit caStackObjects; {$INCLUDE ca.inc} interface uses // Standard Delphi units SysUtils, Classes, // ca units caClasses, caUtils; type //--------------------------------------------------------------------------- // TcaStackInteger //--------------------------------------------------------------------------- TcaStackInteger = class private // Property fields FIndex: Integer; FValue: Integer; // Property methods function GetAsString: String; procedure SetAsString(const Value: String); protected // Protected virtual methods procedure DoCreate(AValue : Integer ); virtual; procedure DoDestroy; virtual; public constructor Create(AValue: Integer); destructor Destroy; override; // Public class methods class function CreateObject(AValue: Integer): TcaStackInteger; class procedure FreeObject; // Properties property AsString: String read GetAsString write SetAsString; property Index: Integer read FIndex; property Value: Integer read FValue write FValue; end; TcaStackIntegerRec = record _VMT: TClass; _FValue : Integer; end; var caStackIntegerRec: TcaStackIntegerRec; implementation //--------------------------------------------------------------------------- // TcaStackInteger //--------------------------------------------------------------------------- constructor TcaStackInteger.Create(AValue: Integer); begin DoCreate(AValue); end; destructor TcaStackInteger.Destroy; begin DoDestroy; end; // Public class methods class function TcaStackInteger.CreateObject(AValue: Integer): TcaStackInteger; begin InitInstance(@caStackIntegerRec); Result := TcaStackInteger(@caStackIntegerRec); try Result.DoCreate(AValue); Result.AfterConstruction; except Result.DoDestroy; Result.CleanupInstance; raise; end; end; class procedure TcaStackInteger.FreeObject; var Obj: TcaStackInteger; begin Obj := TcaStackInteger(@caStackIntegerRec); Obj.BeforeDestruction; Obj.DoDestroy; Obj.CleanupInstance; end; // Protected virtual methods procedure TcaStackInteger.DoCreate(AValue: Integer); begin FValue := AValue; end; procedure TcaStackInteger.DoDestroy; begin // Nada end; // Property methods function TcaStackInteger.GetAsString: String; begin Result := Utils.IntegerToString(FValue, ''); end; procedure TcaStackInteger.SetAsString(const Value: String); begin FValue := Utils.StringToInteger(Value); end; end.
unit ltrapidefine; interface uses SysUtils; const LTRD_ADDR_LOCAL = $7F000001; LTRD_ADDR_DEFAULT = LTRD_ADDR_LOCAL; LTRD_PORT_DEFAULT = 11111; LTR_CRATES_MAX = 16; { Максимальное количество крейтов, которое можно получить с помощью функции LTR_GetCrates(). Для ltrd можно получить список большего кол-ва крейтов с помощью LTR_GetCratesWithInfo() } LTR_MODULES_PER_CRATE_MAX = 16; // Максимальное количество модулей в одном крейте { Фиктивный серийный номер крейта для управления самим сервером (работает и тогда, когда нет ни одного подключенного крейта Команды, которые рассчитаны на этот режим, помечены комментарием "SERVER_CONTROL" } LTR_CSN_SERVER_CONTROL = '#SERVER_CONTROL'; // типы каналов клиент-сервер LTR_CC_CHNUM_CONTROL = 0; // канал для передачи управляющих запросов крейту или ltrd LTR_CC_CHNUM_MODULE1 = 1; // канал для работы c модулем в слоте 1 LTR_CC_CHNUM_MODULE2 = 2; // канал для работы c модулем в слоте 2 LTR_CC_CHNUM_MODULE3 = 3; // канал для работы c модулем в слоте 3 LTR_CC_CHNUM_MODULE4 = 4; // канал для работы c модулем в слоте 4 LTR_CC_CHNUM_MODULE5 = 5; // канал для работы c модулем в слоте 5 LTR_CC_CHNUM_MODULE6 = 6; // канал для работы c модулем в слоте 6 LTR_CC_CHNUM_MODULE7 = 7; // канал для работы c модулем в слоте 7 LTR_CC_CHNUM_MODULE8 = 8; // канал для работы c модулем в слоте 8 LTR_CC_CHNUM_MODULE9 = 9; // канал для работы c модулем в слоте 9 LTR_CC_CHNUM_MODULE10 = 10; // канал для работы c модулем в слоте 10 LTR_CC_CHNUM_MODULE11 = 11; // канал для работы c модулем в слоте 11 LTR_CC_CHNUM_MODULE12 = 12; // канал для работы c модулем в слоте 12 LTR_CC_CHNUM_MODULE13 = 13; // канал для работы c модулем в слоте 13 LTR_CC_CHNUM_MODULE14 = 14; // канал для работы c модулем в слоте 14 LTR_CC_CHNUM_MODULE15 = 15; // канал для работы c модулем в слоте 15 LTR_CC_CHNUM_MODULE16 = 16; // канал для работы c модулем в слоте 16 LTR_CC_CHNUM_USERDATA = 18; // канал для работы с псевдомодулем для пользовательских данных LTR_CC_FLAG_RAW_DATA = $4000; { флаг отладки - ltrd передает клиенту все данные, которые приходят от крейта, без разбивки по модулям } LTR_CC_IFACE_USB = $0100; { явное указание, что соединение должно быть по USB-интерфейсу} LTR_CC_IFACE_ETH = $0200; { явное указание, что соединение должно быть по Ethernet (TCP/IP) } LTR_FLAG_RBUF_OVF = (1 shl 0); // флаг переполнения буфера клиента LTR_FLAG_RFULL_DATA = (1 shl 1); { флаг получения данных в полном формате в функции LTR_GetCrateRawData } // идентификаторы модулей LTR_MID_EMPTY = 0 ; // идентификатор соответствующий LTR_MID_IDENTIFYING = $FFFF; // модуль в процессе определения ID LTR_MID_LTR01 = $0101; // идентификатор модуля LTR01 LTR_MID_LTR11 = $0B0B; // идентификатор модуля LTR11 LTR_MID_LTR22 = $1616; // идентификатор модуля LTR22 LTR_MID_LTR24 = $1818; // идентификатор модуля LTR24 LTR_MID_LTR25 = $1919; // идентификатор модуля LTR25 LTR_MID_LTR27 = $1B1B; // идентификатор модуля LTR27 LTR_MID_LTR34 = $2222; // идентификатор модуля LTR34 LTR_MID_LTR35 = $2323; // идентификатор модуля LTR35 LTR_MID_LTR41 = $2929; // идентификатор модуля LTR41 LTR_MID_LTR42 = $2A2A; // идентификатор модуля LTR42 LTR_MID_LTR43 = $2B2B; // идентификатор модуля LTR43 LTR_MID_LTR51 = $3333; // идентификатор модуля LTR51 LTR_MID_LTR114 = $7272; // идентификатор модуля LTR114 LTR_MID_LTR210 = $D2D2; // идентификатор модуля LTR210 LTR_MID_LTR212 = $D4D4; // идентификатор модуля LTR212 // описание крейта (для TCRATE_INFO) LTR_CRATE_TYPE_UNKNOWN =0; LTR_CRATE_TYPE_LTR010 =10; LTR_CRATE_TYPE_LTR021 =21; LTR_CRATE_TYPE_LTR030 =30; LTR_CRATE_TYPE_LTR031 =31; LTR_CRATE_TYPE_LTR032 =32; LTR_CRATE_TYPE_LTR_CU_1 =40; LTR_CRATE_TYPE_LTR_CEU_1 =41; LTR_CRATE_TYPE_BOOTLOADER =99; // интерфейс крейта (для TCRATE_INFO) LTR_CRATE_IFACE_UNKNOWN =0; LTR_CRATE_IFACE_USB =1; LTR_CRATE_IFACE_TCPIP =2; // состояние крейта (для TIPCRATE_ENTRY) LTR_CRATE_IP_STATUS_OFFLINE =0; LTR_CRATE_IP_STATUS_CONNECTING =1; LTR_CRATE_IP_STATUS_ONLINE =2; LTR_CRATE_IP_STATUS_ERROR =3; // флаги параметров крейта (для TIPCRATE_ENTRY и команды CONTROL_COMMAND_IP_SET_FLAGS) LTR_CRATE_IP_FLAG_AUTOCONNECT =$00000001; LTR_CRATE_IP_FLAG__VALID_BITS_ =$00000001; LTR_MODULE_NAME_SIZE = 16; LTR_CRATE_DEVNAME_SIZE = 32; LTR_CRATE_SERIAL_SIZE = 16; LTR_CRATE_SOFTVER_SIZE = 32; LTR_CRATE_REVISION_SIZE = 16; LTR_CRATE_IMPLEMENTATION_SIZE = 16; LTR_CRATE_BOOTVER_SIZE = 16; LTR_CRATE_CPUTYPE_SIZE = 16; LTR_CRATE_TYPE_NAME = 16; LTR_CRATE_SPECINFO_SIZE = 48; LTR_CRATE_FPGA_NAME_SIZE = 32; LTR_CRATE_FPGA_VERSION_SIZE = 32; LTR_CRATE_THERM_MAX_CNT = 8; { Максимальное кол-во термометров в крейте, показания которых отображаются в статистике } LTR_MODULE_FLAGS_HIGH_BAUD = $0001; { признак, что модуль использует высокую скорость } LTR_MODULE_FLAGS_USE_HARD_SEND_FIFO = $0100; { признак, что модуль использует статистику внутреннего аппаратного FIFO на передачу данных } LTR_MODULE_FLAGS_USE_SYNC_MARK = $0200; { признак, что модуль поддерживает генерирование синхрометок } {---------- константы, оставленные только для обратной совместимости ---------} {$IFNDEF LTRAPI_DISABLE_COMPAT_DEFS} CC_CONTROL = LTR_CC_CHNUM_CONTROL ; CC_MODULE1 = LTR_CC_CHNUM_MODULE1 ; CC_MODULE2 = LTR_CC_CHNUM_MODULE2 ; CC_MODULE3 = LTR_CC_CHNUM_MODULE3 ; CC_MODULE4 = LTR_CC_CHNUM_MODULE4 ; CC_MODULE5 = LTR_CC_CHNUM_MODULE5 ; CC_MODULE6 = LTR_CC_CHNUM_MODULE6 ; CC_MODULE7 = LTR_CC_CHNUM_MODULE7 ; CC_MODULE8 = LTR_CC_CHNUM_MODULE8 ; CC_MODULE9 = LTR_CC_CHNUM_MODULE9 ; CC_MODULE10 = LTR_CC_CHNUM_MODULE10 ; CC_MODULE11 = LTR_CC_CHNUM_MODULE11 ; CC_MODULE12 = LTR_CC_CHNUM_MODULE12 ; CC_MODULE13 = LTR_CC_CHNUM_MODULE13 ; CC_MODULE14 = LTR_CC_CHNUM_MODULE14 ; CC_MODULE15 = LTR_CC_CHNUM_MODULE15 ; CC_MODULE16 = LTR_CC_CHNUM_MODULE16 ; CC_RAW_DATA_FLAG = LTR_CC_FLAG_RAW_DATA; CRATE_MAX = LTR_CRATES_MAX; MODULE_MAX = LTR_MODULES_PER_CRATE_MAX; FLAG_RBUF_OVF = LTR_FLAG_RBUF_OVF; FLAG_RFULL_DATA = LTR_FLAG_RFULL_DATA; // идентификаторы модулей MID_EMPTY = 0 ; // идентификатор соответствующий MID_LTR11 = $0B0B ; // идентификатор модуля LTR11 MID_LTR22 = $1616 ; // идентификатор модуля LTR22 MID_LTR24 = $1818 ; // идентификатор модуля LTR24 MID_LTR27 = $1B1B ; // идентификатор модуля LTR27 MID_LTR34 = $2222 ; // идентификатор модуля LTR34 MID_LTR35 = $2323 ; // идентификатор модуля LTR35 MID_LTR41 = $2929 ; // идентификатор модуля LTR41 MID_LTR42 = $2A2A ; // идентификатор модуля LTR42 MID_LTR43 = $2B2B ; // идентификатор модуля LTR43 MID_LTR51 = $3333 ; // идентификатор модуля LTR51 MID_LTR114 = $7272 ; // идентификатор модуля LTR114 MID_LTR210 = $D2D2 ; // идентификатор модуля LTR210 MID_LTR212 = $D4D4 ; // идентификатор модуля LTR212 CSN_SERVER_CONTROL = LTR_CSN_SERVER_CONTROL; SERIAL_NUMBER_SIZE = LTR_CRATE_SERIAL_SIZE; SADDR_LOCAL = LTRD_ADDR_LOCAL; SADDR_DEFAULT = LTRD_ADDR_DEFAULT; SPORT_DEFAULT = LTRD_PORT_DEFAULT; CRATE_TYPE_UNKNOWN = LTR_CRATE_TYPE_UNKNOWN; CRATE_TYPE_LTR010 = LTR_CRATE_TYPE_LTR010; CRATE_TYPE_LTR021 = LTR_CRATE_TYPE_LTR021; CRATE_TYPE_LTR030 = LTR_CRATE_TYPE_LTR030; CRATE_TYPE_LTR031 = LTR_CRATE_TYPE_LTR031; CRATE_TYPE_LTR032 = LTR_CRATE_TYPE_LTR032; CRATE_TYPE_LTR_CU_1 = LTR_CRATE_TYPE_LTR_CU_1; CRATE_TYPE_LTR_CEU_1 = LTR_CRATE_TYPE_LTR_CEU_1; CRATE_TYPE_BOOTLOADER = LTR_CRATE_TYPE_BOOTLOADER; CRATE_IFACE_UNKNOWN = LTR_CRATE_IFACE_UNKNOWN; CRATE_IFACE_USB = LTR_CRATE_IFACE_USB; CRATE_IFACE_TCPIP = LTR_CRATE_IFACE_TCPIP; CRATE_IP_STATUS_OFFLINE = LTR_CRATE_IP_STATUS_OFFLINE; CRATE_IP_STATUS_CONNECTING = LTR_CRATE_IP_STATUS_CONNECTING; CRATE_IP_STATUS_ONLINE = LTR_CRATE_IP_STATUS_ONLINE; CRATE_IP_STATUS_ERROR = LTR_CRATE_IP_STATUS_ERROR; CRATE_IP_FLAG_AUTOCONNECT = LTR_CRATE_IP_FLAG_AUTOCONNECT; CRATE_IP_FLAG__VALID_BITS_ = LTR_CRATE_IP_FLAG__VALID_BITS_; {$ENDIF} implementation end.
{ AD.A.P.T. Library Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved Original Source Location: https://github.com/LaKraven/ADAPT Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md } unit ADAPT.Collections.Abstract; {$I ADAPT.inc} interface uses {$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES} System.Classes, {$ELSE} Classes, {$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES} ADAPT, ADAPT.Intf, ADAPT.Comparers.Intf, ADAPT.Collections.Intf; {$I ADAPT_RTTI.inc} type /// <summary><c>An Allocation Algorithm for Lists.</c></summary> /// <remarks><c>Dictates how to grow an Array based on its current Capacity and the number of Items we're looking to Add/Insert.</c></remarks> TADExpander = class abstract(TADObject, IADExpander) public { IADExpander } /// <summary><c>Override this to implement the actual Allocation Algorithm</c></summary> /// <remarks><c>Must return the amount by which the Array has been Expanded.</c></remarks> function CheckExpand(const ACapacity, ACurrentCount, AAdditionalRequired: Integer): Integer; virtual; abstract; end; /// <summary><c>A Deallocation Algorithm for Lists.</c></summary> /// <remarks><c>Dictates how to shrink an Array based on its current Capacity and the number of Items we're looking to Delete.</c></remarks> TADCompactor = class abstract(TADObject, IADCompactor) public { IADCompactor } function CheckCompact(const ACapacity, ACurrentCount, AVacating: Integer): Integer; virtual; abstract; end; /// <summary><c>Abstract Base Class for all Collection Classes.</c></summary> /// <remarks> /// <para><c>Use IADCollectionReader or IADCollection if you want to take advantage of Reference Counting.</c></para> /// <para><c>This is NOT Threadsafe</c></para> /// </remarks> TADCollection = class abstract(TADObject, IADCollectionReader, IADCollection) protected FCount: Integer; FInitialCapacity: Integer; FSortedState: TADSortedState; // Getters { IADCollectionReader } function GetCapacity: Integer; virtual; abstract; function GetCount: Integer; virtual; function GetInitialCapacity: Integer; function GetIsCompact: Boolean; virtual; abstract; function GetIsEmpty: Boolean; virtual; function GetSortedState: TADSortedState; virtual; { IADCollection } function GetReader: IADCollectionReader; // Setters { IADCollectionReader } { IADCollection } procedure SetCapacity(const ACapacity: Integer); virtual; abstract; // Overridables procedure CreateArray(const AInitialCapacity: Integer); virtual; abstract; constructor Create(const AInitialCapacity: Integer); reintroduce; virtual; public // Management Methods { IADCollectionReader } { IADCollection } procedure Clear; virtual; abstract; // Properties { IADCollectionReader } property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount; property InitialCapacity: Integer read GetInitialCapacity; property IsCompact: Boolean read GetIsCompact; property IsEmpty: Boolean read GetIsEmpty; property SortedState: TADSortedState read GetSortedState; { IADCollection } property Reader: IADCollectionReader read GetReader; end; /// <summary><c>Abstract Base Type for all Generic List Collection Types.</c></summary> /// <remarks> /// <para><c>Use IADListReader for Read-Only access.</c></para> /// <para><c>Use IADList for Read/Write access.</c></para> /// <para><c>Use IADIterableList for Iterators.</c></para> /// <para><c>Call .Iterator against IADListReader to return the IADIterableList interface reference.</c></para> /// </remarks> TADListBase<T> = class abstract(TADCollection, IADListReader<T>, IADList<T>, IADIterableList<T>) private // Getters { IADListReader<T> } function GetIterator: IADIterableList<T>; { IADList<T> } function GetReader: IADListReader<T>; { IADIterableList<T> } protected FArray: IADArray<T>; FSorter: IADListSorter<T>; // Getters { TADCollection Overrides } function GetCapacity: Integer; override; function GetIsCompact: Boolean; override; { IADListReader<T> } function GetItem(const AIndex: Integer): T; virtual; // Setters { TADCollection Overrides } procedure SetCapacity(const ACapacity: Integer); override; { IADListReader<T> } { IADList<T> } procedure SetItem(const AIndex: Integer; const AItem: T); virtual; abstract; // Each List Type performs a specific process, so we Override this for each List Type { IADIterableList<T> } // Overrides { TADCollection Overrides } procedure CreateArray(const AInitialCapacity: Integer = 0); override; // Overrideables function AddActual(const AItem: T): Integer; virtual; abstract; // Each List Type performs a specific process, so we Override this for each List Type procedure DeleteActual(const AIndex: Integer); virtual; abstract; // Each List Type performs a specific process, so we Override this for each List Type procedure InsertActual(const AItem: T; const AIndex: Integer); virtual; abstract; // Each List Type performs a specific process, so we Override this for each List Type constructor Create(const AInitialCapacity: Integer); override; public // Management Methods { TADCollection Overrides } procedure Clear; override; { IADListReader<T> } { IADList<T> } function Add(const AItem: T): Integer; overload; virtual; procedure Add(const AItems: IADListReader<T>); overload; virtual; procedure AddItems(const AItems: Array of T); virtual; procedure Delete(const AIndex: Integer); virtual; procedure DeleteRange(const AFirst, ACount: Integer); virtual; procedure Insert(const AItem: T; const AIndex: Integer); procedure InsertItems(const AItems: Array of T; const AIndex: Integer); procedure Sort(const AComparer: IADComparer<T>); overload; virtual; procedure Sort(const ASorter: IADListSorter<T>; const AComparer: IADComparer<T>); overload; virtual; procedure SortRange(const AComparer: IADComparer<T>; const AFromIndex: Integer; const AToIndex: Integer); overload; virtual; procedure SortRange(const ASorter: IADListSorter<T>; const AComparer: IADComparer<T>; const AFromIndex: Integer; const AToIndex: Integer); overload; virtual; { IADIterableList<T> } {$IFDEF SUPPORTS_REFERENCETOMETHOD} procedure Iterate(const ACallback: TADListItemCallbackAnon<T>; const ADirection: TADIterateDirection = idRight); overload; {$ENDIF SUPPORTS_REFERENCETOMETHOD} procedure Iterate(const ACallback: TADListItemCallbackOfObject<T>; const ADirection: TADIterateDirection = idRight); overload; procedure Iterate(const ACallback: TADListItemCallbackUnbound<T>; const ADirection: TADIterateDirection = idRight); overload; {$IFDEF SUPPORTS_REFERENCETOMETHOD} procedure IterateBackward(const ACallback: TADListItemCallbackAnon<T>); overload; {$ENDIF SUPPORTS_REFERENCETOMETHOD} procedure IterateBackward(const ACallback: TADListItemCallbackOfObject<T>); overload; procedure IterateBackward(const ACallback: TADListItemCallbackUnbound<T>); overload; {$IFDEF SUPPORTS_REFERENCETOMETHOD} procedure IterateForward(const ACallback: TADListItemCallbackAnon<T>); overload; {$ENDIF SUPPORTS_REFERENCETOMETHOD} procedure IterateForward(const ACallback: TADListItemCallbackOfObject<T>); overload; procedure IterateForward(const ACallback: TADListItemCallbackUnbound<T>); overload; // Properties { IADListReader<T> } property Items[const AIndex: Integer]: T read GetItem; default; property Iterator: IADIterableList<T> read GetIterator; { IADList<T> } property Items[const AIndex: Integer]: T read GetItem write SetItem; default; property Reader: IADListReader<T> read GetReader; end; /// <summary><c>Abstract Base Type for all Expandable/Compactable Generic List Collection Types.</c></summary> /// <remarks> /// <para><c>Use IADListReader for Read-Only access.</c></para> /// <para><c>Use IADList for Read/Write access.</c></para> /// <para><c>Use IADIterableList for Iterators.</c></para> /// <para><c>Call .Iterator against IADListReader to return the IADIterableList interface reference.</c></para> /// <para><c>Use IADCompactable to Get/Set Compactor.</c></para> /// <para><c>Use IADExpandable to Get/Set Expander.</c></para> /// </remarks> TADListExpandableBase<T> = class abstract(TADListBase<T>, IADCompactable, IADExpandable) protected FCompactor: IADCompactor; FExpander: IADExpander; // Getters { IADCompactable } function GetCompactor: IADCompactor; virtual; { IADExpandable } function GetExpander: IADExpander; virtual; // Setters { IADCompactable } procedure SetCompactor(const ACompactor: IADCompactor); virtual; { IADExpandable } procedure SetExpander(const AExpander: IADExpander); virtual; { Overridables } /// <summary><c>Compacts the Array according to the given Compactor Algorithm.</c></summary> procedure CheckCompact(const AAmount: Integer); virtual; /// <summary><c>Expands the Array according to the given Expander Algorithm.</c></summary> procedure CheckExpand(const AAmount: Integer); virtual; public // Management Methods { IADCompactable } procedure Compact; { IADExpandable } // Properties { IADCompactable } property Compactor: IADCompactor read GetCompactor write SetCompactor; { IADExpandable } property Expander: IADExpander read GetExpander write SetExpander; end; /// <summary><c>Abstract Base Type for all Generic Map Collection Types.</c></summary> /// <remarks> /// <para><c>Use IADMapReader for Read-Only access.</c></para> /// <para><c>Use IADMap for Read/Write access.</c></para> /// <para><c>Use IADIterableMap for Iterators.</c></para> /// <para><c>Call .Iterator against IADMapReader to return the IADIterableMap interface reference.</c></para> /// </remarks> TADMapBase<TKey, TValue> = class abstract(TADCollection, IADMapReader<TKey, TValue>, IADMap<TKey, TValue>, IADIterableMap<TKey, TValue>, IADComparable<TKey>) protected FArray: IADArray<IADKeyValuePair<TKey, TValue>>; FComparer: IADComparer<TKey>; FSorter: IADMapSorter<TKey, TValue>; // Getters { IADMapReader<TKey, TValue> } function GetItem(const AKey: TKey): TValue; function GetIterator: IADIterableMap<TKey, TValue>; function GetPair(const AIndex: Integer): IADKeyValuePair<TKey, TValue>; function GetSorter: IADMapSorter<TKey, TValue>; virtual; { IADMap<TKey, TValue> } function GetReader: IADMapReader<TKey, TValue>; { IADIterableMap<TKey, TValue> } { IADComparable<T> } function GetComparer: IADComparer<TKey>; virtual; { IADComparable<T> } procedure SetComparer(const AComparer: IADComparer<TKey>); virtual; // Setters { IADMapReader<TKey, TValue> } { IADMap<TKey, TValue> } procedure SetItem(const AKey: TKey; const AValue: TValue); procedure SetSorter(const ASorter: IADMapSorter<TKey, TValue>); virtual; { IADIterableMap<TKey, TValue> } // Overrides { TADCollection Overrides } function GetCapacity: Integer; override; function GetIsCompact: Boolean; override; procedure CreateArray(const AInitialCapacity: Integer = 0); override; procedure SetCapacity(const ACapacity: Integer); override; // Management Methods /// <summary><c>Adds the Item to the correct Index of the Array WITHOUT checking capacity.</c></summary> /// <returns> /// <para>-1<c> if the Item CANNOT be added.</c></para> /// <para>0 OR GREATER<c> if the Item has be added, where the Value represents the Index of the Item.</c></para> /// </returns> function AddActual(const AItem: IADKeyValuePair<TKey, TValue>): Integer; virtual; /// <summary><c>Determines the Index at which an Item would need to be Inserted for the List to remain in-order.</c></summary> /// <remarks> /// <para><c>This is basically a Binary Sort implementation.<c></para> /// </remarks> function GetSortedPosition(const AKey: TKey): Integer; virtual; /// <summary><c>Defines the default Sorter Type to use for managing the Map.</c></summary> procedure CreateSorter; virtual; abstract; constructor Create(const AInitialCapacity: Integer); override; public // Management Methods { IADMapReader<TKey, TValue> } function Contains(const AKey: TKey): Boolean; function ContainsAll(const AKeys: Array of TKey): Boolean; function ContainsAny(const AKeys: Array of TKey): Boolean; function ContainsNone(const AKeys: Array of TKey): Boolean; function EqualItems(const AMap: IADMapReader<TKey, TValue>): Boolean; function IndexOf(const AKey: TKey): Integer; { IADMap<TKey, TValue> } function Add(const AItem: IADKeyValuePair<TKey, TValue>): Integer; overload; virtual; function Add(const AKey: TKey; const AValue: TValue): Integer; overload; virtual; procedure AddItems(const AItems: Array of IADKeyValuePair<TKey, TValue>); overload; virtual; procedure AddItems(const AMap: IADMapReader<TKey, TValue>); overload; virtual; procedure Compact; procedure Delete(const AIndex: Integer); overload; virtual; procedure DeleteRange(const AFromIndex, ACount: Integer); overload; virtual; procedure Remove(const AKey: TKey); virtual; procedure RemoveItems(const AKeys: Array of TKey); virtual; { TADCollection Overrides } procedure Clear; override; { IADIterableMap<TKey, TValue> } {$IFDEF SUPPORTS_REFERENCETOMETHOD} procedure Iterate(const ACallback: TADListMapCallbackAnon<TKey, TValue>; const ADirection: TADIterateDirection = idRight); overload; {$ENDIF SUPPORTS_REFERENCETOMETHOD} procedure Iterate(const ACallback: TADListMapCallbackOfObject<TKey, TValue>; const ADirection: TADIterateDirection = idRight); overload; procedure Iterate(const ACallback: TADListMapCallbackUnbound<TKey, TValue>; const ADirection: TADIterateDirection = idRight); overload; {$IFDEF SUPPORTS_REFERENCETOMETHOD} procedure IterateBackward(const ACallback: TADListMapCallbackAnon<TKey, TValue>); overload; {$ENDIF SUPPORTS_REFERENCETOMETHOD} procedure IterateBackward(const ACallback: TADListMapCallbackOfObject<TKey, TValue>); overload; procedure IterateBackward(const ACallback: TADListMapCallbackUnbound<TKey, TValue>); overload; {$IFDEF SUPPORTS_REFERENCETOMETHOD} procedure IterateForward(const ACallback: TADListMapCallbackAnon<TKey, TValue>); overload; {$ENDIF SUPPORTS_REFERENCETOMETHOD} procedure IterateForward(const ACallback: TADListMapCallbackOfObject<TKey, TValue>); overload; procedure IterateForward(const ACallback: TADListMapCallbackUnbound<TKey, TValue>); overload; // Properties { IADMapReader<TKey, TValue> } property Items[const AKey: TKey]: TValue read GetItem; default; property Iterator: IADIterableMap<TKey, TValue> read GetIterator; property Pairs[const AIndex: Integer]: IADKeyValuePair<TKey, TValue> read GetPair; { IADMap<TKey, TValue> } property Items[const AKey: TKey]: TValue read GetItem write SetItem; default; property Reader: IADMapReader<TKey, TValue> read GetReader; { IADIterableMap<TKey, TValue> } { IADComparable<T> } property Comparer: IADComparer<TKey> read GetComparer write SetComparer; end; /// <summary><c>Abstract Base Type for all Expandable Generic Map Collection Types.</c></summary> /// <remarks> /// <para><c>Use IADMapReader for Read-Only access.</c></para> /// <para><c>Use IADMap for Read/Write access.</c></para> /// <para><c>Use IADIterableMap for Iterators.</c></para> /// <para><c>Call .Iterator against IADMapReader to return the IADIterableMap interface reference.</c></para> /// <para><c>Use IADCompactable to Get/Set the Compactor.</c></para> /// <para><c>Use IADExpandable to Get/Set the Expander.</c></para> /// </remarks> TADMapExpandableBase<TKey, TValue> = class abstract(TADMapBase<TKey, TValue>, IADCompactable, IADExpandable) protected FCompactor: IADCompactor; FExpander: IADExpander; // Getters { IADCompactable } function GetCompactor: IADCompactor; virtual; { IADExpandable } function GetExpander: IADExpander; virtual; // Setters { IADCompactable } procedure SetCompactor(const ACompactor: IADCompactor); virtual; { IADExpandable } procedure SetExpander(const AExpander: IADExpander); virtual; // Overridables /// <summary><c>Compacts the Array according to the given Compactor Algorithm.</c></summary> procedure CheckCompact(const AAmount: Integer); virtual; /// <summary><c>Expands the Array according to the given Expander Algorithm.</c></summary> procedure CheckExpand(const AAmount: Integer); virtual; public { IADMap<TKey, TValue> } function Add(const AItem: IADKeyValuePair<TKey, TValue>): Integer; overload; override; function Add(const AKey: TKey; const AValue: TValue): Integer; overload; override; procedure AddItems(const AItems: Array of IADKeyValuePair<TKey, TValue>); overload; override; procedure AddItems(const AMap: IADMapReader<TKey, TValue>); overload; override; procedure Delete(const AIndex: Integer); overload; override; procedure DeleteRange(const AFromIndex, ACount: Integer); overload; override; procedure Remove(const AKey: TKey); override; procedure RemoveItems(const AKeys: Array of TKey); override; // Properties { IADCompactable } property Compactor: IADCompactor read GetCompactor write SetCompactor; { IADExpandable } property Expander: IADExpander read GetExpander write SetExpander; end; /// <summary><c>Abstract Base Class for all List Sorters.</c></summary> TADListSorter<T> = class abstract(TADObject, IADListSorter<T>) public procedure Sort(const AArray: IADArray<T>; const AComparer: IADComparer<T>; AFrom, ATo: Integer); overload; virtual; abstract; procedure Sort(AArray: Array of T; const AComparer: IADComparer<T>; AFrom, ATo: Integer); overload; virtual; abstract; end; /// <summary><c>Abstract Base Class for all Map Sorters.</c></summary> TADMapSorter<TKey, TValue> = class abstract(TADObject, IADMapSorter<TKey, TValue>) public procedure Sort(const AArray: IADArray<IADKeyValuePair<TKey,TValue>>; const AComparer: IADComparer<TKey>; AFrom, ATo: Integer); overload; virtual; abstract; procedure Sort(AArray: Array of IADKeyValuePair<TKey,TValue>; const AComparer: IADComparer<TKey>; AFrom, ATo: Integer); overload; virtual; abstract; end; implementation uses ADAPT.Collections; // This is needed for TADListSorterQuick as the Default Sorter. { TADCollection } constructor TADCollection.Create(const AInitialCapacity: Integer); begin inherited Create; FSortedState := ssUnknown; FCount := 0; FInitialCapacity := AInitialCapacity; CreateArray(AInitialCapacity); end; function TADCollection.GetCount: Integer; begin Result := FCount; end; function TADCollection.GetInitialCapacity: Integer; begin Result := FInitialCapacity; end; function TADCollection.GetIsEmpty: Boolean; begin Result := (FCount = 0); end; function TADCollection.GetReader: IADCollectionReader; begin Result := IADCollectionReader(Self); end; function TADCollection.GetSortedState: TADSortedState; begin Result := FSortedState; end; { TADListBase<T> } function TADListBase<T>.Add(const AItem: T): Integer; begin Result := AddActual(AItem); end; procedure TADListBase<T>.Add(const AItems: IADListReader<T>); var I: Integer; begin for I := 0 to AItems.Count - 1 do AddActual(AItems[I]); end; procedure TADListBase<T>.AddItems(const AItems: array of T); var I: Integer; begin for I := Low(AItems) to High(AItems) do AddActual(AItems[I]); end; procedure TADListBase<T>.Clear; begin FArray.Clear; FCount := 0; end; constructor TADListBase<T>.Create(const AInitialCapacity: Integer); begin inherited Create(AInitialCapacity); FSorter := TADListSorterQuick<T>.Create; // Use the Quick Sorter by default. end; procedure TADListBase<T>.CreateArray(const AInitialCapacity: Integer); begin FArray := TADArray<T>.Create(AInitialCapacity); end; procedure TADListBase<T>.Delete(const AIndex: Integer); begin DeleteActual(AIndex); end; procedure TADListBase<T>.DeleteRange(const AFirst, ACount: Integer); var I: Integer; begin for I := AFirst + (ACount - 1) downto AFirst do DeleteActual(I); end; function TADListBase<T>.GetCapacity: Integer; begin Result := FArray.Capacity; end; function TADListBase<T>.GetIsCompact: Boolean; begin Result := (FArray.Capacity = FCount); end; function TADListBase<T>.GetItem(const AIndex: Integer): T; begin Result := FArray[AIndex]; end; function TADListBase<T>.GetIterator: IADIterableList<T>; begin Result := IADIterableList<T>(Self); end; function TADListBase<T>.GetReader: IADListReader<T>; begin Result := IADListReader<T>(Self); end; {$IFDEF SUPPORTS_REFERENCETOMETHOD} procedure TADListBase<T>.Iterate(const ACallback: TADListItemCallbackAnon<T>; const ADirection: TADIterateDirection = idRight); begin case ADirection of idLeft: IterateBackward(ACallback); idRight: IterateForward(ACallback); else raise EADGenericsIterateDirectionUnknownException.Create('Unhandled Iterate Direction given.'); end; end; {$ENDIF SUPPORTS_REFERENCETOMETHOD} procedure TADListBase<T>.Iterate(const ACallback: TADListItemCallbackOfObject<T>; const ADirection: TADIterateDirection); begin case ADirection of idLeft: IterateBackward(ACallback); idRight: IterateForward(ACallback); else raise EADGenericsIterateDirectionUnknownException.Create('Unhandled Iterate Direction given.'); end; end; procedure TADListBase<T>.Insert(const AItem: T; const AIndex: Integer); begin InsertActual(AItem, AIndex); end; procedure TADListBase<T>.InsertItems(const AItems: array of T; const AIndex: Integer); var I: Integer; begin for I := High(AItems) downto Low(AItems) do Insert(AItems[I], AIndex); end; procedure TADListBase<T>.Iterate(const ACallback: TADListItemCallbackUnbound<T>; const ADirection: TADIterateDirection); begin case ADirection of idLeft: IterateBackward(ACallback); idRight: IterateForward(ACallback); else raise EADGenericsIterateDirectionUnknownException.Create('Unhandled Iterate Direction given.'); end; end; {$IFDEF SUPPORTS_REFERENCETOMETHOD} procedure TADListBase<T>.IterateBackward(const ACallback: TADListItemCallbackAnon<T>); var I: Integer; begin for I := FCount - 1 downto 0 do ACallback(FArray[I]); end; {$ENDIF SUPPORTS_REFERENCETOMETHOD} procedure TADListBase<T>.IterateBackward(const ACallback: TADListItemCallbackOfObject<T>); var I: Integer; begin for I := FCount - 1 downto 0 do ACallback(FArray[I]); end; procedure TADListBase<T>.IterateBackward(const ACallback: TADListItemCallbackUnbound<T>); var I: Integer; begin for I := FCount - 1 downto 0 do ACallback(FArray[I]); end; {$IFDEF SUPPORTS_REFERENCETOMETHOD} procedure TADListBase<T>.IterateForward(const ACallback: TADListItemCallbackAnon<T>); var I: Integer; begin for I := 0 to FCount - 1 do ACallback(FArray[I]); end; {$ENDIF SUPPORTS_REFERENCETOMETHOD} procedure TADListBase<T>.IterateForward(const ACallback: TADListItemCallbackOfObject<T>); var I: Integer; begin for I := 0 to FCount - 1 do ACallback(FArray[I]); end; procedure TADListBase<T>.IterateForward(const ACallback: TADListItemCallbackUnbound<T>); var I: Integer; begin for I := 0 to FCount - 1 do ACallback(FArray[I]); end; procedure TADListBase<T>.SetCapacity(const ACapacity: Integer); begin if ACapacity < FCount then raise EADGenericsCapacityLessThanCount.CreateFmt('Given Capacity of %d insufficient for a Collection containing %d Items.', [ACapacity, FCount]) else FArray.Capacity := ACapacity; end; procedure TADListBase<T>.Sort(const ASorter: IADListSorter<T>; const AComparer: IADComparer<T>); begin SortRange(ASorter, AComparer, 0, FCount - 1); end; procedure TADListBase<T>.SortRange(const AComparer: IADComparer<T>; const AFromIndex, AToIndex: Integer); begin SortRange(FSorter, AComparer, AFromIndex, AToIndex); end; procedure TADListBase<T>.Sort(const AComparer: IADComparer<T>); begin SortRange(FSorter, AComparer, 0, FCount - 1); end; procedure TADListBase<T>.SortRange(const ASorter: IADListSorter<T>; const AComparer: IADComparer<T>; const AFromIndex, AToIndex: Integer); begin ASorter.Sort(FArray, AComparer, AFromIndex, AToIndex); end; { TADListExpandableBase<T> } procedure TADListExpandableBase<T>.CheckCompact(const AAmount: Integer); var LShrinkBy: Integer; begin LShrinkBy := Compactor.CheckCompact(FArray.Capacity, FCount, AAmount); if LShrinkBy > 0 then FArray.Capacity := FArray.Capacity - LShrinkBy; end; procedure TADListExpandableBase<T>.CheckExpand(const AAmount: Integer); var LNewCapacity: Integer; begin LNewCapacity := Expander.CheckExpand(FArray.Capacity, FCount, AAmount); if LNewCapacity > 0 then FArray.Capacity := FArray.Capacity + LNewCapacity; end; procedure TADListExpandableBase<T>.Compact; begin FArray.Capacity := FCount; end; function TADListExpandableBase<T>.GetCompactor: IADCompactor; begin Result := FCompactor; end; function TADListExpandableBase<T>.GetExpander: IADExpander; begin Result := FExpander; end; procedure TADListExpandableBase<T>.SetCompactor(const ACompactor: IADCompactor); begin FCompactor := ACompactor; end; procedure TADListExpandableBase<T>.SetExpander(const AExpander: IADExpander); begin FExpander := AExpander; end; { TADMapBase<TKey, TValue> } function TADMapBase<TKey, TValue>.Add(const AKey: TKey; const AValue: TValue): Integer; var LPair: IADKeyValuePair<TKey, TValue>; begin LPair := TADKeyValuePair<TKey, TValue>.Create(AKey, AValue); Result := Add(LPair); end; function TADMapBase<TKey, TValue>.AddActual(const AItem: IADKeyValuePair<TKey, TValue>): Integer; begin Result := GetSortedPosition(AItem.Key); if Result = FCount then FArray[FCount] := AItem else FArray.Insert(AItem, Result); Inc(FCount); end; function TADMapBase<TKey, TValue>.Add(const AItem: IADKeyValuePair<TKey, TValue>): Integer; begin Result := AddActual(AItem); end; procedure TADMapBase<TKey, TValue>.AddItems(const AItems: array of IADKeyValuePair<TKey, TValue>); var I: Integer; begin for I := Low(AItems) to High(AItems) do AddActual(AItems[I]); end; procedure TADMapBase<TKey, TValue>.AddItems(const AMap: IADMapReader<TKey, TValue>); var I: Integer; begin for I := 0 to AMap.Count - 1 do AddActual(AMap.Pairs[I]); end; procedure TADMapBase<TKey, TValue>.Clear; begin FArray.Clear; FArray.Capacity := FInitialCapacity; FCount := 0; end; procedure TADMapBase<TKey, TValue>.Compact; begin FArray.Capacity := FCount; end; function TADMapBase<TKey, TValue>.Contains(const AKey: TKey): Boolean; begin Result := (IndexOf(AKey) > -1); end; function TADMapBase<TKey, TValue>.ContainsAll(const AKeys: array of TKey): Boolean; var I: Integer; begin Result := True; // Optimistic for I := Low(AKeys) to High(AKeys) do if (not Contains(AKeys[I])) then begin Result := False; Break; end; end; function TADMapBase<TKey, TValue>.ContainsAny(const AKeys: array of TKey): Boolean; var I: Integer; begin Result := False; // Pessimistic for I := Low(AKeys) to High(AKeys) do if Contains(AKeys[I]) then begin Result := True; Break; end; end; function TADMapBase<TKey, TValue>.ContainsNone(const AKeys: array of TKey): Boolean; begin Result := (not ContainsAny(AKeys)); end; constructor TADMapBase<TKey, TValue>.Create(const AInitialCapacity: Integer); begin inherited; CreateSorter; end; procedure TADMapBase<TKey, TValue>.CreateArray(const AInitialCapacity: Integer); begin FArray := TADArray<IADKeyValuePair<TKey, TValue>>.Create(AInitialCapacity); end; procedure TADMapBase<TKey, TValue>.Delete(const AIndex: Integer); begin FArray.Delete(AIndex); Dec(FCount); end; procedure TADMapBase<TKey, TValue>.DeleteRange(const AFromIndex, ACount: Integer); var I: Integer; begin for I := AFromIndex + ACount - 1 downto AFromIndex do Delete(I); end; function TADMapBase<TKey, TValue>.EqualItems(const AMap: IADMapReader<TKey, TValue>): Boolean; var I: Integer; begin Result := AMap.Count = FCount; if Result then for I := 0 to AMap.Count - 1 do if (not FComparer.AEqualToB(AMap.Pairs[I].Key, FArray[I].Key)) then begin Result := False; Break; end; end; function TADMapBase<TKey, TValue>.GetCapacity: Integer; begin Result := FArray.Capacity; end; function TADMapBase<TKey, TValue>.GetComparer: IADComparer<TKey>; begin Result := FComparer; end; function TADMapBase<TKey, TValue>.GetIsCompact: Boolean; begin Result := (FArray.Capacity = FCount); end; function TADMapBase<TKey, TValue>.GetItem(const AKey: TKey): TValue; var LIndex: Integer; begin LIndex := IndexOf(AKey); if LIndex > -1 then Result := FArray[LIndex].Value; end; function TADMapBase<TKey, TValue>.GetIterator: IADIterableMap<TKey, TValue>; begin Result := IADIterableMap<TKey, TValue>(Self); end; function TADMapBase<TKey, TValue>.GetPair(const AIndex: Integer): IADKeyValuePair<TKey, TValue>; begin Result := FArray[AIndex]; end; function TADMapBase<TKey, TValue>.GetReader: IADMapReader<TKey, TValue>; begin Result := IADMapReader<TKey, TValue>(Self); end; function TADMapBase<TKey, TValue>.GetSortedPosition(const AKey: TKey): Integer; var LIndex, LLow, LHigh: Integer; begin Result := 0; LLow := 0; LHigh := FCount - 1; if LHigh = -1 then Exit; if LLow < LHigh then begin while (LHigh - LLow > 1) do begin LIndex := (LHigh + LLow) div 2; if FComparer.ALessThanOrEqualToB(AKey, FArray[LIndex].Key) then LHigh := LIndex else LLow := LIndex; end; end; if FComparer.ALessThanB(FArray[LHigh].Key, AKey) then Result := LHigh + 1 else if FComparer.ALessThanB(FArray[LLow].Key, AKey) then Result := LLow + 1 else Result := LLow; end; function TADMapBase<TKey, TValue>.GetSorter: IADMapSorter<TKey, TValue>; begin Result := FSorter; end; function TADMapBase<TKey, TValue>.IndexOf(const AKey: TKey): Integer; var LLow, LHigh, LMid: Integer; begin Result := -1; // Pessimistic if (FCount = 0) then Exit; LLow := 0; LHigh := FCount - 1; repeat LMid := (LLow + LHigh) div 2; if FComparer.AEqualToB(FArray[LMid].Key, AKey) then begin Result := LMid; Break; end else if FComparer.ALessThanB(AKey, FArray[LMid].Key) then LHigh := LMid - 1 else LLow := LMid + 1; until LHigh < LLow; end; {$IFDEF SUPPORTS_REFERENCETOMETHOD} procedure TADMapBase<TKey, TValue>.Iterate(const ACallback: TADListMapCallbackAnon<TKey, TValue>; const ADirection: TADIterateDirection = idRight); begin case ADirection of idLeft: IterateBackward(ACallback); idRight: IterateForward(ACallback); else raise EADGenericsIterateDirectionUnknownException.Create('Unhandled Iterate Direction given.'); end; end; {$ENDIF SUPPORTS_REFERENCETOMETHOD} procedure TADMapBase<TKey, TValue>.Iterate(const ACallback: TADListMapCallbackUnbound<TKey, TValue>; const ADirection: TADIterateDirection); begin case ADirection of idLeft: IterateBackward(ACallback); idRight: IterateForward(ACallback); else raise EADGenericsIterateDirectionUnknownException.Create('Unhandled Iterate Direction given.'); end; end; procedure TADMapBase<TKey, TValue>.Iterate(const ACallback: TADListMapCallbackOfObject<TKey, TValue>; const ADirection: TADIterateDirection); begin case ADirection of idLeft: IterateBackward(ACallback); idRight: IterateForward(ACallback); else raise EADGenericsIterateDirectionUnknownException.Create('Unhandled Iterate Direction given.'); end; end; {$IFDEF SUPPORTS_REFERENCETOMETHOD} procedure TADMapBase<TKey, TValue>.IterateBackward(const ACallback: TADListMapCallbackAnon<TKey, TValue>); var I: Integer; begin for I := FCount - 1 downto 0 do ACallback(FArray[I].Key, FArray[I].Value); end; {$ENDIF SUPPORTS_REFERENCETOMETHOD} procedure TADMapBase<TKey, TValue>.IterateBackward(const ACallback: TADListMapCallbackUnbound<TKey, TValue>); var I: Integer; begin for I := FCount - 1 downto 0 do ACallback(FArray[I].Key, FArray[I].Value); end; procedure TADMapBase<TKey, TValue>.IterateBackward(const ACallback: TADListMapCallbackOfObject<TKey, TValue>); var I: Integer; begin for I := FCount - 1 downto 0 do ACallback(FArray[I].Key, FArray[I].Value); end; {$IFDEF SUPPORTS_REFERENCETOMETHOD} procedure TADMapBase<TKey, TValue>.IterateForward(const ACallback: TADListMapCallbackAnon<TKey, TValue>); var I: Integer; begin for I := 0 to FCount - 1 do ACallback(FArray[I].Key, FArray[I].Value); end; {$ENDIF SUPPORTS_REFERENCETOMETHOD} procedure TADMapBase<TKey, TValue>.IterateForward(const ACallback: TADListMapCallbackUnbound<TKey, TValue>); var I: Integer; begin for I := 0 to FCount - 1 do ACallback(FArray[I].Key, FArray[I].Value); end; procedure TADMapBase<TKey, TValue>.IterateForward(const ACallback: TADListMapCallbackOfObject<TKey, TValue>); var I: Integer; begin for I := 0 to FCount - 1 do ACallback(FArray[I].Key, FArray[I].Value); end; procedure TADMapBase<TKey, TValue>.Remove(const AKey: TKey); var LIndex: Integer; begin LIndex := IndexOf(AKey); if LIndex > -1 then Delete(LIndex); end; procedure TADMapBase<TKey, TValue>.RemoveItems(const AKeys: array of TKey); var I: Integer; begin for I := Low(AKeys) to High(AKeys) do Remove(AKeys[I]); end; procedure TADMapBase<TKey, TValue>.SetCapacity(const ACapacity: Integer); begin FArray.Capacity := ACapacity; end; procedure TADMapBase<TKey, TValue>.SetComparer(const AComparer: IADComparer<TKey>); begin FComparer := AComparer; end; procedure TADMapBase<TKey, TValue>.SetItem(const AKey: TKey; const AValue: TValue); var LIndex: Integer; begin LIndex := IndexOf(AKey); if LIndex > -1 then FArray[LIndex].Value := AValue; end; procedure TADMapBase<TKey, TValue>.SetSorter(const ASorter: IADMapSorter<TKey, TValue>); begin FSorter := ASorter; end; { TADMapExpandableBase<TKey, TValue> } function TADMapExpandableBase<TKey, TValue>.Add(const AItem: IADKeyValuePair<TKey, TValue>): Integer; begin CheckExpand(1); inherited; end; function TADMapExpandableBase<TKey, TValue>.Add(const AKey: TKey; const AValue: TValue): Integer; begin CheckExpand(1); inherited; end; procedure TADMapExpandableBase<TKey, TValue>.AddItems(const AItems: array of IADKeyValuePair<TKey, TValue>); begin CheckExpand(Length(AItems)); inherited; end; procedure TADMapExpandableBase<TKey, TValue>.AddItems(const AMap: IADMapReader<TKey, TValue>); begin CheckExpand(AMap.Count); inherited; end; procedure TADMapExpandableBase<TKey, TValue>.CheckCompact(const AAmount: Integer); var LShrinkBy: Integer; begin LShrinkBy := FCompactor.CheckCompact(FArray.Capacity, FCount, AAmount); if LShrinkBy > 0 then FArray.Capacity := FArray.Capacity - LShrinkBy; end; procedure TADMapExpandableBase<TKey, TValue>.CheckExpand(const AAmount: Integer); var LNewCapacity: Integer; begin LNewCapacity := FExpander.CheckExpand(FArray.Capacity, FCount, AAmount); if LNewCapacity > 0 then FArray.Capacity := FArray.Capacity + LNewCapacity; end; procedure TADMapExpandableBase<TKey, TValue>.Delete(const AIndex: Integer); begin inherited; CheckCompact(1); end; procedure TADMapExpandableBase<TKey, TValue>.DeleteRange(const AFromIndex, ACount: Integer); begin inherited; CheckCompact(ACount); end; function TADMapExpandableBase<TKey, TValue>.GetCompactor: IADCompactor; begin Result := FCompactor; end; function TADMapExpandableBase<TKey, TValue>.GetExpander: IADExpander; begin Result := FExpander; end; procedure TADMapExpandableBase<TKey, TValue>.Remove(const AKey: TKey); begin inherited; CheckCompact(1); end; procedure TADMapExpandableBase<TKey, TValue>.RemoveItems(const AKeys: array of TKey); begin inherited; CheckCompact(Length(AKeys)); end; procedure TADMapExpandableBase<TKey, TValue>.SetCompactor(const ACompactor: IADCompactor); begin FCompactor := ACompactor; end; procedure TADMapExpandableBase<TKey, TValue>.SetExpander(const AExpander: IADExpander); begin FExpander := AExpander; end; end.
unit MeasureUnit.DataSize; interface uses SysUtils, Math; type TNumeralSystem = (Denary, Binary); TDatasizeUnit = record FPowerOfKUnit: Integer; FUnitName: String; end; TDatasizeUnitChangeSetting = record FNumeralSystem: TNumeralSystem; FFromUnit: TDatasizeUnit; FToUnit: TDatasizeUnit; end; TNumeralSystemChangeSetting = record FFromNumeralSystem: TNumeralSystem; FToNumeralSystem: TNumeralSystem; end; TFormatSizeSetting = record FNumeralSystem: TNumeralSystem; FPrecision: Integer; end; const PetaUnit: TDatasizeUnit = (FPowerOfKUnit: 4; FUnitName: 'PB'); TeraUnit: TDatasizeUnit = (FPowerOfKUnit: 3; FUnitName: 'TB'); GigaUnit: TDatasizeUnit = (FPowerOfKUnit: 2; FUnitName: 'GB'); MegaUnit: TDatasizeUnit = (FPowerOfKUnit: 1; FUnitName: 'MB'); KiloUnit: TDatasizeUnit = (FPowerOfKUnit: 0; FUnitName: 'KB'); ByteUnit: TDatasizeUnit = (FPowerOfKUnit: -1; FUnitName: 'B'); function GetDivideUnitSize(DivideUnitType: TNumeralSystem): Integer; function ChangeDatasizeUnit (Size: Double; Setting: TDatasizeUnitChangeSetting): Double; function LiteONUnitToMB(Size: UInt64): UInt64; function MBToLiteONUnit(Size: UInt64): UInt64; function FormatSizeInMB(SizeInMB: Double; Setting: TFormatSizeSetting): String; implementation function GetDivideUnitSize(DivideUnitType: TNumeralSystem): Integer; const DenaryKilo = 1000; BinaryKibi = 1024; begin case DivideUnitType of Denary: exit(DenaryKilo); Binary: exit(BinaryKibi); end; exit(1); end; function ChangeDatasizeUnit (Size: Double; Setting: TDatasizeUnitChangeSetting): Double; begin result := Size * Power(GetDivideUnitSize(Setting.FNumeralSystem), Setting.FFromUnit.FPowerOfKUnit - Setting.FToUnit.FPowerOfKUnit); end; function LiteONUnitToMB(Size: UInt64): UInt64; const LiteONUnitInMB = 64; begin result := Size * LiteONUnitInMB; end; function MBToLiteONUnit(Size: UInt64): UInt64; const LiteONUnitInMB = 64; begin result := Size div LiteONUnitInMB; end; function GetSizeUnitString (SizeInMB: Double; UnitToTest: TDatasizeUnit; Setting: TFormatSizeSetting): String; const Threshold = 0.75; var DivideUnitSize: Integer; UnitSizeInMB: Int64; begin result := ''; DivideUnitSize := GetDivideUnitSize(Setting.FNumeralSystem); UnitSizeInMB := Floor(Power(DivideUnitSize, UnitToTest.FPowerOfKUnit - 1)); if SizeInMB > (UnitSizeInMB * Threshold) then begin result := Format('%.' + IntToStr(Setting.FPrecision) + 'f' + UnitToTest.FUnitName, [SizeInMB / UnitSizeInMB]); end; end; function FormatSizeInMB(SizeInMB: Double; Setting: TFormatSizeSetting): String; begin result := GetSizeUnitString(SizeInMB, PetaUnit, Setting); if result <> '' then exit; result := GetSizeUnitString(SizeInMB, TeraUnit, Setting); if result <> '' then exit; result := GetSizeUnitString(SizeInMB, GigaUnit, Setting); if result <> '' then exit; result := GetSizeUnitString(SizeInMB, MegaUnit, Setting); if result = '' then result := '0MB'; end; end.
unit Teste.Build.JSONData; interface uses System.SysUtils, System.JSON; type TJSONBuildMock = class class function CarregarArquivo(const FileName: TFileName): string; class function CarregarJSONDoArquivo<T: TJSONValue>(const FileName: TFileName): T; end; const ARQUIVO_JSON_SUCESSO = 'build.json'; ARQUIVO_JSON_FALHA = 'build-failure.json'; ARQUIVO_JSON_BUILDING = 'build-building.json'; ARQUIVO_JSON_BUILDING_NULL = 'build_buildingNull.json'; ARQUIVO_JSON_CHANGESET_VAZIO = 'build-sem-changeset-vazio.json'; ARQUIVO_JSON_CHANGESET_NULL = 'build-sem-changeset-null.json'; ARQUIVO_JSON_CHANGESET_NAOEXISTE = 'build-sem-changeset.json'; ARQUIVO_JSON_CHANGESETITEM_NULL = 'build-changeSetItemNull.json'; ARQUIVO_JSON_CHANGESETITEM_VAZIO = 'build-changeSetItem-vazio.json'; ARQUIVO_JSON_CHANGESETITEM_NAOEXISTE = 'build-changeSetItem-naoexiste.json'; ARQUIVO_BUILD = 'maquina.json'; ARQUIVO_BUILD_COMPILANDO = 'simulado\build-compilando.json'; ARQUIVO_BUILDPARADO_ULTIMOOK = 'simulado\build-parado-ultimoOK.json'; implementation uses System.Classes, System.IOUtils; class function TJSONBuildMock.CarregarArquivo( const FileName: TFileName): string; var _arquivoJson: TStringList; begin if not TFile.Exists(FileName) then raise EFileNotFoundException.CreateFmt('O arquivo %s não foi encontrado!', [FileName]); _arquivoJson := TStringList.Create; try _arquivoJson.LoadFromFile(FileName); Result := _arquivoJson.Text; finally _arquivoJson.Free; end; end; class function TJSONBuildMock.CarregarJSONDoArquivo<T>( const FileName: TFileName): T; begin Result := TJSONObject.ParseJSONValue(CarregarArquivo(FileName)) as T; end; end.
program Sample; var A,B : Char; S : String; begin S := 'Hello World'; A := #66; S[1] := A; B := S[7]; WriteLn('A = ', A); WriteLn('S = ', S); WriteLn('B = ', B); end.
program pascal(output); function palindrome(s: string): boolean; var result: boolean; middleChar: integer; lastChar: integer; i: integer; begin middleChar := length(s) / 2; lastChar := length(s) - 1; for i := 1 to middleChar if s[i] <> s[lastChar - i] then return := false; return := true; end;
(** This module contains class / interface for managing the zipping of a project to an archive. @Author David Hoyle @Version 1.0 @Date 05 Jan 2018 **) Unit ITHelper.ZIPManager; Interface {$INCLUDE 'CompilerDefinitions.inc'} Uses Classes, Contnrs, ToolsAPI, ITHelper.Interfaces; Type (** A class which implements the IITHZipManager interface for managing zip file creation. **) TITHZipManager = Class(TInterfacedObject, IITHZipManager) Strict Private FProject : IOTAProject; FGlobalOps : IITHGlobalOptions; FProjectOps : IITHProjectOptions; FMsgMgr : IITHMessageManager; Strict Protected // IITHZipManager Function ZipProjectInformation : Integer; // General Methods Procedure ProcessMsgHandler(Const strMsg: String; Var boolAbort: Boolean); Procedure IdleHandler; Public Constructor Create(Const Project: IOTAProject; Const GlobalOps : IITHGlobalOptions; Const ProjectOps : IITHProjectOptions; Const MessageManager : IITHMessageManager); Destructor Destroy; Override; End; Implementation Uses {$IFDEF CODESITE} CodeSiteLogging, {$ENDIF} SysUtils, Forms, ITHelper.Types, ITHelper.ExternalProcessInfo, ITHelper.TestingHelperUtils, ITHelper.ProcessingForm, ITHelper.CommonFunctions, ITHelper.CustomMessages, ITHelper.ResponseFile; (** A constructor for the TITHZipManager class. @precon None. @postcon Stores reference to interfaces for use later on. @param Project as an IOTAProject as a constant @param GlobalOps as an IITHGlobalOptions as a constant @param ProjectOps as an IITHProjectOptions as a constant @param MessageManager as an IITHMessageManager as a constant **) Constructor TITHZipManager.Create(Const Project: IOTAProject; Const GlobalOps : IITHGlobalOptions; Const ProjectOps : IITHProjectOptions; Const MessageManager : IITHMessageManager); Begin FProject := Project; FGlobalOps := GlobalOps; FProjectOps := ProjectOps; FMsgMgr := MessageManager; End; (** A destructor for the TITHZipManager class. @precon None. @postcon Does nothing - used to check destruction using CodeSite. **) Destructor TITHZipManager.Destroy; Begin Inherited Destroy; End; (** This method is called by the DGHCreateProcess function to ensure the IDE does not lockup and become unresponsive while background process are running. @precon None. @postcon Updates the aplciation message query. **) Procedure TITHZipManager.IdleHandler; Begin Application.ProcessMessages; End; (** This method is called by DGHCreateProcess to capture the comman line messages from the tools and output them to the message window. @precon None. @postcon A message is output to the message view. @nohint boolAbort @param strMsg as a String as a constant @param boolAbort as a Boolean as a reference **) Procedure TITHZipManager.ProcessMsgHandler(Const strMsg: String; Var boolAbort: Boolean); //FI:O804 Begin If strMsg <> '' Then FMsgMgr.AddMsg(strMsg, fnTools, ithfDefault, FMsgMgr.ParentMsg.MessagePntr); End; (** This method build a response file for a command line zip tool in order to backup all the files required to build this project. @precon ProjectOps and Project must be valid instances. @postcon Build a response file for a command line zip tool in order to backup all the files required to build this project. @return an Integer **) Function TITHZipManager.ZipProjectInformation: Integer; ResourceString strZIPToolNotFound = 'ZIP Tool (%s) not found! (%s).'; strRunning = 'Running: %s (%s %s)'; strZipping = 'Zipping'; strProcessing = 'Processing %s...'; strZIPFileNotConfigured = 'ZIP File not configured (%s).'; Const strRESPONSEFILE = '$RESPONSEFILE$'; strFILELIST = '$FILELIST$'; strZIPFILE = '$ZIPFILE$'; Var ResponseFile: IITHResponseFile; iMsg: Integer; strZIPName: String; strBasePath: String; strProject: String; Process: TITHProcessInfo; Begin Result := 0; strProject := GetProjectName(FProject); If FProjectOps.EnableZipping Then Begin ResponseFile := TITHResponseFile.Create(FProject, FGlobalOps, FProjectOps, FMsgMgr); strZIPName := FProjectOps.ZipName; If strZIPName <> '' Then Begin strBasePath := ExpandMacro(FProjectOps.BasePath, FProject.FileName); Process.FEnabled := True; Process.FEXE := ExpandMacro(FGlobalOps.ZipEXE, FProject.FileName); Process.FParams := ExpandMacro(FGlobalOps.ZipParameters, FProject.FileName); If Not FileExists(Process.FEXE) Then Begin Inc(Result); FMsgMgr.AddMsg(Format(strZIPToolNotFound, [Process.FEXE, strProject]), fnHeader, ithfFailure); Exit; End; strZIPName := ExpandMacro(strZIPName, FProject.FileName); ResponseFile.BuildResponseFile(strBasePath, strProject, strZIPName); Process.FParams := StringReplace(Process.FParams, strRESPONSEFILE, ResponseFile.FileName, []); Process.FParams := StringReplace(Process.FParams, strFILELIST, ResponseFile.FileList, []); Process.FParams := StringReplace(Process.FParams, strZIPFILE, strZIPName, []); Process.FDir := ExpandMacro(strBasePath, FProject.FileName); FMsgMgr.ParentMsg := FMsgMgr.AddMsg(Format(strRunning, [ExtractFileName(Process.FEXE), strProject, strZipping]), fnHeader, ithfHeader); TfrmITHProcessing.ShowProcessing(Format(strProcessing, [ExtractFileName(Process.FEXE)])); FMsgMgr.Clear; Result := DGHCreateProcess(Process, ProcessMsgHandler, IdleHandler); For iMsg := 0 To FMsgMgr.Count - 1 Do Case Result Of 0: FMsgMgr[iMsg].ForeColour := FGlobalOps.FontColour[ithfSuccess]; Else FMsgMgr[iMsg].ForeColour := FGlobalOps.FontColour[ithfFailure]; End; If Result <> 0 Then FMsgMgr.ParentMsg.ForeColour := FGlobalOps.FontColour[ithfFailure]; End Else FMsgMgr.AddMsg(Format(strZIPFileNotConfigured, [strProject]), fnHeader, ithfFailure); End; End; End.
unit uUserControl; interface uses System.Classes, system.SysUtils, uUserInfo, uUserAction; type /// <summary> /// 登录结果 /// </summary> TUA_LOGIN_STATUS = ( uaUserNotExist, uaWrongPassword, uaSucceed ); type TUserControl = class private FUserGroupList: TStringList; FUserList: TStringList; FUserRightList: TStringList; /// <summary> /// 用户登录成功后的列表 /// </summary> FUserLognList : TStringList; FUserAction : TUserAction; FUserInfo: TUser; function GetUserList: TStringList; function GetUserRightList: TStringList; function GetUserGroupList: TStringList; public constructor Create; destructor Destroy;override; /// <summary> /// 有户列表 /// </summary> property UserList : TStringList read GetUserList; /// <summary> /// 加载用户列表 /// </summary> procedure LoadUserList; /// <summary> /// 保存用户(新增/编辑) /// </summary> procedure SaveUser(AUser : TUser); /// <summary> /// 删除用户 /// </summary> procedure DelUser(nUname : string);overload; procedure DelUser(AUser : TUser);overload; /// <summary> /// 权限列表 /// </summary> property UserRightList : TStringList read GetUserRightList; /// <summary> /// 加载有户权限列表 /// </summary> procedure LoadUserRightList; /// <summary> /// 保存用户权限(新增/编辑) /// </summary> procedure SaveUserRight(AUserRight : TUserRight); /// <summary> /// 删除用户权限 /// </summary> procedure DelUserRight(sUserRightName: string);overload; procedure DelUserRight(AUserRight : TUserRight);overload; /// <summary> /// 有户组列表 /// </summary> property UserGroupList : TStringList read GetUserGroupList; /// <summary> /// 保存用户组(新增/编辑) /// </summary> procedure SaveUserGroup(AUserGroup : TUserGroup); /// <summary> /// 删除用户组 /// </summary> procedure DelUserGroup(sUserGroupName : string);overload; procedure DelUserGroup(AUserGroup : TUserGroup);overload; /// <summary> /// 通过UserName获取用户信息 /// </summary> function GetUserInfo(sUserName : string) : TUser; /// <summary> /// 加载有户组列表 /// </summary> procedure LoadUserGroupList; /// <summary> /// 通过GroupName获取组信息 /// </summary> function GetGroupInfo(sGroupName : string) : TUserGroup; /// <summary> /// 加载所有列表 /// </summary> procedure LoadUserAllList; /// <summary> /// 用户信息 /// </summary> property UserInfo : TUser read FUserInfo write FUserInfo; /// <summary> /// 登录 /// </summary> function Login( const sLName, sLPassword : string ) : TUA_LOGIN_STATUS; /// <summary> /// 注销 /// </summary> procedure LogOut; /// <summary> /// 判断权限是否存在 /// </summary> function RightExist( sRightName : string ) : Boolean; /// <summary> /// 用户名是否存在 /// </summary> function CheckUNameExists(sUname : string) : Boolean; /// <summary> /// 用户名是否存在 /// </summary> function CheckUGNameExists(sUGname : string) : Boolean; /// <summary> /// 修改密码 /// </summary> procedure UserUpass;overload; //修改登录用户密码 procedure UserUpass(AUser : TUser);overload; //管理用户修改密码 end; var UserControl : TUserControl; implementation uses xFunction, uUpUsPass, System.UITypes; { TUserControl } function TUserControl.CheckUGNameExists(sUGname: string): Boolean; begin Result := FUserAction.CheckUGNameExists(sUGname); end; function TUserControl.CheckUNameExists(sUname: string): Boolean; begin Result := FUserAction.CheckUNameExists(sUname); end; constructor TUserControl.Create; begin FUserList := TStringList.Create; FUserRightList := TStringList.Create; FUserGroupList := TStringList.Create; FUserAction := TUserAction.Create; FUserLognList := TStringList.Create; LoadUserAllList; end; procedure TUserControl.DelUser(nUname: string); var nIndex : Integer; begin FUserAction.DelUser(nUname); nIndex := FUserList.IndexOf(nUname); if nIndex <> -1 then begin FUserList.Objects[nIndex].Free; FUserList.Delete(nIndex); end; end; procedure TUserControl.DelUser(AUser: TUser); begin if Assigned(AUser) then DelUser(AUser.LoginName); end; procedure TUserControl.DelUserGroup(sUserGroupName: string); var nIndex : Integer; begin FUserAction.DelUserGroup(sUserGroupName); nIndex := FUserGroupList.IndexOf(sUserGroupName); if nIndex <> -1 then begin FUserGroupList.Objects[nIndex].Free; FUserGroupList.Delete(nIndex); end; end; procedure TUserControl.DelUserGroup(AUserGroup: TUserGroup); begin if Assigned(AUserGroup) then DelUserGroup(AUserGroup.GroupName); end; procedure TUserControl.DelUserRight(sUserRightName: string); var nIndex : integer; begin FUserAction.DelUserRight(sUserRightName); nIndex := FUserRightList.IndexOf(sUserRightName); if nIndex <> -1 then begin FUserRightList.Objects[nIndex].Free; FUserRightList.Delete(nIndex); end; end; procedure TUserControl.DelUserRight(AUserRight: TUserRight); begin if Assigned(AUserRight) then DelUserRight(AUserRight.RightName); end; destructor TUserControl.Destroy; begin ClearStringList(FUserList); ClearStringList(FUserRightList); ClearStringList(FUserGroupList); ClearStringList(FUserLognList); FUserList.Free; FUserRightList.Free; FUserGroupList.Free; FUserAction.Free; FUserLognList.Free; inherited; end; function TUserControl.GetGroupInfo(sGroupName: string): TUserGroup; var nIndex : integer; begin Result := nil; nIndex := UserGroupList.IndexOf(sGroupName); if nIndex <> -1 then begin Result := TUserGroup(UserGroupList.Objects[nIndex]); end; end; function TUserControl.GetUserGroupList: TStringList; begin LoadUserGroupList; Result := FUserGroupList; end; function TUserControl.GetUserInfo(sUserName : string) : TUser; var nIndex : integer; begin Result := nil; nIndex := UserList.IndexOf(sUserName); if nIndex <> -1 then begin Result := TUser(UserList.Objects[nIndex]); end; end; function TUserControl.GetUserList: TStringList; begin LoadUserList; Result := FUserList; end; function TUserControl.GetUserRightList: TStringList; begin LoadUserRightList; Result := FUserRightList; end; procedure TUserControl.LoadUserAllList; begin LoadUserList; LoadUserRightList; LoadUserGroupList; end; procedure TUserControl.LoadUserGroupList; begin FUserAction.GetAllUserGroups(FUserGroupList); end; procedure TUserControl.LoadUserList; begin FUserAction.GetAllUsers(FUserList); end; procedure TUserControl.LoadUserRightList; begin FUserAction.GetAllUserRights(FUserRightList); end; function TUserControl.Login(const sLName, sLPassword: string): TUA_LOGIN_STATUS; begin FUserInfo := TUser.Create; // 登录 if not FUserAction.GetUserInfo( sLName, FUserInfo ) then Result := uaUserNotExist else begin if UpperCase(GetMD5( sLPassword )) = FUserInfo.Password then Result := uaSucceed else Result := uaWrongPassword; end; // 登录成功后读取权限 if Result = uaSucceed then FUserAction.GetUserRights( FUserInfo.GroupID, FUserLognList ) else FreeAndNil( FUserInfo ); end; procedure TUserControl.LogOut; begin if Assigned( FUserInfo ) then FreeAndNil( FUserInfo ); ClearStringList( FUserLognList ); end; function TUserControl.RightExist(sRightName: string): Boolean; begin result := False; if FUserLognList.IndexOf( sRightName ) <> -1 then Result := True; end; procedure TUserControl.SaveUser(AUser : TUser); var nIndex : Integer; FUser :TUser; begin FUserAction.SaveUser(AUser); if Assigned(AUser) then begin nIndex := FUserGroupList.IndexOf(AUser.LoginName); if nIndex <> -1 then begin FUserList.Delete(nIndex); FUser := TUser.Create; FUser.Assign(AUser); FUserGroupList.AddObject(FUser.LoginName, FUser); end else begin FUser := TUser.Create; FUser.Assign(AUser); FUserGroupList.AddObject(FUser.LoginName, FUser); end; end; end; procedure TUserControl.SaveUserGroup(AUserGroup: TUserGroup); var nIndex : Integer; AGroupUser :TUserGroup; begin FUserAction.SaveUserGroup(AUserGroup); if Assigned(AUserGroup) then begin nIndex := FUserGroupList.IndexOf(AUserGroup.GroupName); if nIndex <> -1 then begin FUserGroupList.Delete(nIndex); AGroupUser := TUserGroup.Create; AGroupUser.Assign(AUserGroup); FUserGroupList.AddObject(AGroupUser.GroupName, AGroupUser); end else begin AGroupUser := TUserGroup.Create; AGroupUser.Assign(AUserGroup); FUserGroupList.AddObject(AGroupUser.GroupName, AGroupUser); end; end; end; procedure TUserControl.SaveUserRight(AUserRight: TUserRight); var nIndex : integer; ARightUser : TUserRight; begin FUserAction.SaveUserRight(AUserRight); if Assigned(AUserRight) then begin nIndex := FUserGroupList.IndexOf(AUserRight.RightName); if nIndex <> -1 then begin TUserGroup(FUserRightList.Objects[nIndex]).Assign(AUserRight); end else begin ARightUser := TUserRight.Create; ARightUser.Assign(AUserRight); FUserGroupList.AddObject(ARightUser.RightName, ARightUser); end; end; end; procedure TUserControl.UserUpass(AUser: TUser); begin if Assigned(AUser) then begin with TfUpUsPass.Create(nil) do begin ShowInfo(AUser); if ShowModal = mrOk then begin SaveInfo; FUserAction.UpUserPass(AUser); HintMessage(0, '修改成功!', '提示'); end; Free; end; end; end; procedure TUserControl.UserUpass; begin UserUpass(UserInfo); end; end.
Unit TextDisp; interface {$I TEXTMODE.INC} uses CRT, Graph, Windows, Memory; type MessageRec = RECORD BitMap : POINTER; OldColor, OldBkColor, ClipSize : WORD; x, y : INTEGER; END; procedure Beep; procedure CursorConvert(X,Y : INTEGER; VAR gX, gY : INTEGER); { convert 80x24 line position to graphics pixels } PROCEDURE MyGotoXY(X,Y: WORD); { replaces Turbo GotoXY in graphics mode} PROCEDURE WriteT(X,Y: WORD; stg : String); { subsitute for GotoXY();Write() with graphic screens } PROCEDURE WriteInt(X,Y: WORD; intnum : INTEGER); { subsitute for GotoXY();Write() with graphic screens } PROCEDURE Message(VAR mp : MessageRec; msg : string); PROCEDURE ClearMsg(mp : MessageRec); { call to clear message } function ErrorMsg(msg : string) : BOOLEAN; { beeps, displays the msg, waits a sec, then returns false } procedure DrawBox(x,y,wide,high : integer); { ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} implementation {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} procedure Beep; BEGIN Sound(500); Delay(500); NoSound; END; function RepeatStr(fill:string; times:integer) : string; var temp : string; i : integer; begin temp := ''; for i := 1 to times do temp := temp + fill; RepeatStr := temp; end; {REPEATSTR} { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE FillRect( x1,y1,x2,y2 : WORD); VAR v : ARRAY[0..3] OF PointType; BEGIN v[0].x := x1; v[0].y := y1; v[1].x := x2; v[1].y := y1; v[2].x := x2; v[2].y := y2; v[3].x := x1; v[3].y := y2; FillPoly(4,v); END; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} procedure CursorConvert(X,Y : INTEGER; VAR gX, gY : INTEGER); { convert 80x25 line position to graphics pixels for 8 pixel font} CONST FontWidth = 8; FontHeight = 8; BEGIN gX := trunc(GetMaxX / 80 * X) - FontWidth; IF gX < 0 THEN gX := 0; IF gX > GetMaxX THEN gX := GetMaxX; gy := trunc(GetMaxY / 24 * Y) - FontHeight; IF gY < 0 THEN gY := 0; END; {CursorConvert} {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE MyGotoXY(X,Y: WORD); { replaces Turbo GotoXY in graphics mode} VAR gx,gy : INTEGER; BEGIN {$IFDEF TextMode } GotoXY(X,Y); {$ELSE } CursorConvert(X,Y,gx,gy); MoveTo(gx,gy); {$ENDIF } END; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE WriteT(X,Y: WORD; stg : String); VAR gx,gy : INTEGER; begin {$IFDEF TextMode } GotoXY(X,Y); Write(stg); {$ELSE } CursorConvert(X,Y,gx,gy); OutTextXY(gx,gy,repeatstr(' ',length(stg))); OutTextXY(gx,gy,stg); {$ENDIF } end; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE WriteInt(X,Y: WORD; intnum : INTEGER); VAR stg : String; gx,gy : INTEGER; begin {$IFDEF TextMode } GotoXY(X,Y); Write(intnum:0); {$ELSE } CursorConvert(X,Y,gx,gy); str(intnum:0,stg); OutTextXY(gx,gy,stg); {$ENDIF } end; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE Message(VAR mp : MessageRec; msg : string); CONST HalfCols = 40; top = 12; bottom = 14; VAR Spaces,i, left, right, x1,y1,x2,y2, len : INTEGER; Error : BYTE; begin len := length(msg); right := HalfCols + len + 2; left := HalfCols - len + 2; IF left < 1 THEN BEGIN left := 1; right := HalfCols * 2 - 1; END; {$IFDEF TextMode } OpenWindow(left,top,right,bottom,Black,red,error); WriteT(left+2,top-1,msg); {$ELSE } CursorConvert(left,top,x1,y1); CursorConvert(right,bottom,x2,y2); mp.ClipSize := ImageSize(x1,y1,x2,y2); GetMem(mp.BitMap,mp.ClipSize); IF mp.BitMap <> NIL THEN BEGIN GetImage(x1,y1,x2,y2,mp.BitMap^); mp.OldColor := GetColor; mp.OldBkColor := GetBkColor; SetColor(Black); SetFillStyle(SolidFill,Red); SetColor(Yellow); FillRect(x1,y1,x2,y2); WriteT(left+2,top+1,msg); mp.x := x1; mp.y := y1; END; {$ENDIF} END; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE ClearMsg(mp : MessageRec); BEGIN {$IFDEF TextMode } CloseWindow; {$ELSE } PutImage(mp.x,mp.y,mp.BitMap^,NormalPut); FreeMem(mp.BitMap,mp.ClipSize); SetColor(mp.OldColor); SetBkColor(mp.OldBkColor); {$ENDIF} END; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function ErrorMsg(msg : string) : BOOLEAN; VAR Error : BOOLEAN; mp : MessageRec; BEGIN Beep; Message(mp,msg); Delay(1000); ClearMsg(mp); ErrorMsg := FALSE; END; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} procedure DrawBox(x,y,wide, high : integer); { x,y is character position WITHIN box at upper left. } var i : integer; begin for i := 0 to high DO BEGIN WriteT(x-1,y+i,char(179)); WriteT(x+wide,y+i,char(179)); END; WriteT(x-1,y+high,char(192)+RepeatStr(char(196),wide)+char(217)); WriteT(x-1,y-1,char(218)+RepeatStr(char(196),wide)+char(191)); end; {drawbox} begin end. 
unit mopformula; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fgl, mopmaterial, moptype, complexes; type { TMOPLay } TMOPLay = class // характеристики слоя public LayName: string; LinkMaterialIndex: integer; MaterialName: string; Thickness: real; OpticThickness: real; Wavelength: real; constructor Create; end; TMOPLays = specialize TFPGList<TMOPLay>; { TMOPBlock } TMOPBlock = class public Repetition: integer; LayIndexes: TIntegerPoints; constructor Create; destructor Destroy; override; end; TMOPBlocks = specialize TFPGList<TMOPBlock>; { TMOPFormula } TMOPFormula = class public Blocks: TMOPBlocks; Lays: TMOPLays; constructor Create; destructor Destroy; override; function Parse(InText: string): boolean; function LinkToMaterialsByName(const Materials: TMOPMaterials): integer; function UpdateMaterialIndex(const Materials: TMOPMaterials; LayNumber: Integer; MatIndex: Integer): boolean; function FindOutThickness(const Materials: TMOPMaterials): boolean; function FindOutLayThickness(const Materials: TMOPMaterials; LayIndex: integer): boolean; function LaysOrder: TIntegerPoints; function GetFormula: string; function GetThickness(Materials: TIntegerPoints): TRealPoints; function GetMaterials(Materials: TIntegerPoints): TIntegerPoints; function IsLayExist(const InLays:TMOPLays; layname: string): integer; end; implementation { TMOPLay } constructor TMOPLay.Create; begin LayName:=''; MaterialName:=''; LinkMaterialIndex:=-1; // не связан с материалами Thickness:=0; OpticThickness:=0; Wavelength:=0; end; { TMOPBlock } constructor TMOPBlock.Create; begin Repetition:=0; LayIndexes:=TIntegerPoints.Create; end; destructor TMOPBlock.Destroy; begin LayIndexes.Free; inherited Destroy; end; { TMOPFormula } constructor TMOPFormula.Create; begin Blocks:=TMOPBlocks.Create; Lays:=TMOPLays.Create; end; destructor TMOPFormula.Destroy; begin Blocks.Free; Lays.Free; inherited Destroy; end; function TMOPFormula.Parse(InText: string): boolean; var i,j,k: integer; txt: string; blo, cob: TStringList; bltxt: boolean; oldls: TMOPLays; const chn = ['0'..'9']; ltsbl = ['a'..'z','-',':']; begin Result:=true; txt:=Trim(LowerCase(InText)); blo:=TStringList.Create; cob:=TStringList.Create; // Разделение на блоки blo.Add(''); cob.Add('1'); bltxt:= true; for i:=1 to Length(txt) do begin if not((txt[i] in chn) xor (bltxt)) then begin bltxt := not bltxt; if not bltxt then begin blo.Append(''); cob.Append(''); end; end; if bltxt then begin if (txt[i] in ltsbl) then blo.Strings[blo.Count-1]:= blo.Strings[blo.Count-1]+txt[i]; end else begin cob.Strings[cob.Count-1]:= cob.Strings[cob.Count-1]+txt[i]; end; end; // Удаление пустых блоков i:=0; while ( i <= blo.Count-1 ) do begin if blo.Strings[i] = '' then begin blo.Delete(i); cob.Delete(i); end; inc(i); end; //Перезапись блоков Blocks.Clear; for i:=0 to cob.Count-1 do begin Blocks.Add(TMOPBlock.Create); txt:=cob.Strings[i]; Blocks.Last.Repetition:=strtoint(txt); end; // Копирование старого списка слоев и создане нового списка слоев oldls:=Lays; Lays:=TMOPLays.Create; //Проход по блокам и парсинг слоев for j:=0 to blo.Count-1 do begin txt:=blo.Strings[j]; for i:=1 to length(txt) do if (txt[i]='-') or (txt[i]=':') then txt[i]:=#13; // Делаем парсинг формулы cob.Text:=txt; // Удаляем пустые элементы i:=0; while ( i <= cob.Count-1 ) do begin if cob.Strings[i]='' then cob.Delete(i); inc(i); end; // Обработка слоев for i:=0 to cob.Count-1 do begin k := IsLayExist(Lays,cob.Strings[i]); if k < 0 then begin k := IsLayExist(oldls,cob.Strings[i]); if k < 0 then begin Lays.Add(TMOPLay.Create); Lays.Last.LayName:=cob.Strings[i]; end else begin lays.Add(oldls.Items[k]); oldls.Delete(k); end; Blocks.Items[j].LayIndexes.Add(Lays.Count-1); end else begin Blocks.Items[j].LayIndexes.Add(k); end; end; end; oldls.Free; blo.Free; cob.Free; end; function TMOPFormula.LinkToMaterialsByName(const Materials: TMOPMaterials ): integer; var j: integer; begin Result:=-1; for j:=0 to Lays.Count-1 do begin Lays.Items[j].LinkMaterialIndex:= Materials.FindByName( Lays.Items[j].MaterialName ); if Lays.Items[j].LinkMaterialIndex < 0 then begin Result:=j; Break; end; end; end; function TMOPFormula.UpdateMaterialIndex(const Materials: TMOPMaterials; LayNumber: Integer; MatIndex: Integer): boolean; begin If (LayNumber < Lays.Count) and (LayNumber >= 0) then begin Lays.Items[LayNumber].LinkMaterialIndex := MatIndex; Lays.Items[LayNumber].MaterialName:= Materials.Items[MatIndex].MaterialName; end; end; function TMOPFormula.FindOutThickness(const Materials: TMOPMaterials): boolean; var j: integer; begin Result:=true; for j:=0 to Lays.Count-1 do FindOutLayThickness(Materials, j); end; function TMOPFormula.FindOutLayThickness(const Materials: TMOPMaterials; LayIndex: integer): boolean; var int: TIntegerPoints; cmp: TComplexPoints; begin result:=true; if (Lays.Items[LayIndex].Wavelength > 0) and (Lays.Items[LayIndex].OpticThickness > 0) and (Lays.Items[LayIndex].LinkMaterialIndex >= 0) then begin int := TIntegerPoints.Create; int.Add(Lays.Items[LayIndex].LinkMaterialIndex); cmp := Materials.GetEpsToWave(int, Lays.Items[LayIndex].Wavelength); Lays.Items[LayIndex].Thickness:=Lays.Items[LayIndex].OpticThickness/ (csqrt(cmp.Items[cmp.Count-1])).re; end; end; function TMOPFormula.LaysOrder: TIntegerPoints; var j,h,k: integer; begin Result:=TIntegerPoints.Create; for j:=0 to Blocks.Count-1 do for h:=0 to Blocks.Items[j].Repetition-1 do for k:=0 to Blocks.Items[j].LayIndexes.Count-1 do Result.Add(Blocks.Items[j].LayIndexes.Items[k]); end; function TMOPFormula.GetFormula: string; var j,i: integer; begin result:=''; for j:=0 to Blocks.Count-1 do begin result:=result+inttostr(Blocks.Items[j].Repetition); for i:=0 to Blocks.Items[j].LayIndexes.Count-1 do if Blocks.Items[j].LayIndexes.Items[i] >=0 then result:=result+':'+Lays.Items[Blocks.Items[j].LayIndexes.Items[i]].LayName else result:=result+':x'; end; end; function TMOPFormula.GetThickness(Materials: TIntegerPoints): TRealPoints; var j: integer; begin Result:=TRealPoints.Create; for j:=0 to Materials.Count-1 do begin Result.Add( Lays.Items[Materials.Items[j]].Thickness ); end; end; function TMOPFormula.GetMaterials(Materials: TIntegerPoints): TIntegerPoints; var j: integer; begin Result:=TIntegerPoints.Create; for j:=0 to Materials.Count-1 do begin Result.Add( Lays.Items[ Materials.Items[j] ].LinkMaterialIndex ); end; end; function TMOPFormula.IsLayExist(const InLays: TMOPLays; layname: string): integer; var i: integer; begin result:=-1; if assigned(InLays) then begin for i:=0 to InLays.Count-1 do if InLays.Items[i].LayName = layname then begin result:=i; break; end; end; end; end.
unit CheckField; interface uses System.SysUtils, System.Classes, FMX.Types, FMX.Controls, System.Types, FMX.Objects, FMX.StdCtrls, System.UITypes, FMX.Graphics, FMX.Dialogs, System.Math, System.Math.Vectors, FMX.Edit, FMX.Layouts, FMX.Effects, ColorClass; type TCheckField = class(TControl) private { Private declarations } protected { Protected declarations } FPointerOnMouseEnter: TNotifyEvent; FPointerOnMouseExit: TNotifyEvent; FPointerOnClick: TNotifyEvent; FPointerOnChange: TNotifyEvent; FText: TLabel; FLayoutIcon: TLayout; FUncheckedIcon: TPath; FCheckedIcon: TPath; FCircleSelect: TCircle; FLayout: TLayout; FBackupFontColor: TAlphaColor; FBackupUncheckedIconColor: TAlphaColor; FDisableOnCheck: TCheckField; procedure Paint; override; procedure Resize; override; procedure Painting; override; procedure OnCheckFieldClick(Sender: TObject); procedure OnCheckFieldMouseEnter(Sender: TObject); procedure OnCheckFieldMouseExit(Sender: TObject); procedure SetFCircleSelectColor(const Value: TAlphaColor); function GetFTag: NativeInt; procedure SetFTag(const Value: NativeInt); function GetFOnClick: TNotifyEvent; procedure SetFOnClick(const Value: TNotifyEvent); function GetFButtonClass: TColorClass; procedure SetFButtonClass(const Value: TColorClass); function GetFCheckedIconColor: TAlphaColor; function GetFUncheckedIcon: TPathData; function GetFUncheckedIconColor: TAlphaColor; procedure SetFCheckedIconColor(const Value: TAlphaColor); procedure SetFUncheckedIcon(const Value: TPathData); procedure SetFUncheckedIconColor(const Value: TAlphaColor); function GetFCheckedIcon: TPathData; procedure SetFCheckedIcon(const Value: TPathData); function GetFIconSize: Single; procedure SetFIconSize(const Value: Single); function GetFText: String; procedure SetFText(const Value: String); function GetFTextSettings: TTextSettings; procedure SetFTextSettings(const Value: TTextSettings); function GetFIsChecked: Boolean; procedure SetFIsChecked(const Value: Boolean); function GetFOnChange: TNotifyEvent; procedure SetFOnChange(const Value: TNotifyEvent); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; function ValidateIsChecked(): Boolean; procedure HideEffectValidation(); published { Published declarations } property Cursor; property Align; property Anchors; property Enabled; property Height; property Opacity; property Visible; property Width; property Size; property Scale; property Margins; property Position; property RotationAngle; property RotationCenter; property HitTest; { Additional properties } property ButtonClass: TColorClass read GetFButtonClass write SetFButtonClass; property Text: String read GetFText write SetFText; property TextSettings: TTextSettings read GetFTextSettings write SetFTextSettings; property IsChecked: Boolean read GetFIsChecked write SetFIsChecked; property UncheckedIcon: TPathData read GetFUncheckedIcon write SetFUncheckedIcon; property CheckedIcon: TPathData read GetFCheckedIcon write SetFCheckedIcon; property UncheckedIconColor: TAlphaColor read GetFUncheckedIconColor write SetFUncheckedIconColor; property CheckedIconColor: TAlphaColor read GetFCheckedIconColor write SetFCheckedIconColor; property IconSize: Single read GetFIconSize write SetFIconSize; property Tag: NativeInt read GetFTag write SetFTag; property DisableOnCheck: TCheckField read FDisableOnCheck write FDisableOnCheck; { Events } property OnPainting; property OnPaint; property OnResize; { Mouse events } property OnChange: TNotifyEvent read GetFOnChange write SetFOnChange; property OnClick: TNotifyEvent read GetFOnClick write SetFOnClick; property OnDblClick; property OnKeyDown; property OnKeyUp; property OnMouseDown; property OnMouseUp; property OnMouseWheel; property OnMouseMove; property OnMouseEnter; property OnMouseLeave; property OnEnter; property OnExit; end; procedure Register; implementation procedure Register; begin RegisterComponents('Componentes Customizados', [TCheckField]); end; { TCheckField } constructor TCheckField.Create(AOwner: TComponent); begin inherited; Self.Width := 250; Self.Height := 30; FText := TLabel.Create(Self); Self.AddObject(FText); FText.Align := TAlignLayout.Client; FText.HitTest := False; FText.Margins.Left := 10; FText.StyledSettings := []; FText.TextSettings.Font.Size := 14; FText.TextSettings.Font.Family := 'SF Pro Display'; FText.TextSettings.FontColor := TAlphaColor($FF323232); FBackupFontColor := TAlphaColor($FF323232); FText.SetSubComponent(True); FText.Stored := False; FLayoutIcon := TLayout.Create(Self); Self.AddObject(FLayoutIcon); FLayoutIcon.Align := TAlignLayout.Left; FLayoutIcon.HitTest := False; FLayoutIcon.SetSubComponent(True); FLayoutIcon.Stored := False; FLayoutIcon.Width := 17; FCircleSelect := TCircle.Create(Self); FLayoutIcon.AddObject(FCircleSelect); FCircleSelect.Align := TAlignLayout.Center; FCircleSelect.HitTest := False; FCircleSelect.SetSubComponent(True); FCircleSelect.Stored := False; FCircleSelect.Stroke.Kind := TBrushKind.None; FCircleSelect.Visible := True; FCircleSelect.Opacity := 0; FCircleSelect.Width := (Self.Height) * 1.4; FCircleSelect.Height := (Self.Height) * 1.4; SetFCircleSelectColor(TRANSPARENT_PRIMARY_COLOR); FCircleSelect.SendToBack; FUncheckedIcon := TPath.Create(Self); FLayoutIcon.AddObject(FUncheckedIcon); FUncheckedIcon.SetSubComponent(True); FUncheckedIcon.Stored := False; FUncheckedIcon.Align := TAlignLayout.Contents; FUncheckedIcon.WrapMode := TPathWrapMode.Fit; FUncheckedIcon.Fill.Color := TAlphaColor($FF757575); FBackupUncheckedIconColor := TAlphaColor($FF757575); FUncheckedIcon.Stroke.Kind := TBrushKind.None; FUncheckedIcon.HitTest := False; FUncheckedIcon.Data.Data := 'M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3M19,5V19H5V5H19Z'; FCheckedIcon := TPath.Create(Self); FLayoutIcon.AddObject(FCheckedIcon); FCheckedIcon.Align := TAlignLayout.Contents; FCheckedIcon.WrapMode := TPathWrapMode.Fit; FCheckedIcon.Fill.Color := TAlphaColor($FF1867C0); FCheckedIcon.Stroke.Kind := TBrushKind.None; FCheckedIcon.HitTest := False; FCheckedIcon.Visible := False; FCheckedIcon.Data.Data := 'M10,17L5,12L6.41,10.58L10,14.17L17.59,6.58L19,8M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3Z'; FCheckedIcon.BringToFront; FLayout := TLayout.Create(Self); Self.AddObject(FLayout); FLayout.Align := TAlignLayout.Contents; FLayout.HitTest := True; FLayout.SetSubComponent(True); FLayout.Stored := False; FLayout.Cursor := crHandPoint; FLayout.OnClick := OnCheckFieldClick; FLayout.OnMouseEnter := OnCheckFieldMouseEnter; FLayout.OnMouseLeave := OnCheckFieldMouseExit; FLayout.BringToFront; end; destructor TCheckField.Destroy; begin if Assigned(FLayout) then FLayout.Free; if Assigned(FCheckedIcon) then FCheckedIcon.Free; if Assigned(FUncheckedIcon) then FUncheckedIcon.Free; if Assigned(FText) then FText.Free; inherited; end; procedure TCheckField.OnCheckFieldClick(Sender: TObject); var CircleEffect: TCircle; begin CircleEffect := TCircle.Create(Self); CircleEffect.HitTest := False; CircleEffect.Parent := FLayoutIcon; CircleEffect.Align := TAlignLayout.Center; CircleEffect.Stroke.Kind := TBrushKind.None; CircleEffect.Fill.Color := FCheckedIcon.Fill.Color; CircleEffect.SendToBack; CircleEffect.Height := 0; CircleEffect.Width := 0; CircleEffect.Opacity := 0.6; CircleEffect.AnimateFloat('Height', FCircleSelect.Height, 0.4, TAnimationType.Out, TInterpolationType.Circular); CircleEffect.AnimateFloat('Width', FCircleSelect.Width, 0.4, TAnimationType.Out, TInterpolationType.Circular); CircleEffect.AnimateFloat('Opacity', 0, 0.5); if not FCheckedIcon.Visible then begin if Assigned(FDisableOnCheck) then begin FDisableOnCheck.HideEffectValidation; FDisableOnCheck.IsChecked := False; end; if FUncheckedIcon.Fill.Color = SOLID_ERROR_COLOR then begin FText.TextSettings.FontColor := FBackupFontColor; FUncheckedIcon.Fill.Color := FBackupUncheckedIconColor; end; FCheckedIcon.Visible := True; FUncheckedIcon.Visible := False; end else if not Assigned(FDisableOnCheck) then begin FUncheckedIcon.Visible := True; FCheckedIcon.Visible := False; end; if Assigned(FPointerOnClick) then FPointerOnClick(Sender); if Assigned(FPointerOnChange) then FPointerOnChange(Sender); end; procedure TCheckField.OnCheckFieldMouseEnter(Sender: TObject); begin FCircleSelect.AnimateFloat('Opacity', 1, 0.2, TAnimationType.InOut); if Assigned(FPointerOnMouseEnter) then FPointerOnMouseEnter(Sender); end; procedure TCheckField.OnCheckFieldMouseExit(Sender: TObject); begin FCircleSelect.AnimateFloat('Opacity', 0, 0.2, TAnimationType.InOut); if Assigned(FPointerOnMouseExit) then FPointerOnMouseExit(Sender); end; procedure TCheckField.Paint; begin inherited; end; procedure TCheckField.Painting; begin inherited; end; procedure TCheckField.Resize; begin inherited; end; function TCheckField.GetFCheckedIconColor: TAlphaColor; begin Result := FCheckedIcon.Fill.Color; end; function TCheckField.GetFIconSize: Single; begin Result := FLayoutIcon.Width; end; function TCheckField.GetFIsChecked: Boolean; begin Result := FCheckedIcon.Visible; end; function TCheckField.GetFOnChange: TNotifyEvent; begin Result := FPointerOnChange; end; function TCheckField.GetFOnClick: TNotifyEvent; begin Result := FPointerOnClick; end; function TCheckField.GetFTag: NativeInt; begin Result := TControl(Self).Tag; end; function TCheckField.GetFText: String; begin Result := FText.Text; end; function TCheckField.GetFTextSettings: TTextSettings; begin Result := FText.TextSettings; end; function TCheckField.GetFUncheckedIcon: TPathData; begin Result := FUncheckedIcon.Data; end; function TCheckField.GetFUncheckedIconColor: TAlphaColor; begin Result := FUncheckedIcon.Fill.Color; end; function TCheckField.GetFButtonClass: TColorClass; begin if FCheckedIcon.Fill.Color = SOLID_PRIMARY_COLOR then Result := TColorClass.Primary else if FCheckedIcon.Fill.Color = SOLID_SECONDARY_COLOR then Result := TColorClass.Secondary else if FCheckedIcon.Fill.Color = SOLID_ERROR_COLOR then Result := TColorClass.Error else if FCheckedIcon.Fill.Color = SOLID_WARNING_COLOR then Result := TColorClass.Warning else if FCheckedIcon.Fill.Color = SOLID_SUCCESS_COLOR then Result := TColorClass.Success else if FCheckedIcon.Fill.Color = SOLID_BLACK then Result := TColorClass.Normal else Result := TColorClass.Custom; end; function TCheckField.GetFCheckedIcon: TPathData; begin Result := FCheckedIcon.Data; end; procedure TCheckField.SetFButtonClass(const Value: TColorClass); begin if Value = TColorClass.Primary then begin SetFCheckedIconColor(SOLID_PRIMARY_COLOR); SetFCircleSelectColor(TRANSPARENT_PRIMARY_COLOR); end else if Value = TColorClass.Secondary then begin SetFCheckedIconColor(SOLID_SECONDARY_COLOR); SetFCircleSelectColor(TRANSPARENT_SECONDARY_COLOR); end else if Value = TColorClass.Error then begin SetFCheckedIconColor(SOLID_ERROR_COLOR); SetFCircleSelectColor(TRANSPARENT_ERROR_COLOR); end else if Value = TColorClass.Warning then begin SetFCheckedIconColor(SOLID_WARNING_COLOR); SetFCircleSelectColor(TRANSPARENT_WARNING_COLOR); end else if Value = TColorClass.Normal then begin SetFCheckedIconColor(SOLID_BLACK); SetFCircleSelectColor(TRANSPARENT_BLACK); end else if Value = TColorClass.Success then begin SetFCheckedIconColor(SOLID_SUCCESS_COLOR); SetFCircleSelectColor(TRANSPARENT_SUCCESS_COLOR); end else begin SetFCheckedIconColor(TAlphaColor($FF323232)); SetFCircleSelectColor(TAlphaColor($1E323232)); end; end; procedure TCheckField.SetFCheckedIcon(const Value: TPathData); begin FCheckedIcon.Data := Value; end; procedure TCheckField.SetFCheckedIconColor(const Value: TAlphaColor); begin FCheckedIcon.Fill.Color := Value; end; procedure TCheckField.SetFCircleSelectColor(const Value: TAlphaColor); begin FCircleSelect.Fill.Color := Value; end; procedure TCheckField.SetFIconSize(const Value: Single); begin FLayoutIcon.Width := Value; FLayoutIcon.Height := Value; Self.Height := (FLayoutIcon.Width) * 1.4; end; procedure TCheckField.SetFIsChecked(const Value: Boolean); begin FCheckedIcon.Visible := Value; FUncheckedIcon.Visible := not Value; end; procedure TCheckField.SetFOnChange(const Value: TNotifyEvent); begin FPointerOnChange := Value; end; procedure TCheckField.SetFOnClick(const Value: TNotifyEvent); begin FPointerOnClick := Value; end; procedure TCheckField.SetFTag(const Value: NativeInt); begin FLayout.Tag := Value; TControl(Self).Tag := Value; end; procedure TCheckField.SetFText(const Value: String); begin FText.Text := Value; end; procedure TCheckField.SetFTextSettings(const Value: TTextSettings); begin FText.TextSettings := Value; FBackupFontColor := Value.FontColor; end; procedure TCheckField.SetFUncheckedIcon(const Value: TPathData); begin FUncheckedIcon.Data := Value; end; procedure TCheckField.SetFUncheckedIconColor(const Value: TAlphaColor); begin FUncheckedIcon.Fill.Color := Value; FBackupUncheckedIconColor := Value; end; function TCheckField.ValidateIsChecked: Boolean; begin if Assigned(FDisableOnCheck) and FDisableOnCheck.IsChecked then Result := FDisableOnCheck.IsChecked else begin if not Self.IsChecked and (FUncheckedIcon.Fill.Color <> SOLID_ERROR_COLOR) then begin FBackupFontColor := FText.TextSettings.FontColor; FBackupUncheckedIconColor := FUncheckedIcon.Fill.Color; FText.TextSettings.FontColor := SOLID_ERROR_COLOR; FUncheckedIcon.Fill.Color := SOLID_ERROR_COLOR; end; Result := Self.IsChecked; end; end; procedure TCheckField.HideEffectValidation; begin if FUncheckedIcon.Fill.Color = SOLID_ERROR_COLOR then begin FText.TextSettings.FontColor := FBackupFontColor; FUncheckedIcon.Fill.Color := FBackupUncheckedIconColor; end; end; end.
unit TestAbsolute; { AFS 11 March 2K This code compiles, but is not semantically meaningfull. It is test cases for the code-formating utility Test the 'absolute' keyword } interface implementation uses Classes, Types; { a hack extracted from a much larger program not easy to cast a method pointer without the compiler thinking you want to call it Double is 8 bytes, same size as a object method pointer } function MethodPointerToDouble (pmMethod: TNotifyEvent): double; var lmMethod: TNotifyEvent; ldCast: double absolute pmMethod; begin lmMethod := pmMethod; Result := ldCast end; { Test absolute with dotted names } var foo: TPoint; var foox: Longint absolute foo.X; var myfoo: TPoint absolute TestAbsolute.foo; end.
unit uDados; interface uses SysUtils, Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, uDWConstsData, uRESTDWPoolerDB, uDWAbout, uniGUIBaseClasses, uniGUIClasses, UniFSToast, uniImageList, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait; type TdmDados = class(TDataModule) Toast: TUniFSToast; imglFA: TUniNativeImageList; FDUsuario: TFDQuery; FDAuxiliar: TFDQuery; FDLogSys: TFDQuery; FDLogSysID: TIntegerField; FDLogSysDIA: TSQLTimeStampField; FDLogSysLOGIN: TStringField; FDLogSysOPERACAO: TStringField; FDLogSysOCORRENCIA: TStringField; FDTransaction1: TFDTransaction; FDConnection1: TFDConnection; FDUsuarioID: TIntegerField; FDUsuarioNOME: TStringField; FDUsuarioEMAIL: TStringField; FDUsuarioLOGIN: TStringField; FDUsuarioSENHA: TStringField; FDUsuarioPERFIL: TStringField; private { Private declarations } public { Public declarations } end; function dmDados: TdmDados; implementation {$R *.dfm} uses UniGUIVars, uniGUIMainModule, MainModule; function dmDados: TdmDados; begin Result := TdmDados(UniMainModule.GetModuleInstance(TdmDados)); end; initialization RegisterModuleClass(TdmDados); end.
unit SFPHelper; interface uses Types, SysUtils, Classes, StreamUtil; const // SIMPLE FRAMED PROTOCOL // 0 1 SFP_FRAME_BOUND = $F0; // bnd SFP_ESCAPE_START = $F1; // esc SFP_ESCAPE_COMMAND_MIN = 0; // esc 00 SFP_ESCAPE_COMMAND_ECHO_FRAME_BOUND= $00; // esc 00 SFP_ESCAPE_COMMAND_ECHO_ESCAPE = $01; // esc 01 SFP_ESCAPE_COMMAND_MAX = $0F; // esc 0F DEFAULT_PIPE_BUFFER_SIZE = 1024; type ESFPInvalidPacket = class(Exception) end; ESFPEOF = class(Exception) end; TSFPHelper = class public class procedure internalWrite(dest: TStream; size: integer; buffer: pointer); class procedure internalRead (src : TStream; size: integer; buffer: pointer); class function internalReadRawFrame(src: TPushbackReadStream; waitForData: PBoolean = nil): TByteDynArray; class procedure writeFrameBound(dest: TStream); class procedure writeData (dest: TStream; size: longint; const buffer: pointer); class procedure writeFrame (dest: TStream; size: longint; const buffer: pointer); class function readFrame(src: TPushbackReadStream; waitForData: PBoolean = nil): TByteDynArray; overload; end; implementation uses Math; class procedure TSFPHelper.internalWrite(dest: TStream; size: integer; buffer: pointer); var count: longint; var p: pAnsiChar; var zeroCounter: integer; begin if size <= 0 then exit; zeroCounter:= 0; p:= buffer; repeat count:= dest.write(p^, min(DEFAULT_PIPE_BUFFER_SIZE, size)); if count = size then break; if 0 = count then begin if 0 < zeroCounter then begin sleep(100); zeroCounter:= 0; end else zeroCounter:= zeroCounter + 1; end; p:= p + count; size:= size - count; until false; end; class procedure TSFPHelper.internalRead(src: TStream; size: integer; buffer: pointer); var count: longint; var p: pAnsiChar; { var zeroCounter: integer; } begin if size <= 0 then exit; { zeroCounter:= 0; } p:= buffer; repeat count:= src.read(p^, size); if 0 = count then begin raise ESFPEOF.create('EOF'); { if 0 < zeroCounter then begin sleep(100); zeroCounter:= 0; end else zeroCounter:= zeroCounter + 1; } end; { if count <> size then sleep(100); } if count = size then break; p:= p + count; size:= size - count; until false; end; class procedure TSFPHelper.writeFrameBound(dest: TStream); const data: byte = SFP_FRAME_BOUND; begin internalWrite(dest, sizeof(data), @data) end; class procedure TSFPHelper.writeData (dest: TStream; size: longint; const buffer: pointer); const ESCAPE_CHAR : byte = SFP_ESCAPE_START ; const ECHO_FRAME_BOUND: byte = SFP_ESCAPE_COMMAND_ECHO_FRAME_BOUND; const ECHO_ESCAPE_CHAR: byte = SFP_ESCAPE_COMMAND_ECHO_ESCAPE ; var startChunk: pAnsiChar; var p : pAnsiChar; var chunkSize : integer; var totalLeft : integer; begin if size <= 0 then exit; startChunk:= buffer; chunkSize := 0; totalLeft := size; p:= startChunk + chunkSize; repeat if totalLeft = 0 then break; if (pbyte(p)^ = SFP_FRAME_BOUND ) or (pbyte(p)^ = SFP_ESCAPE_START) then begin internalWrite(dest, chunkSize, startChunk); internalWrite(dest, 1 , @ESCAPE_CHAR); if (pbyte(p)^ = SFP_FRAME_BOUND) then internalWrite(dest, 1 , @ECHO_FRAME_BOUND) else internalWrite(dest, 1 , @ECHO_ESCAPE_CHAR); //totalLeft:= totalLeft - chunkSize; startChunk:= p + 1; chunkSize:= 0; end else chunkSize:= chunkSize + 1; totalLeft:= totalLeft - 1; p:= p + 1; until false; if chunkSize > 0 then begin internalWrite(dest, chunkSize, startChunk); end; end; class procedure TSFPHelper.writeFrame (dest: TStream; size: longint; const buffer: pointer); begin writeFrameBound(dest); writeData (dest, size, buffer); writeFrameBound(dest); end; { class function TSFPHelper.internalReadRawFrame(src: TPushbackReadStream; waitForData: PBoolean = nil): TByteDynArray; var resultSize: integer; var test : byte ; begin if assigned(waitForData) then waitForData^:= false; resultSize:= 0; setLength(result, 1024 * 1024); repeat if 0 = src.read(test, 1) then begin setLength(result, 0); if 0 < resultSize then begin src.pushback(result, resultSize); end; if assigned(waitForData) then waitForData^:= true; exit; end; if SFP_FRAME_BOUND = test then begin setLength(result, resultSize); exit; end; resultSize:= resultSize + 1; if length(result) < resultSize then setLength(result, length(result) * 2); result[resultSize - 1]:= test; until false; end; } class function TSFPHelper.internalReadRawFrame(src: TPushbackReadStream; waitForData: PBoolean = nil): TByteDynArray; var temp : TByteDynArray; var resultSize: integer; var test : byte ; var readsize : integer; var i : integer; begin setlength(temp, 1024 * 1024); if assigned(waitForData) then waitForData^:= false; resultSize:= 0; setLength(result, 1024 * 1024); repeat //readSize:= src.read(temp[0], length(temp)); //readSize:= tryReadAvailableBytes(src, temp[0], length(temp)); readSize:= tryReadAvailableBytesOrLock(src, temp[0], length(temp)); if 0 = readSize then begin if 0 < resultSize then begin src.pushback(result[0], resultSize); end; if assigned(waitForData) then waitForData^:= true; setLength(result, 0); exit; end; for i:= 0 to readSize - 1 do begin test:= temp[i]; if SFP_FRAME_BOUND = test then begin setLength(result, resultSize); src.pushback(temp[i + 1], readSize - 1 - i); exit; end; resultSize:= resultSize + 1; if length(result) < resultSize then setLength(result, length(result) * 2); result[resultSize - 1]:= test; end; until false; end; class function TSFPHelper.readFrame(src: TPushbackReadStream; waitForData: PBoolean = nil): TByteDynArray; var total : integer; var index : integer; //var srcAnchor : integer; //var destAnchor: integer; begin result:= internalReadRawFrame(src, waitForData); { srcAnchor:= 0; destAnchor:= 0; } index:= 0; total:= length(result); while index < total do begin if result[index] = SFP_ESCAPE_START then begin { move(result[srcAnchor], result[destAnchor], index - srcAnchor); destAnchor:= destAnchor + index - srcAnchor; } index:= index + 1; if total <= index then raise ESFPInvalidPacket.create('Invalid packet: Terminated escape'); if result[index] = SFP_ESCAPE_COMMAND_ECHO_FRAME_BOUND then begin result[index - 1]:= SFP_FRAME_BOUND; { destAnchor:= destAnchor + 1; } end else if result[index] = SFP_ESCAPE_COMMAND_ECHO_ESCAPE then begin result[index - 1]:= SFP_ESCAPE_START; { destAnchor:= destAnchor + 1; } end else raise ESFPInvalidPacket.create('Invalid packet: Illegal escape echo code'); { srcAnchor:= index + 1; } if 0 < (total - index - 1) then move(result[index + 1], result[index], total - index - 1) else break; total:= total - 1; end else if result[index] = SFP_FRAME_BOUND then raise ESFPInvalidPacket.create('Invalid packet: Internal error: not filtered BND.') else index:= index + 1; end; { if srcAnchor < index then begin move(result[srcAnchor], result[destAnchor], index - srcAnchor); destAnchor:= destAnchor + index - srcAnchor; end; } setLength(result, total); end; end.
unit FSTree; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TFileSystemNode = class; { TFileSystem } TFileSystem = class(TComponent) private FRoot: TFileSystemNode; class function GetNodeSeparator: string; function GetRoot: TFileSystemNode; public function FindNodeByFileName(AFileName: string): TFileSystemNode; overload; function FindNodeByFileName(CurrentNode: TFileSystemNode; AFileName: string): TFileSystemNode; overload; property NodeSeparator: string read GetNodeSeparator; property Root: TFileSystemNode read GetRoot; end; { TFileSystemNode } TFileSystemNode = class(TComponent) private FFirstChild, FNext, FParent: TFileSystemNode; FSearchRecord: TSearchRec; function GetFileName: string; function GetFirstChild: TFileSystemNode; function GetNext: TFileSystemNode; function GetNodeName: string; function GetPrevious: TFileSystemNode; function GetRoot: TFileSystemNode; procedure SetPrevious(AValue: TFileSystemNode); procedure SetRoot(AValue: TFileSystemNode); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AFileSystem: TFileSystem; ANodeName: string); virtual; constructor Create(AFileSystem: TFileSystem; AParent: TFileSystemNode; ASearchRec: TSearchRec); virtual; destructor Destroy; override; function IsDirectory: Boolean; function IsValid: Boolean; property FileName: string read GetFileName; property FirstChild: TFileSystemNode read GetFirstChild; property Next: TFileSystemNode read GetNext; property NodeName: string read GetNodeName; property Parent: TFileSystemNode read FParent; property Previous: TFileSystemNode read GetPrevious write SetPrevious; property Root: TFileSystemNode read GetRoot write SetRoot; end; implementation uses Patch, Op; { TFileSystem } function TFileSystem.GetRoot: TFileSystemNode; begin if FRoot = nil then begin FRoot := TFileSystemNode.Create(Self, NodeSeparator); end; Result := FRoot; end; function TFileSystem.FindNodeByFileName(AFileName: string): TFileSystemNode; var Right, NN: string; begin NN := Parse(AFileName, NodeSeparator, Right); if NN = '' then begin Result := Root; if Right <> '' then Result := FindNodeByFileName(Root, Right) end else Exception.CreateFmt('"%s" is an invalid filename.', [AFileName]); end; function TFileSystem.FindNodeByFileName(CurrentNode: TFileSystemNode; AFileName: string): TFileSystemNode; var NN, Right: string; begin NN := Parse(AFileName, NodeSeparator, Right); while Right <> '' do {... Was fehlt hier?}; Result := CurrentNode.FirstChild; while NN <> '' do while Result <> nil do if Result.NodeName = NN then begin NN := Parse(Right, NodeSeparator, Right); if NN <> '' then begin Result := Result.FirstChild; Break end; end else Result := Result.Next; end; { TFileSystemNode } function TFileSystemNode.GetFileName: string; begin Result := NodeName; if Parent <> nil then Result := BuildFileName(Parent.FileName, Result) end; function TFileSystemNode.GetFirstChild: TFileSystemNode; var R: Longint; SR: TSearchRec; begin Result := nil; if Assigned(FFirstChild) then if FFirstChild.IsValid then Result := FFirstChild else begin FFirstChild.Free; Result := GetFirstChild end else if IsDirectory then begin R := FindFirst(BuildFileName(FileName, '*'), faAnyFile, SR); if R = 0 then begin FFirstChild := TFileSystemNode.Create(Owner as TFileSystem, Self, SR); FFirstChild.FreeNotification(Self); Result := FFirstChild end else FindClose(SR) end end; function TFileSystemNode.GetNext: TFileSystemNode; var R: Longint; SR: TSearchRec; begin Result := nil; if Assigned(FNext) then if FNext.IsValid then Result := FNext else begin FNext.Free; Result := GetNext end else begin SR := FSearchRecord; R := FindNext(SR); if R = 0 then begin FNext := TFileSystemNode.Create(Owner as TFileSystem, Parent, SR); FNext.FreeNotification(Self); Result := FNext end else begin FindClose(SR); end; end; end; function TFileSystemNode.GetNodeName: string; begin Result := FSearchRecord.Name; if Result = '' then Result := '/' end; function TFileSystemNode.GetPrevious: TFileSystemNode; var x: TFileSystemNode; begin Result := nil; if Self = Root then Exit; if Parent <> nil then begin x := Parent.FirstChild; if x = Self then Exit; while Assigned(x) do if x.Next = Self then begin Result := x; Break end else x := x.Next end end; function TFileSystemNode.GetRoot: TFileSystemNode; begin Result := (Owner as TFileSystem).Root end; procedure TFileSystemNode.SetPrevious(AValue: TFileSystemNode); begin if AValue = Previous then Exit; if Previous = Parent.FirstChild then begin Parent.FFirstChild.Free; Parent.FFirstChild := AValue; Parent.FFirstChild.FreeNotification(Self) end else with Previous.Previous do begin FNext.Free; FNext := AValue; FNext.FreeNotification(Self); end; end; procedure TFileSystemNode.SetRoot(AValue: TFileSystemNode); begin (Owner as TFileSystem).FRoot := AValue end; procedure TFileSystemNode.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); case Operation of opRemove: if AComponent <> nil then if AComponent = FFirstChild then begin FFirstChild.RemoveFreeNotification(Self); FFirstChild := nil end else if AComponent = FNext then begin FNext.RemoveFreeNotification(Self); FNext := nil end else if AComponent = FParent then begin FParent.RemoveFreeNotification(Self); end; end; end; class function TFileSystem.GetNodeSeparator: string; begin {$ifdef Windows} Result := '\' {$else} Result := '/' {$endif} end; constructor TFileSystemNode.Create(AFileSystem: TFileSystem; ANodeName: string); var SR: TSearchRec; R: Longint; begin inherited Create(AFileSystem); R := FindFirst(ANodeName, faAnyFile, SR); if R = 0 then begin FSearchRecord := SR; end else raise Exception.CreateFmt('File "%s" does not exist.', [ANodeName]) end; constructor TFileSystemNode.Create(AFileSystem: TFileSystem; AParent: TFileSystemNode; ASearchRec: TSearchRec); begin inherited Create(AFileSystem); FSearchRecord := ASearchRec; FParent := AParent; FParent.FreeNotification(Self); end; destructor TFileSystemNode.Destroy; begin FFirstChild.Free; FNext.Free; inherited Destroy; end; function TFileSystemNode.IsDirectory: Boolean; begin Result := FSearchRecord.Attr and faDirectory <> 0; end; function TFileSystemNode.IsValid: Boolean; begin if IsDirectory then Result := DirectoryExists(FileName) else Result := FileExists(FileName) end; end.