text
stringlengths
14
6.51M
unit transparency; //{$mode objfpc}{$H+} {$mode delphi} interface uses windows, graphics; type _MARGINS = packed record cxLeftWidth : Integer; cxRightWidth : Integer; cyTopHeight : Integer; cyBottomHeight : Integer; end; PMargins = ^_MARGINS; TMargins = _MARGINS; DwmIsCompositionEnabledFunc = function(pfEnabled: PBoolean): HRESULT; stdcall; DwmExtendFrameIntoClientAreaFunc = function(destWnd: HWND; const pMarInset: PMargins): HRESULT; stdcall; SetLayeredWindowAttributesFunc = function(destWnd: HWND; cKey: TColor; bAlpha: Byte; dwFlags: DWord): BOOL; stdcall; const WS_EX_LAYERED = $80000; LWA_COLORKEY = 1; function IsAeroEnabled: Boolean; function WindowsAeroGlassCompatible(): Boolean; procedure SetTransParent(aHandle: HWND; aColor: TColor); implementation function ISAeroEnabled: Boolean; var hDwmDLL: Cardinal; fDwmIsCompositionEnabled: DwmIsCompositionEnabledFunc; fDwmExtendFrameIntoClientArea: DwmExtendFrameIntoClientAreaFunc; fSetLayeredWindowAttributesFunc: SetLayeredWindowAttributesFunc; bCmpEnable: Boolean; // mgn: TMargins; begin result:=false; { Continue if Windows version is compatible } if WindowsAeroGlassCompatible then begin { Continue if 'dwmapi' library is loaded } hDwmDLL := LoadLibrary('dwmapi.dll'); if hDwmDLL <> 0 then begin { Get values } @fDwmIsCompositionEnabled := GetProcAddress(hDwmDLL, 'DwmIsCompositionEnabled'); @fDwmExtendFrameIntoClientArea := GetProcAddress(hDwmDLL, 'DwmExtendFrameIntoClientArea'); @fSetLayeredWindowAttributesFunc := GetProcAddress(GetModulehandle(user32), 'SetLayeredWindowAttributes'); { Continue if values are <> nil } if ( (@fDwmIsCompositionEnabled <> nil) and (@fDwmExtendFrameIntoClientArea <> nil) and (@fSetLayeredWindowAttributesFunc <> nil) ) then begin { Continue if composition is enabled } fDwmIsCompositionEnabled(@bCmpEnable); if bCmpEnable = True then begin result := true; end; end; { Free loaded 'dwmapi' library } FreeLibrary(hDWMDLL); end; end; end; function WindowsAeroGlassCompatible(): Boolean; var osVinfo: TOSVERSIONINFO; begin ZeroMemory(@osVinfo, SizeOf(osVinfo)); OsVinfo.dwOSVersionInfoSize := SizeOf(TOSVERSIONINFO); if ( (GetVersionEx(osVInfo) = True) and (osVinfo.dwPlatformId = VER_PLATFORM_WIN32_NT) and (osVinfo.dwMajorVersion >= 6) ) then Result:=True else Result:=False; end; procedure SetTransParent(aHandle: HWND; aColor: TColor); begin windows.SetWindowLong(aHandle, GWL_EXSTYLE, Getwindowlong(aHandle, GWL_EXSTYLE) or WS_EX_LAYERED); windows.SetLayeredWindowAttributes(aHandle, aColor,255, LWA_COLORKEY); end; 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.9 1/4/2005 5:27:20 PM JPMugaas Removed Windows unit from uses clause. Rev 1.8 04/01/2005 15:34:18 ANeillans Renamed InternalSend to RelayInternalSend, as it was conflicting with InternalSend in IdSMTPBase, and no e-mails were ever being sent. Some formatting and spelling corrections Rev 1.7 10/26/2004 10:55:34 PM JPMugaas Updated refs. Rev 1.6 2004.03.06 1:31:52 PM czhower To match Disconnect changes to core. Rev 1.5 2004.02.07 4:57:20 PM czhower Fixed warning. Rev 1.4 2004.02.03 5:45:48 PM czhower Name changes Rev 1.3 1/21/2004 4:03:26 PM JPMugaas InitComponent Rev 1.2 11/4/2003 10:22:56 PM DSiders Use IdException for exceptions moved to the unit. Rev 1.1 2003.10.18 9:42:14 PM czhower Boatload of bug fixes to command handlers. Rev 1.0 6/15/2003 03:27:18 PM JPMugaas Renamed IdDirect SMTP to IdSMTPRelay. Rev 1.15 6/15/2003 01:09:30 PM JPMugaas Now uses new base class in TIdSMTPBase. I removed the old original unoptimized code that made a connection for each recipient for better maintenance and because I doubt anyone would use that anyway. Rev 1.14 6/5/2003 04:54:16 AM JPMugaas Reworkings and minor changes for new Reply exception framework. Rev 1.13 5/26/2003 12:21:50 PM JPMugaas Rev 1.12 5/25/2003 03:54:12 AM JPMugaas Rev 1.11 5/25/2003 01:41:08 AM JPMugaas Sended changed to Sent. TryImplicitTLS now will only be true if UseSSL<>NoSSL. UseEHLO=False will now disable TLS usage and TLS usage being set causes UseEHLO to be true. StatusItem collection Items now have default values for Sent and ReplyCode. Rev 1.10 5/25/2003 12:40:34 AM JPMugaas Published events from TIdExplicitTLSClient to be consistant with other components in Indy and for any custom handling of certain TLS negotiatiation problems. Rev 1.9 5/25/2003 12:17:16 AM JPMugaas Now can support SSL (either requiring SSL or using it if available). This is in addition, it can optionally support ImplicitTLS (note that I do not recommend this because that is depreciated -and the port for it was deallocated and this does incur a performance penalty with an additional connect attempt - and possibly a timeout in some firewall situations). Rev 1.8 5/23/2003 7:48:12 PM BGooijen TIdSMTPRelayStatusItem.FEnhancedCode object was not created Rev 1.7 5/23/2003 05:02:42 AM JPMugaas Rev 1.6 5/23/2003 04:52:22 AM JPMugaas Work started on TIdSMTPRelay to support enhanced error codes. Rev 1.5 5/18/2003 02:31:50 PM JPMugaas Reworked some things so IdSMTP and IdDirectSMTP can share code including stuff for pipelining. Rev 1.4 4/28/2003 03:36:22 PM JPMugaas Revered back to the version I checked in earlier because of my API changes to the DNS classes. Rev 1.2 4/28/2003 07:00:02 AM JPMugaas Should now compile. Rev 1.1 12/6/2002 02:35:22 PM JPMugaas Now compiles with Indy 10. Rev 1.0 11/14/2002 02:17:28 PM JPMugaas } unit IdSMTPRelay; { Original Author: Maximiliano Di Rienzo dirienzo@infovia.com.ar Variation of the TIdSMTP that connects directly with the recipient's SMTP server and delivers the message, it doesn't use a relay SMTP server to deliver the message. Hides the procs Connect and Disconnect (protected now) because these are called internally to connect to the dynamically resolved host based on the MX server of the recipient's domain. The procs related to the auth schema have been removed because they aren't needed. Introduces the property property StatusList:TIdSMTPRelayStatusList; it's a collection containing the status of each recipient's address after the Send method is called and the event property OnDirectSMTPStatus:TIdSMTPRelayStatus; to keep track of the status as the sending is in progress. } interface {$i IdCompilerDefines.inc} uses Classes, IdAssignedNumbers, IdException, IdExceptionCore, IdEMailAddress, IdGlobal, IdHeaderList, IdDNSResolver, IdMessage, IdMessageClient, IdBaseComponent, IdSMTPBase, IdReplySMTP, SysUtils; const DEF_OneConnectionPerDomain = True; type TIdSMTPRelayStatusAction = (dmResolveMS, dmConnecting, dmConnected, dmSending, dmWorkBegin, dmWorkEndOK, dmWorkEndWithException); TIdSMTPRelayStatus = procedure(Sender: TObject; AEMailAddress: TIdEmailAddressItem; Action: TIdSMTPRelayStatusAction) of Object; EIdDirectSMTPCannotAssignHost = class(EIdException); EIdDirectSMTPCannotResolveMX = class(EIdException); TIdSSLSupport = (NoSSL, SupportSSL, RequireSSL); const DEF_SSL_SUPPORT = NoSSL; DEF_TRY_IMPLICITTLS = False; DEF_REPLY_CODE = 0; DEF_SENT = False; type TIdSMTPRelayStatusItem = class(TCollectionItem) protected FSent: Boolean; FExceptionMessage: String; FEmailAddress: String; FReplyCode : Integer; FEnhancedCode : TIdSMTPEnhancedCode; procedure SetEnhancedCode(const Value: TIdSMTPEnhancedCode); public constructor Create(Collection: TCollection); override; destructor Destroy; override; published property EmailAddress: String read FEmailAddress write FEmailAddress; property ExceptionMessage: String read FExceptionMessage write FExceptionMessage; property Sent: Boolean read FSent write FSent default DEF_SENT; property ReplyCode : Integer read FReplyCode write FReplyCode default DEF_REPLY_CODE; property EnhancedCode : TIdSMTPEnhancedCode read FEnhancedCode write SetEnhancedCode; end; TIdSMTPRelayStatusList = class(TOwnedCollection) protected function GetItems(Index: Integer): TIdSMTPRelayStatusItem; procedure SetItems(Index: Integer;const Value: TIdSMTPRelayStatusItem); public function Add : TIdSMTPRelayStatusItem; property Items[Index: Integer]: TIdSMTPRelayStatusItem read GetItems write SetItems; default; end; TIdSMTPRelay = class; TIdSSLSupportOptions = class(TIdBaseComponent) protected FSSLSupport : TIdSSLSupport; FTryImplicitTLS : Boolean; FOwner : TIdSMTPRelay; procedure SetSSLSupport(const Value: TIdSSLSupport); procedure SetTryImplicitTLS(const Value: Boolean); public constructor Create(AOwner : TIdSMTPRelay); procedure Assign(Source: TPersistent); override; published property SSLSupport : TIdSSLSupport read FSSLSupport write SetSSLSupport default DEF_SSL_SUPPORT; property TryImplicitTLS : Boolean read FTryImplicitTLS write SetTryImplicitTLS default DEF_TRY_IMPLICITTLS; end; TIdSMTPRelay = class(TIdSMTPBase) protected FMXServerList: TStrings; FStatusList: TIdSMTPRelayStatusList; FDNSServer: String; FOnDirectSMTPStatus: TIdSMTPRelayStatus; FSSLOptions : TIdSSLSupportOptions; FRelaySender: String; procedure Connect(AEMailAddress : TIdEMailAddressItem); reintroduce; procedure ResolveMXServers(AAddress:String); procedure SetDNSServer(const Value: String); procedure SetOnStatus(const Value: TIdSMTPRelayStatus); procedure SetUseEhlo(const AValue : Boolean); override; procedure SetHost(const Value: String); override; function GetSupportsTLS : boolean; override; procedure ProcessException(AException: Exception; AEMailAddress : TIdEMailAddressItem); procedure SetSSLOptions(const Value: TIdSSLSupportOptions); procedure SetRelaySender(const Value: String); // procedure InitComponent; override; // // holger: .NET compatibility change property Port; public procedure Assign(Source: TPersistent); override; destructor Destroy; override; procedure DisconnectNotifyPeer; override; procedure Send(AMsg: TIdMessage; ARecipients: TIdEMailAddressList); override; published property DNSServer: String read FDNSServer write SetDNSServer; property RelaySender: String read FRelaySender write SetRelaySender; property StatusList: TIdSMTPRelayStatusList read FStatusList; property SSLOptions: TIdSSLSupportOptions read FSSLOptions write SetSSLOptions; property OnDirectSMTPStatus: TIdSMTPRelayStatus read FOnDirectSMTPStatus write SetOnStatus; property OnTLSHandShakeFailed; property OnTLSNotAvailable; property OnTLSNegCmdFailed; end; implementation uses IdGlobalProtocols, IdStack, IdCoderMIME, IdDNSCommon, IdResourceStringsProtocols, IdExplicitTLSClientServerBase, IdSSL, IdStackConsts, IdTCPClient, IdTCPConnection; { TIdSMTPRelay } procedure TIdSMTPRelay.Assign(Source: TPersistent); begin if Source is TIdSMTPRelay then begin MailAgent := TIdSMTPRelay(Source).MailAgent; Port := TIdSMTPRelay(Source).Port; DNSServer := TIdSMTPRelay(Source).DNSServer; end else begin inherited Assign(Source); end; end; procedure TIdSMTPRelay.Connect(AEMailAddress : TIdEMailAddressItem); var LCanImplicitTLS: Boolean; begin LCanImplicitTLS := Self.FSSLOptions.TryImplicitTLS; if LCanImplicitTLS then begin try UseTLS := utUseImplicitTLS; inherited Connect; except on E: EIdSocketError do begin // If 10061 - connection refused - retry without ImplicitTLS // If 10060 - connection timed out - retry without ImplicitTLS if (E.LastError = Id_WSAECONNREFUSED) or (E.LastError = Id_WSAETIMEDOUT) then begin LCanImplicitTLS := False; end else begin raise; end; end; end; end; if not LCanImplicitTLS then begin case Self.FSSLOptions.FSSLSupport of SupportSSL : FUseTLS := utUseExplicitTLS; RequireSSL : FUseTLS := utUseRequireTLS; else FUseTLS := utNoTLSSupport; end; inherited Connect; end; try GetResponse([220]); SendGreeting; StartTLS; except on E : Exception do begin ProcessException(E,AEMailAddress); Disconnect; raise; end; end; end; procedure TIdSMTPRelay.InitComponent; begin inherited InitComponent; FSSLOptions := TIdSSLSupportOptions.Create(Self); FMXServerList := TStringList.Create; FStatusList := TIdSMTPRelayStatusList.Create(Self, TIdSMTPRelayStatusItem); end; destructor TIdSMTPRelay.Destroy; begin FreeAndNil(FSSLOptions); FreeAndNil(FMXServerList); FreeAndNil(FStatusList); inherited Destroy; end; procedure TIdSMTPRelay.DisconnectNotifyPeer; begin inherited DisconnectNotifyPeer; SendCmd('QUIT', 221); {Do not Localize} end; function TIdSMTPRelay.GetSupportsTLS: boolean; begin Result := ( FCapabilities.IndexOf('STARTTLS') > -1 ); //do not localize end; procedure TIdSMTPRelay.ProcessException(AException: Exception; AEMailAddress : TIdEMailAddressItem); var LE: EIdSMTPReplyError; begin with FStatusList.Add do begin EmailAddress := AEmailAddress.Address; Sent := False; ExceptionMessage := AException.Message; if AException is EIdSMTPReplyError then begin LE := AException as EIdSMTPReplyError; ReplyCode := LE.ErrorCode; EnhancedCode.ReplyAsStr := LE.EnhancedCode.ReplyAsStr; end; end; if Assigned(FOnDirectSMTPStatus) then begin FOnDirectSMTPStatus(Self, AEmailAddress, dmWorkEndWithException); end; end; procedure TIdSMTPRelay.ResolveMXServers(AAddress: String); var IdDNSResolver1: TIdDNSResolver; DnsResource : TResultRecord; LMx: TMxRecord; LDomain:String; i: Integer; iPref: Word; begin { Get the list of MX Servers for a given domain into FMXServerList } i := Pos('@', AAddress); if i = 0 then begin raise EIdDirectSMTPCannotResolveMX.CreateFmt(RSDirSMTPInvalidEMailAddress, [AAddress]); end; LDomain := Copy(AAddress, i+1, MaxInt); IdDNSResolver1 := TIdDNSResolver.Create(Self); try FMXServerList.Clear; IdDNSResolver1.AllowRecursiveQueries := True; if Assigned(IOHandler) and (IOHandler.ReadTimeOut > 0) then begin //thirty seconds - maximum amount of time allowed for DNS query IdDNSResolver1.WaitingTime := IOHandler.ReadTimeout; end else begin IdDNSResolver1.WaitingTime := 30000; end; IdDNSResolver1.QueryType := [qtMX]; IdDNSResolver1.Host := DNSServer; IdDNSResolver1.Resolve(LDomain); if IdDNSResolver1.QueryResult.Count > 0 then begin iPref := High(Word); for i := 0 to IdDNSResolver1.QueryResult.Count - 1 do begin DnsResource := IdDNSResolver1.QueryResult[i]; if (DnsResource is TMXRecord) then begin LMx := TMXRecord(DnsResource); // lower preference values at top of the list // could use AddObject and CustomSort, or TIdBubbleSortStringList // currently inserts lower values at top if LMx.Preference < iPref then begin iPref := LMx.Preference; FMXServerList.Insert(0, LMx.ExchangeServer); end else begin FMXServerList.Add(LMx.ExchangeServer); end; end; end; end; if FMXServerList.Count = 0 then begin raise EIdDirectSMTPCannotResolveMX.CreateFmt(RSDirSMTPNoMXRecordsForDomain, [LDomain]); end; finally FreeAndNil(IdDNSResolver1); end; end; procedure TIdSMTPRelay.Send(AMsg: TIdMessage; ARecipients: TIdEMailAddressList); var LAllEntries, LCurDomEntries: TIdEMailAddressList; SDomains: TStrings; LFrom: String; i: Integer; procedure RelayInternalSend(const ALMsg: TIdMessage; const AFrom: String; const AEmailAddresses: TIdEMailAddressList); var ServerIndex:Integer; EMailSent: Boolean; begin if AEmailAddresses.Count = 0 then begin Exit; end; EMailSent := False; if Assigned(FOnDirectSMTPStatus) then begin FOnDirectSMTPStatus(Self, AEmailAddresses[0], dmWorkBegin); end; try try if Assigned(FOnDirectSMTPStatus) then begin FOnDirectSMTPStatus(Self, AEmailAddresses[0], dmResolveMS); end; ResolveMXServers(AEMailAddresses[0].Address); ServerIndex := 0; while (ServerIndex <= FMXServerList.Count - 1) and (not EMailSent) do begin FHost := FMXServerList[ServerIndex]; try if Connected then begin Disconnect; end; if Assigned(FOnDirectSMTPStatus) then begin FOnDirectSMTPStatus(Self, AEmailAddresses[0], dmConnecting); end; Connect(AEmailAddresses[0]); if Assigned(FOnDirectSMTPStatus) then begin FOnDirectSMTPStatus(Self, AEmailAddresses[0], dmConnected); end; if Assigned(FOnDirectSMTPStatus) then begin FOnDirectSMTPStatus(Self, AEmailAddresses[0], dmSending); end; if Trim(MailAgent) <> '' then begin ALMsg.Headers.Values[XMAILER_HEADER] := Trim(MailAgent); end; InternalSend(ALMsg, AFrom, AEmailAddresses); EMailSent := True; with FStatusList.Add do begin EmailAddress := AEmailAddresses[0].Address; Sent := True; end; if Assigned(FOnDirectSMTPStatus) then begin FOnDirectSMTPStatus(Self, AEmailAddresses[0], dmWorkEndOK); end; except // Sit on the error, and move on to the next server. Inc(ServerIndex); end; end; if (not Connected) and (not EMailSent) then // If we were unable to connect to all the servers, throw exception begin raise EIdTCPConnectionError.CreateFmt(RSDirSMTPCantConnectToSMTPSvr, [AEmailAddresses[0].Address]); end; except on E : Exception do begin ProcessException(E, AEmailAddresses[0]); end; end; finally Disconnect; end; end; begin if Trim(FRelaySender) <> '' then begin LFrom := FRelaySender; end else begin LFrom := AMsg.From.Address; end; if Assigned(ARecipients) then begin LAllEntries := ARecipients; end else begin LAllEntries := TIdEMailAddressList.Create(nil); end; try if not Assigned(ARecipients) then begin LAllEntries.AddItems(AMsg.Recipients); LAllEntries.AddItems(AMsg.CCList); LAllEntries.AddItems(AMsg.BccList); end; SDomains := TStringList.Create; try LAllEntries.GetDomains(SDomains); LCurDomEntries := TIdEMailAddressList.Create(nil); try for i := 0 to SDomains.Count -1 do begin LAllEntries.AddressesByDomain(LCurDomEntries, SDomains[i]); RelayInternalSend(AMsg, LFrom, LCurDomEntries); end; finally FreeAndNil(LCurDomEntries); end; finally FreeAndNil(SDomains); end; finally if not Assigned(ARecipients) then begin FreeAndNil(LAllEntries); end; end; end; procedure TIdSMTPRelay.SetDNSServer(const Value: String); begin FDNSServer := Value; end; procedure TIdSMTPRelay.SetHost(const Value: String); begin raise EIdDirectSMTPCannotAssignHost.Create(RSDirSMTPCantAssignHost); end; procedure TIdSMTPRelay.SetOnStatus(const Value: TIdSMTPRelayStatus); begin FOnDirectSMTPStatus := Value; end; procedure TIdSMTPRelay.SetSSLOptions(const Value: TIdSSLSupportOptions); begin FSSLOptions.Assign(Value); end; procedure TIdSMTPRelay.SetUseEhlo(const AValue: Boolean); begin inherited; FSSLOptions.FSSLSupport := noSSL; end; procedure TIdSMTPRelay.SetRelaySender(const Value: String); begin FRelaySender := Value; end; { TIdSMTPRelayStatusList } function TIdSMTPRelayStatusList.Add: TIdSMTPRelayStatusItem; begin Result := TIdSMTPRelayStatusItem(inherited Add); end; function TIdSMTPRelayStatusList.GetItems(Index: Integer): TIdSMTPRelayStatusItem; begin Result := TIdSMTPRelayStatusItem(inherited Items[Index]); end; procedure TIdSMTPRelayStatusList.SetItems(Index: Integer; const Value: TIdSMTPRelayStatusItem); begin Items[Index].Assign(Value); end; { TIdSMTPRelayStatusItem } constructor TIdSMTPRelayStatusItem.Create(Collection: TCollection); begin inherited Create(Collection); FEnhancedCode := TIdSMTPEnhancedCode.Create; FSent := DEF_SENT; FReplyCode := DEF_REPLY_CODE; end; destructor TIdSMTPRelayStatusItem.Destroy; begin FreeAndNil(FEnhancedCode); inherited Destroy; end; procedure TIdSMTPRelayStatusItem.SetEnhancedCode( const Value: TIdSMTPEnhancedCode); begin FEnhancedCode.ReplyAsStr := Value.ReplyAsStr; end; { TIdSSLSupportOptions } procedure TIdSSLSupportOptions.Assign(Source: TPersistent); var LS: TIdSSLSupportOptions; begin if (Source is TIdSSLSupportOptions) then begin LS := TIdSSLSupportOptions(Source); SSLSupport := LS.FSSLSupport; TryImplicitTLS := LS.TryImplicitTLS; end else begin inherited Assign(Source); end; end; constructor TIdSSLSupportOptions.Create(AOwner: TIdSMTPRelay); begin inherited Create; FOwner := AOwner; FSSLSupport := DEF_SSL_SUPPORT; FTryImplicitTLS := DEF_TRY_IMPLICITTLS; end; procedure TIdSSLSupportOptions.SetSSLSupport(const Value: TIdSSLSupport); begin if (Value <> noSSL) and (not IsLoading) then begin FOwner.CheckIfCanUseTLS; end; if (Value <> noSSL) and (not FOwner.UseEhlo) then begin FOwner.FUseEHLO := True; end; if (Value = noSSL) then begin FTryImplicitTLS := False; end; FSSLSupport := Value; end; procedure TIdSSLSupportOptions.SetTryImplicitTLS(const Value: Boolean); begin if Value and (not IsLoading) then begin FOwner.CheckIfCanUseTLS; end; if Value and (Self.FSSLSupport=NoSSL) then begin SSLSupport := SupportSSL; end; FTryImplicitTLS := Value; end; end.
unit uUsuarioPermissaoController; interface uses System.SysUtils, uDMModulo, uRegras, uEnumerador, uDM, Data.DB, System.Generics.Collections, uDMUsuario, Data.DBXJSON , Data.DBXJSONReflect, uUsuarioPermissaoVO, uConverter, System.Variants; type TUsuarioPermissaoController = class private FModel: TDMUsuario; public function PreencherLista: TList<string>; procedure LocalizarUsuario(IdUsuario: Integer); procedure Exportar(); function PermissaoSigla(ASigla: string): Boolean; function ObterPorSigla(AIdUsuario: Integer; ASigla: string): Boolean; property Model: TDMUsuario read FModel write FModel; constructor Create(); destructor Destroy; override; end; implementation { TUsuarioPermissaoController } constructor TUsuarioPermissaoController.Create; begin inherited Create; FModel := TDMUsuario.Create(nil); end; destructor TUsuarioPermissaoController.Destroy; begin FreeAndNil(FModel); inherited; end; procedure TUsuarioPermissaoController.Exportar(); var Negocio: TServerMethods1Client; oObjetoJSON : TJSONValue; lista: TObjectList<TUsuarioPermissaoVO>; model: TUsuarioPermissaoVO; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try lista := TConverte.JSONToObject<TListaUsuarioPermissao>(Negocio.UsuarioPermissaoExportar()); for model in lista do begin dm.cdsUsuarioPermissao.Append; dm.cdsUsuarioPermissaoId.AsInteger := model.Id; dm.cdsUsuarioPermissaoIdUsuario.AsInteger := model.IdUsuario; dm.cdsUsuarioPermissaoSigla.AsString := model.Sigla; dm.cdsUsuarioPermissao.Post; end; dm.Desconectar; finally FreeAndNil(Negocio); FreeAndNil(lista); end; end; procedure TUsuarioPermissaoController.LocalizarUsuario(IdUsuario: Integer); begin FModel.CDSListarPermissaoListar.Close; FModel.CDSListarPermissaoListar.Params[0].AsInteger := IdUsuario; FModel.CDSListarPermissaoListar.Open; end; function TUsuarioPermissaoController.ObterPorSigla(AIdUsuario: Integer; ASigla: string): Boolean; begin Result := dm.cdsUsuarioPermissao.Locate('UsuP_Id; UsuP_Sigla', VarArrayOf([IntToStr(AIdUsuario), ASigla]), []); end; function TUsuarioPermissaoController.PermissaoSigla(ASigla: string): Boolean; begin Result := dm.cdsUsuarioPermissao.Locate('Sigla', ASigla, []); end; function TUsuarioPermissaoController.PreencherLista: TList<string>; var lista: TList<string>; // Negocio: TServerMethods1Client; begin lista := TList<string>.Create; lista.Add('Lib_Chamado_Ocorr_Alt_Data_Hora'); lista.Add('Lib_Chamado_Ocorr_Alt'); lista.Add('Lib_Chamado_Ocorr_Exc'); Result := lista; end; end.
unit vtDialogsRes; // Модуль: "w:\common\components\gui\Garant\VT\vtDialogsRes.pas" // Стереотип: "UtilityPack" // Элемент модели: "vtDialogsRes" MUID: (4B8E6793024B) {$Include w:\common\components\gui\Garant\VT\vtDefine.inc} interface uses l3IntfUses , l3StringIDEx ; const {* Локализуемые строки TvtMiscMessages } str_vtDefaultOpenDlgFilter: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtDefaultOpenDlgFilter'; rValue : 'Все файлы|*.*'); {* 'Все файлы|*.*' } {$If NOT Defined(Nemesis)} {* Локализуемые строки MsgDlg } str_vtMsgDlgWarning: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgWarning'; rValue : 'Warning'); {* 'Warning' } str_vtMsgDlgError: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgError'; rValue : 'Error'); {* 'Error' } str_vtMsgDlgInformation: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgInformation'; rValue : 'Information'); {* 'Information' } str_vtMsgDlgConfirm: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgConfirm'; rValue : 'Confirm'); {* 'Confirm' } {$IfEnd} // NOT Defined(Nemesis) {$If Defined(Nemesis)} const {* Локализуемые строки MsgDlgNemesis } str_vtMsgDlgWarning: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgWarning'; rValue : 'Предупреждение'); {* 'Предупреждение' } str_vtMsgDlgError: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgError'; rValue : 'Ошибка'); {* 'Ошибка' } str_vtMsgDlgInformation: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgInformation'; rValue : 'Информация'); {* 'Информация' } str_vtMsgDlgConfirm: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgConfirm'; rValue : 'Подтверждение'); {* 'Подтверждение' } {$IfEnd} // Defined(Nemesis) const {* Локализуемые строки Custom } str_vtMsgDlgCustom: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgCustom'; rValue : ''); {* '' } {* Локализуемые строки MsgDlgButtons } str_vtMsgDlgYes: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgYes'; rValue : '&Да'); {* '&Да' } str_vtMsgDlgNo: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgNo'; rValue : '&Нет'); {* '&Нет' } str_vtMsgDlgOK: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgOK'; rValue : 'OK'); {* 'OK' } str_vtMsgDlgCancel: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgCancel'; rValue : '&Отмена'); {* '&Отмена' } str_vtMsgDlgAbort: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgAbort'; rValue : '&Прервать'); {* '&Прервать' } str_vtMsgDlgRetry: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgRetry'; rValue : 'Пов&торить'); {* 'Пов&торить' } str_vtMsgDlgIgnore: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgIgnore'; rValue : '&Игнорировать'); {* '&Игнорировать' } str_vtMsgDlgAll: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgAll'; rValue : '&Все'); {* '&Все' } str_vtMsgDlgNoToAll: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgNoToAll'; rValue : '&Нет для всех'); {* '&Нет для всех' } str_vtMsgDlgYesToAll: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgYesToAll'; rValue : '&Да для всех'); {* '&Да для всех' } str_vtMsgDlgHelp: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgHelp'; rValue : '&Справка'); {* '&Справка' } implementation uses l3ImplUses //#UC START# *4B8E6793024Bimpl_uses* //#UC END# *4B8E6793024Bimpl_uses* ; initialization str_vtDefaultOpenDlgFilter.Init; {* Инициализация str_vtDefaultOpenDlgFilter } {$If NOT Defined(Nemesis)} str_vtMsgDlgWarning.Init; {* Инициализация str_vtMsgDlgWarning } {$IfEnd} // NOT Defined(Nemesis) {$If NOT Defined(Nemesis)} str_vtMsgDlgError.Init; {* Инициализация str_vtMsgDlgError } {$IfEnd} // NOT Defined(Nemesis) {$If NOT Defined(Nemesis)} str_vtMsgDlgInformation.Init; {* Инициализация str_vtMsgDlgInformation } {$IfEnd} // NOT Defined(Nemesis) {$If NOT Defined(Nemesis)} str_vtMsgDlgConfirm.Init; {* Инициализация str_vtMsgDlgConfirm } {$IfEnd} // NOT Defined(Nemesis) {$If Defined(Nemesis)} str_vtMsgDlgWarning.Init; {* Инициализация str_vtMsgDlgWarning } {$IfEnd} // Defined(Nemesis) {$If Defined(Nemesis)} str_vtMsgDlgError.Init; {* Инициализация str_vtMsgDlgError } {$IfEnd} // Defined(Nemesis) {$If Defined(Nemesis)} str_vtMsgDlgInformation.Init; {* Инициализация str_vtMsgDlgInformation } {$IfEnd} // Defined(Nemesis) {$If Defined(Nemesis)} str_vtMsgDlgConfirm.Init; {* Инициализация str_vtMsgDlgConfirm } {$IfEnd} // Defined(Nemesis) str_vtMsgDlgCustom.Init; {* Инициализация str_vtMsgDlgCustom } str_vtMsgDlgYes.Init; {* Инициализация str_vtMsgDlgYes } str_vtMsgDlgNo.Init; {* Инициализация str_vtMsgDlgNo } str_vtMsgDlgOK.Init; {* Инициализация str_vtMsgDlgOK } str_vtMsgDlgCancel.Init; {* Инициализация str_vtMsgDlgCancel } str_vtMsgDlgAbort.Init; {* Инициализация str_vtMsgDlgAbort } str_vtMsgDlgRetry.Init; {* Инициализация str_vtMsgDlgRetry } str_vtMsgDlgIgnore.Init; {* Инициализация str_vtMsgDlgIgnore } str_vtMsgDlgAll.Init; {* Инициализация str_vtMsgDlgAll } str_vtMsgDlgNoToAll.Init; {* Инициализация str_vtMsgDlgNoToAll } str_vtMsgDlgYesToAll.Init; {* Инициализация str_vtMsgDlgYesToAll } str_vtMsgDlgHelp.Init; {* Инициализация str_vtMsgDlgHelp } end.
unit uAmsoftBackup; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs, Vcl.ImgList, Vcl.Menus, Vcl.ExtCtrls, System.Win.Registry, System.UITypes, System.DateUtils, Vcl.Forms, IBServices, uBackupThread, ShellApi; const wm_IconMessage = wm_User; type THorario = packed record Hora: TTime; Feito: Boolean; Agendado: Boolean; end; TfrmAmsoftBackup = class(TService) TrayIcon1: TTrayIcon; ImageList1: TImageList; procedure ServiceCreate(Sender: TObject); procedure ServiceExecute(Sender: TService); procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceStop(Sender: TService; var Stopped: Boolean); procedure ServiceShutdown(Sender: TService); procedure ServiceAfterUninstall(Sender: TService); procedure ServiceAfterInstall(Sender: TService); private BackupThread : TBackupThread; FLogado : Boolean; procedure ServiceStopShutdown; public function GetServiceController: TServiceController; override; { Public declarations } end; var frmAmsoftBackup: TfrmAmsoftBackup; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.DFM} uses uMonitor; procedure ServiceController(CtrlCode: DWord); stdcall; begin frmAmsoftBackup.Controller(CtrlCode); end; function TfrmAmsoftBackup.GetServiceController: TServiceController; begin Result := ServiceController; end; procedure TfrmAmsoftBackup.ServiceAfterInstall(Sender: TService); var sVar: Boolean; begin sVar:= True; // if Status = csStopped then // begin // ServiceStart(Self, sVar); // Status := csRunning; // end; end; procedure TfrmAmsoftBackup.ServiceAfterUninstall(Sender: TService); begin FLogado := False; TrayIcon1.BalloonHint := 'Servišo de backup AMERICA SOFT desinstalado!'; TrayIcon1.Animate := True; TrayIcon1.ShowBalloonHint; Sleep(5000); end; procedure TfrmAmsoftBackup.ServiceCreate(Sender: TObject); var sVar: Boolean; begin sVar := True; TrayIcon1.BalloonHint := 'Servišo AMERICA SOFT'; TrayIcon1.Animate := True; TrayIcon1.ShowBalloonHint; Sleep(5000); if Status = csStopped then begin ServiceStart(Self, sVar); Status := csRunning; end; end; procedure TfrmAmsoftBackup.ServiceExecute(Sender: TService); var sVar: Boolean; begin sVar := True; if Status = csStopped then begin ServiceStart(Self, sVar); Status := csRunning; end; while (not self.Terminated) and (FLogado) do begin TrayIcon1.BalloonHint := 'Executando Copia de Seguranša'; TrayIcon1.Animate := True; TrayIcon1.ShowBalloonHint; Sleep(5000); end; if not FLogado then Self.Status := csStopped; end; procedure TfrmAmsoftBackup.ServiceShutdown(Sender: TService); begin ServiceStopShutdown; end; procedure TfrmAmsoftBackup.ServiceStart(Sender: TService; var Started: Boolean); begin ShellExecute(Application.Handle,'',PWideChar(ExtractFilePath(Application.ExeName) + 'MonitorBackup.exe'),'','',SW_SHOWNORMAL); ReportStatus; end; procedure TfrmAmsoftBackup.ServiceStop(Sender: TService; var Stopped: Boolean); begin ServiceStopShutdown; end; procedure TfrmAmsoftBackup.ServiceStopShutdown; begin if Assigned(frmMonitor) then begin Sleep(1000); // ServiceThread.ProcessRequests(False); TrayIcon1.BalloonHint := 'Finalizou backup AMERICA SOFT'; TrayIcon1.Animate := True; TrayIcon1.ShowBalloonHint; Sleep(5000); frmMonitor.Close; end; end; end.
//============================================================================= // sgEventProcessing.pas //============================================================================= // // This unit handles the processing of events, including the reading of text // for SwinGames. This unit and its code is not directly used by typical games. // // An object of the TSDLManager is created and managed in sgCore. Only one // instance should be used (essentially a "singleton" pattern), which is // available in the sdlManager as a global variable. // // Change History: // Version 3: // - 2010-02-11: Andrew : Added key repeat and fixed cursor for 0 length strings // - 2010-02-02: Andrew : Added the ability to define a region for text entry // - 2010-01-13: Cooldave: Fixed error with Bar in SetText. // - 2009-06-23: Clinton: Renamed file/unit, comment/format cleanup/tweaks // // Version 2.0.0: // - 2008-12-17: Andrew: Moved all integers to LongInt // - 2008-12-16: Andrew: Added any key press // Added SetText // // Version 1.1.5: // - 2008-04-18: Andrew: Added EndTextRead // // Version 1.0: // - Various //============================================================================= unit sgEventProcessing; //============================================================================= interface //============================================================================= uses Classes, SDL, SDL_Mixer, SysUtils, SDL_TTF; type KeyDownData = record downAt: LongInt; code: LongInt; keyChar: LongInt; end; EventProcessPtr = procedure(event: PSDL_Event); EventStartProcessPtr = procedure(); TSDLManager = class(TObject) private // private data _quit: Boolean; _keyPressed: Boolean; _readingString: Boolean; _textCancelled: Boolean; _tempString: String; _textSurface: PSDL_Surface; _cursorSurface: PSDL_Surface; _maxStringLen: LongInt; _font: PTTF_Font; _foreColor: TSDL_Color; _area: SDL_Rect; _lastKeyRepeat: LongInt; _KeyDown: Array of KeyDownData; _KeyTyped: Array of LongInt; _EventProcessors: Array of EventProcessPtr; _EventStartProcessors: Array of EventStartProcessPtr; // private methods procedure DoQuit(); procedure CheckQuit(); procedure HandleEvent(event: PSDL_Event); procedure HandleKeydownEvent(event: PSDL_Event); procedure AddKeyData(kyCode, kyChar: LongInt); procedure HandleKeyupEvent(event: PSDL_Event); procedure ProcessKeyPress(keyCode, keyChar: LongInt); procedure CheckKeyRepeat(); public // text reading/draw collection property MaxStringLength: LongInt read _maxStringLen write _maxStringLen; property EnteredString: String read _tempString write _tempString; property IsReading: Boolean read _readingString; property TextEntryWasCancelled: Boolean read _textCancelled; procedure DrawCollectedText(dest: PSDL_Surface); procedure SetText(text: String); procedure StartReadingText(textColor: TSDL_Color; maxLength: LongInt; theFont: PTTF_Font; area: SDL_Rect); function EndReadingText(): String; // key pressed/typed tests function WasKeyTyped(keyCode: LongInt): Boolean; function IsKeyPressed(virtKeyCode: LongInt): Boolean; function WasAKeyPressed(): Boolean; // event register/process Quit procedure RegisterEventProcessor(handle: EventProcessPtr; handle2: EventStartProcessPtr); procedure ProcessEvents(); function HasQuit(): Boolean; // create/destroy constructor Create(); destructor Destroy(); override; end; //============================================================================= implementation //============================================================================= function TSDLManager.WasAKeyPressed(): Boolean; begin result := _keyPressed; end; function TSDLManager.IsKeyPressed(virtKeyCode: LongInt): Boolean; var keys: PUint8; {$IFNDEF FPC} indexAddress: uint32; intPtr: ^UInt8; {$ENDIF} begin keys := SDL_GetKeyState(nil); if keys <> nil then begin {$IFDEF FPC} result := (keys + virtKeyCode)^ = 1; {$ELSE} indexAddress := uint32(keys) + uint32(virtKeyCode); intPtr := Ptr(indexAddress); result := intPtr^ = 1; {$ENDIF} {$IFDEF FPC} if not result then begin if virtKeyCode = SDLK_LSUPER then result := (keys + SDLK_LMETA)^ = 1 else if virtKeyCode = SDLK_RSUPER then result := (keys + SDLK_RMETA)^ = 1; end; {$ENDIF} end else begin result := false; end; end; procedure TSDLManager.CheckQuit(); {$IFDEF FPC} var keys: PUInt8; {$ENDIF} begin {$IFDEF FPC} keys := SDL_GetKeyState(nil); if ((keys + SDLK_LMETA)^ + (keys + SDLK_Q)^ = 2) or ((keys + SDLK_RMETA)^ + (keys + SDLK_Q)^ = 2) or ((keys + SDLK_LALT)^ + (keys + SDLK_F4)^ = 2) or ((keys + SDLK_RALT)^ + (keys + SDLK_F4)^ = 2) then DoQuit() {$ELSE} if IsKeyPressed(SDLK_LALT) and IsKeyPressed(SDLK_F4) then DoQuit() {$ENDIF} end; procedure TSDLManager.ProcessEvents(); var event: TSDL_EVENT; i: LongInt; begin _keyPressed := false; SetLength(_KeyTyped, 0); for i := 0 to High(_EventProcessors) do begin _EventStartProcessors[i](); end; SDL_PumpEvents(); while SDL_PollEvent(@event) > 0 do begin HandleEvent(@event); end; CheckKeyRepeat(); CheckQuit(); end; procedure TSDLManager.CheckKeyRepeat(); var nowTime, timeDown: LongInt; begin if Length(_KeyDown) <> 1 then exit; nowTime := SDL_GetTicks(); timeDown := nowTime - _KeyDown[0].downAt; // 300 is the key repeat delay - hard coded for the moment... if timeDown > 300 then begin ProcessKeyPress(_KeyDown[0].code, _KeyDown[0].keyChar); // 40 is the key repeat delap - hard coded for the moment... _KeyDown[0].downAt := _KeyDown[0].downAt + 30; end; end; procedure TSDLManager.HandleEvent(event: PSDL_Event); var i: LongInt; begin case event^.type_ of SDL_QUITEV: DoQuit(); SDL_KEYDOWN: HandleKeydownEvent(event); SDL_KEYUP: HandleKeyupEvent(event); end; for i := 0 to High(_EventProcessors) do begin _EventProcessors[i](event); end; end; procedure TSDLManager.AddKeyData(kyCode, kyChar: LongInt); var i: Integer; begin if (kyCode = SDLK_LSHIFT) or (kyCode = SDLK_RSHIFT) then exit; // WriteLn(kyCode, ' ', kyChar); for i := 0 to High(_KeyDown) do begin if _KeyDown[i].code = kyCode then exit; end; SetLength(_KeyDown, Length(_KeyDown) + 1); with _KeyDown[High(_KeyDown)] do begin downAt := SDL_GetTicks(); code := kyCode; keyChar := kyChar; end; end; procedure TSDLManager.HandleKeyupEvent(event: PSDL_Event); var i, keyAt: Integer; kyCode: LongInt; begin kyCode := event^.key.keysym.sym; keyAt := -1; for i := 0 to High(_KeyDown) do begin if _KeyDown[i].code = kyCode then begin keyAt := i; break; end; end; if keyAt = -1 then exit; for i := keyAt to High(_KeyDown) -1 do begin _KeyDown[i] := _KeyDown[i + 1]; end; SetLength(_KeyDown, Length(_KeyDown) - 1); end; procedure TSDLManager.ProcessKeyPress(keyCode, keyChar: LongInt); var oldStr, newStr: String; begin if _readingString then begin oldStr := _tempString; //If the key is not a control character if (keyCode = SDLK_BACKSPACE) and (Length(_tempString) > 0) then begin _tempString := Copy(_tempString, 1, Length(_tempString) - 1); end else if (keyCode = SDLK_RETURN) or (keyCode = SDLK_KP_ENTER) then begin _readingString := false; end else if keyCode = SDLK_ESCAPE then begin _tempString := ''; _readingString := false; _textCancelled := true; end else if Length(_tempString) < _maxStringLen then begin case keyChar of //Skip non printable characters 0..31: ; 127..High(UInt16): ; else //Append the character _tempString := _tempString + Char(keyChar); end; end; //If the string was change if oldStr <> _tempString then begin //Free the old surface if assigned(_textSurface) and (_textSurface <> _cursorSurface) then SDL_FreeSurface( _textSurface ); //Render a new text surface if Length(_tempString) > 0 then begin newStr := _tempString + '|'; _textSurface := TTF_RenderText_Blended(_font, PChar(newStr), _foreColor) end else _textSurface := _cursorSurface; end; end; end; procedure TSDLManager.HandleKeydownEvent(event: PSDL_Event); var keyCode: Integer; begin _keyPressed := true; keyCode := event^.key.keysym.sym; SetLength(_KeyTyped, Length(_KeyTyped) + 1); _KeyTyped[High(_KeyTyped)] := keyCode; AddKeyData(keyCode, event^.key.keysym.unicode); ProcessKeyPress(keyCode, event^.key.keysym.unicode); end; procedure TSDLManager.SetText(text: String); var outStr: String; begin _tempString := text; //Free the old surface if assigned(_textSurface) and (_textSurface <> _cursorSurface) then SDL_FreeSurface( _textSurface ); //Render a new text surface if Length(_tempString) > 0 then begin outStr := _tempString + '|'; _textSurface := TTF_RenderText_Blended(_font, PChar(outStr), _foreColor) end else _textSurface := _cursorSurface; end; function TSDLManager.EndReadingText(): String; begin _readingString := false; result := _tempString; end; procedure TSDLManager.DrawCollectedText(dest: PSDL_Surface); var srect, drect: SDL_Rect; textWidth: LongInt; begin if not assigned(dest) then exit; if _readingString and (_textSurface <> nil) then begin textWidth := _textSurface^.w; if textWidth > _area.w then srect.x := textWidth - _area.w else srect.x := 0; srect.y := 0; srect.w := _area.w; srect.h := _area.h; drect := _area; SDL_BlitSurface(_textSurface, @srect, dest, @drect); end; end; procedure TSDLManager.StartReadingText(textColor: TSDL_Color; maxLength: LongInt; theFont: PTTF_Font; area: SDL_Rect); var newStr: String; begin if assigned(_textSurface) and (_textSurface <> _cursorSurface) then begin //Free the old surface SDL_FreeSurface( _textSurface ); _textSurface := nil; end; _readingString := true; _textCancelled := false; _tempString := ''; _maxStringLen := maxLength; _foreColor := textColor; _font := theFont; _area := area; newStr := '|'; if assigned(_cursorSurface) then SDL_FreeSurface(_cursorSurface); _cursorSurface := TTF_RenderText_Blended(_font, PChar(newStr), _foreColor); _textSurface := _cursorSurface; end; constructor TSDLManager.Create(); begin _quit := false; _keyPressed := false; _textSurface := nil; _cursorSurface := nil; _readingString := false; _textCancelled := false; _lastKeyRepeat := 0; SetLength(_EventProcessors, 0); SetLength(_EventStartProcessors, 0); SetLength(_KeyDown, 0); end; destructor TSDLManager.Destroy(); begin if assigned(_textSurface) and (_textSurface <> _cursorSurface) then SDL_FreeSurface(_textSurface); if assigned(_cursorSurface) then SDL_FreeSurface(_cursorSurface); inherited Destroy(); end; procedure TSDLManager.DoQuit(); begin _quit := true; end; function TSDLManager.HasQuit(): Boolean; begin result := _quit; end; function TSDLManager.WasKeyTyped(keyCode: LongInt): Boolean; var i: LongInt; begin result := false; for i := 0 to High(_KeyTyped) do begin if _KeyTyped[i] = keyCode then begin result := true; exit; end; end; end; procedure TSDLManager.RegisterEventProcessor(handle: EventProcessPtr; handle2: EventStartProcessPtr); begin //if handle^ <> nil then begin SetLength(_EventProcessors, Length(_EventProcessors) + 1); _EventProcessors[High(_EventProcessors)] := handle; end; //if handle2^ <> nil then begin SetLength(_EventStartProcessors, Length(_EventStartProcessors) + 1); _EventStartProcessors[High(_EventStartProcessors)] := handle2; end; end; end.
unit ChromeLikeInterfaces; // Модуль: "w:\common\components\gui\Garant\ChromeLikeControls\ChromeLikeInterfaces.pas" // Стереотип: "Interfaces" // Элемент модели: "ChromeLikeInterfaces" MUID: (53F2D7B00186) interface {$If NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)} uses l3IntfUses , Types {$If NOT Defined(NoVCL)} , ImgList {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoVCL)} , Controls {$IfEnd} // NOT Defined(NoVCL) ; type TChromeLikeTabSetParams = record rCloseButtonImages: TCustomImageList; rTabImages: TCustomImageList; rCloseButtonImageIndex: TImageIndex; rCloseButtonHotImageIndex: TImageIndex; end;//TChromeLikeTabSetParams TChromeLikeCaptionMenuKind = ( {* Тип попап-меню в заголовочном контроле } cl_cmkSystem {* Показывать системное меню } , cl_cmkCustom {* Показывать свое меню } , cl_cmkNone {* Не показывать никакого меню } );//TChromeLikeCaptionMenuKind IChromeLikeCaptionControl = interface ['{A051CA0C-AA42-42C4-B5BE-0A024F9C99BC}'] function pm_GetVCLWinControl: TWinControl; function GetMenuKindAtPoint(const aPoint: TPoint): TChromeLikeCaptionMenuKind; procedure ShowContextMenu(const aPoint: TPoint); property VCLWinControl: TWinControl read pm_GetVCLWinControl; end;//IChromeLikeCaptionControl function TChromeLikeTabSetParams_C(aTabImages: TCustomImageList; aCloseButtonImages: TCustomImageList; aCloseButtonImageIndex: TImageIndex; aCloseButtonHotImageIndex: TImageIndex): TChromeLikeTabSetParams; {$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs) implementation {$If NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)} uses l3ImplUses ; function TChromeLikeTabSetParams_C(aTabImages: TCustomImageList; aCloseButtonImages: TCustomImageList; aCloseButtonImageIndex: TImageIndex; aCloseButtonHotImageIndex: TImageIndex): TChromeLikeTabSetParams; //#UC START# *5518DC3B0065_551552FA002B_var* //#UC END# *5518DC3B0065_551552FA002B_var* begin System.FillChar(Result, SizeOf(Result), 0); //#UC START# *5518DC3B0065_551552FA002B_impl* with Result do begin rCloseButtonImages := aCloseButtonImages; rTabImages := aTabImages; rCloseButtonImageIndex := aCloseButtonImageIndex; rCloseButtonHotImageIndex := aCloseButtonHotImageIndex; end; //#UC END# *5518DC3B0065_551552FA002B_impl* end;//TChromeLikeTabSetParams_C {$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs) end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_Queue * Implements a generic thread safe stack *********************************************************************************************************************** } Unit TERRA_Pool; {$I terra.inc} Interface Uses TERRA_String, TERRA_Utils, TERRA_Collections; Type PoolItem = Record Used:Boolean; Obj:CollectionObject; End; Pool = Class(List) Protected _Objects:Array Of PoolItem; _ObjectCount:Integer; Procedure InsertPoolObject(Obj:CollectionObject); Public Procedure Release(); Override; Procedure Clear(); Override; Function Recycle():CollectionObject; // Returns true if insertion was sucessful Function Add(Item:CollectionObject):Boolean; Override; End; Implementation { Pool } Procedure Pool.Clear; Var I:Integer; List,Next:CollectionObject; Begin List := _First; While Assigned(List)Do Begin Next := List.Next; If (Not (List Is CollectionObject)) Then ReleaseObject(List); List := Next; End; _First := Nil; _ItemCount := 0; For I:=0 To Pred(_ObjectCount) Do _Objects[I].Used := False; End; Procedure Pool.Release(); Var I:Integer; Begin Inherited; For I:=0 To Pred(_ObjectCount) Do ReleaseObject(_Objects[I].Obj); End; Procedure Pool.InsertPoolObject(Obj: CollectionObject); Var I:Integer; Begin For I:=0 To Pred(_ObjectCount) Do If (_Objects[I].Obj = Obj) Then Begin _Objects[I].Used := True; Exit; End; For I:=0 To Pred(_ObjectCount) Do If (Not _Objects[I].Used) And (_Objects[I].Obj = Nil) Then Begin _Objects[I].Obj := Obj; Exit; End; If (_ObjectCount<=0) Then _ObjectCount := 1024 Else _ObjectCount := _ObjectCount * 2; SetLength(_Objects, _ObjectCount); InsertPoolObject(Obj); End; Function Pool.Add(Item: CollectionObject): Boolean; Begin Self._Options := Self._Options Or coCheckReferencesOnAdd; Self.Lock(); If Assigned(_First) Then Begin _Last.Next := Item; Item.Next := Nil; _Last := Item; End Else Begin _First := Item; _Last := _First; Item.Next := Nil; End; InsertPoolObject(Item); Self.Unlock(); Result := True; End; Function Pool.Recycle:CollectionObject; Var I:Integer; Begin For I:=0 To Pred(_ObjectCount) Do If (Not _Objects[I].Used) And (Assigned(_Objects[I].Obj)) Then Begin _Objects[I].Used := True; Result := _Objects[I].Obj; Result.Link(Nil); Exit; End; Result := Nil; End; End.
unit eventEdit; interface uses Forms, SysUtils, event, Classes, Controls, ComCtrls, StdCtrls; type TEventEditForm = class(TForm) TimeEdit: TDateTimePicker; DateEdit: TDateTimePicker; OccurEdit: TComboBox; NotesMemo: TMemo; OkButton: TButton; CancelButton: TButton; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; procedure CancelButtonClick(Sender: TObject); procedure OkButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } editing : boolean; public procedure injectEvent(event:TRemindEvent); { public shit } end; var EventEditForm: TEventEditForm; implementation uses main; {$R *.dfm} procedure TEventEditForm.FormCreate(Sender: TObject); begin editing := false; DateEdit.Date := Now(); TimeEdit.Time := Now(); end; procedure TEventEditForm.injectEvent(event:TRemindEvent); var OccurIndex : integer; begin editing := true; with event do begin NotesMemo.Lines.Text := Notes; DateEdit.Date := Date; TimeEdit.Time := Time; OccurIndex := OccurEdit.Items.IndexOf(Occur); if OccurIndex = -1 then OccurIndex := 0; OccurEdit.ItemIndex := OccurIndex; end; end; procedure TEventEditForm.CancelButtonClick(Sender: TObject); begin Close; end; procedure TEventEditForm.OkButtonClick(Sender: TObject); var event:TRemindEvent; MainForm:TMainForm; begin event := TRemindEvent.Create(); with event do begin Notes := NotesMemo.Lines.Text; Date := DateEdit.Date; Time := TimeEdit.Time; Occur := OccurEdit.Items[OccurEdit.ItemIndex]; // 2005-05-17 : super annoying blank occur bug if Occur='' then begin Occur:='once'; end; Completed := false; end; MainForm := TMainForm(Owner); MainForm.SaveEvents(); if editing then begin MainForm.EditEvent(event); end else begin MainForm.NewEvent(event); end; Close; end; end.
PROGRAM TestReadNumber(INPUT, OUTPUT); CONST NegOne = -1; VAR Number: INTEGER; PROCEDURE ReadDigit(VAR InF: TEXT; VAR D: INTEGER); VAR Ch: CHAR; BEGIN {ReadDigit} D := NegOne; IF NOT(EOLN(InF)) THEN BEGIN READ(InF, Ch); IF (Ch = '0') THEN D := 0 ELSE IF (Ch = '1') THEN D := 1 ELSE IF (Ch = '2') THEN D := 2 ELSE IF (Ch = '3') THEN D := 3 ELSE IF (Ch = '4') THEN D := 4 ELSE IF (Ch = '5') THEN D := 5 ELSE IF (Ch = '6') THEN D := 6 ELSE IF (Ch = '7') THEN D := 7 ELSE IF (Ch = '8') THEN D := 8 ELSE IF (Ch = '9') THEN D := 9 END END; {ReadDigit} PROCEDURE ReadNumber(VAR InF: TEXT; VAR N: INTEGER); VAR D: INTEGER; BEGIN {ReadNumber} N := 0; D := 0; WHILE (NOT(EOLN(InF))) AND (D <> NegOne) AND (N <> NegOne) DO BEGIN ReadDigit(InF, D); IF (D <> NegOne) THEN IF ((N * 10) + D) <= MAXINT THEN N := N * 10 + D ELSE N := NegOne END END; {ReadNumber} BEGIN {TestReadNumber} ReadNumber(INPUT, Number); WRITELN(OUTPUT, Number) END. {TestReadNumber}
unit kwFor; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwFor.pas" // Начат: 26.04.2011 19:06 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Scripting::ScriptEngine::Scripting::TkwFor // // Цикл FOR. Повторяет код между словами FOR и NEXT заданное в стеке число раз. // *Пример:* // {code} // : Hello // 3 FOR // 'Hello' . // NEXT // ; // // 3 FOR // Hello // NEXT // {code} // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses tfwScriptingInterfaces, l3Interfaces, kwCompiledWord, l3ParserInterfaces ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\tfwAnonimousWord.imp.pas} TkwFor = class(_tfwAnonimousWord_) {* Цикл FOR. Повторяет код между словами FOR и NEXT заданное в стеке число раз. *Пример:* [code] : Hello 3 FOR 'Hello' . NEXT ; 3 FOR Hello NEXT [code] } protected // realized methods function EndBracket(const aContext: TtfwContext): AnsiString; override; protected // overridden protected methods procedure AfterCompile(var aPrevContext: TtfwContext; var theNewContext: TtfwContext; aCompiled: TkwCompiledWord); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwFor {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses kwCompiledFor, l3Parser, kwInteger, kwString, SysUtils, TypInfo, l3Base, kwIntegerFactory, kwStringFactory, l3String, l3Chars, tfwAutoregisteredDiction, tfwScriptEngine ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwFor; {$Include ..\ScriptEngine\tfwAnonimousWord.imp.pas} // start class TkwFor function TkwFor.EndBracket(const aContext: TtfwContext): AnsiString; //#UC START# *4DB6C99F026E_4DB6DF4E022D_var* //#UC END# *4DB6C99F026E_4DB6DF4E022D_var* begin //#UC START# *4DB6C99F026E_4DB6DF4E022D_impl* Result := 'NEXT'; //#UC END# *4DB6C99F026E_4DB6DF4E022D_impl* end;//TkwFor.EndBracket class function TkwFor.GetWordNameForRegister: AnsiString; //#UC START# *4DB0614603C8_4DB6DF4E022D_var* //#UC END# *4DB0614603C8_4DB6DF4E022D_var* begin //#UC START# *4DB0614603C8_4DB6DF4E022D_impl* Result := 'FOR'; //#UC END# *4DB0614603C8_4DB6DF4E022D_impl* end;//TkwFor.GetWordNameForRegister procedure TkwFor.AfterCompile(var aPrevContext: TtfwContext; var theNewContext: TtfwContext; aCompiled: TkwCompiledWord); //#UC START# *4DB6CE2302C9_4DB6DF4E022D_var* var l_CF : TkwCompiledFor; //#UC END# *4DB6CE2302C9_4DB6DF4E022D_var* begin //#UC START# *4DB6CE2302C9_4DB6DF4E022D_impl* l_CF := TkwCompiledFor.Create(aCompiled); try DoCompiledWord(l_CF, aPrevContext); finally FreeAndNil(l_CF); end;//try..finally inherited; //#UC END# *4DB6CE2302C9_4DB6DF4E022D_impl* end;//TkwFor.AfterCompile {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\tfwAnonimousWord.imp.pas} {$IfEnd} //not NoScripts end.
{$include lem_directives.inc} unit LemPalette; interface uses GR32; type TLemmixPalette = class private fColorArray: TArrayOfColor32; fColorCount: Integer; procedure SetColorCount(Value: Integer); function GetColorS(Index: Integer): TColor32; protected public property ColorS[Index: Integer]: TColor32 read GetColorS; property ColorArray: TArrayOfColor32 read fColorArray; property ColorCount: Integer read fColorCount write SetColorCount; end; implementation { TLemmixPalette } function TLemmixPalette.GetColorS(Index: Integer): TColor32; begin if Index < fColorCount then Result := fColorArray[Index] else Result := 0; end; procedure TLemmixPalette.SetColorCount(Value: Integer); begin if fColorCount = Value then Exit; SetLength(fColorArray, Value); fColorCount := Value; end; end.
unit Mat.AnalysisProcessor; interface uses SysUtils, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Data.DB, System.IOUtils, System.Classes, Vcl.DBGrids, FireDAC.Stan.Option, System.Character, Mat.ProjectGroupParser, Mat.ProjectParser, Mat.ProjectUnitParser; type TAnalysisProgressEvent = procedure(MaxValue, CurrentPosition: Integer) of object; TAnalysisFinishedEvent = procedure(ProjectGroupsAmount, ProjectsAmount, UnitsAmount, LinesAmount, StandardClassesAmount, NonStandardClassesAmount : Integer; IsBDEDetected, IsPointersDetected, IsUniconeDetected, Is32BitSupport, Is64BitSupport, IsAssemblerDetected: Boolean; ProjectVersions: String) of object; TAnalysisProcessor = class private // Current process progress event handler. FOnAnalysisProgress: TAnalysisProgressEvent; // Analysis completion event handler. FAnalysisFinishedEvent: TAnalysisFinishedEvent; FSettingsFolder: string; stFDQuery_Show: TFDQuery; stFDQuery_ShowPG: TFDQuery; stFDQuery_ShowPJ: TFDQuery; stFDQuery_ShowU: TFDQuery; stFDQuery_ShowC: TFDQuery; stFDConnection: TFDConnection; FProjectsGroupList: TProjectsGroupList; FProjectsList: TProjectsList; FUnitStructFile: TUnitStructFile; FUnitStructList: TUnitStructList; FProjectUnitsList: TStringList; FTypesList: TStringList; FUsesList: TStringList; FLastFolder: string; // Initialize class instance. procedure Inititalize; // Inititlize internal instances for new analysis. procedure InitializeNewAnalysis; procedure RemoveProjectUnits(var AUsesList, AProjectUnits: TStringList); public DataSourcePG: TDataSource; DataSourcePj: TDataSource; DataSourceU: TDataSource; DataSourceC: TDataSource; stFDQuery_Update: TFDQuery; function StartNewAnalysis(RootPath: String; IncludeSubfolders: Boolean): Boolean; function CheckStringPresent(FoundString: string; LineString: string): Boolean; function CheckPointerPresent(LineString: string): Boolean; function DetectStandartClasses: Integer; procedure ShowPG(Sort: string); procedure ShowPJ(Sort: string); procedure ShowU(Sort: string); procedure ShowC(Sort: string); procedure InsertToTable(Tablename: string); property OnAnalysisProgress: TAnalysisProgressEvent read FOnAnalysisProgress write FOnAnalysisProgress; property OnAnalysisFinished: TAnalysisFinishedEvent read FAnalysisFinishedEvent write FAnalysisFinishedEvent; property SettingsFolder: string read FSettingsFolder write FSettingsFolder; property LastFolder: string read FLastFolder write FLastFolder; property ProjectsList: TProjectsList read FProjectsList write FProjectsList; property UnitStructFile: TUnitStructFile read FUnitStructFile write FUnitStructFile; property UnitStructList: TUnitStructList read FUnitStructList write FUnitStructList; property ProjectUnitsList: TStringList read FProjectUnitsList write FProjectUnitsList; property UsesList: TStringList read FUsesList write FUsesList; property TypesList: TStringList read FTypesList write FTypesList; // Class constructor. constructor Create; overload; // Destrutor. destructor Destroy; override; end; var FAnalysisProcessor: TAnalysisProcessor; implementation { TAnalysisProcessor } uses Mat.Components, Mat.Constants; constructor TAnalysisProcessor.Create; begin inherited Create; Inititalize; end; destructor TAnalysisProcessor.Destroy; begin FreeAndNil(FProjectsList); FreeAndNil(FProjectsGroupList); inherited; end; procedure TAnalysisProcessor.InitializeNewAnalysis; begin stFDQuery_Update.Sql.Text := CLEAR_PG_TABLE_SQL; stFDQuery_Update.ExecSQL; stFDQuery_Update.Sql.Text := CLEAR_PJ_TABLE_SQL; stFDQuery_Update.ExecSQL; stFDQuery_Update.Sql.Text := CLEAR_UNITS_TABLE_SQL; stFDQuery_Update.ExecSQL; stFDQuery_Update.Sql.Text := CLEAR_USES_TABLE_SQL; stFDQuery_Update.ExecSQL; stFDQuery_Update.Sql.Text := CLEAR_TYPES_TABLE_SQL; stFDQuery_Update.ExecSQL; stFDQuery_Update.Sql.Text := CLEAR_CD_TABLE_SQL; stFDQuery_Update.ExecSQL; stFDQuery_Update.Sql.Clear; FProjectUnitsList.Clear; FUsesList.Clear; FTypesList.Clear; end; procedure TAnalysisProcessor.Inititalize; var DFilename: string; begin FProjectsGroupList := TProjectsGroupList.Create; FProjectsList := TProjectsList.Create; FUnitStructList := TUnitStructList.Create; FProjectUnitsList := TStringList.Create; FProjectUnitsList.Duplicates := dupIgnore; FProjectUnitsList.Sorted := True; FUsesList := TStringList.Create; FUsesList.Duplicates := dupIgnore; FUsesList.Sorted := True; FTypesList := TStringList.Create; FTypesList.Sorted := True; FTypesList.Duplicates := dupIgnore; stFDConnection := TFDConnection.Create(nil); stFDConnection.DriverName := SQL_DRIVER_NAME; DFilename := (ExtractFilePath(ParamStr(0)) + DATABASE_FOLDER + SQL_DATABASE_FILENAME); stFDConnection.Params.Database := DFilename; stFDConnection.LoginPrompt := false; stFDConnection.Connected := True; stFDQuery_Update := TFDQuery.Create(nil); stFDQuery_Update.Connection := stFDConnection; stFDQuery_ShowPG := TFDQuery.Create(nil); stFDQuery_ShowPG.Connection := stFDConnection; stFDQuery_ShowPJ := TFDQuery.Create(nil); stFDQuery_ShowPJ.Connection := stFDConnection; stFDQuery_ShowU := TFDQuery.Create(nil); stFDQuery_ShowU.Connection := stFDConnection; stFDQuery_ShowC := TFDQuery.Create(nil); stFDQuery_ShowC.Connection := stFDConnection; stFDQuery_Show := TFDQuery.Create(nil); stFDQuery_Show.Connection := stFDConnection; stFDQuery_Update.Sql.Text := CREATE_TABLES_SQL; stFDQuery_Update.ExecSQL; DataSourceU := TDataSource.Create(nil); DataSourceU.DataSet := stFDQuery_ShowU; DataSourceC := TDataSource.Create(nil); DataSourceC.DataSet := stFDQuery_ShowC; DataSourcePG := TDataSource.Create(nil); DataSourcePG.DataSet := stFDQuery_ShowPG; DataSourcePj := TDataSource.Create(nil); DataSourcePj.DataSet := stFDQuery_ShowPJ; end; function TAnalysisProcessor.StartNewAnalysis(RootPath: String; IncludeSubfolders: Boolean): Boolean; var ProgGrFile: TProjectGroupFile; Project: TProjectFile; UnitFile: TUnitStructFile; Title, UUses, UTypes: string; ProjectGroupCounter, ProjectGroupInc, StandardClassesAmount, NonStandardClassesAmount, ProjectGroupsAmount, ProjectsAmount, UnitsAmount, LinesAmount: Integer; IsBDEDetected, IsPointersDetected, isUnicodeDetected, Is32BitSupport, Is64BitSupport, IsAssemblerDetected: Boolean; ProjectVersions: String; i: Integer; begin InitializeNewAnalysis; FComponentParser.JSONToSQL; if TDirectory.Exists(RootPath) then begin SettingsFolder := RootPath; FProjectsGroupList.Clear; FProjectsList.Clear; UnitStructList.Clear; FProjectsGroupList.ParseDirectory(RootPath, IncludeSubfolders); ProjectGroupCounter := FProjectsGroupList.Count; ProjectGroupInc := 0; if Assigned(FOnAnalysisProgress) then FOnAnalysisProgress(ProjectGroupCounter, ProjectGroupInc); stFDQuery_Update.Sql.Text := ''; for ProgGrFile in FProjectsGroupList do begin ProjectGroupInc := ProjectGroupInc + 1; if Assigned(FOnAnalysisProgress) then FOnAnalysisProgress(ProjectGroupCounter, ProjectGroupInc); stFDQuery_Update.Sql.Text := (INSERT_PG_SQL); if ProgGrFile.Title.IsEmpty then Title := ProgGrFile.FileName else Title := ProgGrFile.Title; stFDQuery_Update.Params.ParamByName(FTITLE_FIELD_NAME) .Value := Title; stFDQuery_Update.Params.ParamByName(FPATH_FIELD_NAME).Value := ProgGrFile.FullPath; stFDQuery_Update.Params.ParamByName(FVERSION_FIELD_NAME).Value := ProgGrFile.Version; stFDQuery_Update.ExecSQL; for Project in ProgGrFile.Projects do begin if not Project.FullPath.IsEmpty then begin Project.DetectProjectVersion(Project.FullPath); if Project.Is64Support then Is64BitSupport := True; stFDQuery_Update.Sql.Text := (INSERT_PJ_SQL); if Project.Title.IsEmpty then Title := Project.FileName else Title := Project.Title; stFDQuery_Update.Params.ParamByName(FTITLE_FIELD_NAME) .Value := Title; stFDQuery_Update.Params.ParamByName(FPATH_FIELD_NAME).Value := Project.FullPath; stFDQuery_Update.Params.ParamByName(FPGPATH_FIELD_NAME) .Value := ProgGrFile.FullPath; stFDQuery_Update.Params.ParamByName(FVERSION_FIELD_NAME) .Value := Project.Version; stFDQuery_Update.ExecSQL; for UnitFile in Project.Units do begin try stFDQuery_Update.Sql.Text := INSERT_UNITS_SQL; Title := UnitFile.UnitFileName; stFDQuery_Update.Params.ParamByName (FTITLE_FIELD_NAME).Value := Title; stFDQuery_Update.Params.ParamByName (FPATH_FIELD_NAME).Value := UnitFile.UnitPath; stFDQuery_Update.Params.ParamByName (FPPATH_FIELD_NAME).Value := Project.FullPath; stFDQuery_Update.Params.ParamByName (FLINESCOUNT_FIELD_NAME).Value := UnitFile.LinesCount; stFDQuery_Update.Params.ParamByName (FFORMNAME_FIELD_NAME).Value := UnitFile.FormName; stFDQuery_Update.ExecSQL; finally UnitFile.free; end; end; end; end; end; FProjectsList.Clear; UnitStructList.Clear; FProjectsList.ParseDirectory(RootPath, IncludeSubfolders); ProjectGroupCounter := FProjectsList.Count; ProjectGroupInc := 0; if Assigned(FOnAnalysisProgress) then FOnAnalysisProgress(ProjectGroupCounter, ProjectGroupInc); for Project in FProjectsList do begin if not Project.FullPath.IsEmpty then begin Project.DetectProjectVersion(Project.FullPath); if Project.Is64Support then Is64BitSupport := True; stFDQuery_Update.Sql.Text := INSERT_PJ_SQL; if Project.Title.IsEmpty then Title := Project.FileName else Title := Project.Title; stFDQuery_Update.Params.ParamByName(FTITLE_FIELD_NAME) .Value := Title; stFDQuery_Update.Params.ParamByName(FPATH_FIELD_NAME).Value := Project.FullPath; stFDQuery_Update.Params.ParamByName(FPGPATH_FIELD_NAME) .Value := ''; stFDQuery_Update.Params.ParamByName(FVERSION_FIELD_NAME).Value := Project.Version; stFDQuery_Update.ExecSQL; ProjectGroupInc := ProjectGroupInc + 1; if Assigned(FOnAnalysisProgress) then FOnAnalysisProgress(ProjectGroupCounter, ProjectGroupInc); for UnitFile in Project.Units do begin try stFDQuery_Update.Sql.Text := INSERT_UNITS_SQL; Title := UnitFile.UnitFileName; stFDQuery_Update.Params.ParamByName(FTITLE_FIELD_NAME) .Value := Title; stFDQuery_Update.Params.ParamByName(FPATH_FIELD_NAME) .Value := UnitFile.UnitPath; stFDQuery_Update.Params.ParamByName(FPPATH_FIELD_NAME) .Value := Project.FullPath; stFDQuery_Update.Params.ParamByName (FLINESCOUNT_FIELD_NAME).Value := UnitFile.LinesCount; stFDQuery_Update.Params.ParamByName (FFORMNAME_FIELD_NAME).Value := UnitFile.FormName; stFDQuery_Update.ExecSQL; finally UnitFile.free; end; end; end; end; UnitStructList.Clear; UnitStructList.ParseDirectory(RootPath, IncludeSubfolders); ProjectGroupCounter := UnitStructList.Count; ProjectGroupInc := 0; if Assigned(FOnAnalysisProgress) then FOnAnalysisProgress(ProjectGroupCounter, ProjectGroupInc); for UnitFile in UnitStructList do begin try if UnitFile.IsAssemblerDetected then IsAssemblerDetected := True; if UnitFile.IsPointersDetected then IsPointersDetected := True; stFDQuery_Update.Sql.Text := INSERT_UNITS_SQL; Title := UnitFile.UnitFileName; stFDQuery_Update.Params.ParamByName(FTITLE_FIELD_NAME) .Value := Title; stFDQuery_Update.Params.ParamByName(FPATH_FIELD_NAME).Value := UnitFile.UnitPath; stFDQuery_Update.Params.ParamByName(FPPATH_FIELD_NAME) .Value := ''; stFDQuery_Update.Params.ParamByName(FLINESCOUNT_FIELD_NAME) .Value := UnitFile.LinesCount; stFDQuery_Update.Params.ParamByName(FFORMNAME_FIELD_NAME).Value := UnitFile.FormName; stFDQuery_Update.ExecSQL; ProjectGroupInc := ProjectGroupInc + 1; if Assigned(FOnAnalysisProgress) then FOnAnalysisProgress(ProjectGroupCounter, ProjectGroupInc); finally UnitFile.free; end; end; RemoveProjectUnits(FUsesList, FProjectUnitsList); for UUses in FUsesList do begin FComponentParser.ParseFields(UUses); if (LowerCase(UUses) = LowerCase(BDE_USES)) then IsBDEDetected := True; end; for UTypes in FTypesList do begin stFDQuery_Update.Sql.Text := INSERT_USES_SQL; stFDQuery_Update.Params.ParamByName(FTITLE_FIELD_NAME).Value := UTypes; stFDQuery_Update.Params.ParamByName(FLOWER_TITLE_FIELD_NAME).Value := UTypes.ToLower; stFDQuery_Update.ExecSQL; end; ShowPG(DEFAULT_SORT); ShowPJ(DEFAULT_SORT); ShowU(DEFAULT_SORT); ShowC(DEFAULT_SORT); stFDQuery_Show.Sql.Text := SELECT_PG_COUNT; stFDQuery_Show.Open; if not stFDQuery_Show.fields[0].AsString.IsEmpty then ProjectGroupsAmount := StrToInt(stFDQuery_Show.fields[0].AsString); stFDQuery_Show.Sql.Text := SELECT_PJ_COUNT; stFDQuery_Show.Open; if not stFDQuery_Show.fields[0].AsString.IsEmpty then ProjectsAmount := StrToInt(stFDQuery_Show.fields[0].AsString); stFDQuery_Show.Sql.Text := SELECT_UNITS_COUNT; stFDQuery_Show.Open; if not stFDQuery_Show.fields[0].AsString.IsEmpty then UnitsAmount := StrToInt(stFDQuery_Show.fields[0].AsString); stFDQuery_Show.Sql.Text := SELECT_ULINESCOUNT_COUNT; stFDQuery_Show.Open; if not stFDQuery_Show.fields[0].AsString.IsEmpty then LinesAmount := StrToInt(stFDQuery_Show.fields[0].AsString); // By default, all legacy Delphi versions doesn't support Unicode. isUnicodeDetected := false; stFDQuery_Show.Sql.Text := SELECT_PJVERSION; ProjectVersions := ''; stFDQuery_Show.Open; for i := 0 to stFDQuery_Show.RecordCount - 1 do begin ProjectVersions := ProjectVersions + stFDQuery_Show.fields[0] .AsString + ', '; stFDQuery_Show.Next; if i = stFDQuery_Show.RecordCount - 1 then Delete(ProjectVersions, Length(ProjectVersions) - 1, Length(ProjectVersions)); end; // TODO: Determine standard Embarcadero's classes. StandardClassesAmount := DetectStandartClasses; // TODO: Determone non-standard classes. NonStandardClassesAmount := stFDQuery_ShowC.RecordCount - DetectStandartClasses; // By default we have 32-bit support. Is32BitSupport := True; if Assigned(FAnalysisFinishedEvent) then FAnalysisFinishedEvent(ProjectGroupsAmount, ProjectsAmount, UnitsAmount, LinesAmount, StandardClassesAmount, NonStandardClassesAmount, IsBDEDetected, IsPointersDetected, isUnicodeDetected, Is32BitSupport, Is64BitSupport, IsAssemblerDetected, ProjectVersions); Result := True; end else Result := false; end; procedure TAnalysisProcessor.RemoveProjectUnits(var AUsesList, AProjectUnits: TStringList); var LRow: string; begin for LRow in AProjectUnits do if AUsesList.IndexOf(LRow.ToLower) >= 0 then AUsesList.Delete(AUsesList.IndexOf(LRow)); end; procedure TAnalysisProcessor.ShowPG(Sort: string); begin stFDQuery_ShowPG.Sql.Text := SHOW_PG_SQL + Sort; stFDQuery_ShowPG.Open; end; procedure TAnalysisProcessor.ShowPJ(Sort: string); begin stFDQuery_ShowPJ.Sql.Text := SHOW_PJ_SQL + Sort; stFDQuery_ShowPJ.Open; end; procedure TAnalysisProcessor.ShowU(Sort: string); begin stFDQuery_ShowU.Sql.Text := SHOW_U_SQL + Sort; stFDQuery_ShowU.Open; end; procedure TAnalysisProcessor.ShowC(Sort: string); begin stFDQuery_ShowC.Sql.Text :=SHOW_C_SQL +Sort; stFDQuery_ShowC.Open; end; procedure TAnalysisProcessor.InsertToTable(Tablename: string); begin stFDQuery_Update.Sql.Text := (INSERT_INTO_TABLE_SQL_P + Tablename + INSERT_INTO_TABLE_SQL); stFDQuery_Update.Params.ParamByName(FTITLE_FIELD_NAME).Value := FComponentParser.Title; stFDQuery_Update.Params.ParamByName(FLOWER_TITLE_FIELD_NAME).Value := FComponentParser.Title.ToLower; stFDQuery_Update.Params.ParamByName(FPACKAGE_FIELD_NAME).Value := FComponentParser.Package; stFDQuery_Update.Params.ParamByName(FVENDOR_FIELD_NAME).Value := FComponentParser.Vendor; stFDQuery_Update.Params.ParamByName(FPJ_HOME_URL_FIELD_NAME).Value := FComponentParser.ProjectHomeURL; stFDQuery_Update.Params.ParamByName(FLICELCSE_NAME_FIELD_NAME).Value := FComponentParser.LicenseName; stFDQuery_Update.Params.ParamByName(FLICELCSE_TYPE_FIELD_NAME).Value := FComponentParser.LicenseType; stFDQuery_Update.Params.ParamByName(FCLASSES_FIELD_NAME).Value := FComponentParser.Classes; stFDQuery_Update.Params.ParamByName(FPLATFORM_SUPPORT_NAME).Value := FComponentParser.PlatformsSupport; stFDQuery_Update.Params.ParamByName(FRADVERSION_SUPPORT_NAME).Value := FComponentParser.RADStudioVersionsSupport; stFDQuery_Update.Params.ParamByName(FVERSION_COMPATIBILITY_NAME).Value := FComponentParser.VersionsCompatibility; stFDQuery_Update.Params.ParamByName(FANALOGUES_FIELD_NAME).Value := FComponentParser.Analogues; stFDQuery_Update.Params.ParamByName(FCONVERTTO_FIELD_NAME).Value := FComponentParser.ConvertTo; stFDQuery_Update.Params.ParamByName(FCOMMENT_FIELD_NAME).Value := FComponentParser.Comment; stFDQuery_Update.ExecSQL; end; function TAnalysisProcessor.CheckStringPresent(FoundString: string; LineString: string): Boolean; var Position, FoundStringLenght, LineStringLenght: Integer; FFlag, LFlag: Boolean; begin FFlag := false; LFlag := false; LineStringLenght := LineString.Length; FoundStringLenght := FoundString.Length; Position := Pos(FoundString, LineString); if Position > 0 then begin if Position = 1 then FFlag := True else if (Char(LineString[Position - 1]).IsWhiteSpace) or (LineString[Position - 1] = ';') then FFlag := True; if (Char(LineString[Position + FoundStringLenght]).IsWhiteSpace) or (Char(LineString[Position + FoundStringLenght]).IsPunctuation) or ((Position + FoundStringLenght) = LineStringLenght + 1) then LFlag := True; if (FFlag = True) and (LFlag = True) then Result := True else Result := false; end else Result := false; end; function TAnalysisProcessor.CheckPointerPresent(LineString: string): Boolean; var Position, FoundStringLenght: Integer; FFlag, LFlag: Boolean; begin FFlag := false; LFlag := false; FoundStringLenght := 1; Position := Pos('^', LineString); if Position > 0 then begin if (Char(LineString[Position - 1]).IsLetter) then FFlag := True; if (Char(LineString[Position + FoundStringLenght]).IsWhiteSpace) then LFlag := True; if ((LineString[Position + FoundStringLenght] = '.')) then LFlag := True; if ((LineString[Position + FoundStringLenght] = '=')) then LFlag := True; if (FFlag = True) and (LFlag = True) then Result := True else Result := false; end else Result := false; end; function TAnalysisProcessor.DetectStandartClasses: Integer; begin stFDQuery_Show.Sql.Text := (DETECT_STANDART_CLASSES_COUNT_SQL + STANDART_VENDOR_NAME + ''''); stFDQuery_Show.Open; Result := (stFDQuery_Show.fields[0].AsInteger); end; initialization FAnalysisProcessor := TAnalysisProcessor.Create; finalization FreeAndNil(FAnalysisProcessor); end.
Unit Dt_err; { $Id: DT_ERR.PAS,v 1.29 2013/04/19 13:07:39 lulin Exp $ } // $Log: DT_ERR.PAS,v $ // Revision 1.29 2013/04/19 13:07:39 lulin // - портируем. // // Revision 1.28 2008/04/04 15:16:32 fireton // - внешние номера документов из диапазона // // Revision 1.27 2008/02/06 16:16:31 voba // no message // // Revision 1.26 2007/02/12 16:11:00 voba // - заменил использование htModifyRecs на вызов TAbsHtTbl.ModifyRecs // - выделил TdtTable в модуль dt_Table (обертка вокруг функций HyTech по работе с таблицей целиком) // - выделил функции HyTech по работе с Sab в dt_Sab, потом объект сделаю // // Revision 1.25 2006/12/01 11:39:05 voba // no message // // Revision 1.24 2006/08/29 15:28:08 voba // - add procedure HTErr_NeedStackOut // // Revision 1.23 2005/10/21 08:09:36 step // убрана StrAlloc из EHtErrors.CreateInt // // Revision 1.22 2005/04/28 15:04:06 lulin // - переложил ветку B_Tag_Box в HEAD. // // Revision 1.21 2005/04/25 08:56:48 voba // - add type of exception // // Revision 1.20.12.1 2005/04/25 14:05:05 lulin // - bug fix: не компилировался Архивариус. // // Revision 1.21 2005/04/25 08:56:48 voba // - add type of exception // // Revision 1.20 2005/01/20 09:27:55 step // Исправлен текст исключения (по просьбе Гарри) // // Revision 1.19 2004/08/03 08:52:50 step // замена dt_def.pas на DtDefine.inc // // Revision 1.18 2004/07/22 10:33:49 voba // - изменил строковую константу ecUnableUpd // // Revision 1.17 2004/07/16 14:55:36 step // добавлены новые ошибки // // Revision 1.16 2004/01/14 11:53:13 step // Добавлена const ecCanNotRead // // Revision 1.15 2003/05/06 14:04:57 step // Добавлено проверка на зацикленность ссылок в TDocumentData.GetVersionsList // // Revision 1.14 2003/04/29 15:47:27 voba // - добавил нове сообщение об ошибке // // Revision 1.13 2003/04/16 09:19:00 voba // - improvement: добавлена возможность передачи параметров в сообщение об exception // // Revision 1.12 2003/03/13 10:03:20 demon // - new: ecIDAlreadyUsed (попытка повторно использовать идентификатор) // // Revision 1.11 2003/01/16 15:30:35 demon // - new behavior: Новая ошибка - Не задан идентификатор (для загрузки аттрибутов в трубу) // // Revision 1.10 2002/01/16 11:03:06 demon // - cleanup HtDebugInfo and merge with tag NullJournal_bug // // Revision 1.9.2.2 2001/09/06 12:05:53 narry // - change: совместимость с Delphi 6. // // Revision 1.9.2.1 2001/07/09 15:28:47 demon // no message // // Revision 1.9 2001/04/18 08:51:37 voba // Поправил грамматику. Извини, не удержался :) // // Revision 1.8 2000/12/15 15:36:15 law // - вставлены директивы Log. // {$I DtDefine.inc} Interface Uses Dt_Types, SysUtils; Const ecOk = 0; ecNotFound = 101; ecNotEmpty = 102; ecTblNotOpen = 103; ecTblOpen = 104; ecUnableDel = 105; ecNotFamilyID = 106; ecFreeTblErr = 107; ecNotFreeMem = 108; ecUnableUpd = 109; ecSrchNotOpen = 110; ecPathNotFound = 111; ecLocked = 112; ecImportAbort = 113; ecNotAssigned = 114; ecNotGroup = 115; ecUnSynhronize = 116; ecNotEnable = 117; ecNotUniqName = 118; ecCircleLabel = 119; ecTooManyElements = 120; ecFamilyLocked = 121; ecUnableLockFamily = 122; ecAccessDenied = 123; ecEmpty = 124; ecNotField = 125; ecInvalidHome = 126; ecSrchEmpty = 127; ecNotValidSrchType = 128; ecNotValidSab = 129; ecDataCorrupted = 130; ecNotKeyField = 131; ecNotUniqID = 132; ecIDNotAssigned = 133; ecIDAlreadyUsed = 134; ecIDAlreadyUsedParam = 135; ecIDAlreadyUsedInDoc = 136; ecWrongVerLink = 137; ecCanNotRead = 138; ecWrongFieldNumber = 139; ecWrongFieldValue = 140; ecFullRecordNotInit = 141; ecUserRejectedOperation = 142; Type ETableError = class(Exception); EHtErrors = Class(Exception) ErrorValue : Integer; Constructor CreateInt(ErrCode : Integer); overload; Constructor CreateInt(ErrCode : Integer; const Params : array of const); overload; end; EHtErrors_IDAlreadyUsed = Class(EHtErrors) end; EHtErrors_LockTblError = class(EHterrors) end; function DTErrMsg(ErrCode : Integer) : ShortString; function Ht(ID : Integer) : LongInt; procedure HTErr_NeedStackOut(aErrNum : Integer); {* - вызывается из DT_Serv.fn_OnIOError, взводит флаг необходимости выгрузить стек в лог, который проверяется в Ht() } Implementation Uses HT_Dll, l3Base; var lNeedStackOut_ErrNum : Integer = 0; procedure HTErr_NeedStackOut(aErrNum : Integer); begin lNeedStackOut_ErrNum := aErrNum; end; Constructor EHtErrors.CreateInt(ErrCode : Integer); begin CreateInt(ErrCode, []); end; Constructor EHtErrors.CreateInt(ErrCode : Integer; const Params : array of const); var ErrStr : AnsiString; l_Buff220: array[0..220] of AnsiChar; begin if ErrCode<>0 then begin if ErrCode<0 then begin {Это строка с сообщением об ошибке HT} htMessage(ErrCode, @l_Buff220); ErrStr:=SysUtils.Format('%s; Code: %d', [PAnsiChar(@l_Buff220), ErrCode]); end else {Это строка с сообщением об ошибке внутри программы} ErrStr:=DTErrMsg(ErrCode); if High(Params) >= Low(Params) then ErrStr:=Format(ErrStr, Params); end else ErrStr:='ОШИБОК НЕТ !!!'; Inherited Create(ErrStr); ErrorValue:=ErrCode; end; Function DTErrMsg(ErrCode : Integer) : ShortString; Begin Case ErrCode of ecOk : Result:= 'Ошибок нет'; ecNotFound : Result:= 'Элемент не найден'; ecTblNotOpen : Result:= 'Таблица не открыта'; ecSrchNotOpen : Result:= 'Выборка не открыта'; ecTblOpen : Result:= 'Таблица открыта'; ecUnableDel : Result:= 'Удаление невозможно'; ecUnableUpd : Result:= 'Сохранение изменений невозможно'; ecNotEmpty : Result:= 'Элемент не пустой'; ecEmpty : Result:= 'Элемент пустой'; ecNotFamilyID : Result:= 'Семейство таблиц не задано'; ecFamilyLocked : Result:= 'Семейство таблиц закрыто'; ecUnableLockFamily : Result:= 'Невозможно закрыть семейство таблиц'; ecFreeTblErr : Result:= 'Ошибка получения свободного номера'; ecNotFreeMem : Result:= 'Мало свободной памяти'; ecPathNotFound : Result:= 'Путь не найден'; ecLocked : Result:= 'Элемент закрыт'; ecImportAbort : Result:= 'Импорт данных не прошел'; ecNotAssigned : Result:= 'Ключевое свойство не задано'; ecNotGroup : Result:= 'Группа отсутствует'; ecUnSynhronize : Result:= 'Рассинхронизация'; ecNotEnable : Result:= 'Операция невозможна'; ecNotUniqName : Result:= 'Имя не уникальное'; ecCircleLabel : Result:= 'Циклические ссылки'; ecTooManyElements : Result:= 'Слишком много элементов'; ecAccessDenied : Result:= 'Нет прав для доступа'; ecNotField : Result:= 'Не поле таблицы'; ecInvalidHome : Result:= 'Неверный личный каталог'; ecSrchEmpty : Result:= 'Выборка пустая'; ecNotValidSrchType : Result:= 'Неверный тип выборки'; ecNotValidSab : Result:= 'Недопустимый БДС'; ecDataCorrupted : Result:= 'Нарушена структура данных таблицы'; ecNotKeyField : Result:= 'Поле не ключевое'; ecNotUniqID : Result:= 'Неуникальный идентификатор'; ecIDNotAssigned : Result:= 'Идентификатор не задан'; ecIDAlreadyUsed : Result:= 'Идентификатор уже используется'; ecIDAlreadyUsedParam : Result:= 'Идентификатор %d уже используется'; ecIDAlreadyUsedInDoc : Result:= 'Идентификатор #%d уже используется (в документе #%d)'; ecWrongVerLink : Result:= 'Обнаружен цикл в списке редакций документа'; ecCanNotRead : Result:= 'Ошибка при чтении результатов поиска'; ecWrongFieldNumber : Result:= 'Неверный номер поля таблицы'; ecWrongFieldValue : Result:= 'Значение %s недопустимо для поля %s таблицы %s.'; ecFullRecordNotInit: Result:= 'fFullRecord не инициализирован'; ecUserrejectedOperation: Result:= 'Операция отвергнута пользователем'; else Result:= 'Неизвестная ошибка'; end; end; function Ht(ID : LongInt) : LongInt; {var nDosError : SmallInt; // Сюда занесут код, возвращенный ДОС nOperation: SmallInt; // Сюда занесут код операции, приведшей к ошибке lErrstr : array[0..1000] of AnsiChar; lErrstr2 : PAnsiChar; } begin Result := ID; if lNeedStackOut_ErrNum <> 0 then begin l3System.Stack2Log(Format('HTERROR = %d STACK OUT', [lNeedStackOut_ErrNum])); lNeedStackOut_ErrNum := 0; end; { if ID = -1 then lErrstr2 := htExtError(nDosError, nOperation, @lErrstr[0]); } if ID < 0 then raise EHtErrors.CreateInt(ID); end; end.
{$I OVC.INC} {$B-} {Complete Boolean Evaluation} {$I+} {Input/Output-Checking} {$P+} {Open Parameters} {$T-} {Typed @ Operator} {$W-} {Windows Stack Frame} {$X+} {Extended Syntax} {$IFNDEF Win32} {$G+} {286 Instructions} {$N+} {Numeric Coprocessor} {$C MOVEABLE,DEMANDLOAD,DISCARDABLE} {$ENDIF} {*********************************************************} {* OVCSPLIT.PAS 2.17 *} {* Copyright 1995-98 (c) TurboPower Software Co *} {* All rights reserved. *} {*********************************************************} unit OvcSplit; {-Splitter component} interface uses {$IFDEF Win32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs, Buttons, ExtCtrls, OvcBase, OvcData; type TSplitterOrientation = (soVertical, soHorizontal); const spDefAllowResize = True; spDefAutoUpdate = False; spDefBorderStyle = bsNone; spDefCtl3D = True; spDefHeight = 100; spDefMargin = 0; spDefOrientation = soVertical; spDefPosition = 100; spDefSectionColor = clBtnFace; spDefSplitterColor = clWindowText; spDefSplitterSize = 3; spDefWidth = 200; type TOvcSection = class; TOvcSplitter = class; {.Z+} TOvcSectionInfo = class(TPersistent) protected {private} FSplitter : TOvcSplitter; FTag : Integer; function GetColor : TColor; procedure SetColor(Value : TColor); protected public constructor Create(ASplitter : TOvcSplitter; ATag : Integer); virtual; published property Color : TColor read GetColor write SetColor stored False; end; {.Z-} TOvcSplitter = class(TOvcBase) {.Z+} protected {private} {property variables} FAllowResize : Boolean; FAutoUpdate : Boolean; FBorderStyle : TBorderStyle; FMargin : Integer; FOrientation : TSplitterOrientation; FPosition : Integer; FSection : array[0..1] of TOvcSection; FSection1Info : TOvcSectionInfo; FSection2Info : TOvcSectionInfo; FSplitterColor : TColor; FSplitterSize : Integer; {event variables} FOnOwnerDraw : TNotifyEvent; FOnResize : TNotifyEvent; {internal variables} sCanResize : Boolean; sPos : TPoint; {property methods} function GetSection(Index : Integer) : TOvcSection; procedure SetAutoUpdate(Value : Boolean); procedure SetBorderStyle(Value : TBorderStyle); procedure SetMargin(Value : Integer); procedure SetOrientation(Value : TSplitterOrientation); procedure SetPosition(Value : Integer); procedure SetSplitterColor(Value : TColor); procedure SetSplitterSize(Value : Integer); {internal methods} procedure sDrawSplitter(X, Y : Integer); procedure sInvalidateSplitter; procedure sSetPositionPrim(Value : Integer); procedure sSetSectionInfo; {VCL control methods} procedure CMCtl3DChanged(var Msg : TMessage); message CM_CTL3DCHANGED; procedure CMDesignHitTest(var Msg : TCMDesignHitTest); message CM_DESIGNHITTEST; {windows message response methods} procedure WMEraseBkGnd(var Msg : TWMEraseBkGnd); message WM_ERASEBKGND; procedure WMSetCursor(var Msg : TWMSetCursor); message WM_SETCURSOR; protected procedure CreateParams(var Params : TCreateParams); override; procedure CreateWnd; override; procedure DoOnResize; dynamic; procedure DoOnOwnerDraw; virtual; {$IFDEF Win32} function GetChildOwner : TComponent; override; procedure GetChildren(Proc : TGetChildProc {$IFDEF VERSION3}; Root : TComponent {$ENDIF}); override; {$ENDIF} procedure MouseDown(Button : TMouseButton; Shift : TShiftState; X, Y : Integer); override; procedure MouseMove(Shift : TShiftState; X, Y : Integer); override; procedure MouseUp(Button : TMouseButton; Shift : TShiftState; X, Y : Integer); override; procedure Paint; override; procedure ReadState(Reader : TReader); override; {$IFNDEF Win32} procedure WriteComponents(Writer : TWriter); override; {$ENDIF} public constructor Create(AOwner : TComponent); override; destructor Destroy; override; {.Z-} {public methods} procedure Center; {-position the splitter bar in the middle of the region} {public properties} property Section[Index : Integer] : TOvcSection read GetSection; published {properties} property AllowResize : Boolean read FAllowResize write FAllowResize default spDefAllowResize; property AutoUpdate : Boolean read FAutoUpdate write SetAutoUpdate default spDefAutoUpdate; property BorderStyle : TBorderStyle read FBorderStyle write SetBorderStyle default spDefBorderStyle; property Margin : Integer read FMargin write SetMargin default spDefMargin; property Orientation : TSplitterOrientation read FOrientation write SetOrientation default spDefOrientation; property Position : Integer read FPosition write SetPosition; property Section1Info : TOvcSectionInfo read FSection1Info write FSection1Info; property Section2Info : TOvcSectionInfo read FSection2Info write FSection2Info; property SplitterColor : TColor read FSplitterColor write SetSplitterColor default spDefSplitterColor; property SplitterSize : Integer read FSplitterSize write SetSplitterSize default spDefSplitterSize; {events} property OnOwnerDraw : TNotifyEvent read FOnOwnerDraw write FOnOwnerDraw; property OnResize : TNotifyEvent read FOnResize write FOnResize; {inherited properties} property Align; property Color; property Ctl3D default spDefCtl3D; property Enabled; property ParentCtl3D; property ParentShowHint; property ShowHint; property Visible; end; {section to act as parent for components} TOvcSection = class(TWinControl) {.Z+} protected {private} {windows message response methods} procedure WMNCHitTest(var Msg : TWMNCHitTest); message WM_NCHITTEST; protected procedure ReadState(Reader : TReader); override; public constructor Create(AOwner : TComponent); override; {.Z-} published property Color default spDefSectionColor; property Height stored False; property Left stored False; property Top stored False; property Width stored False; end; implementation {*** TOvcSectionInfo ***} constructor TOvcSectionInfo.Create(ASplitter : TOvcSplitter; ATag : Integer); begin inherited Create; FTag := ATag; FSplitter := ASplitter; end; function TOvcSectionInfo.GetColor : TColor; begin Result := FSplitter.FSection[FTag-1].Color; end; procedure TOvcSectionInfo.SetColor(Value : TColor); begin FSplitter.FSection[FTag-1].Color := Value; end; {*** TOvcSection ***} constructor TOvcSection.Create(AOwner : TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csAcceptsControls]; Color := spDefSectionColor; end; procedure TOvcSection.ReadState(Reader : TReader); var {$IFNDEF Win32} OldOwner : TComponent; {$ENDIF} S : TOvcSplitter; begin {$IFDEF Win32} inherited ReadState(Reader); {$ELSE} {change reader so the parent form is the owner of the contained controls} OldOwner := Reader.Owner; Reader.Owner := Reader.Root; try inherited ReadState(Reader); finally Reader.Owner := OldOwner; end; {$ENDIF} if Reader.Parent is TOvcSplitter then begin S := TOvcSplitter(Reader.Parent); if Assigned(S.FSection[Tag-1]) then S.FSection[Tag-1].Free; S.FSection[Tag-1] := Self; end; end; procedure TOvcSection.WMNCHitTest(var Msg : TWMNCHitTest); begin if not (csDesigning in ComponentState) then Msg.Result := HTTRANSPARENT else inherited; end; {*** TOvcSplitter ***} procedure TOvcSplitter.Center; begin case Orientation of soHorizontal : Position := (ClientHeight - SplitterSize) div 2; soVertical : Position := (ClientWidth - SplitterSize) div 2; end; end; procedure TOvcSplitter.CMCtl3DChanged(var Msg : TMessage); begin inherited; if (csLoading in ComponentState) then Exit; {update section size and position} sSetSectionInfo; Refresh; end; procedure TOvcSplitter.CMDesignHitTest(var Msg : TCMDesignHitTest); begin if sCanResize then Msg.Result := 1 else inherited; end; constructor TOvcSplitter.Create(AOwner: TComponent); begin inherited Create(AOwner); Ctl3D := spDefCtl3D; Height := spDefHeight; Width := spDefWidth; {$IFDEF Win32} {!!.12} Exclude(FComponentStyle, csInheritable); {!!.12} {$ENDIF} {!!.12} if Classes.GetClass(TOvcSection.ClassName) = nil then Classes.RegisterClass(TOvcSection); FSection[0] := TOvcSection.Create(Self); FSection[0].Tag := 1; FSection[0].ParentCtl3D := True; FSection[0].Color := spDefSectionColor; FSection[0].Parent := Self; FSection1Info := TOvcSectionInfo.Create(Self, 1); FSection[1] := TOvcSection.Create(Self); FSection[1].Tag := 2; FSection[1].ParentCtl3D := True; FSection[1].Color := spDefSectionColor; FSection[1].Parent := Self; FSection2Info := TOvcSectionInfo.Create(Self, 2); FAllowResize := spDefAllowResize; FAutoUpdate := spDefAutoUpdate; FBorderStyle := spDefBorderStyle; FMargin := spDefMargin; FOrientation := spDefOrientation; FPosition := spDefWidth div 2; FSplitterColor := spDefSplitterColor; FSplitterSize := spDefSplitterSize; sPos.X := -1; sPos.Y := -1; end; procedure TOvcSplitter.CreateParams(var Params : TCreateParams); begin inherited CreateParams(Params); Params.Style := LongInt(Params.Style) or BorderStyles[FBorderStyle]; {!!.D4} end; procedure TOvcSplitter.CreateWnd; begin inherited CreateWnd; {update section size and position} sSetSectionInfo; end; destructor TOvcSplitter.Destroy; var I : Integer; begin for I := 0 to 1 do begin FSection[I].Free; Fsection[I] := nil; end; FSection1Info.Free; FSection1Info := nil; FSection2Info.Free; FSection1Info := nil; inherited Destroy; end; procedure TOvcSplitter.DoOnOwnerDraw; begin if Assigned(FOnOwnerDraw) then FOnOwnerDraw(Self); end; procedure TOvcSplitter.DoOnResize; begin if Assigned(FOnResize) then FOnResize(Self); end; {$IFDEF Win32} function TOvcSplitter.GetChildOwner : TComponent; begin Result := Self; end; procedure TOvcSplitter.GetChildren(Proc : TGetChildProc {$IFDEF VERSION3}; Root : TComponent {$ENDIF}); var I : Integer; begin for I := 0 to 1 do Proc(TControl(FSection[I])); end; {$ENDIF} function TOvcSplitter.GetSection(Index : Integer) : TOvcSection; begin case Index of 0 : Result := FSection[0]; 1 : Result := FSection[1]; else Result := nil; end; end; procedure TOvcSplitter.MouseDown(Button : TMouseButton; Shift : TShiftState; X, Y : Integer); begin inherited MouseDown(Button, Shift, X, Y); if sCanResize then begin if (Button = mbLeft) then begin SetCapture(Handle); sDrawSplitter(X, Y); end; end; end; procedure TOvcSplitter.MouseMove(Shift : TShiftState; X, Y : Integer); begin inherited MouseMove(Shift, X, Y); case Orientation of soHorizontal : if (Y < Margin) or (Y > ClientHeight - Margin) or (Y = Position) then Exit; soVertical : if (X < Margin) or (X > ClientWidth - Margin) or (X = Position) then Exit; end; if (GetCapture = Handle) and sCanResize then begin sDrawSplitter(X, Y); if AutoUpdate then {update section size and position} sSetSectionInfo; end; end; procedure TOvcSplitter.MouseUp(Button : TMouseButton; Shift : TShiftState; X, Y : Integer); begin if sCanResize then begin ReleaseCapture; sCanResize := False; sDrawSplitter(-1, -1); {erase} {update Section size and position} sSetSectionInfo; Refresh; DoOnResize; end; inherited MouseUp(Button, Shift, X, Y); end; procedure TOvcSplitter.Paint; var M : Integer; P, P1 : Integer; S, S1 : Integer; CW, CH : Integer; begin {update section size and position} sSetSectionInfo; if Assigned(FOnOwnerDraw) then begin DoOnOwnerDraw; Exit; end; M := Margin; P := Position; P1 := Position-1; CW := ClientWidth; CH := ClientHeight; S := SplitterSize; S1 := SplitterSize-1; {erase margin area} if Margin > 0 then begin Canvas.Brush.Color := Color; Canvas.FillRect(Rect(0, 0, M, CH)); {left} Canvas.FillRect(Rect(M, 0, CW-M, M)); {top} Canvas.FillRect(Rect(CW-M, 0, CW, CH)); {right} Canvas.FillRect(Rect(M, CH-M, CW-M, CH)); {bottom} end; if not Ctl3D then begin Canvas.Pen.Color := SplitterColor; Canvas.Brush.Color := SplitterColor; case Orientation of soHorizontal : Canvas.Rectangle(M, P, CW-M, P+S); soVertical : Canvas.Rectangle(P, M, P+S, CH-M); end; Exit; end; Canvas.Brush.Color := Color; {draw highlight border (right and bottom of each section)} Canvas.Pen.Color := clBtnHighlight; case Orientation of soHorizontal : begin Canvas.PolyLine([Point(M, P1), Point(CW-M-1, P1), Point(CW-M-1, M-1)]); Canvas.PolyLine([Point(M, CH-M-1), Point(CW-M-1, CH-M-1), Point(CW-M-1, P+S1)]); end; soVertical : begin Canvas.PolyLine([Point(M, CH-M-1), Point(P1, CH-M-1), Point(P1, M-1)]); Canvas.PolyLine([Point(P+S1, CH-M-1), Point(CW-M-1, CH-M-1), Point(CW-M-1, M-1)]); end; end; {draw shadow border (left and top of each section)} Canvas.Pen.Color := clBtnShadow; case Orientation of soHorizontal : begin Canvas.PolyLine([Point(M, P1-1), Point(M, M), Point(CW-M-1, M)]); Canvas.PolyLine([Point(M, CH-M-2), Point(M, P+S), Point(CW-M-1, P+S)]); end; soVertical : begin Canvas.PolyLine([Point(M, CH-M-2), Point(M, M), Point(P1, M)]); Canvas.PolyLine([Point(P+S, CH-M-2), Point(P+S, M), Point(CW-M-1, M)]); end; end; {draw border (left and top of each section)} Canvas.Pen.Color := clBlack; case Orientation of soHorizontal : begin Canvas.PolyLine([Point(M+1, P1-1), Point(M+1, M+1), Point(CW-M-1, M+1)]); Canvas.PolyLine([Point(M+1, CH-M-2), Point(M+1, P+S+1), Point(CW-M-1, P+S+1)]); end; soVertical : begin Canvas.PolyLine([Point(M+1, CH-M-2), Point(M+1, M+1), Point(P-1, M+1)]); Canvas.PolyLine([Point(P+S+1, CH-M-2), Point(P+S+1, M+1), Point(CW-M-1, M+1)]); end; end; Canvas.Pen.Color := Color; Canvas.Brush.Color := Color; case Orientation of soHorizontal : Canvas.Rectangle(M, P, CW-M, P+S); soVertical : Canvas.Rectangle(P, M, P+S, CH-M); end; end; procedure TOvcSplitter.ReadState(Reader : TReader); {$IFNDEF Win32} var OldOwner : TComponent; {$ENDIF} begin {$IFDEF Win32} inherited ReadState(Reader); {$ELSE} {change reader owner so the sections are owned by the splitter} OldOwner := Reader.Owner; Reader.Owner := Self; try inherited ReadState(Reader); finally Reader.Owner := OldOwner; end; {$ENDIF} end; procedure TOvcSplitter.sDrawSplitter(X, Y : Integer); begin if AutoUpdate and (X > -1) and (Y > -1) then begin sInvalidateSplitter; case Orientation of soHorizontal : sSetPositionPrim(Y); soVertical : sSetPositionPrim(X); end; sInvalidateSplitter; Exit; end; {do we need to erase first?} if (sPos.X > -1) or (sPos.Y > -1) then begin case Orientation of soHorizontal : PatBlt(Canvas.Handle, Margin, sPos.Y, ClientWidth-2*Margin, SplitterSize, DSTINVERT); soVertical : PatBlt(Canvas.Handle, sPos.X, Margin, SplitterSize, ClientHeight-2*Margin, DSTINVERT); end; end; {record new position} sPos.X := X; sPos.Y := Y; if not sCanResize then Exit; case Orientation of soHorizontal : begin sSetPositionPrim(sPos.Y); sPos.Y := Position; PatBlt(Canvas.Handle, Margin, Position, ClientWidth-2*Margin, SplitterSize, DSTINVERT); end; soVertical : begin sSetPositionPrim(sPos.X); sPos.X := Position; PatBlt(Canvas.Handle, Position, Margin, SplitterSize, ClientHeight-2*Margin, DSTINVERT); end; end; end; procedure TOvcSplitter.sInvalidateSplitter; var R : TRect; begin case Orientation of soHorizontal : R := Rect(Margin, Position-2, Margin+ClientWidth-2*Margin, Position+SplitterSize+2); soVertical : R := Rect(Position-2, Margin, Position+SplitterSize+2, Margin+ClientHeight-2*Margin); end; InvalidateRect(Handle, @R, True); if Handle <> 0 then {}; end; procedure TOvcSplitter.SetAutoUpdate(Value : Boolean); begin if (Value <> FAutoUpdate) then FAutoUpdate := Value; end; procedure TOvcSplitter.SetBorderStyle(Value : TBorderStyle); begin if (Value <> FBorderStyle) then begin FBorderStyle := Value; RecreateWnd; end; end; procedure TOvcSplitter.SetMargin(Value : Integer); begin if (Value <> FMargin) and (Value >= 0) then begin if (csLoading in ComponentState) then begin FMargin := Value; Exit; end; if not HandleAllocated then Exit; case Orientation of soHorizontal : if 2*Value > ClientHeight - SplitterSize -2 then Exit; soVertical : if 2*Value > ClientWidth - SplitterSize -2 then Exit; end; FMargin := Value; {force position to readjust} sSetPositionPrim(FPosition); {update Section size and position} sSetSectionInfo; Refresh; end; end; procedure TOvcSplitter.SetOrientation(Value : TSplitterOrientation); begin if (Value <> FOrientation) then begin FOrientation := Value; if (csLoading in ComponentState) then Exit; if not HandleAllocated then Exit; {force position to readjust} sSetPositionPrim(FPosition); {update Section size and position} sSetSectionInfo; Refresh; end; end; procedure TOvcSplitter.SetPosition(Value : Integer); begin if (csLoading in ComponentState) then begin FPosition := Value; Exit; end; if not HandleAllocated then Exit; sSetPositionPrim(Value); Refresh; DoOnResize; end; procedure TOvcSplitter.SetSplitterColor(Value : TColor); begin {color to use if not Ctl3D} if (Value <> FSplitterColor) then begin FSplitterColor := Value; Refresh; end; end; procedure TOvcSplitter.SetSplitterSize(Value : Integer); begin if (Value <> FSplitterSize) then begin FSplitterSize := Value; if (csLoading in ComponentState) then Exit; if not HandleAllocated then Exit; {update Section size and position} sSetSectionInfo; Refresh; end; end; procedure TOvcSplitter.sSetPositionPrim(Value : Integer); var MinPos : Integer; MaxPos : Integer; PF : TForm; begin MinPos := Margin + 2; case Orientation of soHorizontal : begin MaxPos := ClientHeight - Margin - SplitterSize - 2; if Value < MinPos then Value := MinPos; if Value > MaxPos then Value := MaxPos; FPosition := Value; end; soVertical : begin MaxPos := ClientWidth - Margin - SplitterSize - 2; if Value < MinPos then Value := MinPos; if Value > MaxPos then Value := MaxPos; FPosition := Value; end; end; {notify the designer of the change} if csDesigning in ComponentState then begin PF := TForm(GetParentForm(Self)); if Assigned(PF) and (PF.Designer <> nil) then PF.Designer.Modified; end; end; procedure TOvcSplitter.sSetSectionInfo; var M : Integer; P : Integer; S : Integer; CW, CH : Integer; begin if (csLoading in ComponentState) then Exit; if not HandleAllocated then Exit; M := Margin; P := Position; CW := ClientWidth; CH := ClientHeight; S := SplitterSize; if Ctl3D then begin case Orientation of soHorizontal : begin FSection[0].SetBounds(M+2, M+2, CW-2*M-3, P-M-3); FSection[1].SetBounds(M+2, P+S+2, CW-2*M-3, CH-P-S-M-3); end; soVertical : begin FSection[0].SetBounds(M+2, M+2, P-M-3, CH-2*M-3); FSection[1].SetBounds(P+S+2, M+2, CW-P-S-M-3, CH-2*M-3); end; end; end else begin case Orientation of soHorizontal : begin FSection[0].SetBounds(M, M, CW-2*M, P-M); FSection[1].SetBounds(M, P+S, CW-2*M, CH-P-S-M); end; soVertical : begin FSection[0].SetBounds(M, M, P-M, CH-2*M); FSection[1].SetBounds(P+S, M, CW-P-S-M, CH-2*M); end; end; end; end; procedure TOvcSplitter.WMEraseBkGnd(var Msg : TWMEraseBkGnd); begin Msg.Result := 1 {don't erase background} end; {!!.12} {revised} procedure TOvcSplitter.WMSetCursor(var Msg : TWMSetCursor); var Cur : hCursor; P : TPoint; begin Cur := 0; if Msg.HitTest = HTCLIENT then begin GetCursorPos(P); P := ScreenToClient(P); {are we over the split region?} case Orientation of soHorizontal : if Abs(Position - P.Y) <= SplitterSize then Cur := Screen.Cursors[crVSplit]; soVertical : if Abs(Position - P.X) <= SplitterSize then Cur := Screen.Cursors[crHSplit]; end; end; sCanResize := (FAllowResize or (csDesigning in ComponentState)) and (Cur <> 0); if sCanResize then SetCursor(Cur) else inherited; end; {$IFNDEF Win32} procedure TOvcSplitter.WriteComponents(Writer : TWriter); var I : Integer; begin for I := 0 to 1 do Writer.WriteComponent(FSection[I]); end; {$ENDIF} end.
unit RDOObjectServer; interface uses SyncObjs, RDOObjectRegistry; type TRDOObjectServer = class public constructor Create( ObjectRegistry : TRDOObjectsRegistry; CriticalSection : TCriticalSection ); public procedure SetCriticalSection( CriticalSection : TCriticalSection ); procedure Lock; procedure UnLock; public function GetProperty( ObjectId : integer; const PropName : string; out ErrorCode : integer; var QueryStatus, RDOCallCnt : integer ) : variant; stdcall; procedure SetProperty( ObjectId : integer; const PropName : string; const PropValue : variant; out ErrorCode : integer; var QueryStatus, RDOCallCnt : integer ); stdcall; procedure CallMethod( ObjectId : integer; const MethodName : string; var Params : variant; var Res : variant; out ErrorCode : integer; var QueryStatus, RDOCallCnt : integer ); stdcall; function GetIdOf( ObjectName : string; out ErrorCode : integer; var QueryStatus : integer ) : integer; stdcall; private fObjectRegistry : TRDOObjectsRegistry; fCriticalSection : TCriticalSection; end; implementation uses Windows, SysUtils, TypInfo, RDOInterfaces, ErrorCodes, Logs; var RDOCallCounter : integer = 0; // TRDOObjectServer constructor TRDOObjectServer.Create( ObjectRegistry : TRDOObjectsRegistry; CriticalSection : TCriticalSection ); begin inherited Create; fObjectRegistry := ObjectRegistry; fCriticalSection := CriticalSection end; procedure TRDOObjectServer.Lock; begin if Assigned( fCriticalSection ) then fCriticalSection.Acquire end; procedure TRDOObjectServer.UnLock; begin if Assigned( fCriticalSection ) then fCriticalSection.Release end; procedure TRDOObjectServer.SetCriticalSection( CriticalSection : TCriticalSection ); begin fCriticalSection := CriticalSection end; function TRDOObjectServer.GetProperty( ObjectId : integer; const PropName : string; out ErrorCode : integer; var QueryStatus, RDOCallCnt : integer ) : variant; var theObject : TObject; thePropInfo : PPropInfo; LockObjIntf : ILockObject; Dummy : variant; TmpWideStr : widestring; begin Result := ''; LockObjIntf := nil; ErrorCode := errNoError; theObject := TObject( ObjectId ); try Lock; try if (theObject <> nil) and (theObject.ClassInfo <> nil) then begin thePropInfo := GetPropInfo( theObject.ClassInfo, PropName ); if thePropInfo <> nil then begin theObject.GetInterface( ILockObject, LockObjIntf ); if LockObjIntf <> nil then LockObjIntf.Lock; try case thePropInfo.PropType^.Kind of tkInteger, tkChar, tkEnumeration, tkSet, tkWChar: Result := GetOrdProp( theObject, thePropInfo ); tkString, tkLString: Result := GetStrProp( theObject, thePropInfo ); tkWString: begin GetWideStrProp( theObject, thePropInfo, TmpWideStr ); Result := TmpWideStr end; tkFloat: Result := GetFloatProp( theObject, thePropInfo ); tkVariant: Result := GetVariantProp( theObject, thePropInfo ) else ErrorCode := errIllegalPropType end finally if LockObjIntf <> nil then LockObjIntf.UnLock end end else begin TVarData( Result ).VType := varVariant; Dummy := UnAssigned; CallMethod( ObjectId, PropName, Dummy, Result, ErrorCode, QueryStatus, RDOCallCnt ); end end else ErrorCode := errUnexistentProperty finally UnLock end except on E : Exception do begin ErrorCode := errIllegalObject; Logs.Log('Survival', DateTimeToStr(Now) + 'Error at: TRDOObjectServer.GetProperty (126) ' + E.Message); end; end end; procedure TRDOObjectServer.SetProperty( ObjectId : integer; const PropName : string; const PropValue : variant; out ErrorCode : integer; var QueryStatus, RDOCallCnt : integer ); var theObject : TObject; thePropInfo : PPropInfo; LockObjIntf : ILockObject; begin ErrorCode := errNoError; theObject := TObject( ObjectId ); try QueryStatus := 411; Lock; QueryStatus := 412; try if (theObject <> nil) and (theObject.ClassInfo <> nil) then begin thePropInfo := GetPropInfo( theObject.ClassInfo, PropName ); if thePropInfo <> nil then try theObject.GetInterface( ILockObject, LockObjIntf ); if LockObjIntf <> nil then LockObjIntf.Lock; try case thePropInfo.PropType^.Kind of tkInteger, tkChar, tkEnumeration, tkSet, tkWChar: SetOrdProp( theObject, thePropInfo, PropValue ); tkString, tkLString: SetStrProp( theObject, thePropInfo, string(PropValue) ); tkWString: SetWideStrProp( theObject, thePropInfo, widestring(PropValue) ); tkFloat: SetFloatProp( theObject, thePropInfo, PropValue ); tkVariant: SetVariantProp( theObject, thePropInfo, PropValue ); else ErrorCode := errIllegalPropType end finally if LockObjIntf <> nil then LockObjIntf.UnLock end except on E : Exception do begin ErrorCode := errIllegalPropValue; Logs.Log('Survival', DateTimeToStr(Now) + 'Error at: TRDOObjectServer.SetProperty (174) ' + E.Message); end; end else ErrorCode := errUnexistentProperty end else ErrorCode := errUnexistentProperty finally UnLock end; QueryStatus := 413; except on E : Exception do begin ErrorCode := errIllegalObject; Logs.Log('Survival', DateTimeToStr(Now) + 'Error at: TRDOObjectServer.SetProperty (186) ' + E.Message); end; end end; procedure TRDOObjectServer.CallMethod( ObjectId : integer; const MethodName : string; var Params : variant; var Res : variant; out ErrorCode : integer; var QueryStatus, RDOCallCnt : integer ); const MaxRegs = 3; JustEAX = 1; var theObject : TObject; MethodAddr : pointer; ParamCount : integer; ParamIndex : integer; ParamsPtr : PVarData; RegsUsed : integer; LockObjIntf : ILockObject; SecLock : TCriticalSection; begin QueryStatus := 521; theObject := TObject( ObjectId ); if ObjectId = 0 then ErrorCode := errIllegalObject else try MethodAddr := theObject.MethodAddress( MethodName ); if MethodAddr <> nil then try ParamIndex := 1; if TVarData( Params ).VType and varArray <> 0 then begin ParamCount := VarArrayHighBound( Params, 1 ); ParamsPtr := VarArrayLock( Params ) end else ParamCount := 0; RegsUsed := 1; theObject.GetInterface( ILockObject, LockObjIntf ); if LockObjIntf <> nil then LockObjIntf.Lock; Lock; SecLock := fCriticalSection; QueryStatus := 522; RDOCallCnt := Windows.InterlockedIncrement(RDOCallCounter); try asm push eax push esi push edi mov eax, ParamCount mov esi, ParamsPtr @NextParam: cmp ParamIndex, eax ja @ResParam cmp word ptr TVarData( [esi] ).VType, varVariant jnz @CheckIfInteger mov edi, TVarData( [esi] ).VPointer cmp RegsUsed, MaxRegs jnz @UseRegister push edi jmp @Iterate @CheckIfInteger: cmp word ptr TVarData( [esi] ).VType, varInteger jnz @CheckIfSingle mov edi, TVarData( [esi] ).VInteger cmp RegsUsed, MaxRegs jnz @UseRegister push edi jmp @Iterate @CheckIfSingle: cmp word ptr TVarData( [esi] ).VType, varSingle jnz @CheckIfDouble push TVarData( [esi] ).VSingle jmp @Iterate @CheckIfDouble: cmp word ptr TVarData( [esi] ).VType, varDouble jnz @String mov edi, dword ptr TVarData( [esi] ).VDouble + Type( dword ) push edi mov edi, dword ptr TVarData( [esi] ).VDouble push edi jmp @Iterate @String: mov edi, TVarData( [esi] ).VOLEStr cmp RegsUsed, MaxRegs jnz @UseRegister push edi jmp @Iterate @UseRegister: cmp RegsUsed, JustEAX jnz @UseECX mov edx, edi inc RegsUsed jmp @Iterate @UseECX: mov ecx, edi inc RegsUsed @Iterate: inc ParamIndex add esi, Type( TVarData ) jmp @NextParam @ResParam: mov edi, Res cmp word ptr TVarData( [ edi ] ).VType, varEmpty jz @DoCall cmp RegsUsed, JustEAX jnz @TryWithECX mov edx, edi jmp @DoCall @TryWithECX: cmp RegsUsed, MaxRegs jz @PushResParam mov ecx, edi jmp @DoCall @PushResParam: push edi @DoCall: mov eax, theObject call MethodAddr pop edi pop esi pop eax end; finally QueryStatus := 523; UnLock; if SecLock <> fCriticalSection then begin fCriticalSection := SecLock; {$IFDEF USELogs} try Logs.Log('Survival', DateTimeToStr(Now) + ' Ignored result of function ' + MethodName); except end; {$ENDIF} end; if LockObjIntf <> nil then LockObjIntf.UnLock; if TVarData( Params ).VType and varArray <> 0 then VarArrayUnlock( Params ) end except on E : Exception do begin QueryStatus := 524; ErrorCode := errIllegalParamList; Logs.Log('Survival', DateTimeToStr(Now) + ' Error at: TRDOObjectServer.CallMethod "' + MethodName + '" (319) ' + E.Message); end; end else ErrorCode := errUnexistentMethod except on E : exception do begin QueryStatus := 524; ErrorCode := errIllegalObject; Logs.Log('Survival', DateTimeToStr(Now) + ' Error at: TRDOObjectServer.CallMethod "' + MethodName + '" (326) ' + E.Message); end; end; end; function TRDOObjectServer.GetIdOf( ObjectName : string; out ErrorCode : integer; var QueryStatus : integer ) : integer; var ObjectId : integer; begin ObjectId := fObjectRegistry.GetObjectId( ObjectName ); if ObjectId = NoId then ErrorCode := errIllegalObject else ErrorCode := errNoError; Result := ObjectId end; end.
unit WebBrowserHostTest; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, CustomWebBrowser; type TWebBrowserForm = class(TForm) procedure FormShow(Sender: TObject); private { Private declarations } fWebBrowser : TCustomWebBrowser; public { Public declarations } end; var WebBrowserForm: TWebBrowserForm; implementation uses ActiveX, LogFile; {$R *.DFM} procedure TWebBrowserForm.FormShow(Sender: TObject); var UseLess : OleVariant; URL : OleVariant; { OLEObjDisp : IDispatch; OLEObj : IOLEObject; } begin SetLogFile('webbrowser.log'); UseLess := NULL; fWebBrowser := TCustomWebBrowser.Create(Self); TControl(fWebBrowser).Parent := Self; fWebBrowser.Align := alClient; fWebBrowser.HideScrollBars := true; fWebBrowser.HideBorders := true; URL := InputBox('Customized IE 4.0', 'Enter HTTP &address you want to connect to: ', 'http://www.iosphere.net'); //URL := 'C:'; fWebBrowser.Navigate2(URL, UseLess, UseLess, UseLess, UseLess); end; end.
unit Model.EnderecosBases; interface uses Common.ENum, FireDAC.Comp.Client, System.SysUtils, DAO.Conexao; type TEnderecosBases = class private FLogradouro: string; FSequencia: integer; FBairro: string; FUF: string; FCEP: string; FNumero: string; FPadrao: integer; FComplemento: string; FBase: integer; FReferencia: string; FCidade: string; FTipo: string; FAcao: TAcao; FConexao: TConexao; function Inserir(): Boolean; function Alterar(): Boolean; function Excluir(): Boolean; function GetSeq(): Integer; public property Base: integer read FBase write FBase; property Sequencia: integer read FSequencia write FSequencia; property Tipo: string read FTipo write FTipo; property Logradouro: string read FLogradouro write FLogradouro; property Numero: string read FNumero write FNumero; property Complemento: string read FComplemento write FComplemento; property Padrao: integer read FPadrao write FPadrao; property Bairro: string read FBairro write FBairro; property Cidade: string read FCidade write FCidade; property UF: string read FUF write FUF; property CEP: string read FCEP write FCEP; property Referencia: string read FReferencia write FReferencia; property Acao: TAcao read FAcao write FAcao; constructor Create(); function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; end; const TABLENAME = 'tbenderecosagentes'; SQLINSERT = 'insert into ' + TABLENAME + '(cod_agente, seq_endereco, des_tipo, des_logradouro, num_logradouro, des_complemento, dom_correspondencia, ' + 'des_bairro, nom_cidade, uf_estado, num_cep, des_referencia) ' + 'values ' + '(:cod_agente, :seq_endereco, :des_tipo, :des_logradouro,:num_logradouro,:des_complemento, :dom_correspondencia, ' + ':des_bairro, :nom_cidade, :uf_estado, :num_cep, :des_referencia); '; SQLUPDATE = 'update ' + TABLENAME + ' set ' + 'des_tipo = des_tipo, des_logradouro = :des_logradouro, num_logradouro = :num_logradouro, ' + 'des_complemento = :des_complemento, dom_correspondencia = :dom_correspondencia, ' + 'des_bairro = :des_bairro, nom_cidade = :nom_cidade, uf_estado = :uf_estado, num_cep = :num_cep, ' + 'des_referencia = :des_referencia ' + 'where ' + 'cod_agente = :cod_agente and seq_endereco = :seq_endereco;'; SQLDELETE = 'delete from ' + TABLENAME + 'where cod_agente = :cod_agente '; SQLQUERY = 'select cod_agente, seq_endereco, des_tipo, des_logradouro, num_logradouro, des_complemento, ' + 'dom_correspondencia, des_bairro, nom_cidade, uf_estado, num_cep, des_referencia ' + 'from ' + TABLENAME; implementation { TEnderecosBases } function TEnderecosBases.Alterar: Boolean; var fdQuery : TFDQuery; begin try Result := False; fdQuery := FConexao.ReturnQuery; fdQuery.ExecSQL(SQLUPDATE, [FTipo, FLogradouro, FNumero, FComplemento, FPadrao, FBairro, FCidade, FUF, FCEP, FReferencia, FBase, FSequencia]); Result := True; finally fdQuery.Connection.Close; fdQuery.Free; end; end; constructor TEnderecosBases.Create; begin FConexao := TConexao.Create; end; function TEnderecosBases.Excluir: Boolean; var fdQuery: TFDQuery; begin try Result := False; fdQuery := FConexao.ReturnQuery; fdQuery.ExecSQL(SQLDELETE, [FBase]); Result := True; finally fdQuery.Connection.Close; fdQuery.Free; end; end; function TEnderecosBases.GetSeq: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(seq_endereco),0) + 1 from ' + TABLENAME + ' where cod_agente = ' + FBase.ToString); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TEnderecosBases.Gravar: Boolean; begin Result:= False; case FAcao of tacIndefinido: Exit; tacIncluir: Result := Inserir(); tacAlterar: Result := Alterar(); tacExcluir: Result := Excluir(); tacPesquisa: Exit; end; end; function TEnderecosBases.Inserir: Boolean; var fdQuery: TFDQuery; begin try Result := False; fdQuery := FConexao.ReturnQuery; FSequencia := GetSeq(); fdQuery.ExecSQL(SQLINSERT, [FBase, FSequencia, FTipo, FLogradouro, FNumero, FComplemento, FPadrao, FBairro, FCidade, FUF, FCEP, FReferencia]); Result := True; finally fdQuery.Connection.Close; fdQuery.Free; end; end; function TEnderecosBases.Localizar(aParam: array of variant): TFDQuery; var fdQuery: TFDQuery; begin if Length(aParam) < 2 then Exit; fdQuery := FConexao.ReturnQuery; fdQuery.SQL.Add(SQLQUERY); if aParam[0] = 'CODIGO' then begin if Length(aParam) = 2 then begin fdQuery.SQL.Add('where cod_agente = :cod_agente'); fdQuery.ParamByName('cod_agente').AsInteger := aParam[1]; end else if Length(aParam) = 3 then begin fdQuery.SQL.Add('where cod_agente = :cod_agente and seq_endereco = :seq_endereco'); fdQuery.ParamByName('cod_agente').AsInteger := aParam[1]; fdQuery.ParamByName('seq_endereco').AsInteger := aParam[2]; end; end else if aParam[0] = 'LOGRADOURO' then begin if Length(aParam) = 2 then begin fdQuery.SQL.Add('where des_logradouro like :des_logradouro'); fdQuery.ParamByName('des_logradouro').AsString := aParam[1]; end else if Length(aParam) = 3 then begin fdQuery.SQL.Add('where des_logradouro like :des_logradouro and num_logradouro like :num_logradouro'); fdQuery.ParamByName('des_logradouro').AsString := aParam[1]; fdQuery.ParamByName('num_logradouro').AsString := aParam[2]; end; end else if aParam[0] = 'CEP' then begin fdQuery.SQL.Add('where num_cep like :num_cep'); fdquery.ParamByName('num_cep').AsString := aParam[1]; end else if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + aParam[1]); end else if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]); end; fdQuery.Open(); Result := fdQuery; end; end.
unit MapTypes; interface uses Windows, Classes, Graphics, GameTypes, LanderTypes, Protocol, VoyagerServerInterfaces, Circuits, CircuitsHandler, Land, Vehicles, LocalCacheTypes, Config; const cBasicZoomRes : TZoomRes = zr32x64; cBasicRotation : TRotation = drNorth; type TZoomFactor = record m : integer; n : integer; end; const cZoomFactors : array [TZoomRes] of TZoomFactor = ( (m : 1 shl ord(zr4x8); n : 1 shl ord(zr32x64)), (m : 1 shl ord(zr8x16); n : 1 shl ord(zr32x64)), (m : 1 shl ord(zr16x32); n : 1 shl ord(zr32x64)), (m : 1 shl ord(zr32x64); n : 1 shl ord(zr32x64)) ); type TMapImage = TGameImage; type TMapPoint = record r, c : integer; end; const idMask = $FFFF0000; idLandMask = $00000000; idConcreteMask = $00010000; idBuildingMask = $00020000; idRoadBlockMask = $00030000; idCarMask = $00040000; idRailroadBlockMask = $00050000; idTraincarMask = $00060000; idPlaneMask = $00070000; idEffectMask = $00080000; idRailingMask = $00090000; idPedestrianMask = $000a0000; idRGBColorMask = $80000000; type idLand = byte; idConcrete = byte; idBuilding = word; idCompany = word; idRoadBlock = byte; idCar = byte; idRailroadBlock = byte; idTraincar = byte; idPlane = byte; idFluid = byte; idEffect = byte; idPedestrian = byte; type TSoundData = record wavefile : string; atenuation : single; priority : integer; looped : boolean; probability : single; period : integer; end; type PSoundDataArray = ^TSoundDataArray; TSoundDataArray = array [0..0] of TSoundData; type TSoundSetKind = (ssNone, ssAnimDriven, ssStochastic); type TSoundSetData = record Kind : TSoundSetKind; Count : integer; Sounds : PSoundDataArray; end; type TLoadedImg = (ldimgNormal, ldimgDefault, ldimgNone); type PLandBlockClass = ^TLandBlockClass; TLandBlockClass = record id : integer; ImagePath : string; LoadedImg : TLoadedImg; TerrainType : string; SoundData : TSoundData; end; type PLandAccident = ^TLandAccident; TLandAccident = record x, y : integer; visclass : integer; end; type TFacId = byte; type TBuildOptions = (boDefault, boOnlyOnLand, boOnlyOnWater, boBoth); type TEffectOption = (eoGlassed, eoAnimated); TEffectOptions = set of TEffectOption; type TEfxData = record id : integer; x, y : integer; Options : TEffectOptions; end; type PEfxDataArray = ^TEfxDataArray; TEfxDataArray = array [0..0] of TEfxData; type TBuildingEfxData = record Count : integer; Efxs : PEfxDataArray; end; type PBuildingClass = ^TBuildingClass; TBuildingClass = packed record id : idBuilding; Size : smallint; Height : integer; Name : string; ImagePath : string; LoadedImg : TLoadedImg; TerrainType : string; Urban : boolean; Accident : boolean; ZoneType : TZoneType; VoidSquares : byte; FacId : TFacId; Requires : TFacId; HideColor : TColor; Selectable : boolean; BuildOpts : TBuildOptions; Animated : boolean; AnimArea : TRect; LevelSignX : integer; LevelSignY : integer; EfxData : TBuildingEfxData; SoundData : TSoundSetData; end; type TPedestrians = TInterfaceList; type IBuildingClassBag = interface procedure Add(const which : TBuildingClass); function Get(id : idBuilding) : PBuildingClass; function GetByName(var startidx : integer; const classname : string) : PBuildingClass; function GetMaxId : idBuilding; procedure Clear; end; type TCarDir = (cdNorth, cdSouth, cdEast, cdWest); type TRoadSide = (rsNorth, rsSouth, rsEast, rsWest); type TRouteNode = record x : integer; y : integer; angle : TAngle; end; type PRouteNodeArray = ^TRouteNodeArray; TRouteNodeArray = array [0..0] of TRouteNode; type TSpriteRoute = record Count : integer; Alloc : integer; Nodes : PRouteNodeArray; end; type TRouteSegment = record sx, sy : integer; ex, ey : integer; angle : TAngle; frames : integer; end; type PRouteSegmentArray = ^TRouteSegmentArray; TRouteSegmentArray = array [0..0] of TRouteSegment; type TSegmentedSpriteRoute = record Count : integer; Alloc : integer; Segments : PRouteSegmentArray; end; type TCarRoutes = array [TRoadSide, TCarDir] of TSpriteRoute; type PRoadBlockClass = ^TRoadBlockClass; TRoadBlockClass = record id : idRoadBlock; ImagePath : string; RailingImgPath : string; CarRoutes : TCarRoutes; Freq : integer; end; type PCarClass = ^TCarClass; TCarClass = record id : idCar; valid : boolean; ImagePaths : array [TAngle] of string; Prob : single; Cargo : TCargoKind; SoundData : TSoundData; end; type TTrainRoutes = array [TVehicleDirection, TVehicleDirection] of TSpriteRoute; type PRailRoadBlockClass = ^TRailroadBlockClass; TRailroadBlockClass = record id : integer; ImagePath : string; TrainRoutes : TTrainRoutes; end; type PTraincarClass = ^TTraincarClass; TTraincarClass = record id : idTraincar; ImagePaths : array [TAngle] of string; SoundData : TSoundData; end; type PPlaneClass = ^TPlaneClass; TPlaneClass = record id : idPlane; valid : boolean; ImagePaths : array [TAngle] of string; Prob : single; Speed : single; SoundData : TSoundData; end; type PFluidClass = ^TFluidClass; TFluidClass = record id : idFluid; Color : TColor; end; type PEffectClass = ^TEffectClass; TEffectClass = record id : idEffect; ImagePath : string; XHook : integer; YHook : integer; SoundData : TSoundSetData; end; type PImageInfo = ^TImageInfo; TImageInfo = record FrameCount : byte; Width : integer; Height : integer; end; PPedestrianClass = ^TPedestrianClass; TPedestrianClass = record id : idPedestrian; valid : boolean; DelayTick : word; ImagePaths : array [TAngle] of string; ImageInfo : array [TAngle] of TImageInfo; end; // Map objects type TConcrete = byte; type TBuildingInfo = record idx : integer; r, c : integer; end; type TRoad = integer; type TRailroad = byte; type PCargoData = ^TCargoData; TCargoData = record Slopes : array [TCarDir, TCargoKind] of integer; Cargos : array [TCargoKind] of integer; end; const cargoNone : PCargoData = nil; type TCarId = word; type IWorldMapInit = interface procedure SetClientView(const which : IClientView); procedure SetCircuitsHandler(const which : ICircuitsHandler); procedure SetCoordConverter(const which : ICoordinateConverter); procedure SetTraincarsArray(const which : IVehicleArray); procedure SetMinimize(const value: boolean); procedure DestroyAll; end; type IWorldMap = interface function GetRows : integer; function GetColumns : integer; function GetConcrete(i, j : integer) : TConcrete; function CheckForWater(i, j : integer) : boolean; function CheckForConcrete(i, j : integer) : boolean; function GetBuilding(i, j : integer; out buildinfo : TBuildingInfo) : boolean; function CheckForBuilding(i, j : integer) : boolean; function GetRoad(i, j : integer) : TRoad; {$IFDEF USECARGODATA} function GetCargoData(i, j : integer) : PCargoData; procedure SetCargoData(i, j : integer; which : PCargoData); {$ENDIF} function GetRailroad(i, j : integer) : TRailroad; function GetCar(i, j : integer; side : TRoadSide) : TCarId; procedure SetCar(i, j : integer; side : TRoadSide; car : TCarId); {$ifdef Pedestrian} procedure AddPedestrian(const i, j : integer; const Pedestrian : IUnknown); procedure RemovePedestrian(const i, j : integer; const Pedestrian : IUnknown); function GetPedestrian(i, j : integer) : TPedestrians; {$ENDIF} end; // Local cache type ILocalCacheManager = interface procedure SetClientView(const ClientView : IClientView); procedure SetConfigHolder(const ConfigHolder : IConfigHolder); function Load(const url : string) : boolean; procedure SetAdviseSink(const Sink : ILocalCacheAdviseSink); function GetLandMap : TMapImage; {$IFDEF LANDACCIDENTS} function GetLandAccidentCount : integer; function GetLandAccident(i : integer) : PLandAccident; {$ENDIF} function GetBuildingClass(id : idBuilding) : PBuildingClass; function GetRoadBlockClass(id : idRoadBlock) : PRoadBlockClass; function GetCarClassCount : integer; function GetCarClass(id : idCar) : PCarClass; function GetRailroadBlockClass(id : idRailroadBlock) : PRailroadBlockClass; function GetTraincarClassCount : integer; function GetTraincarClass(id : idTraincar) : PTraincarClass; function GetPlaneClassCount : integer; function GetPlaneClass(id : idPlane) : PPlaneClass; function GetFluidClass(id : idFluid) : PFluidClass; function GetEffectClass(id : idEffect) : PEffectClass; function GetPedestrianClassCount : integer; function GetPedestrianClass(id : idPedestrian) : PPedestrianClass; function GetLandClass(landId : idLand) : PLandBlockClass; function GetLandImage(const zoom : TZoomRes; id : idLand; suit : integer) : TGameImage; procedure LandImageReleased(const zoom : TZoomRes; id : idLand; suit : integer); {$IFDEF LANDACCIDENTS} function GetLandAccidentImage(const zoom : TZoomRes; id : idBuilding; suit : integer) : TGameImage; procedure LandAccidentImageReleased(const zoom : TZoomRes; id : idBuilding; suit : integer); {$ENDIF} function GetBuildingImage(const zoom : TZoomRes; id : idBuilding) : TGameImage; function GetConcreteImage(const zoom : TZoomRes; id : idConcrete) : TGameImage; function GetRoadBlockImage(const zoom : TZoomRes; id : idRoadBlock) : TGameImage; function GetRailingImage(const zoom : TZoomRes; id : idRoadBlock) : TGameImage; function GetCarImage(const zoom : TZoomRes; id : idCar; angle : TAngle) : TGameImage; function GetRailroadBlockImage(const zoom : TZoomRes; id : idRailroadBlock) : TGameImage; function GetTraincarImage(const zoom : TZoomRes; id : idTraincar; angle : TAngle) : TGameImage; function GetPlaneImage(const zoom : TZoomRes; id : idPlane; angle : TAngle) : TGameImage; function GetEffectImage(const zoom : TZoomRes; id : idEffect) : TGameImage; function GetPedestrianImage(const zoom : TZoomRes; id : idPedestrian; angle : TAngle) : TGameImage; function GetSpareImage(const zoom : TZoomRes) : TGameImage; function GetDownloadImage(const zoom : TZoomRes) : TGameImage; function GetShadeImage(const zoom : TZoomRes) : TGameImage; function GetRedShadeImage(const zoom : TZoomRes) : TGameImage; function GetBlackShadeImage(const zoom : TZoomRes) : TGameImage; {$IFDEF SHOWCNXS} function GetCnxSourceDownImage(const zoom : TZoomRes) : TGameImage; function GetCnxSourceTopImage(const zoom : TZoomRes) : TGameImage; function GetCnxDestDownImage(const zoom : TZoomRes) : TGameImage; function GetCnxDestTopImage(const zoom : TZoomRes) : TGameImage; {$ENDIF} function GetBuildingClasses : IBuildingClassBag; procedure DestroyAll; end; type TErrorCode = VoyagerServerInterfaces.TErrorCode; TObjectReport = VoyagerServerInterfaces.TObjectReport; TSegmentReport = VoyagerServerInterfaces.TSegmentReport; IClientView = VoyagerServerInterfaces.IClientView; implementation end.
unit Model.Bases; interface uses Common.ENum, FireDAC.Comp.Client, System.SysUtils, DAO.Conexao; type TBases = class private FConexao : TConexao; FCodigo: Integer; FRazaoSocial: String; FNomeFantasia: String; FTipoDoc: String; FCNPJCPF: String; FIE: String; FIEST: String; FIM: String; FCNAE: String; FCRT: Integer; FNumeroCNH: String; FCategoriaCNH: String; FValidadeCNH: TDate; FPaginaWeb: String; FStatus: Integer; FObs: String; FDataCadastro: TDate; FDataAlteracao: TDate; FValorVerba: Double; FTipoConta: String; FCodigoBanco: String; FNumeroAgente: String; FNumeroConta: String; FNomeFavorecido: String; FCNPJCPFFavorecido: String; FFormaPagamento: String; FCentroCusto: Integer; FGrupo: Integer; FAcao: TAcao; FTabela: Integer; FChave: String; function Inserir(): Boolean; function Alterar(): Boolean; function Excluir(): Boolean; public property Codigo: Integer read FCodigo write FCodigo; property RazaoSocial: String read FRazaoSocial write FRazaoSocial; property NomeFantasia: String read FNomeFantasia write FNomeFantasia; property TipoDoc: String read FTipoDoc write FTipoDoc; property CNPJCPF: String read FCNPJCPF write FCNPJCPF; property IE: String read FIE write FIE; property IEST: String read FIEST write FIEST; property IM: String read FIM write FIM; property CNAE: String read FCNAE write FCNAE; property CRT: Integer read FCRT write FCRT; property NumeroCNH: String read FNumeroCNH write FNumeroCNH; property CategoriaCNH: String read FCategoriaCNH write FCategoriaCNH; property ValidadeCNH: TDate read FValidadeCNH write FValidadeCNH; property PaginaWeb: String read FPaginaWeb write FPaginaWeb; property Status: Integer read FStatus write FStatus; property Obs: String read FObs write FObs; property DataCadastro: TDate read FDataCadastro write FDataCadastro; property DataAlteracao: TDate read FDataAlteracao write FDataAlteracao; property ValorVerba: Double read FValorVerba write FValorVerba; property TipoConta: String read FTipoConta write FTipoConta; property CodigoBanco: String read FCodigoBanco write FCodigoBanco; property NumeroAgente: String read FNumeroAgente write FNumeroAgente; property NumeroConta: String read FNumeroConta write FNumeroConta; property NomeFavorecido: String read FNomeFavorecido write FNomeFavorecido; property CNPJCPFFavorecido: String read FCNPJCPFFavorecido write FCNPJCPFFavorecido; property FormaPagamento: String read FFormaPagamento write FFormaPagamento; property CentroCusto: Integer read FCentroCusto write FCentroCusto; property Grupo: Integer read FGrupo write FGrupo; property Chave: String read FChave write FChave; property Tabela: Integer read FTabela write FTabela; property Acao: TAcao read FAcao write FAcao; constructor Create(); function Localizar(aParam: array of variant): TFDQuery; function LocalizarExato(aParam: array of variant): Boolean; function Gravar(): Boolean; function GetField(sField: String; sKey: String; sKeyValue: String): String; function SetupModel(FDBases: TFDQuery): Boolean; procedure ClearModel; end; const TABLENAME = 'tbagentes'; SQLUPDATE = 'update ' + TABLENAME + ' set ' + 'des_razao_social = :des_razao_social, nom_fantasia = :nom_fantasia, des_tipo_doc = :des_tipo_doc, ' + 'num_cnpj = :num_cnpj, num_ie = :num_ie, num_iest = :num_iest, num_im = :num_im, cod_cnae = :cod_cnae, ' + 'cod_crt = :cod_crt, num_cnh = :num_cnh, des_categoria_cnh = :des_categoria_cnh, ' + 'dat_validade_cnh = :dat_validade_cnh, des_pagina = :des_pagina, ' + 'cod_status = :cod_status, ' + 'des_observacao = :des_observacao, dat_cadastro = :dat_cadastro, dat_alteracao = :dat_alteracao, ' + 'val_verba = :val_verba, des_tipo_conta = :des_tipo_conta, cod_banco = :cod_banco, cod_agencia = :cod_agencia, ' + 'num_conta = :num_conta, nom_favorecido = :nom_favorecido, num_cpf_cnpj_favorecido = :num_cpf_cnpj_favorecido, ' + 'des_forma_pagamento = :des_forma_pagamento, cod_centro_custo = :cod_centro_custo, cod_grupo = :cod_grupo, ' + 'des_chave = :des_chave, cod_tabela = :cod_tabela ' + 'where ' + 'cod_agente = :cod_agente'; SQLDELETE = 'delete from ' + TABLENAME + ' where cod_agente = :cod_agente'; SQLINSERT = 'insert into ' + TABLENAME + '(cod_agente, des_razao_social, nom_fantasia, des_tipo_doc, num_cnpj, num_ie, num_iest, num_im, cod_cnae, ' + 'cod_crt, num_cnh, des_categoria_cnh, dat_validade_cnh, des_pagina, cod_status, des_observacao, ' + 'dat_cadastro, dat_alteracao, val_verba, des_tipo_conta, cod_banco, cod_agencia, num_conta, ' + 'nom_favorecido, num_cpf_cnpj_favorecido, des_forma_pagamento, cod_centro_custo, ' + 'cod_grupo, des_chave, cod_tabela) ' + 'values ' + '(:cod_agente, :des_razao_social, :nom_fantasia, :des_tipo_doc, :num_cnpj,:num_ie,:num_iest,:num_im,:cod_cnae, ' + ':cod_crt, :num_cnh, :des_categoria_cnh, :dat_validade_cnh, :des_pagina, :cod_status, :des_observacao, ' + ':dat_cadastro, :dat_alteracao, :val_verba, :des_tipo_conta, :cod_banco, :cod_agencia, :num_conta, ' + ':nom_favorecido, :num_cpf_cnpj_favorecido, :des_forma_pagamento, :cod_centro_custo, ' + ':cod_grupo, :des_chave, :cod_tabela) '; SQLQUERY = 'select cod_agente, des_razao_social, nom_fantasia, des_tipo_doc, num_cnpj, num_ie, num_iest, num_im, ' + 'cod_cnae, cod_crt, num_cnh, des_categoria_cnh, dat_validade_cnh, des_pagina, cod_status, des_observacao, ' + 'dat_cadastro, dat_alteracao, val_verba, des_tipo_conta, cod_banco, cod_agencia, num_conta, nom_favorecido, ' + 'num_cpf_cnpj_favorecido, des_forma_pagamento, cod_centro_custo, cod_grupo, des_chave, cod_tabela ' + 'from ' + TABLENAME; implementation { TBases } function TBases.Alterar: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL(SQLUPDATE, [FRazaoSocial, FNomeFantasia, FTipoDoc, FCNPJCPF, FIE, FIEST, FIM, FCNAE, FCRT, FNumeroCNH, FCategoriaCNH, FValidadeCNH, FPaginaWeb, FStatus, FObs, FDataCadastro, FDataAlteracao, FValorVerba, FTipoConta, FCodigoBanco, FNumeroAgente, FNumeroConta, FNomeFavorecido, FCNPJCPFFavorecido, FFormaPagamento, FCentroCusto, FGrupo, FChave, FTabela, FCodigo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; procedure TBases.ClearModel(); begin FCodigo := 0; FRazaoSocial := ''; FNomeFantasia := ''; FTipoDoc := ''; FCNPJCPF := ''; FIE := ''; FIEST := ''; FIM := ''; FCNAE := ''; FCRT := 0; FNumeroCNH := ''; FCategoriaCNH := ''; FValidadeCNH := StrToDate('31/12/1899'); FPaginaWeb := ''; FStatus := 0; FObs := ''; FDataCadastro := StrToDate('31/12/1899'); FDataAlteracao := StrToDate('31/12/1899'); FValorVerba := 0; FTipoConta := ''; FCodigoBanco := ''; FNumeroAgente := ''; FNumeroConta := ''; FNomeFavorecido := ''; FCNPJCPFFavorecido := ''; FFormaPagamento := ''; FCentroCusto := 0; FGrupo := 0; FTabela := 0; FChave := ''; end; constructor TBases.Create; begin FConexao := TConexao.Create; end; function TBases.Excluir: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL(SQLDELETE, [FCodigo]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TBases.GetField(sField, sKey, sKeyValue: String): String; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.SQL.Text := 'select ' + sField + ' from ' + TABLENAME + ' where ' + sKey + ' = ' + sKeyValue; FDQuery.Open(); if not FDQuery.IsEmpty then Result := FDQuery.FieldByName(sField).AsString; finally FDQuery.Free; end; end; function TBases.Gravar: Boolean; begin Result := False; case FAcao of tacIncluir: Result := Inserir(); tacAlterar: Result := Alterar(); tacExcluir: Result := Excluir(); end; end; function TBases.Inserir: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL(SQLINSERT, [FCodigo, FRazaoSocial, FNomeFantasia, FTipoDoc, FCNPJCPF, FIE, FIEST, FIM, FCNAE, FCRT, FNumeroCNH, FCategoriaCNH, FValidadeCNH, FPaginaWeb, FStatus, FObs, FDataCadastro, FDataAlteracao, FValorVerba, FTipoConta, FCodigoBanco, FNumeroAgente, FNumeroConta, FNomeFavorecido, FCNPJCPFFavorecido, FFormaPagamento, FCentroCusto, FGrupo, FChave, FTabela]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TBases.Localizar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add(SQLQUERY); if aParam[0] = 'CODIGO' then begin FDQuery.SQL.Add('where cod_agente = :cod_agente'); FDQuery.ParamByName('cod_agente').AsInteger := aParam[1]; end else if aParam[0] = 'CNPJ' then begin FDQuery.SQL.Add('where num_cnpj = :num_cnpj'); FDQuery.ParamByName('num_cnpj').AsString := aParam[1]; end else if aParam[0] = 'RAZAO' then begin FDQuery.SQL.Add('where des_razao_social like :des_razao_social'); FDQuery.ParamByName('des_razao_social').AsString := aParam[1]; end else if aParam[0] = 'FANTASIA' then begin FDQuery.SQL.Add('where nom_fantasia = :nom_fantasia'); FDQuery.ParamByName('nom_fantasia').AsString := aParam[1]; end else if aParam[0] = 'IE' then begin FDQuery.SQL.Add('where num_ie = :num_ie'); FDQuery.ParamByName('num_ie').AsString := aParam[1]; end else if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + aParam[1]); end else if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open; Result := FDQuery; end; function TBases.LocalizarExato(aParam: array of variant): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'CODIGO' then begin FDQuery.SQL.Add('where cod_agente = :cod_agente'); FDQuery.ParamByName('cod_agente').AsInteger := aParam[1]; end else if aParam[0] = 'CNPJ' then begin FDQuery.SQL.Add('where num_cnpj = :num_cnpj'); FDQuery.ParamByName('num_cnpj').AsString := aParam[1]; end else if aParam[0] = 'RAZAO' then begin FDQuery.SQL.Add('where des_razao_social like :des_razao_social'); FDQuery.ParamByName('des_razao_social').AsString := aParam[1]; end else if aParam[0] = 'FANTASIA' then begin FDQuery.SQL.Add('where nom_fantasia = :nom_fantasia'); FDQuery.ParamByName('nom_fantasia').AsString := aParam[1]; end else if aParam[0] = 'IE' then begin FDQuery.SQL.Add('where num_ie = :num_ie'); FDQuery.ParamByName('num_ie').AsString := aParam[1]; end else if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + aParam[1]); end; FDQuery.Open; if not FDQuery.IsEmpty then begin FDQuery.First; Result := SetupModel(FDQuery); end else begin ClearModel(); Exit; end; Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TBases.SetupModel(FDBases: TFDQuery): Boolean; begin try Result := False; FCodigo := FDBases.FieldByName('cod_agente').AsInteger; FRazaoSocial := FDBases.FieldByName('des_razao_social').AsString; FNomeFantasia := FDBases.FieldByName('nom_fantasia').AsString; FTipoDoc := FDBases.FieldByName('des_tipo_doc').AsString; FCNPJCPF := FDBases.FieldByName('num_cnpj').AsString; FIE := FDBases.FieldByName('num_ie').AsString; FIEST := FDBases.FieldByName('num_iest').AsString; FIM := FDBases.FieldByName('num_im').AsString; FCNAE := FDBases.FieldByName('cod_cnae').AsString; FCRT := FDBases.FieldByName('cod_crt').AsInteger; FNumeroCNH := FDBases.FieldByName('num_cnh').AsString; FCategoriaCNH := FDBases.FieldByName('des_categoria_cnh').AsString; FValidadeCNH := FDBases.FieldByName('dat_validade_cnh').AsDateTime; FPaginaWeb := FDBases.FieldByName('des_pagina').AsString; FStatus := FDBases.FieldByName('cod_status').AsInteger; FObs := FDBases.FieldByName('des_observacao').AsString; FDataCadastro := FDBases.FieldByName('dat_cadastro').AsDateTime; FDataAlteracao := FDBases.FieldByName('dat_alteracao').AsDateTime; FValorVerba := FDBases.FieldByName('val_verba').AsFloat; FTipoConta := FDBases.FieldByName('des_tipo_conta').AsString; FCodigoBanco := FDBases.FieldByName('cod_banco').AsString; FNumeroAgente := FDBases.FieldByName('cod_agencia').AsString; FNumeroConta := FDBases.FieldByName('num_conta').AsString; FNomeFavorecido := FDBases.FieldByName('nom_favorecido').AsString; FCNPJCPFFavorecido := FDBases.FieldByName('num_cpf_cnpj_favorecido').AsString; FFormaPagamento := FDBases.FieldByName('des_forma_pagamento').AsString; FCentroCusto := FDBases.FieldByName('cod_centro_custo').AsInteger; FGrupo := FDBases.FieldByName('cod_grupo').AsInteger; FChave := FDBases.FieldByName('des_chave').AsString; FTabela := FDBases.FieldByName('cod_tabela').AsInteger; finally Result := True; end; end; end.
unit adl_structures; interface uses adl_defines; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the graphics adapter. /// /// This structure is used to store various information about the graphics adapter. This /// information can be returned to the user. Alternatively, it can be used to access various driver calls to set /// or fetch various settings upon the user's request. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type AdapterInfo = record /// \ALL_STRUCT_MEM /// Size of the structure. iSize: Integer; /// The ADL index handle. One GPU may be associated with one or two index handles iAdapterIndex: Integer; /// The unique device ID associated with this adapter. strUDID: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// The BUS number associated with this adapter. iBusNumber: Integer; /// The driver number associated with this adapter. iDeviceNumber: Integer; /// The function number. iFunctionNumber: Integer; /// The vendor ID associated with this adapter. iVendorID: Integer; /// Adapter name. strAdapterName: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// Display name. For example, "\\\\Display0" for Windows or ":0:0" for Linux. strDisplayName: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// Present or not; 1 if present and 0 if not present.It the logical adapter is present, the display name such as \\\\.\\Display1 can be found from OS iPresent: Integer; /// \WIN_STRUCT_MEM /// Exist or not; 1 is exist and 0 is not present. iExist: Integer; /// Driver registry path. strDriverPath: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// Driver registry path Ext for. strDriverPathExt: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// PNP string from Windows. strPNPString: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// It is generated from EnumDisplayDevices. iOSDisplayIndex: Integer; end; LPAdapterInfo = ^AdapterInfo; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the Linux X screen information. /// /// This structure is used to store the current screen number and xorg.conf ID name assoicated with an adapter index. /// This structure is updated during ADL_Main_Control_Refresh or ADL_ScreenInfo_Update. /// Note: This structure should be used in place of iXScreenNum and strXScreenConfigName in AdapterInfo as they will be /// deprecated. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the ASIC memory. /// /// This structure is used to store various information about the ASIC memory. This /// information can be returned to the user. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLMemoryInfo = record /// Memory size in bytes. iMemorySize: Int64; /// Memory type in string. strMemoryType: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// Memory bandwidth in Mbytes/s. iMemoryBandwidth: Int64; end; LPADLMemoryInfo = ^ADLMemoryInfo; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about memory required by type /// /// This structure is returned by ADL_Adapter_ConfigMemory_Get, which given a desktop and display configuration /// will return the Memory used. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLMemoryRequired = ( iMemoryReq, /// Memory in bytes required: Int64 iType, /// Type of Memory \ref define_adl_validmemoryrequiredfields: Integer iDisplayFeatureValue /// Display features \ref define_adl_visiblememoryfeatures that are using this type of memory: Integer ); LPADLMemoryRequired = ^ADLMemoryRequired; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the features associated with a display /// /// This structure is a parameter to ADL_Adapter_ConfigMemory_Get, which given a desktop and display configuration /// will return the Memory used. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// //type ADLMemoryDisplayFeatures = ( //iDisplayIndex, /// ADL Display index: Integer //iDisplayFeatureValue /// features that the display is using \ref define_adl_visiblememoryfeatures: Integer //); //LPADLMemoryDisplayFeatures = ^ADLMemoryDisplayFeatures; OOPS ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing DDC information. /// /// This structure is used to store various DDC information that can be returned to the user. /// Note that all fields of type int are actually defined as unsigned int types within the driver. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDDCInfo = record /// Size of the structure ulSize: Integer; /// Indicates whether the attached display supports DDC. If this field is zero on return, no other DDC information fields will be used. ulSupportsDDC: Integer; /// Returns the manufacturer ID of the display device. Should be zeroed if this information is not available. ulManufacturerID: Integer; /// Returns the product ID of the display device. Should be zeroed if this information is not available. ulProductID: Integer; /// Returns the name of the display device. Should be zeroed if this information is not available. cDisplayName: array[0..ADL_MAX_DISPLAY_NAME - 1] of AnsiChar; /// Returns the maximum Horizontal supported resolution. Should be zeroed if this information is not available. ulMaxHResolution: Integer; /// Returns the maximum Vertical supported resolution. Should be zeroed if this information is not available. ulMaxVResolution: Integer; /// Returns the maximum supported refresh rate. Should be zeroed if this information is not available. ulMaxRefresh: Integer; /// Returns the display device preferred timing mode's horizontal resolution. ulPTMCx: Integer; /// Returns the display device preferred timing mode's vertical resolution. ulPTMCy: Integer; /// Returns the display device preferred timing mode's refresh rate. ulPTMRefreshRate: Integer; /// Return EDID flags. ulDDCInfoFlag: Integer; end; LPADLDDCInfo = ^ADLDDCInfo; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing DDC information. /// /// This structure is used to store various DDC information that can be returned to the user. /// Note that all fields of type int are actually defined as unsigned int types within the driver. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDDCInfo2 = record /// Size of the structure ulSize: Integer; /// Indicates whether the attached display supports DDC. If this field is zero on return, no other DDC /// information fields will be used. ulSupportsDDC: Integer; /// Returns the manufacturer ID of the display device. Should be zeroed if this information is not available. ulManufacturerID: Integer; /// Returns the product ID of the display device. Should be zeroed if this information is not available. ulProductID: Integer; /// Returns the name of the display device. Should be zeroed if this information is not available. cDisplayName: array[0..ADL_MAX_DISPLAY_NAME - 1] of AnsiChar; /// Returns the maximum Horizontal supported resolution. Should be zeroed if this information is not available. ulMaxHResolution: Integer; /// Returns the maximum Vertical supported resolution. Should be zeroed if this information is not available. ulMaxVResolution: Integer; /// Returns the maximum supported refresh rate. Should be zeroed if this information is not available. ulMaxRefresh: Integer; /// Returns the display device preferred timing mode's horizontal resolution. ulPTMCx: Integer; /// Returns the display device preferred timing mode's vertical resolution. ulPTMCy: Integer; /// Returns the display device preferred timing mode's refresh rate. ulPTMRefreshRate: Integer; /// Return EDID flags. ulDDCInfoFlag: Integer; /// Returns 1 if the display supported packed pixel, 0 otherwise bPackedPixelSupported: Integer; /// Returns the Pixel formats the display supports \ref define_ddcinfo_pixelformats iPanelPixelFormat: Integer; /// Return EDID serial ID. ulSerialID: Integer; /// Return minimum monitor luminance data ulMinLuminanceData: Integer; /// Return average monitor luminance data ulAvgLuminanceData: Integer; /// Return maximum monitor luminance data ulMaxLuminanceData: Integer; /// Bit vector of supported transfer functions \ref define_source_content_TF iSupportedTransferFunction: Integer; /// Bit vector of supported color spaces \ref define_source_content_CS iSupportedColorSpace: Integer; /// Display Red Chromaticity X coordinate multiplied by 10000 iNativeDisplayChromaticityRedX: Integer; /// Display Red Chromaticity Y coordinate multiplied by 10000 iNativeDisplayChromaticityRedY: Integer; /// Display Green Chromaticity X coordinate multiplied by 10000 iNativeDisplayChromaticityGreenX: Integer; /// Display Green Chromaticity Y coordinate multiplied by 10000 iNativeDisplayChromaticityGreenY: Integer; /// Display Blue Chromaticity X coordinate multiplied by 10000 iNativeDisplayChromaticityBlueX: Integer; /// Display Blue Chromaticity Y coordinate multiplied by 10000 iNativeDisplayChromaticityBlueY: Integer; /// Display White Point X coordinate multiplied by 10000 iNativeDisplayChromaticityWhitePointX: Integer; /// Display White Point Y coordinate multiplied by 10000 iNativeDisplayChromaticityWhitePointY: Integer; /// Display diffuse screen reflectance 0-1 (100%) in units of 0.01 iDiffuseScreenReflectance: Integer; /// Display specular screen reflectance 0-1 (100%) in units of 0.01 iSpecularScreenReflectance: Integer; /// Bit vector of supported color spaces \ref define_HDR_support iSupportedHDR: Integer; /// Bit vector for freesync flags iFreesyncFlags: Integer; // Reserved for future use iReserved: array[1..9]of Integer; end; LPADLDDCInfo2 = ^ADLDDCInfo2; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information controller Gamma settings. /// /// This structure is used to store the red, green and blue color channel information for the. /// controller gamma setting. This information is returned by ADL, and it can also be used to /// set the controller gamma setting. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLGamma = record /// Red color channel gamma value. fRed: Single; /// Green color channel gamma value. fGreen: Single; /// Blue color channel gamma value. fBlue: Single; end; LPADLGamma = ^ADLGamma; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about component video custom modes. /// /// This structure is used to store the component video custom mode. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLCustomMode = record /// Custom mode flags. They are returned by the ADL driver. iFlags: Integer; /// Custom mode width. iModeWidth: Integer; /// Custom mode height. iModeHeight: Integer; /// Custom mode base width. iBaseModeWidth: Integer; /// Custom mode base height. iBaseModeHeight: Integer; /// Custom mode refresh rate. iRefreshRate: Integer; end; LPADLCustomMode = ^ADLCustomMode; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing Clock information for OD5 calls. /// /// This structure is used to retrieve clock information for OD5 calls. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLGetClocksOUT = record ulHighCoreClock: Cardinal; ulHighMemoryClock: Cardinal; ulHighVddc: Cardinal; ulCoreMin: Cardinal; ulCoreMax: Cardinal; ulMemoryMin: Cardinal; ulMemoryMax: Cardinal; ulActivityPercent: Cardinal; ulCurrentCoreClock: Cardinal; ulCurrentMemoryClock: Cardinal; ulReserved: Cardinal; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing HDTV information for display calls. /// /// This structure is used to retrieve HDTV information information for display calls. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDisplayConfig = record /// Size of the structure ulSize: Cardinal; /// HDTV connector type. ulConnectorType: Cardinal; /// HDTV capabilities. ulDeviceData: Cardinal; /// Overridden HDTV capabilities. ulOverridedDeviceData: Cardinal; /// Reserved field ulReserved: Cardinal; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the display device. /// /// This structure is used to store display device information /// such as display index, type, name, connection status, mapped adapter and controller indexes, /// whether or not multiple VPUs are supported, local display connections or not (through Lasso), etc. /// This information can be returned to the user. Alternatively, it can be used to access various driver calls to set /// or fetch various display device related settings upon the user's request. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDisplayID = record /// The logical display index belonging to this adapter. iDisplayLogicalIndex: Integer; ///\brief The physical display index. /// For example, display index 2 from adapter 2 can be used by current adapter 1.\n /// So current adapter may enumerate this adapter as logical display 7 but the physical display /// index is still 2. iDisplayPhysicalIndex: Integer; /// The persistent logical adapter index for the display. iDisplayLogicalAdapterIndex: Integer; ///\brief The persistent physical adapter index for the display. /// It can be the current adapter or a non-local adapter. \n /// If this adapter index is different than the current adapter, /// the Display Non Local flag is set inside DisplayInfoValue. iDisplayPhysicalAdapterIndex: Integer; end; LPADLDisplayID = ^ADLDisplayID; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the display device. /// /// This structure is used to store various information about the display device. This /// information can be returned to the user, or used to access various driver calls to set /// or fetch various display-device-related settings upon the user's request /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDisplayInfo = record /// The DisplayID structure displayID: ADLDisplayID; ///\deprecated The controller index to which the display is mapped.\n Will not be used in the future\n iDisplayControllerIndex: Integer; /// The display's EDID name. strDisplayName: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// The display's manufacturer name. strDisplayManufacturerName: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// The Display type. For example: CRT, TV, CV, DFP. iDisplayType: Integer; /// The display output type. For example: HDMI, SVIDEO, COMPONMNET VIDEO. iDisplayOutputType: Integer; /// The connector type for the device. iDisplayConnector: Integer; ///\brief The bit mask identifies the number of bits ADLDisplayInfo is currently using. \n /// It will be the sum all the bit definitions in ADL_DISPLAY_DISPLAYINFO_xxx. iDisplayInfoMask: Integer; /// The bit mask identifies the display status. \ref define_displayinfomask iDisplayInfoValue: Integer; end; LPADLDisplayInfo = ^ADLDisplayInfo; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the display port MST device. /// /// This structure is used to store various MST information about the display port device. This /// information can be returned to the user, or used to access various driver calls to /// fetch various display-device-related settings upon the user's request /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDisplayDPMSTInfo = record /// The ADLDisplayID structure displayID: ADLDisplayID; /// total bandwidth available on the DP connector iTotalAvailableBandwidthInMpbs: Integer; /// bandwidth allocated to this display iAllocatedBandwidthInMbps: Integer; // info from DAL DpMstSinkInfo /// string identifier for the display strGlobalUniqueIdentifier: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// The link count of relative address, rad[0] upto rad[linkCount] are valid radLinkCount: Integer; /// The physical connector ID, used to identify the physical DP port iPhysicalConnectorID: Integer; /// Relative address, address scheme starts from source side rad: array[0..ADL_MAX_RAD_LINK_COUNT - 1] of AnsiChar; end; LPADLDisplayDPMSTInfo = ^ADLDisplayDPMSTInfo; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing the display mode definition used per controller. /// /// This structure is used to store the display mode definition used per controller. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDisplayMode = record /// Vertical resolution (in pixels). iPelsHeight: Integer; /// Horizontal resolution (in pixels). iPelsWidth: Integer; /// Color depth. iBitsPerPel: Integer; /// Refresh rate. iDisplayFrequency: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing detailed timing parameters. /// /// This structure is used to store the detailed timing parameters. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDetailedTiming = record /// Size of the structure. iSize: Integer; /// Timing flags. \ref define_detailed_timing_flags sTimingFlags: Smallint; /// Total width (columns). sHTotal: Smallint; /// Displayed width. sHDisplay: Smallint; /// Horizontal sync signal offset. sHSyncStart: Smallint; /// Horizontal sync signal width. sHSyncWidth: Smallint; /// Total height (rows). sVTotal: Smallint; /// Displayed height. sVDisplay: Smallint; /// Vertical sync signal offset. sVSyncStart: Smallint; /// Vertical sync signal width. sVSyncWidth: Smallint; /// Pixel clock value. sPixelClock: Smallint; /// Overscan right. sHOverscanRight: Smallint; /// Overscan left. sHOverscanLeft: Smallint; /// Overscan bottom. sVOverscanBottom: Smallint; /// Overscan top. sVOverscanTop: Smallint; sOverscan8B: Smallint; sOverscanGR: Smallint; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing display mode information. /// /// This structure is used to store the display mode information. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDisplayModeInfo = record /// Timing standard of the current mode. \ref define_modetiming_standard iTimingStandard: Integer; /// Applicable timing standards for the current mode. iPossibleStandard: Integer; /// Refresh rate factor. iRefreshRate: Integer; /// Num of pixels in a row. iPelsWidth: Integer; /// Num of pixels in a column. iPelsHeight: Integer; /// Detailed timing parameters. sDetailedTiming: ADLDetailedTiming; end; ///////////////////////////////////////////////////////////////////////////////////////////// /// \brief Structure containing information about display property. /// /// This structure is used to store the display property for the current adapter. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDisplayProperty = record /// Must be set to sizeof the structure iSize: Integer; /// Must be set to \ref ADL_DL_DISPLAYPROPERTY_TYPE_EXPANSIONMODE or \ref ADL_DL_DISPLAYPROPERTY_TYPE_USEUNDERSCANSCALING iPropertyType: Integer; /// Get or Set \ref ADL_DL_DISPLAYPROPERTY_EXPANSIONMODE_CENTER or \ref ADL_DL_DISPLAYPROPERTY_EXPANSIONMODE_FULLSCREEN or \ref ADL_DL_DISPLAYPROPERTY_EXPANSIONMODE_ASPECTRATIO or \ref ADL_DL_DISPLAYPROPERTY_TYPE_ITCFLAGENABLE iExpansionMode: Integer; /// Display Property supported? 1: Supported, 0: Not supported iSupport: Integer; /// Display Property current value iCurrent: Integer; /// Display Property Default value iDefault: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Clock. /// /// This structure is used to store the clock information for the current adapter /// such as core clock and memory clock info. ///\nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLClockInfo = record /// Core clock in 10 KHz. iCoreClock: Integer; /// Memory clock in 10 KHz. iMemoryClock: Integer; end; LPADLClockInfo = ^ADLClockInfo; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about I2C. /// /// This structure is used to store the I2C information for the current adapter. /// This structure is used by the ADL_Display_WriteAndReadI2C() function. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLI2C = record /// Size of the structure iSize: Integer; /// Numerical value representing hardware I2C. iLine: Integer; /// The 7-bit I2C slave device address, shifted one bit to the left. iAddress: Integer; /// The offset of the data from the address. iOffset: Integer; /// Read from or write to slave device. \ref ADL_DL_I2C_ACTIONREAD or \ref ADL_DL_I2C_ACTIONWRITE or \ref ADL_DL_I2C_ACTIONREAD_REPEATEDSTART iAction: Integer; /// I2C clock speed in KHz. iSpeed: Integer; /// A numerical value representing the number of bytes to be sent or received on the I2C bus. iDataSize: Integer; /// Address of the AnsiCharacters which are to be sent or received on the I2C bus. pcData: PAnsiChar; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about EDID data. /// /// This structure is used to store the information about EDID data for the adapter. /// This structure is used by the ADL_Display_EdidData_Get() and ADL_Display_EdidData_Set() functions. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDisplayEDIDData = record /// Size of the structure iSize: Integer; /// Set to 0 iFlag: Integer; /// Size of cEDIDData. Set by ADL_Display_EdidData_Get() upon return iEDIDSize: Integer; /// 0, 1 or 2. If set to 3 or above an error ADL_ERR_INVALID_PARAM is generated iBlockIndex: Integer; /// EDID data cEDIDData: array [0..ADL_MAX_EDIDDATA_SIZE - 1] of AnsiChar; /// Reserved iReserved: array[1..4] of Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about input of controller overlay adjustment. /// /// This structure is used to store the information about input of controller overlay adjustment for the adapter. /// This structure is used by the ADL_Display_ControllerOverlayAdjustmentCaps_Get, ADL_Display_ControllerOverlayAdjustmentData_Get, and /// ADL_Display_ControllerOverlayAdjustmentData_Set() functions. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLControllerOverlayInput = record /// Should be set to the sizeof the structure iSize: Integer; ///\ref ADL_DL_CONTROLLER_OVERLAY_ALPHA or \ref ADL_DL_CONTROLLER_OVERLAY_ALPHAPERPIX iOverlayAdjust: Integer; /// Data. iValue: Integer; /// Should be 0. iReserved: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about overlay adjustment. /// /// This structure is used to store the information about overlay adjustment for the adapter. /// This structure is used by the ADLControllerOverlayInfo() function. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLAdjustmentinfo = record /// Default value iDefault: Integer; /// Minimum value iMin: Integer; /// Maximum Value iMax: Integer; /// Step value iStep: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about controller overlay information. /// /// This structure is used to store information about controller overlay info for the adapter. /// This structure is used by the ADL_Display_ControllerOverlayAdjustmentCaps_Get() function. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLControllerOverlayInfo = record /// Should be set to the sizeof the structure iSize: Integer; /// Data. sOverlayInfo: ADLAdjustmentinfo; /// Should be 0. iReserved: array[1..3] of Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing GL-Sync module information. /// /// This structure is used to retrieve GL-Sync module information for /// Workstation Framelock/Genlock. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLGLSyncModuleID = record /// Unique GL-Sync module ID. iModuleID: Integer; /// GL-Sync GPU port index (to be passed into ADLGLSyncGenlockConfig.lSignalSource and ADLGlSyncPortControl.lSignalSource). iGlSyncGPUPort: Integer; /// GL-Sync module firmware version of Boot Sector. iFWBootSectorVersion: Integer; /// GL-Sync module firmware version of User Sector. iFWUserSectorVersion: Integer; end; LPADLGLSyncModuleID = ^ADLGLSyncModuleID ; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing GL-Sync ports capabilities. /// /// This structure is used to retrieve hardware capabilities for the ports of the GL-Sync module /// for Workstation Framelock/Genlock (such as port type and number of associated LEDs). /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLGLSyncPortCaps = record /// Port type. Bitfield of ADL_GLSYNC_PORTTYPE_* \ref define_glsync iPortType: Integer; /// Number of LEDs associated for this port. iNumOfLEDs: Integer; end; LPADLGLSyncPortCaps = ^ADLGLSyncPortCaps; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing GL-Sync Genlock settings. /// /// This structure is used to get and set genlock settings for the GPU ports of the GL-Sync module /// for Workstation Framelock/Genlock.\n /// \see define_glsync /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLGLSyncGenlockConfig = record /// Specifies what fields in this structure are valid \ref define_glsync iValidMask: Integer; /// Delay (ms) generating a sync signal. iSyncDelay: Integer; /// Vector of framelock control bits. Bitfield of ADL_GLSYNC_FRAMELOCKCNTL_* \ref define_glsync iFramelockCntlVector: Integer; /// Source of the sync signal. Either GL_Sync GPU Port index or ADL_GLSYNC_SIGNALSOURCE_* \ref define_glsync iSignalSource: Integer; /// Use sampled sync signal. A value of 0 specifies no sampling. iSampleRate: Integer; /// For interlaced sync signals, the value can be ADL_GLSYNC_SYNCFIELD_1 or *_BOTH \ref define_glsync iSyncField: Integer; /// The signal edge that should trigger synchronization. ADL_GLSYNC_TRIGGEREDGE_* \ref define_glsync iTriggerEdge: Integer; /// Scan rate multiplier applied to the sync signal. ADL_GLSYNC_SCANRATECOEFF_* \ref define_glsync iScanRateCoeff: Integer; end; LPADLGLSyncGenlockConfig = ^ADLGLSyncGenlockConfig; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing GL-Sync port information. /// /// This structure is used to get status of the GL-Sync ports (BNC or RJ45s) /// for Workstation Framelock/Genlock. /// \see define_glsync /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLGlSyncPortInfo = record /// Type of GL-Sync port (ADL_GLSYNC_PORT_*). iPortType: Integer; /// The number of LEDs for this port. It's also filled within ADLGLSyncPortCaps. iNumOfLEDs: Integer; /// Port state ADL_GLSYNC_PORTSTATE_* \ref define_glsync iPortState: Integer; /// Scanned frequency for this port (vertical refresh rate in milliHz; 60000 means 60 Hz). iFrequency: Integer; /// Used for ADL_GLSYNC_PORT_BNC. It is ADL_GLSYNC_SIGNALTYPE_* \ref define_glsync iSignalType: Integer; /// Used for ADL_GLSYNC_PORT_RJ45PORT*. It is GL_Sync GPU Port index or ADL_GLSYNC_SIGNALSOURCE_*. \ref define_glsync iSignalSource: Integer; end; LPADLGlSyncPortInfo = ^ADLGlSyncPortInfo; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing GL-Sync port control settings. /// /// This structure is used to configure the GL-Sync ports (RJ45s only) /// for Workstation Framelock/Genlock. /// \see define_glsync /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLGlSyncPortControl = record /// Port to control ADL_GLSYNC_PORT_RJ45PORT1 or ADL_GLSYNC_PORT_RJ45PORT2 \ref define_glsync iPortType: Integer; /// Port control data ADL_GLSYNC_PORTCNTL_* \ref define_glsync iControlVector: Integer; /// Source of the sync signal. Either GL_Sync GPU Port index or ADL_GLSYNC_SIGNALSOURCE_* \ref define_glsync iSignalSource: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing GL-Sync mode of a display. /// /// This structure is used to get and set GL-Sync mode settings for a display connected to /// an adapter attached to a GL-Sync module for Workstation Framelock/Genlock. /// \see define_glsync /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLGlSyncMode = record /// Mode control vector. Bitfield of ADL_GLSYNC_MODECNTL_* \ref define_glsync iControlVector: Integer; /// Mode status vector. Bitfield of ADL_GLSYNC_MODECNTL_STATUS_* \ref define_glsync iStatusVector: Integer; /// Index of GL-Sync connector used to genlock the display/controller. iGLSyncConnectorIndex: Integer; end; LPADLGlSyncMode = ^ADLGlSyncMode; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing GL-Sync mode of a display. /// /// This structure is used to get and set GL-Sync mode settings for a display connected to /// an adapter attached to a GL-Sync module for Workstation Framelock/Genlock. /// \see define_glsync /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLGlSyncMode2 = record /// Mode control vector. Bitfield of ADL_GLSYNC_MODECNTL_* \ref define_glsync iControlVector: Integer; /// Mode status vector. Bitfield of ADL_GLSYNC_MODECNTL_STATUS_* \ref define_glsync iStatusVector: Integer; /// Index of GL-Sync connector used to genlock the display/controller. iGLSyncConnectorIndex: Integer; /// Index of the display to which this GLSync applies to. iDisplayIndex: Integer; end; LPADLGlSyncMode2 = ^ADLGlSyncMode2; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing the packet info of a display. /// /// This structure is used to get and set the packet information of a display. /// This structure is used by ADLDisplayDataPacket. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLInfoPacket = record hb0: AnsiChar; hb1: AnsiChar; hb2: AnsiChar; /// sb0~sb27 sb: array[0..27] of AnsiChar; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing the AVI packet info of a display. /// /// This structure is used to get and set AVI the packet info of a display. /// This structure is used by ADLDisplayDataPacket. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLAVIInfoPacket = record //Valid user defined data/ /// byte 3, bit 7 bPB3_ITC: AnsiChar; /// byte 5, bit [7:4]. bPB5: AnsiChar; end; // Overdrive clock setting structure definition. ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing the Overdrive clock setting. /// /// This structure is used to get the Overdrive clock setting. /// This structure is used by ADLAdapterODClockInfo. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLODClockSetting = record /// Deafult clock iDefaultClock: Integer; /// Current clock iCurrentClock: Integer; /// Maximum clcok iMaxClock: Integer; /// Minimum clock iMinClock: Integer; /// Requested clcock iRequestedClock: Integer; /// Step iStepClock: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing the Overdrive clock information. /// /// This structure is used to get the Overdrive clock information. /// This structure is used by the ADL_Display_ODClockInfo_Get() function. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLAdapterODClockInfo = record /// Size of the structure iSize: Integer; /// Flag \ref define_clockinfo_flags iFlags: Integer; /// Memory Clock sMemoryClock: ADLODClockSetting; /// Engine Clock sEngineClock: ADLODClockSetting; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing the Overdrive clock configuration. /// /// This structure is used to set the Overdrive clock configuration. /// This structure is used by the ADL_Display_ODClockConfig_Set() function. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLAdapterODClockConfig = record /// Size of the structure iSize: Integer; /// Flag \ref define_clockinfo_flags iFlags: Integer; /// Memory Clock iMemoryClock: Integer; /// Engine Clock iEngineClock: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about current power management related activity. /// /// This structure is used to store information about current power management related activity. /// This structure (Overdrive 5 interfaces) is used by the ADL_PM_CurrentActivity_Get() function. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLPMActivity = record /// Must be set to the size of the structure iSize: Integer; /// Current engine clock. iEngineClock: Integer; /// Current memory clock. iMemoryClock: Integer; /// Current core voltage. iVddc: Integer; /// GPU utilization. iActivityPercent: Integer; /// Performance level index. iCurrentPerformanceLevel: Integer; /// Current PCIE bus speed. iCurrentBusSpeed: Integer; /// Number of PCIE bus lanes. iCurrentBusLanes: Integer; /// Maximum number of PCIE bus lanes. iMaximumBusLanes: Integer; /// Reserved for future purposes. iReserved: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about thermal controller. /// /// This structure is used to store information about thermal controller. /// This structure is used by ADL_PM_ThermalDevices_Enum. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLThermalControllerInfo = record /// Must be set to the size of the structure iSize: Integer; /// Possible valies: \ref ADL_DL_THERMAL_DOMAIN_OTHER or \ref ADL_DL_THERMAL_DOMAIN_GPU. iThermalDomain: Integer; /// GPU 0, 1, etc. iDomainIndex: Integer; /// Possible valies: \ref ADL_DL_THERMAL_FLAG_INTERRUPT or \ref ADL_DL_THERMAL_FLAG_FANCONTROL iFlags: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about thermal controller temperature. /// /// This structure is used to store information about thermal controller temperature. /// This structure is used by the ADL_PM_Temperature_Get() function. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLTemperature = record /// Must be set to the size of the structure iSize: Integer; /// Temperature in millidegrees Celsius. iTemperature: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about thermal controller fan speed. /// /// This structure is used to store information about thermal controller fan speed. /// This structure is used by the ADL_PM_FanSpeedInfo_Get() function. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLFanSpeedInfo = record /// Must be set to the size of the structure iSize: Integer; /// \ref define_fanctrl iFlags: Integer; /// Minimum possible fan speed value in percents. iMinPercent: Integer; /// Maximum possible fan speed value in percents. iMaxPercent: Integer; /// Minimum possible fan speed value in RPM. iMinRPM: Integer; /// Maximum possible fan speed value in RPM. iMaxRPM: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about fan speed reported by thermal controller. /// /// This structure is used to store information about fan speed reported by thermal controller. /// This structure is used by the ADL_Overdrive5_FanSpeed_Get() and ADL_Overdrive5_FanSpeed_Set() functions. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLFanSpeedValue = record /// Must be set to the size of the structure iSize: Integer; /// Possible valies: \ref ADL_DL_FANCTRL_SPEED_TYPE_PERCENT or \ref ADL_DL_FANCTRL_SPEED_TYPE_RPM iSpeedType: Integer; /// Fan speed value iFanSpeed: Integer; /// The only flag for now is: \ref ADL_DL_FANCTRL_FLAG_USER_DEFINED_SPEED iFlags: Integer; end; //////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing the range of Overdrive parameter. /// /// This structure is used to store information about the range of Overdrive parameter. /// This structure is used by ADLODParameters. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLODParameterRange = record /// Minimum parameter value. iMin: Integer; /// Maximum parameter value. iMax: Integer; /// Parameter step value. iStep: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive parameters. /// /// This structure is used to store information about Overdrive parameters. /// This structure is used by the ADL_Overdrive5_ODParameters_Get() function. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLODParameters = record /// Must be set to the size of the structure iSize: Integer; /// Number of standard performance states. iNumberOfPerformanceLevels: Integer; /// Indicates whether the GPU is capable to measure its activity. iActivityReportingSupported: Integer; /// Indicates whether the GPU supports discrete performance levels or performance range. iDiscretePerformanceLevels: Integer; /// Reserved for future use. iReserved: Integer; /// Engine clock range. sEngineClock: ADLODParameterRange; /// Memory clock range. sMemoryClock: ADLODParameterRange; /// Core voltage range. sVddc: ADLODParameterRange; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive level. /// /// This structure is used to store information about Overdrive level. /// This structure is used by ADLODPerformanceLevels. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLODPerformanceLevel = record /// Engine clock. iEngineClock: Integer; /// Memory clock. iMemoryClock: Integer; /// Core voltage. iVddc: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive performance levels. /// /// This structure is used to store information about Overdrive performance levels. /// This structure is used by the ADL_Overdrive5_ODPerformanceLevels_Get() and ADL_Overdrive5_ODPerformanceLevels_Set() functions. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLODPerformanceLevels = record /// Must be set to sizeof( \ref ADLODPerformanceLevels ) + sizeof( \ref ADLODPerformanceLevel ) * (ADLODParameters.iNumberOfPerformanceLevels - 1) iSize: Integer; iReserved: Integer; /// Array of performance state descriptors. Must have ADLODParameters.iNumberOfPerformanceLevels elements. aLevels: array[0..0] of ADLODPerformanceLevel; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the proper CrossfireX chains combinations. /// /// This structure is used to store information about the CrossfireX chains combination for a particular adapter. /// This structure is used by the ADL_Adapter_Crossfire_Caps(), ADL_Adapter_Crossfire_Get(), and ADL_Adapter_Crossfire_Set() functions. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLCrossfireComb = record /// Number of adapters in this combination. iNumLinkAdapter: Integer; /// A list of ADL indexes of the linked adapters in this combination. iAdaptLink: array[0..2] of Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing CrossfireX state and error information. /// /// This structure is used to store state and error information about a particular adapter CrossfireX combination. /// This structure is used by the ADL_Adapter_Crossfire_Get() function. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLCrossfireInfo = record /// Current error code of this CrossfireX combination. iErrorCode: Integer; /// Current \ref define_crossfirestate iState: Integer; /// If CrossfireX is supported by this combination. The value is either \ref ADL_TRUE or \ref ADL_FALSE. iSupported: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// /// \brief Structure containing information about the BIOS. /// /// This structure is used to store various information about the Chipset. This /// information can be returned to the user. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLBiosInfo = record strPartNumber: array[0..ADL_MAX_PATH - 1] of AnsiChar ;///< Part number. strVersion: array[0..ADL_MAX_PATH - 1] of AnsiChar ;///< Version number. strDate: array[0..ADL_MAX_PATH - 1] of AnsiChar ;///< BIOS date in yyyy/mm/dd hh:mm format. end; LPADLBiosInfo = ^ADLBiosInfo; ///////////////////////////////////////////////////////////////////////////////////////////// /// \brief Structure containing information about adapter location. /// /// This structure is used to store information about adapter location. /// This structure is used by ADLMVPUStatus. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLAdapterLocation = record /// PCI Bus number : 8 bits iBus: Integer; /// Device number : 5 bits iDevice: Integer; /// Function number : 3 bits iFunction: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// /// \brief Structure containing version information /// /// This structure is used to store software version information, description of the display device and a web link to the latest installed Catalyst drivers. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLVersionsInfo = record /// Driver Release (Packaging) Version (e.g. 8.71-100128n-094835E-ATI) strDriverVer: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// Catalyst Version(e.g. "10.1"). strCatalystVersion: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// Web link to an XML file with information about the latest AMD drivers and locations (e.g. "http://www.amd.com/us/driverxml" ) strCatalystWebLink: array[0..ADL_MAX_PATH - 1] of AnsiChar; end; LPADLVersionsInfo = ^ADLVersionsInfo; ///////////////////////////////////////////////////////////////////////////////////////////// /// \brief Structure containing version information /// /// This structure is used to store software version information, description of the display device and a web link to the latest installed Catalyst drivers. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLVersionsInfoX2 = record /// Driver Release (Packaging) Version (e.g. "16.20.1035-160621a-303814C") strDriverVer: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// Catalyst Version(e.g. "15.8"). strCatalystVersion: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// Crimson Version(e.g. "16.6.2"). strCrimsonVersion: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// Web link to an XML file with information about the latest AMD drivers and locations (e.g. "http://support.amd.com/drivers/xml/driver_09_us.xml" ) strCatalystWebLink: array[0..ADL_MAX_PATH - 1] of AnsiChar; end; LPADLVersionsInfoX2 = ^ADLVersionsInfoX2; ///////////////////////////////////////////////////////////////////////////////////////////// /// \brief Structure containing information about MultiVPU capabilities. /// /// This structure is used to store information about MultiVPU capabilities. /// This structure is used by the ADL_Display_MVPUCaps_Get() function. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLMVPUCaps = record /// Must be set to sizeof( ADLMVPUCaps ). iSize: Integer; /// Number of adapters. iAdapterCount: Integer; /// Bits set for all possible MVPU masters. \ref MVPU_ADAPTER_0 .. \ref MVPU_ADAPTER_3 iPossibleMVPUMasters: Integer; /// Bits set for all possible MVPU slaves. \ref MVPU_ADAPTER_0 .. \ref MVPU_ADAPTER_3 iPossibleMVPUSlaves: Integer; /// Registry path for each adapter. cAdapterPath: array[0..ADL_DL_MAX_MVPU_ADAPTERS - 1, 0..ADL_DL_MAX_REGISTRY_PATH - 1] of AnsiChar; end; ///////////////////////////////////////////////////////////////////////////////////////////// /// \brief Structure containing information about MultiVPU status. /// /// This structure is used to store information about MultiVPU status. /// Ths structure is used by the ADL_Display_MVPUStatus_Get() function. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLMVPUStatus = record /// Must be set to sizeof( ADLMVPUStatus ). iSize: Integer; /// Number of active adapters. iActiveAdapterCount: Integer; /// MVPU status. iStatus: Integer; /// PCI Bus/Device/Function for each active adapter participating in MVPU. aAdapterLocation: array[0..ADL_DL_MAX_MVPU_ADAPTERS - 1] of ADLAdapterLocation; end; // Displays Manager structures /////////////////////////////////////////////////////////////////////////// /// \brief Structure containing information about the activatable source. /// /// This structure is used to store activatable source information /// This information can be returned to the user. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLActivatableSource = record /// The Persistent logical Adapter Index. iAdapterIndex: Integer; /// The number of Activatable Sources. iNumActivatableSources: Integer; /// The bit mask identifies the number of bits ActivatableSourceValue is using. (Not currnetly used) iActivatableSourceMask: Integer; /// The bit mask identifies the status. (Not currnetly used) iActivatableSourceValue: Integer; end; LPADLActivatableSource = ^ADLActivatableSource; ///////////////////////////////////////////////////////////////////////////////////////////// /// \brief Structure containing information about display mode. /// /// This structure is used to store the display mode for the current adapter /// such as X, Y positions, screen resolutions, orientation, /// color depth, refresh rate, progressive or interlace mode, etc. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLMode = record /// Adapter index. iAdapterIndex: Integer; /// Display IDs. displayID: ADLDisplayID; /// Screen position X coordinate. iXPos: Integer; /// Screen position Y coordinate. iYPos: Integer; /// Screen resolution Width. iXRes: Integer; /// Screen resolution Height. iYRes: Integer; /// Screen Color Depth. E.g., 16, 32. iColourDepth: Integer; /// Screen refresh rate. Could be fractional E.g. 59.97 fRefreshRate: Single; /// Screen orientation. E.g., 0, 90, 180, 270. iOrientation: Integer; /// Vista mode flag indicating Progressive or Interlaced mode. iModeFlag: Integer; /// The bit mask identifying the number of bits this Mode is currently using. It is the sum of all the bit definitions defined in \ref define_displaymode iModeMask: Integer; /// The bit mask identifying the display status. The detailed definition is in \ref define_displaymode iModeValue: Integer; end; LPADLMode = ^ADLMode; ///////////////////////////////////////////////////////////////////////////////////////////// /// \brief Structure containing information about display target information. /// /// This structure is used to store the display target information. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDisplayTarget = record /// The Display ID. displayID: ADLDisplayID; /// The display map index identify this manner and the desktop surface. iDisplayMapIndex: Integer; /// The bit mask identifies the number of bits DisplayTarget is currently using. It is the sum of all the bit definitions defined in \ref ADL_DISPLAY_DISPLAYTARGET_PREFERRED. iDisplayTargetMask: Integer; /// The bit mask identifies the display status. The detailed definition is in \ref ADL_DISPLAY_DISPLAYTARGET_PREFERRED. iDisplayTargetValue: Integer; end; LPADLDisplayTarget = ^ADLDisplayTarget; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the display SLS bezel Mode information. /// /// This structure is used to store the display SLS bezel Mode information. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type tagADLBezelTransientMode = record /// Adapter Index iAdapterIndex: Integer; /// SLS Map Index iSLSMapIndex: Integer; /// The mode index iSLSModeIndex: Integer; /// The mode displayMode: ADLMode; /// The number of bezel offsets belongs to this map iNumBezelOffset: Integer; /// The first bezel offset array index in the native mode array iFirstBezelOffsetArrayIndex: Integer; /// The bit mask identifies the bits this structure is currently using. It will be the total OR of all the bit definitions. iSLSBezelTransientModeMask: Integer; /// The bit mask identifies the display status. The detail definition is defined below. iSLSBezelTransientModeValue: Integer; end; ADLBezelTransientMode = tagADLBezelTransientMode; LPADLBezelTransientMode = ^ADLBezelTransientMode; ///////////////////////////////////////////////////////////////////////////////////////////// /// \brief Structure containing information about the adapter display manner. /// /// This structure is used to store adapter display manner information /// This information can be returned to the user. Alternatively, it can be used to access various driver calls to /// fetch various display device related display manner settings upon the user's request. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLAdapterDisplayCap = record /// The Persistent logical Adapter Index. iAdapterIndex: Integer; /// The bit mask identifies the number of bits AdapterDisplayCap is currently using. Sum all the bits defined in ADL_ADAPTER_DISPLAYCAP_XXX iAdapterDisplayCapMask: Integer; /// The bit mask identifies the status. Refer to ADL_ADAPTER_DISPLAYCAP_XXX iAdapterDisplayCapValue: Integer; end; LPADLAdapterDisplayCap = ^ADLAdapterDisplayCap; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about display mapping. /// /// This structure is used to store the display mapping data such as display manner. /// For displays with horizontal or vertical stretch manner, /// this structure also stores the display order, display row, and column data. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDisplayMap = record /// The current display map index. It is the OS desktop index. For example, if the OS index 1 is showing clone mode, the display map will be 1. iDisplayMapIndex: Integer; /// The Display Mode for the current map displayMode: ADLMode; /// The number of display targets belongs to this map\n iNumDisplayTarget: Integer; /// The first target array index in the Target array\n iFirstDisplayTargetArrayIndex: Integer; /// The bit mask identifies the number of bits DisplayMap is currently using. It is the sum of all the bit definitions defined in ADL_DISPLAY_DISPLAYMAP_MANNER_xxx. iDisplayMapMask: Integer; ///The bit mask identifies the display status. The detailed definition is in ADL_DISPLAY_DISPLAYMAP_MANNER_xxx. iDisplayMapValue: Integer; end; LPADLDisplayMap = ^ADLDisplayMap; ///////////////////////////////////////////////////////////////////////////////////////////// /// \brief Structure containing information about the display device possible map for one GPU /// /// This structure is used to store the display device possible map /// This information can be returned to the user. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLPossibleMap = record /// The current PossibleMap index. Each PossibleMap is assigned an index iIndex: Integer; /// The adapter index identifying the GPU for which to validate these Maps & Targets iAdapterIndex: Integer; /// Number of display Maps for this GPU to be validated iNumDisplayMap: Integer; /// The display Maps list to validate displayMap: LPADLDisplayMap; /// the number of display Targets for these display Maps iNumDisplayTarget: Integer; /// The display Targets list for these display Maps to be validated. displayTarget: LPADLDisplayTarget; end; LPADLPossibleMap = ^ADLPossibleMap; ///////////////////////////////////////////////////////////////////////////////////////////// /// \brief Structure containing information about display possible mapping. /// /// This structure is used to store the display possible mapping's controller index for the current display. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLPossibleMapping = record iDisplayIndex: Integer ;///< The display index. Each display is assigned an index. iDisplayControllerIndex: Integer ;///< The controller index to which display is mapped. iDisplayMannerSupported: Integer ;///< The supported display manner. end; LPADLPossibleMapping = ^ADLPossibleMapping; ///////////////////////////////////////////////////////////////////////////////////////////// /// \brief Structure containing information about the validated display device possible map result. /// /// This structure is used to store the validated display device possible map result /// This information can be returned to the user. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLPossibleMapResult = record /// The current display map index. It is the OS Desktop index. For example, OS Index 1 showing clone mode. The Display Map will be 1. iIndex: Integer; // The bit mask identifies the number of bits PossibleMapResult is currently using. It will be the sum all the bit definitions defined in ADL_DISPLAY_POSSIBLEMAPRESULT_VALID. iPossibleMapResultMask: Integer; /// The bit mask identifies the possible map result. The detail definition is defined in ADL_DISPLAY_POSSIBLEMAPRESULT_XXX. iPossibleMapResultValue: Integer; end; LPADLPossibleMapResult = ^ADLPossibleMapResult; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the display SLS Grid information. /// /// This structure is used to store the display SLS Grid information. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLSLSGrid = record /// The Adapter index. iAdapterIndex: Integer; /// The grid index. iSLSGridIndex: Integer; /// The grid row. iSLSGridRow: Integer; /// The grid column. iSLSGridColumn: Integer; /// The grid bit mask identifies the number of bits DisplayMap is currently using. Sum of all bits defined in ADL_DISPLAY_SLSGRID_ORIENTATION_XXX iSLSGridMask: Integer; /// The grid bit value identifies the display status. Refer to ADL_DISPLAY_SLSGRID_ORIENTATION_XXX iSLSGridValue: Integer; end; LPADLSLSGrid = ^ADLSLSGrid; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the display SLS Map information. /// /// This structure is used to store the display SLS Map information. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLSLSMap = record /// The Adapter Index iAdapterIndex: Integer; /// The current display map index. It is the OS Desktop index. For example, OS Index 1 showing clone mode. The Display Map will be 1. iSLSMapIndex: Integer; /// Indicate the current grid grid: ADLSLSGrid; /// OS surface index iSurfaceMapIndex: Integer; /// Screen orientation. E.g., 0, 90, 180, 270 iOrientation: Integer; /// The number of display targets belongs to this map iNumSLSTarget: Integer; /// The first target array index in the Target array iFirstSLSTargetArrayIndex: Integer; /// The number of native modes belongs to this map iNumNativeMode: Integer; /// The first native mode array index in the native mode array iFirstNativeModeArrayIndex: Integer; /// The number of bezel modes belongs to this map iNumBezelMode: Integer; /// The first bezel mode array index in the native mode array iFirstBezelModeArrayIndex: Integer; /// The number of bezel offsets belongs to this map iNumBezelOffset: Integer; /// The first bezel offset array index in the iFirstBezelOffsetArrayIndex: Integer; /// The bit mask identifies the number of bits DisplayMap is currently using. Sum all the bit definitions defined in ADL_DISPLAY_SLSMAP_XXX. iSLSMapMask: Integer; /// The bit mask identifies the display map status. Refer to ADL_DISPLAY_SLSMAP_XXX iSLSMapValue: Integer; end; LPADLSLSMap = ^ADLSLSMap; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the display SLS Offset information. /// /// This structure is used to store the display SLS Offset information. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLSLSOffset = record /// The Adapter Index iAdapterIndex: Integer; /// The current display map index. It is the OS Desktop index. For example, OS Index 1 showing clone mode. The Display Map will be 1. iSLSMapIndex: Integer; /// The Display ID. displayID: ADLDisplayID; /// SLS Bezel Mode Index iBezelModeIndex: Integer; /// SLS Bezel Offset X iBezelOffsetX: Integer; /// SLS Bezel Offset Y iBezelOffsetY: Integer; /// SLS Display Width iDisplayWidth: Integer; /// SLS Display Height iDisplayHeight: Integer; /// The bit mask identifies the number of bits Offset is currently using. iBezelOffsetMask: Integer; /// The bit mask identifies the display status. iBezelffsetValue: Integer; end; LPADLSLSOffset = ^ADLSLSOffset; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the display SLS Mode information. /// /// This structure is used to store the display SLS Mode information. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLSLSMode = record /// The Adapter Index iAdapterIndex: Integer; /// The current display map index. It is the OS Desktop index. For example, OS Index 1 showing clone mode. The Display Map will be 1. iSLSMapIndex: Integer; /// The mode index iSLSModeIndex: Integer; /// The mode for this map. displayMode: ADLMode; /// The bit mask identifies the number of bits Mode is currently using. iSLSNativeModeMask: Integer; /// The bit mask identifies the display status. iSLSNativeModeValue: Integer; end; LPADLSLSMode = ^ADLSLSMode; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the display Possible SLS Map information. /// /// This structure is used to store the display Possible SLS Map information. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLPossibleSLSMap = record /// The current display map index. It is the OS Desktop index. /// For example, OS Index 1 showing clone mode. The Display Map will be 1. iSLSMapIndex: Integer; /// Number of display map to be validated. iNumSLSMap: Integer; /// The display map list for validation lpSLSMap: LPADLSLSMap; /// the number of display map config to be validated. iNumSLSTarget: Integer; /// The display target list for validation. lpDisplayTarget: LPADLDisplayTarget; end; LPADLPossibleSLSMap = ^ADLPossibleSLSMap; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the SLS targets. /// /// This structure is used to store the SLS targets information. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLSLSTarget = record /// the logic adapter index iAdapterIndex: Integer; /// The SLS map index iSLSMapIndex: Integer; /// The target ID displayTarget: ADLDisplayTarget; /// Target postion X in SLS grid iSLSGridPositionX: Integer; /// Target postion Y in SLS grid iSLSGridPositionY: Integer; /// The view size width, height and rotation angle per SLS Target viewSize: ADLMode; /// The bit mask identifies the bits in iSLSTargetValue are currently used iSLSTargetMask: Integer; /// The bit mask identifies status info. It is for function extension purpose iSLSTargetValue: Integer; end; LPADLSLSTarget = ^ADLSLSTarget; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the Adapter offset stepping size. /// /// This structure is used to store the Adapter offset stepping size information. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLBezelOffsetSteppingSize = record /// the logic adapter index iAdapterIndex: Integer; /// The SLS map index iSLSMapIndex: Integer; /// Bezel X stepping size offset iBezelOffsetSteppingSizeX: Integer; /// Bezel Y stepping size offset iBezelOffsetSteppingSizeY: Integer; /// Identifies the bits this structure is currently using. It will be the total OR of all the bit definitions. iBezelOffsetSteppingSizeMask: Integer; /// Bit mask identifies the display status. iBezelOffsetSteppingSizeValue: Integer; end; LPADLBezelOffsetSteppingSize = ^ADLBezelOffsetSteppingSize; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about the overlap offset info for all the displays for each SLS mode. /// /// This structure is used to store the no. of overlapped modes for each SLS Mode once user finishes the configuration from Overlap Widget /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLSLSOverlappedMode = record /// the SLS mode for which the overlap is configured SLSMode: ADLMode; /// the number of target displays in SLS. iNumSLSTarget: Integer; /// the first target array index in the target array iFirstTargetArrayIndex: Integer; end; ADLSLSTargetOverlap = ADLSLSOverlappedMode; LPADLSLSTargetOverlap = ^ADLSLSTargetOverlap; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about driver supported PowerExpress Config Caps /// /// This structure is used to store the driver supported PowerExpress Config Caps /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLPXConfigCaps = record /// The Persistent logical Adapter Index. iAdapterIndex: Integer; /// The bit mask identifies the number of bits PowerExpress Config Caps is currently using. It is the sum of all the bit definitions defined in ADL_PX_CONFIGCAPS_XXXX /ref define_powerxpress_constants. iPXConfigCapMask: Integer; /// The bit mask identifies the PowerExpress Config Caps value. The detailed definition is in ADL_PX_CONFIGCAPS_XXXX /ref define_powerxpress_constants. iPXConfigCapValue: Integer; end; LPADLPXConfigCaps = ^ADLPXConfigCaps; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about an application /// /// This structure is used to store basic information of an application /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLApplicationData = record /// Path Name strPathName: array[0..ADL_MAX_PATH - 1] of AnsiChar; /// File Name strFileName: array[0..ADL_APP_PROFILE_FILENAME_LENGTH - 1] of AnsiChar; /// Creation timestamp strTimeStamp: array[0..ADL_APP_PROFILE_TIMESTAMP_LENGTH - 1] of AnsiChar; /// Version strVersion: array[0..ADL_APP_PROFILE_VERSION_LENGTH - 1] of AnsiChar; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about an application /// /// This structure is used to store basic information of an application /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLApplicationDataX2 = record /// Path Name strPathName: array[0..ADL_MAX_PATH - 1] of WideChar; /// File Name strFileName: array[0..ADL_APP_PROFILE_FILENAME_LENGTH - 1] of WideChar; /// Creation timestamp strTimeStamp: array[0..ADL_APP_PROFILE_TIMESTAMP_LENGTH - 1] of WideChar; /// Version strVersion: array[0..ADL_APP_PROFILE_VERSION_LENGTH - 1] of WideChar; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about an application /// /// This structure is used to store basic information of an application including process id /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLApplicationDataX3 = record /// Path Name strPathName: array[0..ADL_MAX_PATH - 1] of WideChar; /// File Name strFileName: array[0..ADL_APP_PROFILE_FILENAME_LENGTH - 1] of WideChar; /// Creation timestamp strTimeStamp: array[0..ADL_APP_PROFILE_TIMESTAMP_LENGTH - 1] of WideChar; /// Version strVersion: array[0..ADL_APP_PROFILE_VERSION_LENGTH - 1] of WideChar; //Application Process id iProcessId: Word; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information of a property of an application profile /// /// This structure is used to store property information of an application profile /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _PropertyRecord = record /// Property Name strName: array [0..ADL_APP_PROFILE_PROPERTY_LENGTH - 1] of AnsiChar; /// Property Type eType: ADLProfilePropertyType; /// Data Size in bytes iDataSize: Integer; /// Property Value, can be any data type uData: array[0..0] of Byte; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about an application profile /// /// This structure is used to store information of an application profile /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// //type _ADLApplicationProfile = record /// Number of properties //iCount: Integer; /// Buffer to store all property records //record[1]: PropertyRecord; //end; OOPS ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about an OD5 Power Control feature /// /// This structure is used to store information of an Power Control feature /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLPowerControlInfo = record /// Minimum value. iMinValue: Integer; /// Maximum value. iMaxValue: Integer; /// The minimum change in between minValue and maxValue. iStepValue: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about an controller mode /// /// This structure is used to store information of an controller mode /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLControllerMode = record /// This falg indicates actions that will be applied by set viewport /// The value can be a combination of ADL_CONTROLLERMODE_CM_MODIFIER_VIEW_POSITION, /// ADL_CONTROLLERMODE_CM_MODIFIER_VIEW_PANLOCK and ADL_CONTROLLERMODE_CM_MODIFIER_VIEW_SIZE iModifiers: Integer; /// Horizontal view starting position iViewPositionCx: Integer; /// Vertical view starting position iViewPositionCy: Integer; /// Horizontal left panlock position iViewPanLockLeft: Integer; /// Horizontal right panlock position iViewPanLockRight: Integer; /// Vertical top panlock position iViewPanLockTop: Integer; /// Vertical bottom panlock position iViewPanLockBottom: Integer; /// View resolution in pixels (width) iViewResolutionCx: Integer; /// View resolution in pixels (hight) iViewResolutionCy: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about a display /// /// This structure is used to store information about a display /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDisplayIdentifier = record /// ADL display index ulDisplayIndex: Cardinal; /// manufacturer ID of the display ulManufacturerId: Cardinal; /// product ID of the display ulProductId: Cardinal; /// serial number of the display ulSerialNo: Cardinal; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive 6 clock range /// /// This structure is used to store information about Overdrive 6 clock range /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLOD6ParameterRange = record /// The starting value of the clock range iMin: Integer; /// The ending value of the clock range iMax: Integer; /// The minimum increment between clock values iStep: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive 6 capabilities /// /// This structure is used to store information about Overdrive 6 capabilities /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLOD6Capabilities = record /// Contains a bitmap of the OD6 capability flags. Possible values: \ref ADL_OD6_CAPABILITY_SCLK_CUSTOMIZATION, /// \ref ADL_OD6_CAPABILITY_MCLK_CUSTOMIZATION, \ref ADL_OD6_CAPABILITY_GPU_ACTIVITY_MONITOR iCapabilities: Integer; /// Contains a bitmap indicating the power states /// supported by OD6. Currently only the performance state /// is supported. Possible Values: \ref ADL_OD6_SUPPORTEDSTATE_PERFORMANCE iSupportedStates: Integer; /// Number of levels. OD6 will always use 2 levels, which describe /// the minimum to maximum clock ranges. /// The 1st level indicates the minimum clocks, and the 2nd level /// indicates the maximum clocks. iNumberOfPerformanceLevels: Integer; /// Contains the hard limits of the sclk range. Overdrive /// clocks cannot be set outside this range. sEngineClockRange: ADLOD6ParameterRange; /// Contains the hard limits of the mclk range. Overdrive /// clocks cannot be set outside this range. sMemoryClockRange: ADLOD6ParameterRange; /// Value for future extension iExtValue: Integer; /// Mask for future extension iExtMask: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive 6 clock values. /// /// This structure is used to store information about Overdrive 6 clock values. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLOD6PerformanceLevel = record /// Engine (core) clock. iEngineClock: Integer; /// Memory clock. iMemoryClock: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive 6 clocks. /// /// This structure is used to store information about Overdrive 6 clocks. This is a /// variable-sized structure. iNumberOfPerformanceLevels indicate how many elements /// are contained in the aLevels array. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLOD6StateInfo = record /// Number of levels. OD6 uses clock ranges instead of discrete performance levels. /// iNumberOfPerformanceLevels is always 2. The 1st level indicates the minimum clocks /// in the range. The 2nd level indicates the maximum clocks in the range. iNumberOfPerformanceLevels: Integer; /// Value for future extension iExtValue: Integer; /// Mask for future extension iExtMask: Integer; /// Variable-sized array of levels. /// The number of elements in the array is specified by iNumberofPerformanceLevels. aLevels: array[0..0] of ADLOD6PerformanceLevel; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about current Overdrive 6 performance status. /// /// This structure is used to store information about current Overdrive 6 performance status. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLOD6CurrentStatus = record /// Current engine clock in 10 KHz. iEngineClock: Integer; /// Current memory clock in 10 KHz. iMemoryClock: Integer; /// Current GPU activity in percent. This /// indicates how "busy" the GPU is. iActivityPercent: Integer; /// Not used. Reserved for future use. iCurrentPerformanceLevel: Integer; /// Current PCI-E bus speed iCurrentBusSpeed: Integer; /// Current PCI-E bus # of lanes iCurrentBusLanes: Integer; /// Maximum possible PCI-E bus # of lanes iMaximumBusLanes: Integer; /// Value for future extension iExtValue: Integer; /// Mask for future extension iExtMask: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive 6 thermal contoller capabilities /// /// This structure is used to store information about Overdrive 6 thermal controller capabilities /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLOD6ThermalControllerCaps = record /// Contains a bitmap of thermal controller capability flags. Possible values: \ref ADL_OD6_TCCAPS_THERMAL_CONTROLLER, \ref ADL_OD6_TCCAPS_FANSPEED_CONTROL, /// \ref ADL_OD6_TCCAPS_FANSPEED_PERCENT_READ, \ref ADL_OD6_TCCAPS_FANSPEED_PERCENT_WRITE, \ref ADL_OD6_TCCAPS_FANSPEED_RPM_READ, \ref ADL_OD6_TCCAPS_FANSPEED_RPM_WRITE iCapabilities: Integer; /// Minimum fan speed expressed as a percentage iFanMinPercent: Integer; /// Maximum fan speed expressed as a percentage iFanMaxPercent: Integer; /// Minimum fan speed expressed in revolutions-per-minute iFanMinRPM: Integer; /// Maximum fan speed expressed in revolutions-per-minute iFanMaxRPM: Integer; /// Value for future extension iExtValue: Integer; /// Mask for future extension iExtMask: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive 6 fan speed information /// /// This structure is used to store information about Overdrive 6 fan speed information /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLOD6FanSpeedInfo = record /// Contains a bitmap of the valid fan speed type flags. Possible values: \ref ADL_OD6_FANSPEED_TYPE_PERCENT, \ref ADL_OD6_FANSPEED_TYPE_RPM, \ref ADL_OD6_FANSPEED_USER_DEFINED iSpeedType: Integer; /// Contains current fan speed in percent (if valid flag exists in iSpeedType) iFanSpeedPercent: Integer; /// Contains current fan speed in RPM (if valid flag exists in iSpeedType) iFanSpeedRPM: Integer; /// Value for future extension iExtValue: Integer; /// Mask for future extension iExtMask: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive 6 fan speed value /// /// This structure is used to store information about Overdrive 6 fan speed value /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLOD6FanSpeedValue = record /// Indicates the units of the fan speed. Possible values: \ref ADL_OD6_FANSPEED_TYPE_PERCENT, \ref ADL_OD6_FANSPEED_TYPE_RPM iSpeedType: Integer; /// Fan speed value (units as indicated above) iFanSpeed: Integer; /// Value for future extension iExtValue: Integer; /// Mask for future extension iExtMask: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive 6 PowerControl settings. /// /// This structure is used to store information about Overdrive 6 PowerControl settings. /// PowerControl is the feature which allows the performance AnsiCharacteristics of the GPU /// to be adjusted by changing the PowerTune power limits. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLOD6PowerControlInfo = record /// The minimum PowerControl adjustment value iMinValue: Integer; /// The maximum PowerControl adjustment value iMaxValue: Integer; /// The minimum difference between PowerControl adjustment values iStepValue: Integer; /// Value for future extension iExtValue: Integer; /// Mask for future extension iExtMask: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive 6 PowerControl settings. /// /// This structure is used to store information about Overdrive 6 PowerControl settings. /// PowerControl is the feature which allows the performance AnsiCharacteristics of the GPU /// to be adjusted by changing the PowerTune power limits. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLOD6VoltageControlInfo = record /// The minimum VoltageControl adjustment value iMinValue: Integer; /// The maximum VoltageControl adjustment value iMaxValue: Integer; /// The minimum difference between VoltageControl adjustment values iStepValue: Integer; /// Value for future extension iExtValue: Integer; /// Mask for future extension iExtMask: Integer; end; //////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing ECC statistics namely SEC counts and DED counts /// Single error count - count of errors that can be corrected /// Doubt Error Detect - count of errors that cannot be corrected /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLECCData = record // Single error count - count of errors that can be corrected iSec: Integer; // Double error detect - count of errors that cannot be corrected iDed: Integer; end; /// \brief Handle to ADL client context. /// /// ADL clients obtain context handle from initial call to \ref ADL2_Main_Control_Create. /// Clients have to pass the handle to each subsequent ADL call and finally destroy /// the context with call to \ref ADL2_Main_Control_Destroy /// \nosubgrouping type ADL_CONTEXT_HANDLE = pointer; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing the display mode definition used per controller. /// /// This structure is used to store the display mode definition used per controller. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDisplayModeX2 = record /// Horizontal resolution (in pixels). iWidth: Integer; /// Vertical resolution (in lines). iHeight: Integer; /// Interlaced/Progressive. The value will be set for Interlaced as ADL_DL_TIMINGFLAG_INTERLACED. If not set it is progressive. Refer define_detailed_timing_flags. iScanType: Integer; /// Refresh rate. iRefreshRate: Integer; /// Timing Standard. Refer define_modetiming_standard. iTimingStandard: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive 6 extension capabilities /// /// This structure is used to store information about Overdrive 6 extension capabilities /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLOD6CapabilitiesEx = record /// Contains a bitmap of the OD6 extension capability flags. Possible values: \ref ADL_OD6_CAPABILITY_SCLK_CUSTOMIZATION, /// \ref ADL_OD6_CAPABILITY_MCLK_CUSTOMIZATION, \ref ADL_OD6_CAPABILITY_GPU_ACTIVITY_MONITOR, /// \ref ADL_OD6_CAPABILITY_POWER_CONTROL, \ref ADL_OD6_CAPABILITY_VOLTAGE_CONTROL, \ref ADL_OD6_CAPABILITY_PERCENT_ADJUSTMENT, //// \ref ADL_OD6_CAPABILITY_THERMAL_LIMIT_UNLOCK iCapabilities: Integer; /// The Power states that support clock and power customization. Only performance state is currently supported. /// Possible Values: \ref ADL_OD6_SUPPORTEDSTATE_PERFORMANCE iSupportedStates: Integer; /// Returns the hard limits of the SCLK overdrive adjustment range. Overdrive clocks should not be adjusted outside of this range. The values are specified as +/- percentages. sEngineClockPercent: ADLOD6ParameterRange; /// Returns the hard limits of the MCLK overdrive adjustment range. Overdrive clocks should not be adjusted outside of this range. The values are specified as +/- percentages. sMemoryClockPercent: ADLOD6ParameterRange; /// Returns the hard limits of the Power Limit adjustment range. Power limit should not be adjusted outside this range. The values are specified as +/- percentages. sPowerControlPercent: ADLOD6ParameterRange; /// Reserved for future expansion of the structure. iExtValue: Integer; /// Reserved for future expansion of the structure. iExtMask: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive 6 extension state information /// /// This structure is used to store information about Overdrive 6 extension state information /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLOD6StateEx = record /// The current engine clock adjustment value, specified as a +/- percent. iEngineClockPercent: Integer; /// The current memory clock adjustment value, specified as a +/- percent. iMemoryClockPercent: Integer; /// The current power control adjustment value, specified as a +/- percent. iPowerControlPercent: Integer; /// Reserved for future expansion of the structure. iExtValue: Integer; /// Reserved for future expansion of the structure. iExtMask: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive 6 extension recommended maximum clock adjustment values /// /// This structure is used to store information about Overdrive 6 extension recommended maximum clock adjustment values /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLOD6MaxClockAdjust = record /// The recommended maximum engine clock adjustment in percent, for the specified power limit value. iEngineClockMax: Integer; /// The recommended maximum memory clock adjustment in percent, for the specified power limit value. /// Currently the memory is independent of the Power Limit setting, so iMemoryClockMax will always return the maximum /// possible adjustment value. This field is here for future enhancement in case we add a dependency between Memory Clock /// adjustment and Power Limit setting. iMemoryClockMax: Integer; /// Reserved for future expansion of the structure. iExtValue: Integer; /// Reserved for future expansion of the structure. iExtMask: Integer; end; //////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing the Connector information /// /// this structure is used to get the connector information like length, positions & etc. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLConnectorInfo = record ///index of the connector(0-based) iConnectorIndex: Integer; ///used for disply identification/ordering iConnectorId: Integer; ///index of the slot, 0-based index. iSlotIndex: Integer; ///Type of the connector. \ref define_connector_types iType: Integer; ///Position of the connector(in millimeters), from the right side of the slot. iOffset: Integer; ///Length of the connector(in millimeters). iLength: Integer; end; //////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing the slot information /// /// this structure is used to get the slot information like length of the slot, no of connectors on the slot & etc. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLBracketSlotInfo = record ///index of the slot, 0-based index. iSlotIndex: Integer; ///length of the slot(in millimeters). iLength: Integer; ///width of the slot(in millimeters). iWidth: Integer; end; //////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing MST branch information /// /// this structure is used to store the MST branch information /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLMSTRad = record ///depth of the link. iLinkNumber: Integer; /// Relative address, address scheme starts from source side rad: array[0..ADL_MAX_RAD_LINK_COUNT - 1] of AnsiChar; end; //////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing port information /// /// this structure is used to get the display or MST branch information /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLDevicePort = record ///index of the connector. iConnectorIndex: Integer; ///Relative MST address. If MST RAD contains 0 it means DP or Root of the MST topology. For non DP connectors MST RAD is ignored. aMSTRad: ADLMSTRad; end; //////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing supported connection types and properties /// /// this structure is used to get the supported connection types and supported properties of given connector /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLSupportedConnections = record ///Bit vector of supported connections. Bitmask is defined in constants section. \ref define_connection_types iSupportedConnections: Integer; ///Array of bitvectors. Each bit vector represents supported properties for one connection type. Index of this array is connection type (bit number in mask). iSupportedProperties: array[0..ADL_MAX_CONNECTION_TYPES - 1] of Integer; end; //////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing connection state of the connector /// /// this structure is used to get the current Emulation status and mode of the given connector /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLConnectionState = record ///The value is bit vector. Each bit represents status. See masks constants for details. \ref define_emulation_status iEmulationStatus: Integer; ///It contains information about current emulation mode. See constants for details. \ref define_emulation_mode iEmulationMode: Integer; ///If connection is active it will contain display id, otherwise CWDDEDI_INVALID_DISPLAY_INDEX iDisplayIndex: Integer; end; //////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing connection properties information /// /// this structure is used to retrieve the properties of connection type /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLConnectionProperties = record //Bit vector. Represents actual properties. Supported properties for specific connection type. \ref define_connection_properties iValidProperties: Integer; //Bitrate(in MHz). Could be used for MST branch, DP or DP active dongle. \ref define_linkrate_constants iBitrate: Integer; //Number of lanes in DP connection. \ref define_lanecount_constants iNumberOfLanes: Integer; //Color depth(in bits). \ref define_colordepth_constants iColorDepth: Integer; //3D capabilities. It could be used for some dongles. For instance: alternate framepack. Value of this property is bit vector. iStereo3DCaps: Integer; ///Output Bandwidth. Could be used for MST branch, DP or DP Active dongle. \ref define_linkrate_constants iOutputBandwidth: Integer; end; //////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing connection information /// /// this structure is used to retrieve the data from driver which includes /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLConnectionData = record ///Connection type. based on the connection type either iNumberofPorts or IDataSize,EDIDdata is valid, \ref define_connection_types iConnectionType: Integer; ///Specifies the connection properties. aConnectionProperties: ADLConnectionProperties; ///Number of ports iNumberofPorts: Integer; ///Number of Active Connections iActiveConnections: Integer; ///actual size of EDID data block size. iDataSize: Integer; ///EDID Data EdidData: array[0..ADL_MAX_DISPLAY_EDID_DATA_SIZE - 1] of AnsiChar; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about an controller mode including Number of Connectors /// /// This structure is used to store information of an controller mode /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLAdapterCapsX2 = record /// AdapterID for this adapter iAdapterID: Integer; /// Number of controllers for this adapter iNumControllers: Integer; /// Number of displays for this adapter iNumDisplays: Integer; /// Number of overlays for this adapter iNumOverlays: Integer; /// Number of GLSyncConnectors iNumOfGLSyncConnectors: Integer; /// The bit mask identifies the adapter caps iCapsMask: Integer; /// The bit identifies the adapter caps \ref define_adapter_caps iCapsValue: Integer; /// Number of Connectors for this adapter iNumConnectors: Integer; end; type ADL_ERROR_RECORD_SEVERITY = ( ADL_GLOBALLY_UNCORRECTED = 1, ADL_LOCALLY_UNCORRECTED = 2, ADL_DEFFERRED = 3, ADL_CORRECTED = 4); //typedef union _ADL_ECC_EDC_FLAG //struct; //unsigned int isEccAccessing : 1; //unsigned int reserved : 31; //end; oops u32All = UInt32; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about EDC Error Record /// /// This structure is used to store EDC Error Record /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLErrorRecord = record // Severity of error Severity: ADL_ERROR_RECORD_SEVERITY; // Is the counter valid? countValid: Integer; // Counter value, if valid count: Word; // Is the location information valid? locationValid: Integer; // Physical location of error CU: Word ;// CU number on which error occurred, if known StructureName: array[0..31] of AnsiChar ;// e.g. LDS, TCC, etc. // Time of error record creation (e.g. time of query, or time of poison interrupt) timestamp: array[0..31] of AnsiChar; //tiestamp ? padding: array[0..2] of Word; end; type _ADL_EDC_BLOCK_ID = ( ADL_EDC_BLOCK_ID_SQCIS = 1, ADL_EDC_BLOCK_ID_SQCDS = 2, ADL_EDC_BLOCK_ID_SGPR = 3, ADL_EDC_BLOCK_ID_VGPR = 4, ADL_EDC_BLOCK_ID_LDS = 5, ADL_EDC_BLOCK_ID_GDS = 6, ADL_EDC_BLOCK_ID_TCL1 = 7, ADL_EDC_BLOCK_ID_TCL2 = 8); _ADL_ERROR_INJECTION_MODE = ( ADL_ERROR_INJECTION_MODE_SINGLE = 1, ADL_ERROR_INJECTION_MODE_MULTIPLE = 2, ADL_ERROR_INJECTION_MODE_ADDRESS = 3); {typedef union _ADL_ERROR_PATTERN struct; unsigned long EccInjVector : 16; unsigned long EccInjEn : 9; unsigned long EccBeatEn : 4; unsigned long EccChEn : 4; unsigned long reserved : 31; end; OOPS } u64Value = UInt64; {type _ADL_ERROR_INJECTION_DATA = record unsigned long long errorAddress; ADL_ERROR_PATTERN errorPattern; end; OOPS } ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about EDC Error Injection /// /// This structure is used to store EDC Error Injection /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// {type ADLErrorInjection = record ADL_EDC_BLOCK_ID blockId; ADL_ERROR_INJECTION_MODE errorInjectionMode; end; OOPS type ADLErrorInjectionX2 = record ADL_EDC_BLOCK_ID blockId; ADL_ERROR_INJECTION_MODE errorInjectionMode; ADL_ERROR_INJECTION_DATA errorInjectionData; end; } ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing per display FreeSync capability information. /// /// This structure is used to store the FreeSync capability of both the display and /// the GPU the display is connected to. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLFreeSyncCap = record /// FreeSync capability flags. \ref define_freesync_caps iCaps: Integer; /// Reports minimum FreeSync refresh rate supported by the display in micro hertz iMinRefreshRateInMicroHz: Integer; /// Reports maximum FreeSync refresh rate supported by the display in micro hertz iMaxRefreshRateInMicroHz: Integer; /// Reserved iReserved: array[0..4] of Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing per display Display Connectivty Experience Settings /// /// This structure is used to store the Display Connectivity Experience settings of a /// display /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// {type ADLDceSettings = record DceSettingsType type ;// Defines which structure is in the union below union; struct; bool qualityDetectionEnabled; end; struct; DpLinkRate linkRate ;// Read-only unsigned int numberOfActiveLanes ;// Read-only unsigned int numberofTotalLanes ;// Read-only relativePreEmphasis ;// Allowable values are -2 to +2: Integer relativeVoltageSwing ;// Allowable values are -2 to +2: Integer persistFlag: Integer; end; struct; bool linkProtectionEnabled ;// Read-only end; end; iReserved[15]: Integer; end; OOPS } ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Graphic Core /// /// This structure is used to get Graphic Core Info /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLGraphicCoreInfo = record /// indicate the graphic core generation iGCGen: Integer; /// Total number of CUs. Valid for GCN (iGCGen == GCN) iNumCUs: Integer; /// Number of processing elements per CU. Valid for GCN (iGCGen == GCN) iNumPEsPerCU: Integer; /// Total number of SIMDs. Valid for Pre GCN (iGCGen == Pre-GCN) iNumSIMDs: Integer; /// Total number of ROPs. Valid for both GCN and Pre GCN iNumROPs: Integer; /// reserved for future use iReserved: array[0..10] of Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive N clock range /// /// This structure is used to store information about Overdrive N clock range /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLODNParameterRange = record /// The starting value of the clock range iMode: Integer; /// The starting value of the clock range iMin: Integer; /// The ending value of the clock range iMax: Integer; /// The minimum increment between clock values iStep: Integer; /// The default clock values iDefault: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive N capabilities /// /// This structure is used to store information about Overdrive N capabilities /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type _ADLODNCapabilities = record /// Number of levels which describe the minimum to maximum clock ranges. /// The 1st level indicates the minimum clocks, and the 2nd level /// indicates the maximum clocks. iMaximumNumberOfPerformanceLevels: Integer; /// Contains the hard limits of the sclk range. Overdrive /// clocks cannot be set outside this range. sEngineClockRange: ADLODNParameterRange; /// Contains the hard limits of the mclk range. Overdrive /// clocks cannot be set outside this range. sMemoryClockRange: ADLODNParameterRange; /// Contains the hard limits of the vddc range. Overdrive /// clocks cannot be set outside this range. svddcRange: ADLODNParameterRange; /// Contains the hard limits of the power range. Overdrive /// clocks cannot be set outside this range. power: ADLODNParameterRange; /// Contains the hard limits of the power range. Overdrive /// clocks cannot be set outside this range. powerTuneTemperature: ADLODNParameterRange ; /// Contains the hard limits of the Temperature range. Overdrive /// clocks cannot be set outside this range. fanTemperature: ADLODNParameterRange; /// Contains the hard limits of the Fan range. Overdrive /// clocks cannot be set outside this range. fanSpeed: ADLODNParameterRange; /// Contains the hard limits of the Fan range. Overdrive /// clocks cannot be set outside this range. minimumPerformanceClock: ADLODNParameterRange; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive level. /// /// This structure is used to store information about Overdrive level. /// This structure is used by ADLODPerformanceLevels. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLODNPerformanceLevel = record /// clock. iClock: Integer; /// VDCC. iVddc: Integer; /// enabled iEnabled: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive N performance levels. /// /// This structure is used to store information about Overdrive performance levels. /// This structure is used by the ADL_OverdriveN_ODPerformanceLevels_Get() and ADL_OverdriveN_ODPerformanceLevels_Set() functions. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLODNPerformanceLevels = record iSize: Integer; //Automatic/manual iMode: Integer; /// Must be set to sizeof( \ref ADLODPerformanceLevels ) + sizeof( \ref ADLODPerformanceLevel ) * (ADLODParameters.iNumberOfPerformanceLevels - 1) iNumberOfPerformanceLevels: Integer; /// Array of performance state descriptors. Must have ADLODParameters.iNumberOfPerformanceLevels elements. aLevels: array[0..0] of ADLODNPerformanceLevel; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive N Fan Speed. /// /// This structure is used to store information about Overdrive Fan control . /// This structure is used by the ADL_OverdriveN_ODPerformanceLevels_Get() and ADL_OverdriveN_ODPerformanceLevels_Set() functions. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLODNFanControl = record iMode: Integer; iFanControlMode: Integer; iCurrentFanSpeedMode: Integer; iCurrentFanSpeed: Integer; iTargetFanSpeed: Integer; iTargetTemperature: Integer; iMinPerformanceClock: Integer; iMinFanLimit: Integer; end; PADLODNFanControl = ^ADLODNFanControl; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about Overdrive N power limit. /// /// This structure is used to store information about Overdrive power limit. /// This structure is used by the ADL_OverdriveN_ODPerformanceLevels_Get() and ADL_OverdriveN_ODPerformanceLevels_Set() functions. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLODNPowerLimitSetting = record iMode: Integer; iTDPLimit: Integer; iMaxOperatingTemperature: Integer; end; type ADLODNPerformanceStatus = record iCoreClock: Integer; iMemoryClock: Integer; iDCEFClock: Integer; iGFXClock: Integer; iUVDClock: Integer; iVCEClock: Integer; iGPUActivityPercent: Integer; iCurrentCorePerformanceLevel: Integer; iCurrentMemoryPerformanceLevel: Integer; iCurrentDCEFPerformanceLevel: Integer; iCurrentGFXPerformanceLevel: Integer; iUVDPerformanceLevel: Integer; iVCEPerformanceLevel: Integer; iCurrentBusSpeed: Integer; iCurrentBusLanes: Integer; iMaximumBusLanes: Integer; iVDDC: Integer; iVDDCI: Integer; end; ///////////////////////////////////////////////////////////////////////////////////////////// ///\brief Structure containing information about PPLog settings. /// /// This structure is used to store information about PPLog settings. /// This structure is used by the ADL2_PPLogSettings_Set() and ADL2_PPLogSettings_Get() functions. /// \nosubgrouping //////////////////////////////////////////////////////////////////////////////////////////// type ADLPPLogSettings = record BreakOnAssert: Integer; BreakOnWarn: Integer; LogEnabled: Integer; LogFieldMask: Integer; LogDestinations: Integer; LogSeverityEnabled: Integer; LogSourceMask: Integer; PowerProfilingEnabled: Integer; PowerProfilingTimeInterval: Integer; end; implementation end.
unit BlockTicker; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TBlockTicker = class( TCustomControl ) public constructor Create(AOwner: TComponent); override; private fFont : TFont; fBuffer : TBitmap; fCaption : TCaption; fIndex : integer; fForeColor : TColor; fBackColor : TColor; fLitColor : TColor; fCompleted : boolean; fHorzMargin : integer; fVertMargin : integer; fHovering : boolean; fShowBack : boolean; private procedure SetCaption( aCaption : TCaption ); published property Font : TFont read fFont write fFont; property Caption : TCaption read fCaption write SetCaption; property ForeColor : TColor read fForeColor write fForeColor; property BackColor : TColor read fBackColor write fBackColor; property LitColor : TColor read fLitColor write fLitColor; property HorzMargin : integer read fHorzMargin write fHorzMargin; property VertMargin : integer read fVertMargin write fVertMargin; property Hovering : boolean read fHovering write fHovering; property ShowBack : boolean read fShowBack write fShowBack; published property Align; property OnClick; public procedure Tick; protected procedure SetBounds( ALeft, ATop, AWidth, AHeight : integer); override; procedure MouseMove( Shift : TShiftState; X, Y : integer); override; procedure Paint; override; private procedure UpdateImage; private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; end; procedure Register; implementation // TBlockTicker constructor TBlockTicker.Create(AOwner: TComponent); begin inherited; fFont := TFont.Create; end; procedure TBlockTicker.SetCaption( aCaption : TCaption ); begin fCaption := aCaption; fIndex := 1; fCompleted := false; end; procedure TBlockTicker.Tick; begin if not fCompleted then begin if fIndex < length(Caption) then inc(fIndex) else fCompleted := true; UpdateImage; Invalidate; end; end; procedure TBlockTicker.SetBounds( ALeft, ATop, AWidth, AHeight : integer); begin inherited; fBuffer.Free; fBuffer := TBitmap.Create; fBuffer.Width := AWidth; fBuffer.Height := AHeight; UpdateImage; end; procedure TBlockTicker.MouseMove( Shift : TShiftState; X, Y : integer); var MouseWasCaptured : boolean; begin inherited; if Hovering then begin Cursor := crHandPoint; MouseWasCaptured := MouseCapture; MouseCapture := (x >= 0) and (y >= 0) and (x < Width) and (y < Height); if MouseCapture xor MouseWasCaptured then begin UpdateImage; Invalidate; end; end else Cursor := crDefault; end; procedure TBlockTicker.Paint; begin Canvas.Draw( 0, 0, fBuffer ); end; procedure TBlockTicker.UpdateImage; type TRGB = packed record x, b, g, r : byte; end; var R : TRect; subStr : string; c1, c2 : TRGB; midlit : TColor; middrk : TColor; i : integer; begin R := Rect( 0, 0, Width, Height ); InflateRect( R, -HorzMargin, -VertMargin ); fBuffer.Canvas.Font.Assign( Font ); fBuffer.Canvas.Brush.Color := BackColor; c1 := TRGB(LitColor); c2 := TRGB(ForeColor); c1.r := (c1.r + c2.r) div 2; c1.g := (c1.g + c2.g) div 2; c1.b := (c1.b + c2.b) div 2; c1.x := (c1.x + c2.x) div 2; midlit := TColor(c1); c1 := TRGB(BackColor); c2 := TRGB(ForeColor); c1.r := (2*c1.r + c2.r) div 3; c1.g := (2*c1.g + c2.g) div 3; c1.b := (2*c1.b + c2.b) div 3; c1.x := (2*c1.x + c2.x) div 3; middrk := TColor(c1); with fBuffer.Canvas do begin Brush.Style := bsSolid; Pen.Style := psSolid; Pen.Color := BackColor; Rectangle( 0, 0, Width + 1, Height + 1 ); if fShowBack then begin Pen.Color := middrk; for i := 0 to pred(Height div 2) do begin MoveTo( 0, 2*i ); LineTo( Width + 1, 2*i ); end; end; Brush.Style := bsClear; if not fCompleted then begin subStr := copy( Caption, 1, fIndex ); if MouseCapture and Hovering then Font.Style := Font.Style + [fsUnderline] else Font.Style := Font.Style - [fsUnderline]; Font.Color := LitColor; DrawText( Handle, pchar(subStr + '|'), fIndex + 1, R, DT_WORDBREAK or DT_NOPREFIX ); Font.Color := midlit; DrawText( Handle, pchar(subStr), fIndex - 1, R, DT_WORDBREAK or DT_NOPREFIX ); Font.Color := ForeColor; DrawText( Handle, pchar(subStr), fIndex - 2, R, DT_WORDBREAK or DT_NOPREFIX ); end else begin Font.Color := ForeColor; if MouseCapture and Hovering then Font.Style := Font.Style + [fsUnderline] else Font.Style := Font.Style - [fsUnderline]; DrawText( Handle, pchar(Caption), -1, R, DT_WORDBREAK or DT_NOPREFIX ); end; end; end; procedure TBlockTicker.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; // Register procedure Register; begin RegisterComponents('Five', [TBlockTicker]); end; end.
unit IntegerList; interface uses Classes; { TLongIntListCom class } type PLongIntItem = ^TLongIntItem; TLongIntItem = record FLongInt: LongInt; FObject: TObject; end; PLongIntItemList = ^TLongIntItemList; TLongIntItemList = array[0..MaxListSize] of TLongIntItem; TIntegerList = class; TIntegerListEnumerator = class private FIndex: Integer; FList: TIntegerList; public constructor Create(AList: TIntegerList); function GetCurrent: LongInt; function MoveNext: Boolean; property Current: LongInt read GetCurrent; end; TIntegerList = class(TPersistent) private FList: PLongIntItemList; FCount: Integer; FCapacity: Integer; FSorted: Boolean; FDuplicates: TDuplicates; FUpdateCount: Integer; FOnChange: TNotifyEvent; FOnChanging: TNotifyEvent; procedure ExchangeItems(Index1, Index2: Integer); procedure Grow; procedure QuickSort(L, R: Integer); procedure InsertItem(Index: Integer; const Value: LongInt); procedure SetSorted(Value: Boolean); protected procedure Changed; virtual; procedure Changing; virtual; procedure Error(const Msg: string; Data: Integer); function Get(Index: Integer): LongInt; virtual; function GetCapacity: Integer; virtual; function GetCount: Integer; virtual; function GetObject(Index: Integer): TObject; virtual; procedure Put(Index: Integer; const Value: Longint); virtual; procedure PutObject(Index: Integer; AObject: TObject); virtual; procedure SetCapacity(NewCapacity: Integer); virtual; procedure SetUpdateState(Updating: Boolean); virtual; function GetTextStr: string; virtual; procedure SetTextStr(const Value: string); virtual; public destructor Destroy; override; function Add(const Value: LongInt): Integer; virtual; function AddObject(const Value: LongInt; AObject: TObject): Integer; virtual; procedure AddIdList(AIdList: TIntegerList); virtual; procedure Append(const Value: Longint); procedure Assign(Source: TIntegerList); reintroduce; procedure BeginUpdate; procedure Clear; virtual; procedure Delete(Index: Integer); virtual; procedure EndUpdate; function Equals(AIdList: TIntegerList): Boolean; reintroduce; procedure Exchange(Index1, Index2: Integer); virtual; function Find(const Value: LongInt; var Index: Integer): Boolean; virtual; function IndexOf(const Value: LongInt): Integer; virtual; function IndexOfObject(AObject: TObject): Integer; procedure Insert(Index: Integer; const Value: Longint); virtual; procedure InsertObject(Index: Integer; const Value: Longint; AObject: TObject); function Last(): Integer; procedure LoadFromFile(const Filename: string); virtual; procedure LoadFromStream(Stream: TStream); virtual; procedure Move(CurIndex, NewIndex: Integer); virtual; function Remove(const Value: LongInt): Longint; virtual; procedure Release; virtual; export; procedure SaveToFile(const Filename: string); virtual; procedure SaveToStream(Stream: TStream); virtual; procedure Sort; virtual; function GetEnumerator: TIntegerListEnumerator; function CompareTo(AIntegerList: TIntegerList): Integer; function HasIdenticalContentsAs(AIntegerList: TIntegerList): Boolean; property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount; property Duplicates: TDuplicates read FDuplicates write FDuplicates; property Sorted: Boolean read FSorted write SetSorted; property Objects[Index: Integer]: TObject read GetObject write PutObject; property Values[Index: Integer]: Longint read Get write Put; default; property Items[Index: Integer]: Longint read Get write Put; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnChanging: TNotifyEvent read FOnChanging write FOnChanging; end; implementation uses RTLConsts, SysUtils; destructor TIntegerList.Destroy; begin FOnChange := nil; FOnChanging := nil; inherited Destroy; FCount := 0; SetCapacity(0); end; function TIntegerList.Add(const Value: LongInt): Integer; begin if not Sorted then Result := FCount else if Find(Value, Result) then case Duplicates of dupIgnore: Exit; dupError: Error(SDuplicateString, 0); end; InsertItem(Result, Value); end; procedure TIntegerList.Changed; begin if (FUpdateCount = 0) and Assigned(FOnChange) then FOnChange(Self); end; procedure TIntegerList.Changing; begin if (FUpdateCount = 0) and Assigned(FOnChanging) then FOnChanging(Self); end; procedure TIntegerList.Clear; begin if FCount <> 0 then begin Changing; FCount := 0; SetCapacity(0); Changed; end; end; function TIntegerList.CompareTo(AIntegerList: TIntegerList): Integer; var i: Integer; begin Result := AIntegerList.Count - Count; if Result <> 0 then EXIT; for i := 0 to Count-1 do begin Result := AIntegerList[i] - Items[i]; if Result <> 0 then EXIT; end; end; procedure TIntegerList.Delete(Index: Integer); begin if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); Changing; Dec(FCount); if Index < FCount then System.Move(FList^[Index + 1], FList^[Index], (FCount - Index) * SizeOf(TLongIntItem)); Changed; end; procedure TIntegerList.Exchange(Index1, Index2: Integer); begin if (Index1 < 0) or (Index1 >= FCount) then Error(SListIndexError, Index1); if (Index2 < 0) or (Index2 >= FCount) then Error(SListIndexError, Index2); Changing; ExchangeItems(Index1, Index2); Changed; end; procedure TIntegerList.ExchangeItems(Index1, Index2: Integer); var Temp: Integer; Item1, Item2: PLongIntItem; begin Item1 := @FList^[Index1]; Item2 := @FList^[Index2]; Temp := Integer(Item1^.FLongInt); Integer(Item1^.FLongInt) := Integer(Item2^.FLongInt); Integer(Item2^.FLongInt) := Temp; Temp := Integer(Item1^.FObject); Integer(Item1^.FObject) := Integer(Item2^.FObject); Integer(Item2^.FObject) := Temp; end; function TIntegerList.Find(const Value: LongInt; var Index: Integer): Boolean; var L, H, i: Integer; C: Int64; begin if Sorted then begin Result := False; L := 0; H := FCount - 1; while L <= H do begin i := (L + H) shr 1; C := int64(FList^[i].FLongInt) - int64(Value); if C < 0 then L := i + 1 else begin H := i - 1; if C = 0 then begin Result := True; if Duplicates <> dupAccept then L := i; end; end; end; Index := L; end else begin Index := IndexOf(Value); Result := Index >= 0; end; end; function TIntegerList.Get(Index: Integer): LongInt; begin if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); Result := FList^[Index].FLongInt; end; function TIntegerList.GetCapacity: Integer; begin Result := FCapacity; end; function TIntegerList.GetCount: Integer; begin Result := FCount; end; function TIntegerList.GetObject(Index: Integer): TObject; begin if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); Result := FList^[Index].FObject; end; procedure TIntegerList.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; function TIntegerList.HasIdenticalContentsAs( AIntegerList: TIntegerList): Boolean; begin Result := CompareTo(AIntegerList) = 0; end; function TIntegerList.IndexOf(const Value: LongInt): Integer; begin if not Sorted then begin for Result := 0 to GetCount - 1 do if Value = Get(Result) then Exit; Result := -1; end else if not Find(Value, Result) then Result := -1; end; procedure TIntegerList.Insert(Index: Integer; const Value: LongInt); begin if Sorted then Error(SSortedListError, 0); if (Index < 0) or (Index > FCount) then Error(SListIndexError, Index); InsertItem(Index, Value); end; procedure TIntegerList.InsertItem(Index: Integer; const Value: LongInt); begin Changing; if FCount = FCapacity then Grow; if Index < FCount then System.Move(FList^[Index], FList^[Index + 1], (FCount - Index) * SizeOf(TLongIntItem)); with FList^[Index] do begin FLongint := Value; FObject := nil; end; Inc(FCount); Changed; end; procedure TIntegerList.Put(Index: Integer; const Value: Longint); begin if Sorted then Error(SSortedListError, 0); if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); Changing; FList^[Index].FLongint := Value; Changed; end; procedure TIntegerList.PutObject(Index: Integer; AObject: TObject); begin if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); Changing; FList^[Index].FObject := AObject; Changed; end; procedure TIntegerList.QuickSort(L, R: Integer); var i, j: Integer; P: Longint; begin repeat i := L; j := R; P := FList^[(L + R) shr 1].FLongint; repeat while FList^[i].FLongInt < P do Inc(i); while FList^[j].FLongInt > P do Dec(j); if i <= j then begin ExchangeItems(i, j); Inc(i); Dec(j); end; until i > j; if L < j then QuickSort(L, j); L := i; until i >= R; end; procedure TIntegerList.SetCapacity(NewCapacity: Integer); begin ReallocMem(FList, NewCapacity * SizeOf(TLongIntItem)); FCapacity := NewCapacity; end; procedure TIntegerList.SetSorted(Value: Boolean); begin if FSorted <> Value then begin if Value then Sort; FSorted := Value; end; end; procedure TIntegerList.SetUpdateState(Updating: Boolean); begin if Updating then Changing else Changed; end; procedure TIntegerList.Sort; begin if not Sorted and (FCount > 1) then begin Changing; QuickSort(0, FCount - 1); Changed; end; end; function TIntegerList.AddObject(const Value: Longint; AObject: TObject): Integer; begin Result := Add(Value); PutObject(Result, AObject); end; procedure TIntegerList.Append(const Value: Longint); begin Add(Value); end; procedure TIntegerList.AddIdList(AIdList: TIntegerList); var i: Integer; begin BeginUpdate; try for i := 0 to AIdList.Count - 1 do AddObject(AIdList[i], AIdList.Objects[i]); finally EndUpdate; end; end; procedure TIntegerList.Assign(Source: TIntegerList); begin BeginUpdate; try Clear; AddIdList(Source); finally EndUpdate; end; end; procedure TIntegerList.BeginUpdate; begin if FUpdateCount = 0 then SetUpdateState(True); Inc(FUpdateCount); end; procedure TIntegerList.EndUpdate; begin Dec(FUpdateCount); if FUpdateCount = 0 then SetUpdateState(False); end; function TIntegerList.Equals(AIdList: TIntegerList): Boolean; var i, Count: Integer; begin Result := False; Count := GetCount; if Count <> AIdList.GetCount then Exit; for i := 0 to Count - 1 do if Get(i) <> AIdList.Get(i) then Exit; Result := True; end; function TIntegerList.IndexOfObject(AObject: TObject): Integer; begin for Result := 0 to GetCount - 1 do if GetObject(Result) = AObject then Exit; Result := -1; end; procedure TIntegerList.InsertObject(Index: Integer; const Value: LongInt; AObject: TObject); begin Insert(Index, Value); PutObject(Index, AObject); end; function TIntegerList.Last: Integer; begin Result := Items[Count - 1]; end; procedure TIntegerList.LoadFromFile(const Filename: string); var Stream: TStream; begin Stream := TFileStream.Create(Filename, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); finally Stream.Free; end; end; procedure TIntegerList.LoadFromStream(Stream: TStream); var Size: Integer; S: string; begin BeginUpdate; try Size := Stream.Size - Stream.Position; SetString(S, nil, Size); Stream.Read(Pointer(S)^, Size); SetTextStr(S); finally EndUpdate; end; end; procedure TIntegerList.Move(CurIndex, NewIndex: Integer); var TempObject: TObject; TempLongint: LongInt; begin if CurIndex <> NewIndex then begin BeginUpdate; try TempLongint := Get(CurIndex); TempObject := GetObject(CurIndex); Delete(CurIndex); InsertObject(NewIndex, TempLongint, TempObject); finally EndUpdate; end; end; end; procedure TIntegerList.SaveToFile(const Filename: string); var Stream: TStream; begin Stream := TFileStream.Create(Filename, fmCreate); try SaveToStream(Stream); finally Stream.Free; end; end; procedure TIntegerList.SaveToStream(Stream: TStream); var S: string; begin S := GetTextStr; Stream.WriteBuffer(Pointer(S)^, Length(S)); end; procedure TIntegerList.Error(const Msg: string; Data: Integer); function ReturnAddr: Pointer; asm MOV EAX,[EBP+4] end; begin raise EStringListError.CreateFmt(Msg, [Data]) at ReturnAddr; end; function TIntegerList.GetTextStr: string; var i, L, Size, Count: Integer; P: PChar; S: string; begin Count := GetCount; Size := 0; for i := 0 to Count - 1 do begin S := IntToStr(Get(i)); Inc(Size, Length(S) + 2); end; SetString(Result, nil, Size); P := Pointer(Result); for i := 0 to Count - 1 do begin S := IntToStr(Get(i)); L := Length(S); if L <> 0 then begin System.Move(Pointer(S)^, P^, L); Inc(P, L); end; P^ := #13; Inc(P); P^ := #10; Inc(P); end; end; procedure TIntegerList.SetTextStr(const Value: string); var P, Start: PChar; S: string; begin BeginUpdate; try Clear; P := Pointer(Value); if P <> nil then while P^ <> #0 do begin Start := P; while not CharInSet(P^, [#0, #10, #13]) do Inc(P); SetString(S, Start, P - Start); try Add(StrToInt(S)); except end; if P^ = #13 then Inc(P); if P^ = #10 then Inc(P); end; finally EndUpdate; end; end; function TIntegerList.Remove(const Value: Integer): Longint; begin Result := IndexOf(Value); if Result <> -1 then Delete(Result); end; procedure TIntegerList.Release; begin Destroy; end; function TIntegerList.GetEnumerator: TIntegerListEnumerator; begin Result := TIntegerListEnumerator.Create(Self); end; { TLongIntListEnumerator } constructor TIntegerListEnumerator.Create(AList: TIntegerList); begin inherited Create; FIndex := -1; FList := AList; end; function TIntegerListEnumerator.GetCurrent: LongInt; begin Result := FList[FIndex]; end; function TIntegerListEnumerator.MoveNext: Boolean; begin Result := FIndex < FList.Count - 1; if Result then Inc(FIndex); end; end.
unit l3TempMemoryStream; { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3TempMemoryStream - } { Начат: 25.06.2003 14:42 } { $Id: l3TempMemoryStream.pas,v 1.3 2006/01/17 09:23:22 narry Exp $ } // $Log: l3TempMemoryStream.pas,v $ // Revision 1.3 2006/01/17 09:23:22 narry // - исправление: размер буфера по умолчанию 1 Мб // // Revision 1.2 2003/06/25 11:18:22 law // - bug fix: неправильно проверялось достижение максимального размера. // // Revision 1.1 2003/06/25 11:14:27 law // - new unit: l3TempMemoryStream - содержит класс Tl3TempMemoryStream - потокв памяти, который имеет ограничение на размер, после достижения которого все данные вымещаются во временный файл. // {$I l3Define.inc } interface uses Classes, l3Types, l3Base, l3BaseStream, l3Memory, l3Stream ; const cMaxTempMemoryStreamSize = 1024 * 1024; type Tl3TempMemoryStream = class(Tl3Stream) private // internal fields f_MaxSize : Long; f_Mem : Tl3MemoryStream; f_File : Tl3TempFileStream; protected // internal methods procedure Release; override; {-} public // public methods constructor Create(aMaxSize : Long = cMaxTempMemoryStreamSize); reintroduce; {-} function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; {-} function Read(var Buffer; Count: Longint): Longint; override; {-} function Write(const Buffer; Count: Longint): Longint; override; {-} end;//Tl3TempMemoryStream implementation // start class Tl3TempMemoryStream constructor Tl3TempMemoryStream.Create(aMaxSize : Long = cMaxTempMemoryStreamSize); //reintroduce; {-} begin inherited Create; if (aMaxSize = 0) then f_MaxSize := cMaxTempMemoryStreamSize else f_MaxSize := aMaxSize; f_Mem := Tl3MemoryStream.Make; end; procedure Tl3TempMemoryStream.Release; //override; {-} begin l3Free(f_Mem); l3Free(f_File); inherited; end; function Tl3TempMemoryStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; //override; {-} begin if (f_Mem = nil) then begin if (f_File = nil) then Result := 0 else Result := f_File.Seek(Offset, Origin); end else Result := f_Mem.Seek(Offset, Origin); end; function Tl3TempMemoryStream.Read(var Buffer; Count: Longint): Longint; //override; {-} begin if (f_Mem = nil) then begin if (f_File = nil) then Result := 0 else Result := f_File.Read(Buffer, Count); end else Result := f_Mem.Read(Buffer, Count); end; function Tl3TempMemoryStream.Write(const Buffer; Count: Longint): Longint; //override; {-} begin if (f_Mem = nil) then begin if (f_File = nil) then Result := 0 else Result := f_File.Write(Buffer, Count); end else begin if (f_Mem.Position + Count >= f_MaxSize) then begin f_File := Tl3TempFileStream.Create; try f_File.CopyFrom(f_Mem, 0); l3Free(f_Mem); Result := f_File.Write(Buffer, Count); except l3Free(f_File); raise; end;//try..except end else Result := f_Mem.Write(Buffer, Count); end;//f_Mem = nil end; end.
unit AppProcMonitor; interface uses BaseApp, BaseWinApp, BaseWinThreadRefObj, BaseCmdWin, BaseWinProcess; type TAppPath = class(TBaseWinAppPath) protected public end; TExProcessCtrl = record ExProc: TExProcess; end; TOwnProcessArray = array[0..16 - 1] of TOwnProcess; TExProcessArray = array[0..16 - 1] of TExProcessCtrl; TAppProcMonitorData = record BaseCmdWnd: TBaseCmdWnd; OwnProcArray: TOwnProcessArray; ExProcLock: TWinLock; ExProcArray: TExProcessArray; end; TAppProcMonitor = class(TBaseWinApp) protected fAppProcMonitorData: TAppProcMonitorData; function GetPath: TBaseAppPath; override; public constructor Create(AppClassId: AnsiString); override; function Initialize: Boolean; override; procedure Run; override; end; var GlobalApp: TAppProcMonitor = nil; implementation uses Windows, define_message, define_procmonitor; { TAppProcMonitor } constructor TAppProcMonitor.Create(AppClassId: AnsiString); begin inherited; FillChar(fAppProcMonitorData, SizeOf(fAppProcMonitorData), 0); end; function TAppProcMonitor.GetPath: TBaseAppPath; begin if nil = fBaseWinAppData.AppPath then begin fBaseWinAppData.AppPath := TAppPath.Create(Self); end; Result := fBaseWinAppData.AppPath; end; function AppCmdWndProcA(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; begin Result := 0; case AMsg of WM_ProcMonitor_C2S_Notify: begin case wParam of Cmd_Monitor_C2S_AddMonitor : begin // client 通知监控添加自己 if 0 <> lParam then begin end; end; Cmd_Monitor_C2S_RemoveMonitor : begin // client 通知监控移除自己 // end; Cmd_Monitor_C2S_ReportStatusOK : begin // client 状态正常通知 // lparam = processId end; Cmd_Monitor_C2S_ReportShutDown : begin // client 将要关闭 请监控 end; Cmd_Monitor_C2S_ReportRestart : begin // client 将要重启 请监控 end; end; end; else Result := DefWindowProcA(AWnd, AMsg, wParam, lParam); end; end; function TAppProcMonitor.Initialize: Boolean; begin Result := inherited Initialize; if Result then begin //Result := CreateCmdWndA(Self, @fBaseCmdWnd, @AppCmdWndProcA); Result := CreateCmdWndA(GUID_ProcessMonitor, @fAppProcMonitorData.BaseCmdWnd, @AppCmdWndProcA); end; end; procedure TAppProcMonitor.Run; begin inherited; RunAppMsgLoop; end; end.
Program a2test2; {This program uses the same units as a1test, but it gives you a menu interface to manage two collections (c1 and c2). You can insert, delete, join, print and get the size of either collection. Use this to test your code during development. Make sure you hand in a compiled version of this program too.} uses BinTrADT, a2unit; var C1,C2: collection; choice: integer; s: collection_element; begin IdentifyMyself; writeln; create(c1); create(c2); repeat writeln; writeln('1. Insert into C1,'); writeln('2. Insert into C2,'); writeln('3. Delete from C1,'); writeln('4. Delete from C2,'); writeln('5. Join C1 to C2,'); writeln('6. Get size of C1,'); writeln('7. Get size of C2,'); writeln('8. Print C1,'); writeln('9. Print C2,'); writeln('10. quit'); writeln; readln(choice); case choice of 1: begin Write('String to insert into C1: '); readln(s); Insert(C1, s); end; 2: begin Write('String to insert into C2: '); readln(s); Insert(C2, s); end; 3: begin Write('String to delete from C1: '); readln(s); Delete(C1, s); end; 4: begin Write('String to delete from C2: '); readln(s); Delete(C2, s); end; 5: begin Writeln('Joining C1 to C2, and calling create(C2) again'); Writeln('Now C1 contains all elements from C1 and C2, and C2 is empty'); Join(C1, C2); Create(C2); end; 6: begin Writeln('C1 has ',Size(C1),' elements'); end; 7: begin Writeln('C2 has ',Size(C2),' elements'); end; 8: begin Writeln('Contents of C1:'); writeln; Print(C1); end; 9: begin Writeln('Contents of C2:'); writeln; Print(C2); end; end; until (choice = 10); destroy(c1); destroy(C2); writeln('C1 and C2 destroyed'); IF MemCheck then writeln('Memory check passed') else writeln('Memory check failed - possible memory leak'); writeln; writeln('Bye Bye...'); end.
unit Patterns.Observable; interface uses System.Generics.Collections; type TObservable = class; IObserver = interface /// <remarks> /// Oryginalny this method name was `update`. It was changed because of the VCL warning (W1010): Method 'Update' hides virtual method of base type 'TWinControl' /// Documentation for Vcl.Controls.TControl.Update: /// http://docwiki.embarcadero.com/Libraries/Rio/en/Vcl.Controls.TControl.Update /// </remarks> procedure OnObserverUpdate(AObservable: TObservable; AObject: TObject); end; TObservable = class strict private FObservers: TArray<IObserver>; procedure _addObserverToArray(o: IObserver); function _findObserverInArray(o: IObserver): integer; procedure _deleteObserverFromArray(o: IObserver); private FIsChanged: Boolean; public /// <summary> /// Indicates that this object has no longer changed, or that it has /// already notified all of its observers of its most recent change, /// so that the hasChanged method will now return false. /// </summary> // clearChanged was protected procedure clearChanged(); /// <summary> /// Marks this Observable object as having been changed; the hasChanged /// method will now return true. /// </summary> // setChangedChanged was protected procedure setChanged(); /// <summary> /// Adds an observer to the set of observers for this object, provided /// that it is not the same as some observer already in the set. /// </summary> procedure addObserver(o: IObserver); /// <summary> /// Returns the number of observers of this Observable object. /// </summary> function countObservers(): integer; /// <summary> /// Deletes an observer from the set of observers of this object. /// </summary> procedure deleteObserver(o: IObserver); /// <summary> /// Clears the observer list so that this object no longer has any observers. /// </summary> procedure deleteObservers(); /// <summary> /// Tests if this object has changed. /// </summary> function hasChanged(): Boolean; /// <summary> /// If this object has changed, as indicated by the hasChanged method, /// then notify all of its observers and then call the clearChanged /// method to indicate that this object has no longer changed. /// </summary> procedure notifyObservers(); overload; /// <summary> /// If this object has changed, as indicated by the hasChanged method, // then notify all of its observers and then call the clearChanged method // to indicate that this object has no longer changed. /// </summary> procedure notifyObservers(arg: TObject); overload; end; implementation uses System.SysUtils; { Observable } procedure TObservable.addObserver(o: IObserver); begin _addObserverToArray(o); end; procedure TObservable._addObserverToArray(o: IObserver); begin SetLength(FObservers, Length(FObservers) + 1); FObservers[High(FObservers)] := o; end; procedure TObservable.clearChanged; begin FIsChanged := False; end; function TObservable.countObservers: integer; begin Result := Length(FObservers); end; procedure TObservable.deleteObserver(o: IObserver); begin _deleteObserverFromArray(o); end; procedure TObservable._deleteObserverFromArray(o: IObserver); var idx: integer; j: integer; begin idx := _findObserverInArray(o); if idx < 0 then raise ERangeError.Create('Error Message') else begin for j := idx + 1 to High(FObservers) do FObservers[j - 1] := FObservers[j]; SetLength(FObservers, Length(FObservers) - 1); end; end; procedure TObservable.deleteObservers; begin SetLength(FObservers, 0); end; function TObservable._findObserverInArray(o: IObserver): integer; begin for Result := 0 to High(FObservers) do exit; Result := -1; end; function TObservable.hasChanged: Boolean; begin Result := FIsChanged; end; procedure TObservable.notifyObservers(arg: TObject); begin end; procedure TObservable.notifyObservers; var o: IObserver; begin if FIsChanged then for o in FObservers do o.OnObserverUpdate(self, nil); end; procedure TObservable.setChanged; begin FIsChanged := true; end; end.
unit uCadastroAluno; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uBase, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.Buttons, Vcl.ExtCtrls, 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, Vcl.StdCtrls, Vcl.Mask; type TfrmCadastroAluno = class(TfrmCadastroBase) qrAluno: TFDQuery; dsAluno: TDataSource; edtId: TEdit; edtNome: TEdit; edtCpf: TMaskEdit; Código: TLabel; Nome: TLabel; CPF: TLabel; qrAlunoID: TIntegerField; qrAlunoNOME: TStringField; qrAlunoCPF: TStringField; procedure SpeedButton2Click(Sender: TObject); procedure SpeedButton3Click(Sender: TObject); procedure dbCellClick(Column: TColumn); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton5Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure edtCpfKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } procedure LimparCampos; procedure ExibirRegistros; end; var frmCadastroAluno: TfrmCadastroAluno; implementation {$R *.dfm} uses uModulo, uSystemUtils; procedure TfrmCadastroAluno.dbCellClick(Column: TColumn); begin inherited; if qrAluno.FieldByName('cpf').AsString <> null then begin edtId.Text := qrAluno.FieldByName('id').AsString; edtNome.Text := qrAluno.FieldByName('nome').AsString; edtCpf.Text := qrAluno.FieldByName('cpf').AsString; edtId.Enabled := False; edtCpf.Enabled := False; end; end; procedure TfrmCadastroAluno.edtCpfKeyPress(Sender: TObject; var Key: Char); begin inherited; if not IsNumber(Key) then Key := #0; end; procedure TfrmCadastroAluno.ExibirRegistros; begin qrAluno.Close; qrAluno.SQL.Clear; qrAluno.SQL.Add('SELECT * FROM aluno'); qrAluno.SQL.Add(' ORDER BY id ASC '); qrAluno.Open(); end; procedure TfrmCadastroAluno.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; frmCadastroAluno := nil; end; procedure TfrmCadastroAluno.LimparCampos; begin edtId.Text := ''; edtNome.Text := ''; edtCpf.Text := ''; end; procedure TfrmCadastroAluno.SpeedButton1Click(Sender: TObject); begin inherited; LimparCampos; ExibirRegistros; edtNome.SetFocus; end; procedure TfrmCadastroAluno.SpeedButton2Click(Sender: TObject); begin inherited; if Trim(edtNome.Text) = '' then begin ShowMessage('Campo nome obrigatório.'); edtNome.SetFocus; Exit; end; if Trim(edtCpf.Text) = '' then begin ShowMessage('Campo cpf obrigatório.'); edtCpf.SetFocus; Exit; end; qrAluno.Close; qrAluno.SQL.Clear; qrAluno.SQL.Add('SELECT * FROM aluno WHERE cpf = :cpf'); qrAluno.ParamByName('cpf').AsString := edtCpf.Text; qrAluno.Open; if qrAluno.IsEmpty then begin qrAluno.Close; qrAluno.SQL.Clear; qrAluno.SQL.Add('INSERT INTO aluno (nome, cpf)'); qrAluno.SQL.Add('VALUES (:nome, :cpf)'); qrAluno.ParamByName('nome').AsString := edtNome.Text; qrAluno.ParamByName('cpf').AsString := edtCpf.Text; qrAluno.ExecSQL; ShowMessage('Cadastro realizado com sucesso.'); LimparCampos; ExibirRegistros; Exit; end else begin ShowMessage('Aluno possui cadastro.'); Exit; end; qrAluno.Destroy; end; procedure TfrmCadastroAluno.SpeedButton3Click(Sender: TObject); begin inherited; if not db.Columns.Grid.Focused then begin ShowMessage('Selecione um registro para exclusão.'); db.SetFocus; Exit; end; if MsgConfirm('Deseja excluir registro?') then begin qrAluno.Close; qrAluno.SQL.Clear; qrAluno.SQL.Add('DELETE FROM aluno WHERE id = :id'); qrAluno.ParamByName('id').AsString := edtId.Text; qrAluno.ExecSQL; LimparCampos; ExibirRegistros; ShowMessage('Registro excluido com sucesso.'); edtNome.SetFocus; end; end; procedure TfrmCadastroAluno.SpeedButton5Click(Sender: TObject); begin inherited; if Trim(edtId.Text) = '' then begin ShowMessage('Selecione um registro para atualização.'); db.SetFocus; Exit; end; qrAluno.Close; qrAluno.SQL.Clear; qrAluno.SQL.Add('UPDATE aluno'); qrAluno.SQL.Add('SET nome = :nome'); qrAluno.SQL.Add('WHERE id = :id'); qrAluno.ParamByName('id').AsString := edtId.Text; qrAluno.ParamByName('nome').AsString := edtNome.Text; qrAluno.ExecSQL; ShowMessage('Cadastro atualizado com sucesso.'); LimparCampos; ExibirRegistros; end; end.
{$ASMMODE INTEL} VAR num: byte; answ: word; BEGIN WriteLn('Введите число [0..255]: '); Readln(num); answ := 0; ASM MOV AL, num //в AL записываем введенное число MOV CL, 10 //в CL всегда будет запсано 10 (делить будем брять последнюю цифру числа) MOV ESI, ESP //сохраняем в ESI первоначальный указатель стека, что бы узнать сколько цифр из стека доставать @1: MOV AH, 0 //обнуляем, тк в AH помещается остаток от деления DIV CL //делим на 10 (в AH помещается остаток, а в AL - частное) MOVZX DX, AH //остаток переносим в DX (тк AH - 8 бит, а DX - 16 бит, поэтому используем команду MOVZX. Она заполняет недостоющие биты 0) PUSH DX //помещаем остаток в стек CMP AL, 0 //проверяем не закончилось ли число JNE @1 //если число еще осталость, то повторяем цикл MOV BX, 0 @2: SHL BX, 4 //смещаем биты на 4 влево (потом в эти освободившиеся биты будем ложить цифру) POP DX //вытаскиваем из стека цифру (сначала вытаскиваются старшие цифры) OR BX, DX //помещаем в 4 первых бита BX цифру CMP ESI, ESP //проверяем есть ли еще цифры в стеке JNE @2 //если есть то повторяем цикл MOV answ, BX //записываем ответ (получается запокованное двоично-десятичное число (одна цифра занимает 4 бита)) END; Writeln(answ); Readln(); END.
unit ListAnalysisTree; {* Дерево анализа списка } // Модуль: "w:\garant6x\implementation\Garant\tie\Garant\GblAdapterLib\ListAnalysisTree.pas" // Стереотип: "SimpleClass" // Элемент модели: "ListAnalysisTree" MUID: (4A9F669C007E) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , ree , DynamicTreeUnit ; type ListAnalysisTree = {final} class {* Дерево анализа списка } private expanded: ByteBool; {* флажок, были ли развёрнуты узлы дерева в соответствии с правилом: Если узел пуст, он показывается свернутым с нулем напротив в скобках. Если в нем что-то есть, то разворачивается. } public NodeType_: ; NodeDelegateType_: ; public constructor Make(const stree); reintroduce; stdcall; procedure AddNotifier(var root; var notifier: INodeNotifier); override; end;//ListAnalysisTree implementation uses l3ImplUses , ApplicationHelper //#UC START# *4A9F669C007Eimpl_uses* //#UC END# *4A9F669C007Eimpl_uses* ; constructor ListAnalysisTree.Make(const stree); //#UC START# *4A9F727601E7_4A9F669C007E_var* //#UC END# *4A9F727601E7_4A9F669C007E_var* begin //#UC START# *4A9F727601E7_4A9F669C007E_impl* !!! Needs to be implemented !!! //#UC END# *4A9F727601E7_4A9F669C007E_impl* end;//ListAnalysisTree.Make procedure ListAnalysisTree.AddNotifier(var root; var notifier: INodeNotifier); //#UC START# *46011F130203_4A9F669C007E_var* //#UC END# *46011F130203_4A9F669C007E_var* begin //#UC START# *46011F130203_4A9F669C007E_impl* !!! Needs to be implemented !!! //#UC END# *46011F130203_4A9F669C007E_impl* end;//ListAnalysisTree.AddNotifier end.
unit Demos; interface uses SysUtils, Classes, tfTypes, tfBytes, tfHashes, tfCiphers, EncryptedStreams; procedure TestAll; implementation // Encrypts file using TCipher procedure EncryptAES1(const FileName: string; const Key: ByteArray; Nonce: UInt64); var InStream, OutStream: TStream; begin InStream:= TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try OutStream:= TFileStream.Create(FileName + '1.aes', fmCreate); try OutStream.WriteBuffer(Nonce, SizeOf(Nonce)); TCipher.AES.ExpandKey(Key, CTR_ENCRYPT, Nonce) .EncryptStream(InStream, OutStream); finally OutStream.Free; end; finally InStream.Free; end; end; // Encrypts file using TStreamCipher procedure EncryptAES2(const FileName: string; const Key: ByteArray; Nonce: UInt64); var InStream, OutStream: TStream; // StreamCipher: TStreamCipher; begin InStream:= TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try OutStream:= TFileStream.Create(FileName + '2.aes', fmCreate); try OutStream.WriteBuffer(Nonce, SizeOf(Nonce)); TStreamCipher.AES.ExpandKey(Key, Nonce) .ApplyToStream(InStream, OutStream); finally OutStream.Free; end; finally InStream.Free; end; end; // Encrypts file using TEncryptedStream procedure EncryptAES3(const FileName: string; const Key: ByteArray; Nonce: UInt64); var InStream, OutStream: TStream; // StreamCipher: TStreamCipher; begin InStream:= TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try OutStream:= TEncryptedFileStream.Create(FileName + '3.aes', fmCreate, TStreamCipher.AES.ExpandKey(Key, Nonce)); try OutStream.CopyFrom(InStream, 0); finally OutStream.Free; end; finally InStream.Free; end; end; // Check all 3 encrypted files are identical procedure CheckEncrypted(const FileName: string); var Digest1, Digest2, Digest3: ByteArray; begin Digest1:= THash.SHA256.UpdateFile(FileName+'1.aes').Digest; Digest2:= THash.SHA256.UpdateFile(FileName+'2.aes').Digest; Digest3:= THash.SHA256.UpdateFile(FileName+'3.aes').Digest; Assert(Digest1 = Digest2); Assert(Digest1 = Digest3); end; procedure TestRead(const FileName: string; const Key: ByteArray; Nonce: UInt64); const BUF_SIZE = 999; var Stream1, Stream2: TStream; Buffer1, Buffer2: array[0..BUF_SIZE-1] of Byte; I: Integer; begin Stream1:= TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try Stream2:= TEncryptedFileStream.Create(FileName + '3.aes', fmOpenRead or fmShareDenyWrite, TStreamCipher.AES.ExpandKey(Key, Nonce)); try Stream1.ReadBuffer(Buffer1, BUF_SIZE); Stream2.ReadBuffer(Buffer2, BUF_SIZE); Assert(CompareMem(@Buffer1, @Buffer2, BUF_SIZE)); Stream1.Position:= 333; Stream2.Position:= 333; Stream1.ReadBuffer(Buffer1, BUF_SIZE); Stream2.ReadBuffer(Buffer2, BUF_SIZE); Assert(CompareMem(@Buffer1, @Buffer2, BUF_SIZE)); Stream1.Position:= 4000; Stream2.Position:= 4000; Stream1.ReadBuffer(Buffer1, BUF_SIZE); Stream2.ReadBuffer(Buffer2, BUF_SIZE); Assert(CompareMem(@Buffer1, @Buffer2, BUF_SIZE)); Stream1.Position:= 4000 - BUF_SIZE; Stream2.Position:= 4000 - BUF_SIZE; Stream1.ReadBuffer(Buffer1, BUF_SIZE); Stream2.ReadBuffer(Buffer2, BUF_SIZE); Assert(CompareMem(@Buffer1, @Buffer2, BUF_SIZE)); finally Stream2.Free; end; finally Stream1.Free; end; end; procedure TestAll; const HexKey = '000102030405060708090A0B0C0D0E0F'; Nonce = 42; var Name: string; Key: ByteArray; begin Name:= ParamStr(0); Key:= ByteArray.ParseHex(HexKey); EncryptAES1(Name, Key, Nonce); EncryptAES2(Name, Key, Nonce); EncryptAES3(Name, Key, Nonce); CheckEncrypted(Name); TestRead(Name, Key, Nonce); end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit frmProcedureRun; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, MemDS, VirtualTable, cxContainer, cxTextEdit, cxMemo, cxRichEdit, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxSplitter, OraProcSource; type TProcedureRunFrm = class(TForm) Panel1: TPanel; btnExecute: TcxButton; btnCancel: TcxButton; Panel2: TPanel; Panel3: TPanel; cxSplitter1: TcxSplitter; gridDBParams: TcxGridDBTableView; cxGrid1Level1: TcxGridLevel; cxGrid1: TcxGrid; edtSQL: TcxRichEdit; vtParams: TVirtualTable; dsParams: TDataSource; gridDBParamsNAME: TcxGridDBColumn; gridDBParamsDATA_TYPE: TcxGridDBColumn; gridDBParamsMODE: TcxGridDBColumn; gridDBParamsVALUE: TcxGridDBColumn; vtParamsobject_name: TStringField; vtParamssequence: TIntegerField; vtParamsargument_name: TStringField; vtParamsDATA_SIZE: TStringField; vtParamsdata_type: TStringField; vtParamsin_out: TStringField; vtParamsVALUE: TStringField; gridDBParamsColumn1: TcxGridDBColumn; procedure btnCancelClick(Sender: TObject); procedure gridDBParamsEditValueChanged(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem); procedure btnExecuteClick(Sender: TObject); private { Private declarations } ProcSource: TProcSource; procedure GetParameters; procedure SetParameters; public { Public declarations } procedure Init(FProcSource: TProcSource); end; var ProcedureRunFrm: TProcedureRunFrm; implementation {$R *.dfm} uses Util, VisualOptions, GenelDM; procedure TProcedureRunFrm.Init(FProcSource: TProcSource); begin ProcedureRunFrm := TProcedureRunFrm.Create(Application); Self := ProcedureRunFrm; DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); ProcSource := FProcSource; GetParameters; SetParameters; ShowModal; Free; end; procedure TProcedureRunFrm.GetParameters; begin vtParams.Close; vtParams.Tag := 9; vtParams.Assign(ProcSource.Arguments); vtParams.Open; vtParams.AddField('VALUE',ftString,50); with vtParams do begin while not Eof do begin edit; FieldByName('VALUE').AsString := 'NULL'; post; next; end; end; vtParams.Tag := 0; end; procedure TProcedureRunFrm.SetParameters; var param, paramsStr, paramsValue: string; i: integer; begin i := 0; with vtParams do begin First; while not Eof do begin inc(i); paramsStr := paramsStr +ln+' '+FieldByName('argument_name').AsString +' '+FieldByName('data_type').AsString; if FieldByName('DATA_SIZE').AsString <> '' then paramsStr := paramsStr +'('+FieldByName('DATA_SIZE').AsString+')'; paramsStr := paramsStr +';'; paramsValue := paramsValue +ln+' '+FieldByName('argument_name').AsString +' := '+GetColumnValue(FieldByName('data_type').AsString,FieldByName('VALUE').AsString ) +';'; param := param +' '+FieldByName('argument_name').AsString; Next; if i <> RecordCount then param := param +','; end; end; edtSQL.Text :='DECLARE' +paramsStr +ln+'BEGIN' +paramsValue +ln+' '+ProcSource.OWNER+'.'+ProcSource.SOURCE_NAME; if paramsStr <> '' then edtSQL.Text := edtSQL.Text + '('+param+')'; edtSQL.Text := edtSQL.Text +';'+ln +' COMMIT;'+ln +'END;'; CodeColors(self, 'Default', edtSQL, false); end; procedure TProcedureRunFrm.btnCancelClick(Sender: TObject); begin close; end; procedure TProcedureRunFrm.gridDBParamsEditValueChanged( Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem); begin SetParameters; end; procedure TProcedureRunFrm.btnExecuteClick(Sender: TObject); begin ProcSource.RunSource(edtSQL.Text); close; end; end.
unit UDMCarteira; interface uses SysUtils, Classes, FMTBcd, DB, DBClient, Provider, SqlExpr; type TDMCarteira = class(TDataModule) sdsCarteira: TSQLDataSet; dspCarteira: TDataSetProvider; cdsCarteira: TClientDataSet; dsCarteira: TDataSource; sdsCarteiraID: TIntegerField; sdsCarteiraCODCARTEIRA: TStringField; sdsCarteiraCODBANCO: TStringField; sdsCarteiraNOMEBANCO: TStringField; cdsCarteiraID: TIntegerField; cdsCarteiraCODCARTEIRA: TStringField; cdsCarteiraCODBANCO: TStringField; cdsCarteiraNOMEBANCO: TStringField; sdsCarteiraNOMECARTEIRA: TStringField; cdsCarteiraNOMECARTEIRA: TStringField; sdsCarteiraGERARNOSSONUMERO: TStringField; cdsCarteiraGERARNOSSONUMERO: TStringField; sdsCarteiraGERARREMESSA: TStringField; cdsCarteiraGERARREMESSA: TStringField; sdsCarteiraCODCARTEIRA_IMP: TStringField; cdsCarteiraCODCARTEIRA_IMP: TStringField; procedure DataModuleCreate(Sender: TObject); procedure dspCarteiraUpdateError(Sender: TObject; DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind; var Response: TResolverResponse); private { Private declarations } public { Public declarations } end; var DMCarteira: TDMCarteira; ctCarteira : String; implementation uses DmdDatabase; {$R *.dfm} procedure TDMCarteira.DataModuleCreate(Sender: TObject); begin ctCarteira := sdsCarteira.CommandText; end; procedure TDMCarteira.dspCarteiraUpdateError(Sender: TObject; DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind; var Response: TResolverResponse); begin Response := rrAbort; raise exception.Create(E.Message); end; end.
unit namcoio_56xx_58xx; interface uses timer_engine; type tin_f=function:byte; tout_f=procedure (data:byte); namco_5x_chip=class constructor create(num_cpu,tipo:byte); destructor free; public reset_status:boolean; procedure run; function read(direccion:byte):byte; procedure write(direccion,valor:byte); procedure reset_internal(reset_status:boolean); procedure reset; procedure change_io(in0,in1,in2,in3:tin_f;out0,out1:tout_f); private tipo:byte; ram:array[0..$f] of byte; coins,coins_per_cred,creds_per_coin:array[0..1] of byte; in_count,credits,lastcoins,lastbuttons:byte; in_f:array[0..3] of tin_f; out_f:array[0..1] of tout_f; timer_io:byte; procedure handle_coins(swap:byte); procedure run_internal; end; var namco_5x_0,namco_5x_1:namco_5x_chip; const NAMCO_56XX=0; NAMCO_58XX=1; NAMCO_59XX=2; implementation var chips_total:integer=-1; procedure run_io_0; begin namco_5x_0.run_internal; timers.enabled(namco_5x_0.timer_io,false); end; procedure run_io_1; begin namco_5x_1.run_internal; timers.enabled(namco_5x_1.timer_io,false); end; constructor namco_5x_chip.create(num_cpu,tipo:byte); begin self.in_f[0]:=nil; self.in_f[1]:=nil; self.in_f[2]:=nil; self.in_f[3]:=nil; self.out_f[0]:=nil; self.out_f[1]:=nil; self.tipo:=tipo; chips_total:=chips_total+1; //1536000*0.000001*50=76,8 case chips_total of 0:self.timer_io:=timers.init(num_cpu,76.8,run_io_0,nil,false); 1:self.timer_io:=timers.init(num_cpu,76.8,run_io_1,nil,false); end; end; destructor namco_5x_chip.free; begin chips_total:=chips_total-1; end; procedure namco_5x_chip.reset; begin self.reset_status:=false; fillchar(self.ram,$10,0); end; procedure namco_5x_chip.change_io(in0,in1,in2,in3:tin_f;out0,out1:tout_f); begin self.in_f[0]:=in0; self.in_f[1]:=in1; self.in_f[2]:=in2; self.in_f[3]:=in3; self.out_f[0]:=out0; self.out_f[1]:=out0; end; procedure namco_5x_chip.run; begin timers.enabled(self.timer_io,true); end; function namco_5x_chip.read(direccion:byte):byte; begin // RAM is 4-bit wide; Pac & Pal requires the | 0xf0 otherwise Easter egg doesn't work read:=$f0 or self.ram[direccion and $f]; end; procedure namco_5x_chip.write(direccion,valor:byte); begin self.ram[direccion and $f]:=valor and $f; end; procedure namco_5x_chip.handle_coins(swap:byte); var val,toggled,credit_add,credit_sub,button:byte; begin credit_add:=0; credit_sub:=0; val:=not(self.in_f[0]); // pins 38-41 toggled:=val xor self.lastcoins; self.lastcoins:=val; // check coin insertion if (val and toggled and $1)<>0 then begin self.coins[0]:=self.coins[0]+1; if (self.coins[0]>=(self.coins_per_cred[0] and 7)) then begin credit_add:=self.creds_per_coin[0]-(self.coins_per_cred[0] shr 3); self.coins[0]:=self.coins[0]-(self.coins_per_cred[0] and 7); end else begin if (self.coins_per_cred[0] and 8)<>0 then credit_add:=1; end; end; if (val and toggled and $02)<>0 then begin self.coins[1]:=self.coins[1]+1; if (self.coins[1]>=(self.coins_per_cred[1] and 7)) then begin credit_add:=self.creds_per_coin[1]-(self.coins_per_cred[1] shr 3); self.coins[1]:=self.coins[1]-(self.coins_per_cred[1] and 7); end else begin if (self.coins_per_cred[1] and 8)<>0 then credit_add:=1; end; end; if (val and toggled and $08)<>0 then credit_add:= 1; val:=not(self.in_f[3]); // pins 30-33 toggled:=val xor self.lastbuttons; self.lastbuttons:=val; // check start buttons, only if the game allows if ((self.ram[9] and $f)=0) then begin // the other argument is IORAM_READ(10) = 1, meaning unknown if (val and toggled and $04)<>0 then begin if (self.credits>=1) then credit_sub:=1; end else begin if (val and toggled and $08)<>0 then begin if (self.credits>=2) then credit_sub:=2; end; end; end; self.credits:=self.credits+credit_add-credit_sub; self.ram[0 xor swap]:=(self.credits div 10) and $f; // BCD credits self.ram[1 xor swap]:=(self.credits mod 10) and $f; // BCD credits self.ram[2 xor swap]:=credit_add and $f; // credit increment (coin inputs) self.ram[3 xor swap]:=credit_sub and $f; // credit decrement (start buttons) self.ram[4]:=not(self.in_f[1]) and $f; // pins 22-25 button:=((val and $05) shl 1) or (val and toggled and $05); self.ram[5]:=button and $f; // pins 30 & 32 normal and impulse self.ram[6]:=not(self.in_f[2]) and $f; // pins 26-29 button:=(val and $a) or ((val and toggled and $a) shr 1); self.ram[7]:=button and $f; // pins 31 & 33 normal and impulse end; procedure namco_5x_chip.run_internal; var i,n,rng,seed:byte; function NEXT(n:byte):byte; begin if (n and 1)<>0 then next:=(n xor $90) shr 1 else next:=n shr 1; end; begin case self.tipo of NAMCO_56XX:case (self.ram[8] and $f) of //Namco 56XX 0:; // nop? 1:begin // read switch inputs self.ram[0]:=not(self.in_f[0]) and $f; // pins 38-41 self.ram[1]:=not(self.in_f[1]) and $f; // pins 22-25 self.ram[2]:=not(self.in_f[2]) and $f; // pins 26-29 self.ram[3]:=not(self.in_f[3]) and $f; // pins 30-33 if @self.out_f[0]<>nil then self.out_f[0](self.ram[9] and $f); // output to pins 13-16 (motos, pacnpal, gaplus) if @self.out_f[1]<>nil then self.out_f[1](self.ram[$a] and $f); // output to pins 17-20 (gaplus) end; 2:begin // initialize coinage settings self.coins_per_cred[0]:=self.ram[9] and $f; self.creds_per_coin[0]:=self.ram[$a] and $f; self.coins_per_cred[1]:=self.ram[$b] and $f; self.creds_per_coin[1]:=self.ram[$c] and $f; // IORAM_READ(13) = 1; meaning unknown - possibly a 3rd coin input? (there's a IPT_UNUSED bit in port A) // IORAM_READ(14) = 1; meaning unknown - possibly a 3rd coin input? (there's a IPT_UNUSED bit in port A) // IORAM_READ(15) = 0; meaning unknown end; 4:begin // druaga, digdug chip #1: read dip switches and inputs // superpac chip #0: process coin and start inputs, read switch inputs self.handle_coins(0); end; 7:begin // bootup check (liblrabl only) // liblrabl chip #1: 9-15 = f 1 2 3 4 0 0, expects 2 = e // liblrabl chip #2: 9-15 = 0 1 4 5 5 0 0, expects 7 = 6 self.ram[2]:=$e; self.ram[7]:=$6; end; 8:begin // bootup check // superpac: 9-15 = f f f f f f f, expects 0-1 = 6 9. 0x69 = f+f+f+f+f+f+f. // motos: 9-15 = f f f f f f f, expects 0-1 = 6 9. 0x69 = f+f+f+f+f+f+f. // phozon: 9-15 = 1 2 3 4 5 6 7, expects 0-1 = 1 c. 0x1c = 1+2+3+4+5+6+7 n:=0; for i:=9 to 15 do n:=n+(self.ram[i] and $f); self.ram[0]:=n shr 4; self.ram[1]:=n and $f; end; 9:begin // read dip switches and inputs if @self.out_f[0]<>nil then self.out_f[0](0); // set pin 13 = 0 self.ram[0]:=not(self.in_f[0]) and $f; self.ram[2]:=not(self.in_f[1]) and $f; self.ram[4]:=not(self.in_f[2]) and $f; self.ram[5]:=not(self.in_f[3]) and $f; if @self.out_f[0]<>nil then self.out_f[0](1); // set pin 13 = 0 self.ram[1]:=not(self.in_f[0]) and $f; self.ram[3]:=not(self.in_f[1]) and $f; self.ram[5]:=not(self.in_f[2]) and $f; self.ram[7]:=not(self.in_f[3]) and $f; end; end; NAMCO_58XX:case (self.ram[8] and $f) of //Namco 58XX 0:; //nop 1:begin // read switch inputs self.ram[4]:=not(self.in_f[0]) and $f; self.ram[5]:=not(self.in_f[1]) and $f; self.ram[6]:=not(self.in_f[2]) and $f; self.ram[7]:=not(self.in_f[3]) and $f; //WRITE_PORT(space,0,IORAM_READ(9)); // output to pins 13-16 (toypop) //WRITE_PORT(space,1,IORAM_READ(10)); // output to pins 17-20 (toypop) end; 2:begin // initialize coinage settings self.coins_per_cred[0]:=self.ram[9] and $f; self.creds_per_coin[0]:=self.ram[$a] and $f; self.coins_per_cred[1]:=self.ram[$b] and $f; self.creds_per_coin[1]:=self.ram[$c] and $f; // IORAM_READ(13) = 1; meaning unknown - possibly a 3rd coin input? (there's a IPT_UNUSED bit in port A) // IORAM_READ(14) = 0; meaning unknown - possibly a 3rd coin input? (there's a IPT_UNUSED bit in port A) // IORAM_READ(15) = 0; meaning unknown end; 3:self.handle_coins(2); //coin handle 4:begin // read dip switches and inputs if @self.out_f[0]<>nil then self.out_f[0](0); // set pin 13 = 0 self.ram[0]:=not(self.in_f[0]) and $f; self.ram[2]:=not(self.in_f[1]) and $f; self.ram[4]:=not(self.in_f[2]) and $f; self.ram[6]:=not(self.in_f[3]) and $f; if @self.out_f[0]<>nil then self.out_f[0](1); // set pin 13 = 0 self.ram[1]:=not(self.in_f[0]) and $f; self.ram[3]:=not(self.in_f[1]) and $f; self.ram[5]:=not(self.in_f[2]) and $f; self.ram[7]:=not(self.in_f[3]) and $f; end; 5:begin // bootup check { mode 5 values are checked against these numbers during power up mappy: 9-15 = 3 6 5 f a c e, expects 1-7 = 8 4 6 e d 9 d grobda: 9-15 = 2 3 4 5 6 7 8, expects 2 = f and 6 = c phozon: 9-15 = 0 1 2 3 4 5 6, expects 0-7 = 0 2 3 4 5 6 c a gaplus: 9-15 = f f f f f f f, expects 0-1 = f f This has been determined to be the result of repeated XORs, controlled by a 7-bit LFSR. The following algorithm should be equivalent to the original one (though probably less efficient). The first nibble of the result however is uncertain. It is usually 0, but in some cases it toggles between 0 and F. We use a kludge to give Gaplus the F it expects.} //initialize the LFSR depending on the first two arguments n:=((self.ram[9] and $f)*16+(self.ram[$a] and $f)) and $7f; seed:=$22; for i:=0 to n-1 do seed:=NEXT(seed); // calculate the answer for i:=1 to 7 do begin n:=0; rng:=seed; if (rng and 1)<>0 then n:=n xor (not(self.ram[$b]) and $f); rng:=NEXT(rng); seed:=rng; // save state for next loop if (rng and 1)<>0 then n:=n xor (not(self.ram[$a]) and $f); rng:=NEXT(rng); if (rng and 1)<>0 then n:=n xor (not(self.ram[9]) and $f); rng:=NEXT(rng); if (rng and 1)<>0 then n:=n xor (not(self.ram[$f]) and $f); rng:=NEXT(rng); if (rng and 1)<>0 then n:=n xor (not(self.ram[$e]) and $f); rng:=NEXT(rng); if (rng and 1)<>0 then n:=n xor (not(self.ram[$d]) and $f); rng:=NEXT(rng); if (rng and 1)<>0 then n:=n xor (not(self.ram[$c]) and $f); self.ram[i]:=not(n) and $f; end; self.ram[0]:=0; // kludge for gaplus if (self.ram[9] and $f)=$f then self.ram[0]:=$f; end; end; NAMCO_59XX:case (self.ram[8] and $f) of //Namco 59XX 0:; // nop? 3:begin // pacnpal chip #1: read dip switches and inputs self.ram[4]:=not(self.in_f[0]) and $f; // pins 38-41, pin 13 = 0 ? self.ram[5]:=not(self.in_f[2]) and $f; // pins 26-29 ? self.ram[6]:=not(self.in_f[1]) and $f; // pins 22-25 ? self.ram[7]:=not(self.in_f[3]) and $f; // pins 30-33 end; end; end; end; procedure namco_5x_chip.reset_internal(reset_status:boolean); begin self.reset_status:=reset_status; if reset_status then begin // reset internal registers self.lastcoins:=0; self.lastbuttons:=0; self.credits:= 0; self.coins[0]:=0; self.coins_per_cred[0]:=1; self.creds_per_coin[0]:=1; self.coins[1]:=0; self.coins_per_cred[1]:=1; self.creds_per_coin[1]:=1; self.in_count:=0; end; end; end.
{****************************************************************} { TWebImage component } { for Delphi & C++Builder } { version 1.1 } { } { written by } { TMS Software } { copyright © 2000-2004 } { Email : info@tmssoftware.com } { Web : http://www.tmssoftware.com } {****************************************************************} unit WebImgRegDE; interface {$I TMSDEFS.INC} uses WebImage, WebImgDE, Classes, {$IFDEF DELPHI6_LVL} DesignIntf, DesignEditors {$ELSE} DsgnIntf {$ENDIF} ; procedure Register; implementation procedure Register; begin RegisterPropertyEditor(TypeInfo(TWebPicture), TWebImage, 'WebPicture', TWebPictureProperty); end; end.
unit MazeStatistics; interface uses MazeMain; type //Parameters for comparison TStatRoute = (SolveLength, FullRoute); TStatSolveAlg = record case AllSolveAlg: Boolean of False: (SolveAlg: TMazeSolveAlg); end; TStatGenAlg = record case AllGenAlg: Boolean of False: (GenAlg: TMazeGenAlg); end; TYValueArr = array of Double; TColumnNames = array of String; function GetStatistic(const Condition: TStatRoute; const SolveAlg: TStatSolveAlg; const GenAlg: TStatGenAlg; const Sizeable: Boolean): TYValueArr; Function GetColumnName(const SolveAlg: TStatSolveAlg; const GenAlg: TStatGenAlg; const Sizeable: Boolean): TColumnNames; Function GetChartTitleText(const Condition: TStatRoute; const SolveAlg: TStatSolveAlg; const GenAlg: TStatGenAlg; const Sizeable: Boolean): String; implementation uses MazeSave; //Calculate amount of columns in chart procedure SetAnswLeng(var Answ: TYValueArr; const SolveAlg: TStatSolveAlg;const GenAlg: TStatGenAlg; const Sizeable: Boolean); overload; begin if SolveAlg.AllSolveAlg = True then SetLength(Answ, Ord(High(TMazeSolveAlg))+1) else if GenAlg.AllGenAlg = True then SetLength(Answ, Ord(High(TMazeGenAlg))+1) else if Sizeable = True then SetLength(Answ, Ord(High(TMazeSize))+1); end; procedure SetAnswLeng(var Answ: TColumnNames; const SolveAlg: TStatSolveAlg;const GenAlg: TStatGenAlg; const Sizeable: Boolean); overload; begin if SolveAlg.AllSolveAlg = True then SetLength(Answ, Ord(High(TMazeSolveAlg))+1) else if GenAlg.AllGenAlg = True then SetLength(Answ, Ord(High(TMazeGenAlg))+1) else if Sizeable = True then SetLength(Answ, Ord(High(TMazeSize))+1); end; //Clculate average number procedure CalcAverageNumb(var AnswArr: TYValueArr; const Amount: array of Integer); var I: Integer; begin for I := 0 to High(AnswArr) do if Amount[I] <> 0 then AnswArr[i] := AnswArr[I]/Amount[I]; end; //IDstanation between two points function GetDistBetweenPoints(const Point1, Point2: TPos): Double; begin Result := Sqrt(Sqr(Point1.PosX-Point2.PosX)+Sqr(Point1.PosY-Point2.PosY)); end; //Calculate values for chart function GetStatistic(const Condition: TStatRoute; const SolveAlg: TStatSolveAlg; const GenAlg: TStatGenAlg; const Sizeable: Boolean): TYValueArr; var Stat: TMazeStat; i: Integer; SetSolveAlg: Set of TMazeSolveAlg; SetGenAlg: Set of TMazeGenAlg; MazeAmount: array of Integer; begin //Set available parameters if SolveAlg.AllSolveAlg then SetSolveAlg := [BFS, DFS, LeftHand, RightHand] else SetSolveAlg := [SolveAlg.SolveAlg]; if GenAlg.AllGenAlg then SetGenAlg := [HuntAKill, BackTrack, Prim] else SetGenAlg := [GenAlg.GenAlg]; SetAnswLeng(Result, SolveAlg, GenAlg, Sizeable); SetLength(MazeAmount, Length(Result)); //Unload all records frome type file for I := GetRecordsAmount(TypeFileAddr) downto 1 do begin Stat := ReadFromTypeFile(I, TypeFileAddr); //Uses only available files if Stat.MazeSolveAlg in SetSolveAlg then begin if Stat.MazeGenAlg in SetGenAlg then begin //Add data to array to calculate chart if Sizeable = True then begin Inc(MazeAmount[Ord(Stat.MazeSize)]); Result[Ord(Stat.MazeSize)] := Result[Ord(Stat.MazeSize)] + Stat.VisitedCells.Route/GetDistBetweenPoints(Stat.StartPoint, Stat.EndPoint) end else begin if SolveAlg.AllSolveAlg then begin Inc(MazeAmount[Ord(Stat.MazeSolveAlg)]); if Condition = SolveLength then Result[Ord(Stat.MazeSolveAlg)] := Result[Ord(Stat.MazeSolveAlg)] + Stat.VisitedCells.Route/GetDistBetweenPoints(Stat.StartPoint, Stat.EndPoint) else Result[Ord(Stat.MazeSolveAlg)] := Result[Ord(Stat.MazeSolveAlg)] + Stat.VisitedCells.FullRoute/GetDistBetweenPoints(Stat.StartPoint, Stat.EndPoint) end else if GenAlg.AllGenAlg then begin Inc(MazeAmount[Ord(Stat.MazeGenAlg)]); if Condition = SolveLength then Result[Ord(Stat.MazeGenAlg)] := Result[Ord(Stat.MazeGenAlg)] + Stat.VisitedCells.Route/GetDistBetweenPoints(Stat.StartPoint, Stat.EndPoint) else Result[Ord(Stat.MazeGenAlg)] := Result[Ord(Stat.MazeGenAlg)] + Stat.VisitedCells.FullRoute/GetDistBetweenPoints(Stat.StartPoint, Stat.EndPoint); end; end; end; end; end; CalcAverageNumb(Result, MazeAmount); end; //Get name of collumns in chart Function GetColumnName(const SolveAlg: TStatSolveAlg; const GenAlg: TStatGenAlg; const Sizeable: Boolean): TColumnNames; var I: Integer; Begin SetAnswLeng(Result, SolveAlg, GenAlg, Sizeable); for I := Low(Result) to High(Result) do if SolveAlg.AllSolveAlg then Result[I] := GetSolveAlgStr(TMazeSolveAlg(I)) else if GenAlg.AllGenAlg then Result[I] := GetGenAlgStr(TMazeGenAlg(I)) else if Sizeable then Result[I] := GetMazeSizeStr(TMazeSize(I)); End; //Get name of the chart Function GetChartTitleText(const Condition: TStatRoute; const SolveAlg: TStatSolveAlg; const GenAlg: TStatGenAlg; const Sizeable: Boolean): String; //Get sequence of names of generations alg Function GetGenAlgSetStr(const GenerationCond: TStatGenAlg): String; var I: Integer; Begin Result := ''; if GenerationCond.AllGenAlg then begin for I := Ord(Low(TMazeGenAlg)) to Ord(High(TMazeGenAlg)) do Result := Result + GetGenAlgStr(TMazeGenAlg(I)) + ', '; SetLength(Result, Length(Result)-2); end else Result := GetGenAlgStr(GenerationCond.GenAlg); end; //Get sequence of names of solves alg Function GetSolveAlgSetStr(const SolveCond: TStatSolveAlg): String; var I: Integer; Begin Result := ''; if SolveCond.AllSolveAlg then begin for I := Ord(Low(TMazeSolveAlg)) to Ord(High(TMazeSolveAlg)) do Result := Result + GetSolveAlgStr(TMazeSolveAlg(I)) + ', '; SetLength(Result, Length(Result)-2); end else Result := GetSolveAlgStr(SolveCond.SolveAlg); end; begin Result := ''; if Condition = SolveLength then Result := 'Средняя длина прохождения для алгоритма(ов) генерации ' + GetGenAlgSetStr(GenAlg) + '.' else Result := 'Кол-во посещенных клеток для алгоритма(ов) прохождения ' + GetSolveAlgSetStr(SolveAlg) + ' и алгоритма(ов) генерации ' + GetGenAlgSetStr(GenAlg) + '.'; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Generics.Collections, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cefvcl, ceflib, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Buttons, Vcl.Samples.Spin, System.DateUtils, Data.DB, MemDS, DBAccess, MyAccess, DALoader, MyLoader; type TReturn = record Return_Result:boolean; Return_Message:WideString; end; type TGame = record GameID:string; GameYear:string; GameDateTime:string; GameName:WideString; LeagueName:WideString; HomeTeam:string; VisitTeam:string; OddsURL:WideString; end; type TOdds = record GameID:string; OddsType:string; OddsOption:string; PR:string; Stock:string; Quota:string; end; type TForm1 = class(TForm) Panel1: TPanel; StatusBar1: TStatusBar; Panel2: TPanel; Panel3: TPanel; mmo_message: TMemo; lbledt_url: TLabeledEdit; chrm1: TChromium; btn_run: TBitBtn; grp1: TGroupBox; lbledt_user: TLabeledEdit; lbledt_pwd: TLabeledEdit; grp2: TGroupBox; chk_autoupdate: TCheckBox; se_update_interval: TSpinEdit; lbl1: TLabel; grp3: TGroupBox; chk_allupdate: TCheckBox; se_update_begin: TSpinEdit; lbl2: TLabel; lbl3: TLabel; se_update_end: TSpinEdit; grp4: TGroupBox; lbl4: TLabel; cbb_line: TComboBox; tmr_autorun: TTimer; lbl_countdown: TLabel; myconn1: TMyConnection; ml_games: TMyLoader; ml_odds: TMyLoader; qry_temp: TMyQuery; procedure btn_runClick(Sender: TObject); procedure chrm1AddressChange(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const url: ustring); procedure FormCreate(Sender: TObject); procedure chrm1LoadEnd(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer); procedure cbb_lineChange(Sender: TObject); procedure chk_allupdateClick(Sender: TObject); procedure tmr_autorunTimer(Sender: TObject); procedure ml_gamesPutData(Sender: TDALoader); procedure ml_oddsPutData(Sender: TDALoader); private { Private declarations } function checkLoginData:TReturn; function checkBeginEnd:TReturn; procedure writeMessage(Content:WideString); procedure doLogin(account:string; pwd:string); procedure getGameList(const str:ustring); procedure getOddsList(const str:ustring); procedure getIsNeedLogin(const str:ustring); public { Public declarations } procedure setGameData(innerText:string; var game:TGame); procedure setOddsOption(OddsType:string); function getOddsURL(innerHTML:WideString):string; function getPRData(innerText:WideString):string; function getStockData(innerText:WideString):string; function getDefaultQuota(OddsType:string; OddsOption:string):Integer; function ConvertToFloat(str:string):Real; end; var Form1: TForm1; GameList:TList<TGame>; OddsList:TList<TOdds>; CS_OddsOption:TDictionary<string, Integer>; CSFF_OddsOption:TDictionary<string, Integer>; TS_OddsOption:TDictionary<string, Integer>; FGT_OddsOption:TDictionary<string, Integer>; TG777_USER: string; TG777_PWD: string; TG777_URL: string; IsNeedLogin: Boolean; GameStartIndex,GameEndIndex:integer; implementation {$R *.dfm} uses MSHTML, ActiveX, ComObj; procedure TForm1.cbb_lineChange(Sender: TObject); begin //依据不同线路,载入相对的页面 case cbb_line.ItemIndex of 0:TG777_URL:= 'http://w3.tg777.net/'; 1: TG777_URL:= 'http://w2.tg777.net/'; 2: TG777_URL:= 'http://w1.tg777.net/'; else TG777_URL:= 'http://w1.tg777.net/'; end; chrm1.Load(TG777_URL); end; function TForm1.checkLoginData:TReturn; var myreturn:TReturn; begin //检查帐号是否为空 if Trim(lbledt_user.Text) = '' then begin myreturn.Return_Result:=False; myreturn.Return_Message:='帐号不得为空白 !'; Result:=myreturn; end //检查密码是否为空 else if Trim(lbledt_pwd.Text) = '' then begin myreturn.Return_Result:=False; myreturn.Return_Message:='密码不得为空白 !'; Result:=myreturn; end //帐号、密码都有填写 else begin myreturn.Return_Result:=True; myreturn.Return_Message:=''; Result:=myreturn; end; end; function TForm1.checkBeginEnd:TReturn; var myreturn:TReturn; begin if (se_update_begin.Value > se_update_end.Value) then begin myreturn.Return_Result:=False; myreturn.Return_Message:='起始笔数不得大於结束笔数 !'; end else if (se_update_end.Value < se_update_begin.Value) then begin myreturn.Return_Result:=False; myreturn.Return_Message:='结束笔数不得小於起始笔数 !'; end else begin myreturn.Return_Result:=True; myreturn.Return_Message:=''; end; Result:=myreturn; end; procedure TForm1.chk_allupdateClick(Sender: TObject); begin if chk_allupdate.Checked then begin se_update_begin.Enabled:=False; se_update_end.Enabled:=False; end else begin se_update_begin.Enabled:=True; se_update_end.Enabled:=True; end; end; procedure TForm1.writeMessage(Content:WideString); begin mmo_message.Lines.Add('['+formatdatetime('yyyy-mm-dd hh:nn:ss.zzz',Now)+'] '+Trim(Content)); end; procedure TForm1.btn_runClick(Sender: TObject); begin if (checkBeginEnd.Return_Result = True) then begin //第一次执行,先迈行登入动作 if IsNeedLogin = True then begin if checkLoginData.Return_Result = True then begin doLogin(lbledt_user.Text, lbledt_pwd.Text); end; end //非第一次执行,载入赛事页面 else begin chrm1.Load(TG777_URL+'list.php'); end; end else begin MessageDlg(checkBeginEnd.Return_Message, mtError, [mbok], 0); end; end; procedure TForm1.chrm1AddressChange(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const url: ustring); begin lbledt_url.Text:=url; end; procedure TForm1.chrm1LoadEnd(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer); begin //mmo_message.Lines.Add(frame.Url); //首頁 if (Trim(frame.Url) = TG777_URL) then begin btn_run.Enabled:=True; browser.MainFrame.GetSourceProc(getIsNeedLogin); end; //赛事列表 if (StringReplace(frame.Url, TG777_URL, '', [rfReplaceAll, rfIgnoreCase]) = 'controler/listmenu.php') then begin btn_run.Enabled:=False; browser.GetFrame('leftmenu').GetSourceProc(getGameList); end; //盘口列表 if Pos('newopen.php', frame.Url) > 0 then begin btn_run.Enabled:=False; browser.MainFrame.GetSourceProc(getOddsList); end; end; procedure TForm1.FormCreate(Sender: TObject); begin GameList:=TList<TGame>.Create; OddsList:=TList<TOdds>.Create; GameStartIndex:=0; TG777_URL:='http://w1.tg777.net/'; CS_OddsOption:=TDictionary<string, Integer>.Create; CSFF_OddsOption:=TDictionary<string, Integer>.Create; TS_OddsOption:=TDictionary<string, Integer>.Create; FGT_OddsOption:=TDictionary<string, Integer>.Create; setOddsOption('CS'); setOddsOption('CSFF'); setOddsOption('TS'); setOddsOption('FGT'); end; procedure TForm1.doLogin(account:string; pwd:string); var js:string; begin js:='document.getElementById("account").value = "'+Trim(account)+'"; '+ 'document.getElementById("pwd").value = "'+Trim(pwd)+'"; '+ 'document.getElementsByClassName("btn_login")[0].onclick();'; chrm1.Browser.MainFrame.ExecuteJavaScript(js, lbledt_url.Text, 0); end; procedure TForm1.getGameList(const str:ustring); var Document:IHTMLDocument2; Body:IHTMLElement2; Tags:IHTMLElementCollection; Tag:IHTMLElement; i:integer; v:Variant; Game:TGame; begin Document:=CreateComObject(Class_HTMLDOcument) as IHTMLDocument2; GameList.Clear; //取得所有赛事资料 try Document.designMode:='on'; while Document.readyState <> 'complete' do Application.ProcessMessages; v:=VarArrayCreate([0, 0], varVariant); v[0]:=str; Document.write(PSafeArray(TVarData(v).VArray)); Document.designMode:='off'; while Document.readyState <> 'complete' do Application.ProcessMessages; Body:=Document.body as IHTMLElement2; Tags:=Body.getElementsByTagName('li'); for i:=0 to Pred(Tags.length) do begin Tag := Tags.item(i, EmptyParam) as IHTMLElement; if AnsiSameText(Copy(Tag._className,1,3), 'two') then begin if (Tag.parentElement.parentElement._className = 'has-sub open') then begin Game.GameID:=Trim(StringReplace(Tag._className, 'two', '', [rfReplaceAll, rfIgnoreCase])); Game.GameYear:=IntToStr(YearOf(Date())); Game.OddsURL:=getOddsURL(Tag.innerHTML); setGameData(Tag.innerText, Game); GameList.Add(Game); end; end; end; finally Document:=nil; end; //全部更新 if chk_allupdate.Checked then begin GameStartIndex:=0; GameEndIndex:=GameList.Count - 1; chrm1.Load(GameList[GameStartIndex].OddsURL); end //部份更新 else begin //起始數筆小於全部筆數 if (se_update_begin.Value - 1 <= GameList.Count) then begin GameStartIndex:=se_update_begin.Value - 1; //結束筆數大於全部筆數 if (se_update_end.Value - 1 > GameList.Count) then begin GameEndIndex:=GameList.Count - 1; end //結束筆數小於等於全部筆數 else begin GameEndIndex:=se_update_end.Value - 1; end; chrm1.Load(GameList[GameStartIndex].OddsURL); end else begin writeMessage('更新范围起始笔数超过全部笔数('+IntToStr(GameList.Count)+') !!'); btn_run.Enabled:=True; end; end; end; procedure TForm1.getOddsList(const str:ustring); var Document:IHTMLDocument2; Body:IHTMLElement2; Tags:IHTMLElementCollection; Tag:IHTMLElement; i:integer; v:Variant; Odds:TOdds; begin //仍在范围内,更新赛事盘口 if GameStartIndex <= GameEndIndex then begin //将赛事资料写到资料库 ml_games.Load; //取得盘口资料 Document:=CreateComObject(Class_HTMLDOcument) as IHTMLDocument2; OddsList.Clear; try Document.designMode:='on'; while Document.readyState <> 'complete' do Application.ProcessMessages; v:=VarArrayCreate([0, 0], varVariant); v[0]:=str; Document.write(PSafeArray(TVarData(v).VArray)); Document.designMode:='off'; while Document.readyState <> 'complete' do Application.ProcessMessages; Body:=Document.body as IHTMLElement2; Tags:=Body.getElementsByTagName('td'); i:=0; while i < Tags.length - 1 do begin try Odds.GameID:=GameList[GameStartIndex].GameID; Tag:=Tags.item(i, EmptyParam) as IHTMLElement; //波胆 if (AnsiSameText(Copy(Tag.id,1,7), 'arthur1')) and (Length(Tag.id) >= 8) and (Tag._className = 'openallcenter') and (Trim(Tag.innerText) <> '') then begin Odds.OddsType:='CS'; //选项 Odds.OddsOption:=Trim(Tag.innerText); //获利 Inc(i); Tag:=Tags.item(i, EmptyParam) as IHTMLElement; Odds.PR:=getPRData(Tag.innerText); //可交易量 Inc(i); Tag:=Tags.item(i, EmptyParam) as IHTMLElement; Odds.Stock:=getStockData(Tag.innerText); Odds.Quota:=IntToStr(getDefaultQuota(Odds.OddsType, Odds.OddsOption)); OddsList.Add(Odds); end //上半场波胆 else if (AnsiSameText(Copy(Tag.id,1,7), 'arthur2')) and (Length(Tag.id) >= 8) and (Trim(Tag.innerText) <> '') then begin Odds.OddsType:='CSFF'; //选项 Odds.OddsOption:=Trim(Tag.innerText); //获利 Inc(i); Tag:=Tags.item(i, EmptyParam) as IHTMLElement; Odds.PR:=getPRData(Tag.innerText); //可交易量 Inc(i); Tag:=Tags.item(i, EmptyParam) as IHTMLElement; Odds.Stock:=getStockData(Tag.innerText); Odds.Quota:=IntToStr(getDefaultQuota(Odds.OddsType, Odds.OddsOption)); OddsList.Add(Odds); end //总得分 else if (AnsiSameText(Copy(Tag.id,1,7), 'arthur3')) and (Length(Tag.id) >= 8) and (Trim(Tag.innerText) <> '') then begin Odds.OddsType:='TS'; //选项 Odds.OddsOption:=Trim(Tag.innerText); //获利 Inc(i); Tag:=Tags.item(i, EmptyParam) as IHTMLElement; Odds.PR:=getPRData(Tag.innerText); //可交易量 Inc(i); Tag:=Tags.item(i, EmptyParam) as IHTMLElement; Odds.Stock:=getStockData(Tag.innerText); Odds.Quota:=IntToStr(getDefaultQuota(Odds.OddsType, Odds.OddsOption)); OddsList.Add(Odds); end //首入球时间 else if AnsiSameText(Copy(Tag.id,1,6), 'arthur') and (Length(Tag.id) = 7) and (Trim(Tag.innerText) <> '') then begin Odds.OddsType:='FGT'; //选项 Odds.OddsOption:=Trim(Tag.innerText); //获利 Inc(i); Tag:=Tags.item(i, EmptyParam) as IHTMLElement; Odds.PR:=getPRData(Tag.innerText); //可交易量 Inc(i); Tag:=Tags.item(i, EmptyParam) as IHTMLElement; Odds.Stock:=getStockData(Tag.innerText); Odds.Quota:=IntToStr(getDefaultQuota(Odds.OddsType, Odds.OddsOption)); OddsList.Add(Odds); end; finally Inc(i); end; end; finally //将盘口资料写到资料库 ml_odds.Load; Document:=nil; Inc(GameStartIndex); //下一笔仍存范围内,载入下场赛事盘口资料页面 if GameStartIndex <= GameEndIndex then begin chrm1.Load(GameList[GameStartIndex].OddsURL); end //已执行完所有范围内的赛事,回到首页 else begin chrm1.Load(TG777_URL); end; end; end end; procedure TForm1.getIsNeedLogin(const str:ustring); var Document:IHTMLDocument2; Body:IHTMLElement2; Tags:IHTMLElementCollection; Tag:IHTMLElement; i:integer; v:Variant; begin Document:=CreateComObject(Class_HTMLDOcument) as IHTMLDocument2; GameList.Clear; //检查登入按钮是否存在 try Document.designMode:='on'; while Document.readyState <> 'complete' do Application.ProcessMessages; v:=VarArrayCreate([0, 0], varVariant); v[0]:=str; Document.write(PSafeArray(TVarData(v).VArray)); Document.designMode:='off'; while Document.readyState <> 'complete' do Application.ProcessMessages; Body:=Document.body as IHTMLElement2; Tags:=Body.getElementsByTagName('button'); IsNeedLogin:=False; for i:=0 to Pred(Tags.length) do begin Tag := Tags.item(i, EmptyParam) as IHTMLElement; if AnsiSameText(Trim(Tag.innerText), '登入') then begin IsNeedLogin:=True; end; end; finally Document:=nil; end; end; procedure TForm1.setGameData(innerText:string; var game:TGame); var sl,sl2:TStringList; begin sl:=TStringList.Create; sl2:=TStringList.Create; try sl.StrictDelimiter:=True; sl.Delimiter:=#13; sl.DelimitedText:=innerText; if sl.Count = 2 then begin //第一行 sl2.StrictDelimiter:=True; sl2.Delimiter:=' '; sl2.DelimitedText:=Trim(sl[0]); game.GameDateTime:=Trim(sl2[0])+' '+Trim(sl2[1]); game.LeagueName:=Trim(sl2[3]); //第二行 sl2.StrictDelimiter:=True; sl2.Delimiter:=' '; sl2.DelimitedText:=Trim(sl[1]); game.GameName:=Trim(sl[1]); game.HomeTeam:=Trim(sl2[0]); game.VisitTeam:=Trim(sl2[2]); end; finally sl.Destroy; sl2.Destroy; end; end; procedure TForm1.tmr_autorunTimer(Sender: TObject); var myTime:TDateTime; begin //倒数时间未到 if lbl_countdown.Caption <> '00:00:00' then begin myTime:=StrToTime(lbl_countdown.Caption); myTime:=IncSecond(myTime, -1); end //倒数时间已到 else begin btn_run.Click; myTime:=StrToTime(lbl_countdown.Caption); myTime:=IncSecond(myTime, se_update_interval.Value); end; lbl_countdown.Caption:=FormatDateTime('hh:nn:ss',myTime); lbl_countdown.Refresh; end; function TForm1.getOddsURL(innerHTML:WideString):string; var tempstring:WideString; a2,a1,a,c,d,f,h:WideString; sl:TStringList; begin try sl:=TStringList.Create; tempstring:=Copy(innerHTML, Pos('(' , innerHTML) + 1, Pos(')', innerHTML) - Pos('(', innerHTML) - 1); sl.StrictDelimiter:=True; sl.Delimiter:=','; sl.DelimitedText:=tempstring; a2:='mid='+sl[0]; a1:='name='+sl[1]; a:='gameid='+sl[2]; c:=sl[3]; d:='gc12='+sl[4]; f:='gamename='+sl[5]; h:='time='+sl[6]; tempstring:=TG777_URL+'controler/newopen.php?'+a2+'&'+a1+'&'+a+'&'+d+'&'+f+'&'+h; finally sl.Destroy; end; Result:=tempstring; end; function TForm1.getPRData(innerText:WideString):string; begin if Trim(innerText) <> '' then begin Result:=StringReplace(Trim(innerText), '%', '', [rfReplaceAll, rfIgnoreCase]); end else begin Result:=''; end; end; function TForm1.getStockData(innerText:WideString):string; begin if Trim(innerText) <> '' then begin Result:=StringReplace(Trim(innerText), '¥', '', [rfReplaceAll, rfIgnoreCase]); end else begin Result:=''; end; end; procedure TForm1.ml_gamesPutData(Sender: TDALoader); var sql:string; begin writeMessage('=============================================================================================='); writeMessage('赛事('+IntToStr(GameStartIndex+1)+'/'+IntToStr(GameList.Count)+') '+GameList[GameStartIndex].GameYear+' '+GameList[GameStartIndex].GameDateTime+' '+GameList[GameStartIndex].LeagueName+' '+GameList[GameStartIndex].GameName+'('+GameList[GameStartIndex].GameID+')'); writeMessage('=============================================================================================='); sql:='SELECT 1 FROM Games WHERE GameID = "'+GameList[GameStartIndex].GameID+'" '; qry_temp.Active:=False; qry_temp.SQL.Clear; qry_temp.SQL.Add(sql); qry_temp.Active:=True; if qry_temp.RecordCount = 0 then begin ml_games.PutColumnData('GameID', 1, GameList[GameStartIndex].GameID); ml_games.PutColumnData('GameYear', 1, GameList[GameStartIndex].GameYear); ml_games.PutColumnData('GameDateTime', 1, GameList[GameStartIndex].GameDateTime); ml_games.PutColumnData('GameName', 1, GameList[GameStartIndex].GameName); ml_games.PutColumnData('LeagueName', 1, GameList[GameStartIndex].LeagueName); ml_games.PutColumnData('HomeTeam', 1, GameList[GameStartIndex].HomeTeam); ml_games.PutColumnData('VisitTeam', 1, GameList[GameStartIndex].VisitTeam); writeMessage('新增赛事资料成功 !'); end end; procedure TForm1.ml_oddsPutData(Sender: TDALoader); var sql:string; i:Integer; newPR:string; begin for i:=0 to OddsList.Count -1 do begin sql:='SELECT PR,IsAutoUpdate FROM Odds WHERE GameID = "'+OddsList[i].GameID+'" AND OddsType = "'+OddsList[i].OddsType+'" AND OddsOption = "'+OddsList[i].OddsOption+'"'; qry_temp.Active:=False; qry_temp.SQL.Clear; qry_temp.SQL.Add(sql); qry_temp.Active:=True; //不存在资料库,新增 if (qry_temp.RecordCount = 0) then begin ml_odds.PutColumnData('GameID', i+1, OddsList[i].GameID); ml_odds.PutColumnData('OddsType', i+1, OddsList[i].OddsType); ml_odds.PutColumnData('OddsOption', i+1, OddsList[i].OddsOption); if OddsList[i].PR <> '' then ml_odds.PutColumnData('PR', i+1, OddsList[i].PR) else ml_odds.PutColumnData('PR', i+1, 'NULL'); if OddsList[i].Quota <> '' then ml_odds.PutColumnData('Quota', i+1, OddsList[i].Quota) else ml_odds.PutColumnData('Quota', i+1, 'NULL'); writeMessage(OddsList[i].OddsType+' '+OddsList[i].OddsOption+' '+OddsList[i].PR+' '+OddsList[i].Quota+' 新增盘口资料成功 !'); end //有存在资料库、获利不同且设定为自动更新 else if (qry_temp.RecordCount = 1) and (ConvertToFloat(qry_temp.FieldByName('PR').AsString) <> ConvertToFloat(OddsList[i].PR)) and (qry_temp.FieldByName('IsAutoUpdate').AsInteger = 1) then begin newPR:=qry_temp.FieldByName('PR').AsString; if OddsList[i].PR = '' then sql:='UPDATE Odds SET PR = NULL, UpdateDate = "'+FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz',Now)+'" WHERE GameID = "'+OddsList[i].GameID+'" AND OddsType = "'+OddsList[i].OddsType+'" AND OddsOption = "'+OddsList[i].OddsOption+'"' else sql:='UPDATE Odds SET PR = '+OddsList[i].PR+', UpdateDate = "'+FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz',Now)+'" WHERE GameID = "'+OddsList[i].GameID+'" AND OddsType = "'+OddsList[i].OddsType+'" AND OddsOption = "'+OddsList[i].OddsOption+'"'; qry_temp.Active:=False; qry_temp.SQL.Clear; qry_temp.SQL.Add(sql); qry_temp.Execute; writeMessage(OddsList[i].OddsType+' '+OddsList[i].OddsOption+' ('+newPR+' => '+OddsList[i].PR+') 更新盘口资料成功 !'); end; end; end; procedure TForm1.setOddsOption(OddsType:string); var sql:string; begin OddsType:=UpperCase(Trim(OddsType)); sql:='SELECT * FROM OddsOption WHERE OddsType = "'+OddsType+'"'; qry_temp.Active:=False; qry_temp.SQL.Clear; qry_temp.SQL.Add(sql); qry_temp.Active:=True; while not qry_temp.Eof do begin if (OddsType = 'CS') then CS_OddsOption.Add(qry_temp.FieldByName('OddsOption').AsString, qry_temp.FieldByName('DefaultQuota').AsInteger) else if (OddsType = 'CSFF') then CSFF_OddsOption.Add(qry_temp.FieldByName('OddsOption').AsString, qry_temp.FieldByName('DefaultQuota').AsInteger) else if (OddsType = 'TS') then TS_OddsOption.Add(qry_temp.FieldByName('OddsOption').AsString, qry_temp.FieldByName('DefaultQuota').AsInteger) else if (OddsType = 'FGT') then FGT_OddsOption.Add(qry_temp.FieldByName('OddsOption').AsString, qry_temp.FieldByName('DefaultQuota').AsInteger); qry_temp.Next; end; end; function TForm1.getDefaultQuota(OddsType:string; OddsOption:string):Integer; var DefaultQuota:Integer; begin OddsType:=UpperCase(Trim(OddsType)); OddsOption:=Trim(OddsOption); if OddsType = 'CS' then begin if (CS_OddsOption.TryGetValue(OddsOption, DefaultQuota) = True) then Result:=DefaultQuota else Result:=0; end else if OddsType = 'CSFF' then begin if (CSFF_OddsOption.TryGetValue(OddsOption, DefaultQuota) = True) then Result:=DefaultQuota else Result:=0; end else if OddsType = 'TS' then begin if (TS_OddsOption.TryGetValue(OddsOption, DefaultQuota) = True) then Result:=DefaultQuota else Result:=0; end else if OddsType = 'FGT' then begin if (FGT_OddsOption.TryGetValue(OddsOption, DefaultQuota) = True) then Result:=DefaultQuota else Result:=0; end else begin Result:=0; end; end; function TForm1.ConvertToFloat(str:string):Real; begin if (str = '') or (str = Null) then Result:=0 else Result:=StrToFloat(str); end; end.
namespace Sugar.Test; interface uses Sugar, RemObjects.Elements.EUnit; type StringBuilderTest = public class (Test) private Builder: StringBuilder; public method Setup; override; method Append; method AppendRange; method AppendChar; method AppendLine; method Clear; method Delete; method Replace; method Substring; method SubstringRange; method Insert; method Length; method Chars; method Constructors; end; implementation method StringBuilderTest.Setup; begin Builder := new StringBuilder; end; method StringBuilderTest.Append; begin Assert.IsNotNil(Builder.Append("Hello")); Assert.AreEqual(Builder.ToString, "Hello"); var Value := Builder.Append(" "); Assert.IsNotNil(Value); Assert.AreEqual(Value.ToString, "Hello "); Assert.AreEqual(Builder.Append("").ToString, "Hello "); end; method StringBuilderTest.AppendRange; begin Assert.IsNotNil(Builder.Append("Hello", 1, 2)); Assert.AreEqual(Builder.ToString, "el"); var Value := Builder.Append("Hello", 0, 1); Assert.IsNotNil(Value); Assert.AreEqual(Value.ToString, "elH"); Assert.AreEqual(Builder.Append("", 0, 0).ToString, "elH"); //no changes Assert.AreEqual(Builder.Append("qwerty", 1, 0).ToString, "elH"); //count = 0, no changes Assert.AreEqual(Builder.Append(nil, 0, 0).ToString, "elH"); //count = 0 and index = 0, no changes end; method StringBuilderTest.AppendChar; begin Assert.IsNotNil(Builder.Append('q', 3)); Assert.AreEqual(Builder.ToString, "qqq"); var Value := Builder.Append('x', 2); Assert.IsNotNil(Value); Assert.AreEqual(Value.ToString, "qqqxx"); Assert.Throws(->Builder.Append('z', -1).ToString); end; method StringBuilderTest.AppendLine; begin var NL := Sugar.Environment.NewLine; Assert.IsNotNil(Builder.AppendLine("Hello")); Assert.AreEqual(Builder.ToString, "Hello"+NL); Assert.IsNotNil(Builder.AppendLine); Assert.AreEqual(Builder.ToString, "Hello"+NL+NL); end; method StringBuilderTest.Clear; begin Assert.IsNotNil(Builder.Append("Hello")); Assert.AreEqual(Builder.ToString, "Hello"); Builder.Clear; Assert.AreEqual(Builder.Length, 0); Assert.AreEqual(Builder.ToString, ""); end; method StringBuilderTest.Delete; begin Assert.IsNotNil(Builder.Append("Hello")); Assert.AreEqual(Builder.ToString, "Hello"); Assert.IsNotNil(Builder.Delete(1, 3)); Assert.AreEqual(Builder.ToString, "Ho"); Assert.AreEqual(Builder.Delete(1, 0).ToString, "Ho"); Assert.Throws(->Builder.Delete(-1, 1)); Assert.Throws(->Builder.Delete(1, -1)); Assert.Throws(->Builder.Delete(50, 1)); Assert.Throws(->Builder.Delete(1, 50)); end; method StringBuilderTest.Replace; begin Assert.IsNotNil(Builder.Append("Hello")); Assert.AreEqual(Builder.ToString, "Hello"); Assert.IsNotNil(Builder.Replace(2, 2, "xx")); Assert.AreEqual(Builder.ToString, "Hexxo"); Assert.Throws(->Builder.Replace(1, 1, nil)); Assert.Throws(->Builder.Replace(-1, 1, "q")); Assert.Throws(->Builder.Replace(1, -1, "q")); Assert.Throws(->Builder.Replace(50, 1, "q")); Assert.Throws(->Builder.Replace(0, 50, "q")); end; method StringBuilderTest.Substring; begin Assert.IsNotNil(Builder.Append("Hello")); Assert.AreEqual(Builder.ToString, "Hello"); var Value := Builder.Substring(3); Assert.IsNotNil(Value); Assert.AreEqual(Value, "lo"); Assert.AreEqual(Builder.Substring(Builder.Length), ""); Assert.AreEqual(Builder.Substring(0), Builder.ToString); Assert.Throws(->Builder.Substring(-1)); Assert.Throws(->Builder.Substring(Builder.Length + 1)); end; method StringBuilderTest.SubstringRange; begin Assert.IsNotNil(Builder.Append("Hello")); Assert.AreEqual(Builder.ToString, "Hello"); var Value := Builder.Substring(2, 3); Assert.IsNotNil(Value); Assert.AreEqual(Value, "llo"); Assert.AreEqual(Builder.Substring(4, 1), "o"); Assert.AreEqual(Builder.Substring(0, Builder.Length), Builder.ToString); Assert.Throws(->Builder.Substring(-1, 1)); Assert.Throws(->Builder.Substring(1, -1)); Assert.Throws(->Builder.Substring(0, 50)); Assert.Throws(->Builder.Substring(50, 0)); end; method StringBuilderTest.Insert; begin Assert.IsNotNil(Builder.Append("Hlo")); Assert.AreEqual(Builder.ToString, "Hlo"); Assert.IsNotNil(Builder.Insert(1, "el")); Assert.AreEqual(Builder.ToString, "Hello"); Assert.AreEqual(Builder.Insert(2, "").ToString, "Hello"); Assert.AreEqual(Builder.Insert(0, "z").ToString, "zHello"); Assert.AreEqual(Builder.Insert(Builder.Length, "z").ToString, "zHelloz"); Assert.Throws(->Builder.Insert(0, nil)); Assert.Throws(->Builder.Insert(-1, "x")); Assert.Throws(->Builder.Insert(25, "x")); Assert.Throws(->Builder.Insert(25, "")); end; method StringBuilderTest.Length; begin Assert.AreEqual(Builder.Length, 0); Assert.IsNotNil(Builder.Append("Hello")); Assert.AreEqual(Builder.ToString, "Hello"); Assert.AreEqual(Builder.Length, 5); Builder.Length := 3; Assert.AreEqual(Builder.Length, 3); Assert.AreEqual(Builder.ToString, "Hel"); Builder.Length := 0; Assert.AreEqual(Builder.Length, 0); Assert.AreEqual(Builder.ToString, ""); //extending length Assert.IsNotNil(Builder.Append("Hello")); Builder.Length := 10; Assert.AreEqual(Builder.Length, 10); Assert.AreEqual(Builder.Chars[6], #0); Assert.AreEqual(Builder.ToString, "Hello"+#0#0#0#0#0); Assert.Throws(->begin Builder.Length := -1 end); end; method StringBuilderTest.Chars; begin var Value: array of Char := ['H', 'e', 'l', 'l', 'o']; Assert.IsNotNil(Builder.Append("Hello")); Assert.AreEqual(Builder.ToString, "Hello"); Assert.AreEqual(Builder.Length, 5); for i: Integer := 0 to Builder.Length - 1 do Assert.AreEqual(Builder.Chars[i], Value[i]); Builder.Length := 10; Assert.AreEqual(Builder.Chars[6], #0); Assert.Throws(->Builder.Chars[-1]); Assert.Throws(->Builder.Chars[50]); end; method StringBuilderTest.Constructors; begin Builder := new StringBuilder("Hello"); Assert.AreEqual(Builder.Length, 5); Assert.AreEqual(Builder.ToString, "Hello"); Builder := new StringBuilder(3); Assert.AreEqual(Builder.Length, 0); Builder.Append("Hello"); Assert.AreEqual(Builder.Length, 5); Assert.AreEqual(Builder.ToString, "Hello"); end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, LMessages; type { TMyPanel } TMyPanel = class(TPanel) private FMouseDown: boolean; FMouseDownPnt: TPoint; procedure UpdateCursor(AShift: TShiftState); public constructor Create(TheOwner: TComponent); override; 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 MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure DragOver(Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); override; procedure MouseEnter; override; procedure MouseLeave; override; end; type { TForm1 } TForm1 = class(TForm) PanelMain1: TPanel; PanelMain2: TPanel; procedure FormCreate(Sender: TObject); procedure PanelMain1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); private FPanel, FPanel2: TMyPanel; public end; var Form1: TForm1; implementation uses LCLIntf, LCLProc, LCLType; {$R *.lfm} { TMyPanel } procedure TMyPanel.UpdateCursor(AShift: TShiftState); //var //P: TPoint; begin //P:= ScreenToClient(Mouse.CursorPos); //if not PtInRect(ClientRect, P) then exit; if Mouse.IsDragging then begin if ssCtrl in AShift then DragCursor:= crMultiDrag else DragCursor:= crDrag; Cursor:= DragCursor; end else Cursor:= crIBeam; end; constructor TMyPanel.Create(TheOwner: TComponent); begin inherited Create(TheOwner); FMouseDownPnt:= Point(-1, -1); Cursor:= crIBeam; DragMode:= dmManual; //to emulate code in ATSynEdit end; procedure TMyPanel.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; if (Key=VK_CONTROL) then begin UpdateCursor(Shift); Key:= 0; end; end; procedure TMyPanel.KeyUp(var Key: Word; Shift: TShiftState); begin inherited; if Mouse.IsDragging then EndDrag(true); if (Key=VK_CONTROL) then begin UpdateCursor(Shift); Key:= 0; end; end; procedure TMyPanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); FMouseDownPnt:= Point(X, Y); FMouseDown:= true; end; procedure TMyPanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); FMouseDownPnt:= Point(-1, -1); FMouseDown:= false; UpdateCursor(Shift); end; procedure TMyPanel.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited MouseMove(Shift, X, Y); if FMouseDown then begin if Abs(X-FMouseDownPnt.X) + Abs(Y-FMouseDownPnt.Y)>=6 then if not Mouse.IsDragging then BeginDrag(true); UpdateCursor(Shift); end; end; procedure TMyPanel.DragOver(Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin if Source is TMyPanel then Accept:= true else inherited DragOver(Source, X, Y, State, Accept); end; procedure TMyPanel.MouseEnter; begin inherited; Caption:= 'Mouse entered'; end; procedure TMyPanel.MouseLeave; begin inherited MouseLeave; Caption:= ''; end; { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin FPanel:= TMyPanel.Create(Self); FPanel.Parent:= PanelMain1; FPanel.Color:= clMoneyGreen; FPanel.BorderSpacing.Around:= 12; FPanel.Align:= alClient; FPanel.Width:= 200; FPanel.Show; FPanel2:= TMyPanel.Create(Self); FPanel2.Parent:= PanelMain2; FPanel2.Color:= clSkyBlue; FPanel2.BorderSpacing.Around:= 12; FPanel2.Align:= alClient; FPanel2.Show; end; procedure TForm1.PanelMain1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept:= false; end; end.
{ ********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ******************************************************************** } unit FGX.Toasts.Android; interface uses FGX.Toasts, AndroidApi.JNI.Toasts, AndroidApi.JNI.GraphicsContentViewText, AndroidApi.JNI.Widget, System.UITypes; type { TfgAndroidToast } TfgAndroidToast = class(TfgToast) private FToast: JToast; FBackgroundView: JView; FIconView: JImageView; FMessageView: JTextView; protected { inherited } procedure DoBackgroundColorChanged; override; procedure DoDurationChanged; override; procedure DoMessageChanged; override; procedure DoMessageColorChanged; override; procedure DoIconChanged; override; { Creating custom view and preparing data for Toast } function CreateBitmapIcon: JBitmap; function CreateBackgroundImage: JBitmap; procedure CreateCustomView; procedure RemoveCustomView; public constructor Create(const AMessage: string; const ADuration: TfgToastDuration); destructor Destroy; override; property Toast: JToast read FToast; end; { TfgAndroidToastService } TfgAndroidToastService = class(TInterfacedObject, IFGXToastService) public { IFGXToastService } function CreateToast(const AMessage: string; const ADuration: TfgToastDuration): TfgToast; procedure Show(const AToast: TfgToast); procedure Cancel(const AToast: TfgToast); end; TfgToastDurationHelper = record helper for TfgToastDuration public function ToJDuration: Integer; end; procedure RegisterService; procedure UnregisterService; implementation uses System.SysUtils, System.Types, System.IOUtils, Androidapi.Helpers, Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, FMX.Platform, FMX.Helpers.Android, FMX.Graphics, FMX.Surfaces, FMX.Types, FGX.Helpers.Android, FGX.Graphics, FGX.Asserts; procedure RegisterService; begin TPlatformServices.Current.AddPlatformService(IFGXToastService, TfgAndroidToastService.Create); end; procedure UnregisterService; begin TPlatformServices.Current.RemovePlatformService(IFGXToastService); end; { TfgAndroidToast } constructor TfgAndroidToast.Create(const AMessage: string; const ADuration: TfgToastDuration); begin Assert(AMessage <> ''); inherited Create; CallInUIThreadAndWaitFinishing(procedure begin FToast := TJToast.JavaClass.makeText(TAndroidHelper.Context, StrToJCharSequence(AMessage), ADuration.ToJDuration); end); Message := AMessage; Duration := ADuration; end; function TfgAndroidToast.CreateBackgroundImage: JBitmap; var Bitmap: TBitmap; begin Bitmap := Create9PatchShadow(TSizeF.Create(100, 20), BackgroundColor); try Result := BitmapToJBitmap(Bitmap) finally Bitmap.Free; end; end; procedure TfgAndroidToast.CreateCustomView; const CENTER_VERTICAL = 16; IMAGE_MARGIN_RIGHT = 10; var Layout: JLinearLayout; DestBitmap: JBitmap; Params : JViewGroup_LayoutParams; begin RemoveCustomView; { Background } Layout := TJLinearLayout.JavaClass.init(TAndroidHelper.Context); Layout.setOrientation(TJLinearLayout.JavaClass.HORIZONTAL); Layout.setPadding(Round(TfgToast.DefaultPadding.Left), Round(TfgToast.DefaultPadding.Top), Round(TfgToast.DefaultPadding.Right), Round(TfgToast.DefaultPadding.Bottom)); Layout.setGravity(CENTER_VERTICAL); Layout.setBackgroundColor(AlphaColorToJColor(TfgToast.DefaultBackgroundColor)); Params := TJViewGroup_LayoutParams.JavaClass.init(TJViewGroup_LayoutParams.JavaClass.WRAP_CONTENT, TJViewGroup_LayoutParams.JavaClass.WRAP_CONTENT); Layout.setLayoutParams(Params); FBackgroundView := Layout; { Image } DestBitmap := CreateBitmapIcon; if DestBitmap <> nil then begin FIconView := TJImageView.JavaClass.init(TAndroidHelper.Context); FIconView.setImageBitmap(DestBitmap); FIconView.setPadding(0, 0, IMAGE_MARGIN_RIGHT, 0); Params := TJViewGroup_LayoutParams.JavaClass.init(TJViewGroup_LayoutParams.JavaClass.WRAP_CONTENT, TJViewGroup_LayoutParams.JavaClass.WRAP_CONTENT); FIconView.setLayoutParams(Params); Layout.addView(FIconView, Params); end; { Message } FMessageView := TJTextView.JavaClass.init(TAndroidHelper.Context); FMessageView.setText(StrToJCharSequence(Message)); FMessageView.setTextColor(AlphaColorToJColor(MessageColor)); Params := TJViewGroup_LayoutParams.JavaClass.init(TJViewGroup_LayoutParams.JavaClass.WRAP_CONTENT, TJViewGroup_LayoutParams.JavaClass.WRAP_CONTENT); FMessageView.setLayoutParams(Params); Layout.addView(FMessageView); FToast.setView(Layout); end; function TfgAndroidToast.CreateBitmapIcon: JBitmap; begin if HasIcon then Result := BitmapToJBitmap(Icon) else Result := nil; end; destructor TfgAndroidToast.Destroy; begin FToast := nil; inherited; end; procedure TfgAndroidToast.DoBackgroundColorChanged; begin inherited; if FBackgroundView <> nil then FBackgroundView.setBackgroundColor(AlphaColorToJColor(BackgroundColor)) else Toast.getView.setBackgroundColor(AlphaColorToJColor(BackgroundColor)); end; procedure TfgAndroidToast.DoDurationChanged; begin AssertIsNotNil(FToast); inherited; CallInUIThreadAndWaitFinishing(procedure begin FToast.setDuration(Duration.ToJDuration); end); end; procedure TfgAndroidToast.DoIconChanged; begin AssertIsNotNil(Icon); AssertIsNotNil(Toast); inherited; if HasIcon then begin if FIconView = nil then CreateCustomView else FIconView.setImageBitmap(CreateBitmapIcon); end else RemoveCustomView; end; procedure TfgAndroidToast.DoMessageChanged; begin AssertIsNotNil(FToast); inherited; CallInUIThreadAndWaitFinishing(procedure begin FToast.setText(StrToJCharSequence(Message)); if FMessageView <> nil then FMessageView.setText(StrToJCharSequence(Message)); end); end; procedure TfgAndroidToast.DoMessageColorChanged; const TJR_idmessage = 16908299; var LMessageView: JView; TextView: JTextView; begin inherited; if FMessageView <> nil then FMessageView.setTextColor(AlphaColorToJColor(MessageColor)) else begin LMessageView := Toast.getView.findViewById(TJR_idmessage); if LMessageView <> nil then begin TextView := TJTextView.Wrap((LMessageView as ILocalObject).GetObjectID); TextView.setTextColor(AlphaColorToJColor(MessageColor)); end; end; end; procedure TfgAndroidToast.RemoveCustomView; begin Toast.setView(nil); FBackgroundView := nil; FIconView := nil; FMessageView := nil; end; { TfgAndroidToastService } procedure TfgAndroidToastService.Cancel(const AToast: TfgToast); begin AssertIsNotNil(AToast); AssertIsClass(AToast, TfgAndroidToast); CallInUIThreadAndWaitFinishing(procedure begin TfgAndroidToast(AToast).Toast.cancel; end); end; function TfgAndroidToastService.CreateToast(const AMessage: string; const ADuration: TfgToastDuration): TfgToast; begin Result := TfgAndroidToast.Create(AMessage, ADuration); end; procedure TfgAndroidToastService.Show(const AToast: TfgToast); begin AssertIsNotNil(AToast); AssertIsClass(AToast, TfgAndroidToast); CallInUIThreadAndWaitFinishing(procedure begin TfgAndroidToast(AToast).Toast.show; end); end; { TfgToastDurationHelper } function TfgToastDurationHelper.ToJDuration: Integer; begin case Self of TfgToastDuration.Short: Result := TJToast.JavaClass.LENGTH_SHORT; TfgToastDuration.Long: Result := TJToast.JavaClass.LENGTH_LONG; else raise Exception.Create('Unknown value of [FGX.Toasts.TfgToastDuration])'); end; end; end.
unit PatchMemory; Interface uses Windows, ImageHlp, SysUtils; var BasePointer: pointer; type TPatchMemory = Class DllNameToPatch: String; //Имя DLL, в секции импорта которой будем производить изменения DllNameToFind: String; //Имя DLL, функцию которой мы хотим перехватить (например, 'KERNEL32.dll') FuncNameToFind: String; //Функция, которую мы хотим перехватить (например, 'CreateProcessA') NewFunctionAddr: Pointer; //Адрес функции - заменителя OldFunctionAddr: Pointer; //Старый адрес замещенной функции procedure Patch; //Выполняет замену стандартной функции на нашу procedure UnPatch; //Отменяет патчинг Constructor Create; Destructor Destroy; Override; private AddrWherePatching: Pointer; //Для UnPatch function GetDwordByRVA(rva: dword):dword; function GetStringByRVA(rva: dword):pchar; function GetPointerByRVA(rva: DWORD):Pointer; function GetRVAByPointer(P: Pointer):DWORD; procedure WriteDwordToMemory(Kuda: Pointer; Data: DWORD); end; ////////////////////////////////////////////////////////// implementation ////////////////////////////////////////////////////////// procedure say(s:String); //Отладочная печать begin // MessageBox(0,pchar(s),'',0); end; ////////////////////////////////////////////////////////////// Constructor TPatchMemory.Create; begin inherited Create; end; ////////////////////////////////////////////////////////////// destructor TPatchMemory.Destroy; begin say('Destroy'); inherited Destroy; end; ////////////////////////////////////////////////// function TPatchMemory.GetDwordByRVA(rva: dword):dword; //Получает значение (4 байтовое целое без знака - DWORD) из памяти по //смещению (RVA) begin asm push ebx; mov ebx, [rva]; add ebx, [BasePointer]; mov eax, [ebx]; mov Result, eax; pop ebx; end; end; ////////////////////////////////////////////////// function TPatchMemory.GetStringByRVA(rva: dword):pchar; //Получает строку по указателю RVA begin asm mov eax, [rva]; add eax, [BasePointer]; mov Result, eax; end; end; ////////////////////////////////////////////////// function TPatchMemory.GetPointerByRVA(rva: DWORD):Pointer; //Получает указатель из RVA (т.е. прибавляет к rva значение BasePointer) begin asm mov eax, rva; add eax, [BasePointer]; mov Result, eax; end; end; ////////////////////////////////////////////////// function TPatchMemory.GetRVAByPointer(P: Pointer):DWORD; //Получает указатель RVA из указателя //(т.е. вычитает из указателя значение BasePointer) begin asm mov eax, [p]; sub eax, BasePointer; mov Result, eax; end; end; ////////////////////////////////////////////////// Procedure TPatchMemory.WriteDwordToMemory( //Пишем 4 байта в память по указателю. Kuda: Pointer; //Адрес куда пишем Data: DWORD //Значение которое пишем ); var BytesWritten: DWORD; var hProcess: THandle; var old: DWORD; begin hProcess := GetCurrentProcess(//Функция WinAPI ); //Разрешаем доступ на запись по указанному адресу VirtualProtect(//Функция WinAPI kuda, //адрес 4, //число байт (будут затронуты 1 или 2 страницы памяти размером 4К) PAGE_EXECUTE_READWRITE, //атрибуты доступа @old); //сюда будут возвращены старые атрибуты BytesWritten:=0; //Записываем 4 байта WriteProcessMemory(//Функция WinAPI hProcess, kuda, @data, 4, BytesWritten); //Восстанавливаем прежние атрибуты доступа VirtualProtect(//Функция WinAPI kuda, 4, old, @old); end; ////////////////////////////////////////////////////////// procedure TPatchMemory.Patch; var ulSize: ULONG; var rva: DWORD; var ImportTableOffset: pointer; var OffsetDllName: DWORD; var OffsetFuncAddrs: DWORD; var FunctionAddr: DWORD; var DllName: String; var FuncAddrToFind: DWORD; begin //В Windows 2000 DLL в этот момент, возможно, еще не загружена if DWORD(GetModuleHandle(pchar(DllNameToPatch)))=0 then begin LoadLibrary(pchar(DllNameToPatch)); end; //Получаем адрес функции, который мы хотим найти в таблице IAT FuncAddrToFind:= DWORD( GetProcAddress(//Функция Windows API GetModuleHandle(//Функция Windows API pchar(DllNameToFind) ), pchar(FuncNameToFind) )); say(DllNameToFind+' '+FuncNameToFind); say('FuncAddrToFind: '+IntToHex(FuncAddrToFind,8)); OldFunctionAddr:=Pointer(FuncAddrToFind); //Получаем адрес, по которому расположена в памяти dll - "жертва". BasePointer:=pointer(GetModuleHandle(//Функция Windows API pChar(DllNameToPatch))); //Получаем смещение таблицы импорта ImportTableOffset:= ImageDirectoryEntryToData( //Функция Windows API BasePointer, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, ulSize); //Переводим смещение таблицы импорта в формат RVA //(смещение относительно начала DLL) rva:=GetRvaByPointer(ImportTableOffset); repeat {Проходим по таблице импорта. Каждая запись в таблице импорта имеет длину 20 байт: +0 - указатель на таблицу имен функций (для Borland ее нет) +4 - ? +8 - ? +12 - Указатель (RVA) на имя DLL +16 - указатель на таблицу адресов функций } OffsetDllName := GetDwordByRVA(rva+12); if OffsetDllName = 0 then break; //Если таблица кончилась, выходим DllName := GetStringByRVA(OffsetDllName);//Имя DLL OffsetFuncAddrs:=GetDwordByRva(rva+16); repeat //Цикл по списку функций DLL FunctionAddr:=Dword(GetDwordByRva(OffsetFuncAddrs)); if FunctionAddr=0 then break; //Если функции закончились, выходим if FunctionAddr=FuncAddrToFind then begin //Нашли - выполняем патч AddrWherePatching:=GetPointerByRva(OffsetFuncAddrs); WriteDwordToMemory( AddrWherePatching, DWORD(NewFunctionAddr)); //say('AddrWherePatching: '+IntToHex(Dword(AddrWherePatching),8)); end; inc(OffsetFuncAddrs,4); until false; rva:=rva+20; until false; end; ////////////////////////////////////////////////////////// procedure TPatchMemory.UnPatch; begin say('AddrWherePatching: '+IntToHex(Dword(AddrWherePatching),8)); say('OldFunctionAddr: '+IntToHex(Dword(OldFunctionAddr),8)); WriteDwordToMemory( AddrWherePatching, DWORD(OldFunctionAddr)); end; end.
unit SensorFrame; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, IniFiles, Misc, ExtCtrls, SyncObjs, ConversionForm, SensorTypes; type TFrameSensor = class(TFrame) Panel1: TPanel; cbOn: TCheckBox; stCount: TStaticText; Label4: TLabel; stResult: TStaticText; stX: TStaticText; edQueryCmd: TEdit; Label1: TLabel; Label2: TLabel; edPeriod: TEdit; Label3: TLabel; BtnConversion: TButton; procedure cbOnClick(Sender: TObject); procedure BtnConversionClick(Sender: TObject); private { Private declarations } Section:String; procedure CalcCoeffs; public { Public declarations } CS:TCriticalSection; AdrList:TList; BusNumber:Integer; NetNumber:Integer; Period:Integer; // ADC & conversion parameters VoltageMode:Boolean; ADCRange:Integer; PhysScale,VoltsScale:Double; Ia,Ib,R:Double; Ua,Ub:Double; Xm,Xa,Xb:Double; CoeffK,CoeffB:Double; // Error flags IsErrADCComm:Boolean; IsErrADCRange:Boolean; IsErrAnalog:Boolean; X:Single; ShowSumX:Double; ShowQueryCnt,ShowResponseCnt,ShowMeasureCnt:Integer; isSensorOn:Boolean; QueryCmd:String; MeasureCnt:Integer; SumX:Double; CounterPoll:Integer; PrevSampleNum:Cardinal; ReadyForOutput:Boolean; ValidConfig:Boolean; NotFirstSample:Boolean; constructor Create(AOwner:TComponent);override; procedure LoadFromIniSection(Ini:TIniFile; const Section:String); procedure WriteToIni(Ini:TIniFile); function Validate:Boolean; procedure TimerProc(const fSampleNum:Double); // procedure TimerShow; procedure ShowInfo; destructor Destroy;override; end; TAddress=class(TObject) Host:String; Port:Integer; constructor Create(const Host:String; Port:Integer); end; implementation {$R *.DFM} //uses Main; function fmt(X:Double):String; begin Result:=Format('%.5f',[X]); if Result[1]<>'-' then Result:=' '+Result; if Length(Result)>8 then SetLength(Result,8); end; { TFrameSensor } destructor TFrameSensor.Destroy; var i:Integer; begin if AdrList<>nil then begin for i:=0 to AdrList.Count-1 do TObject(AdrList[i]).Free; AdrList.Free; end; CS.Free; inherited; end; procedure TFrameSensor.LoadFromIniSection(Ini: TIniFile; const Section: String); var i,Cnt:Integer; begin AdrList:=TList.Create; Self.Section:=Section; isSensorOn:=Ini.ReadInteger(Section,'On',1)<>0; NetNumber:=Ini.ReadInteger(Section,'NetNumber',0); cbOn.Checked:=isSensorOn; cbOn.Caption:='№'+IntToStr(NetNumber)+' вкл.'; edQueryCmd.Text:=Ini.ReadString(Section,'QueryCmd','#010'); edPeriod.Text:=Ini.ReadString(Section,'Period','1'); // ADC & conversion parameters VoltageMode:=Ini.ReadInteger(Section,'VoltageMode',0)<>0; ADCRange:=Ini.ReadInteger(Section,'ADCRange',9); if VoltageMode then begin Ua:=Ini.ReadFloat(Section,'Ua',0.0); Ub:=Ini.ReadFloat(Section,'Ub',2.5); end else begin Ia:=Ini.ReadFloat(Section,'Ia',0.004); Ib:=Ini.ReadFloat(Section,'Ib',0.020); R:=Ini.ReadFloat(Section,'R',125); Ua:=Ia*R; Ub:=Ib*R; end; Xm:=Ini.ReadFloat(Section,'Xm',0); Xa:=Ini.ReadFloat(Section,'Xa',0); Xb:=Ini.ReadFloat(Section,'Xb',60); CalcCoeffs; // Cnt:=Ini.ReadInteger(Section,'DataCopies',0); for i:=1 to Cnt do begin AdrList.Add(TAddress.Create( Ini.ReadString(Section,'Host'+IntToStr(i),''), Ini.ReadInteger(Section,'Port'+IntToStr(i),0) )); end; end; procedure TFrameSensor.TimerProc(const fSampleNum:Double); var pX:^TAnalogData; SX:Double; MC:Integer; SampleNum:Cardinal; begin SampleNum:=Trunc(fSampleNum);//Round if not NotFirstSample then begin NotFirstSample:=True; PrevSampleNum:=SampleNum; end; ReadyForOutput:=PrevSampleNum<>SampleNum; PrevSampleNum:=SampleNum; if ReadyForOutput then begin CS.Acquire; SX:=SumX; MC:=MeasureCnt; SumX:=0; MeasureCnt:=0; if (MC>0) then X:=SX/MC else begin pX:=@X; if isSensorOn then begin if IsErrAnalog then SetErrAnalog(pX^) else if IsErrADCRange then SetErrADCRange(pX^) else if IsErrADCComm then SetErrADCComm(pX^) else SetErrUnknown(pX^); end else SetSensorRepair(pX^); end; CS.Release; end; end; procedure TFrameSensor.ShowInfo; var SX:Double; QC,MC,RC:Integer; begin CS.Enter; QC:=ShowQueryCnt; RC:=ShowResponseCnt; MC:=ShowMeasureCnt; SX:=ShowSumX; ShowQueryCnt:=0; ShowResponseCnt:=0; ShowMeasureCnt:=0; ShowSumX:=0; CS.Leave; stCount.Caption:=IntToStr(RC)+' из '+IntToStr(QC)+' '; if MC>0 then begin SX:=SX/MC; stX.Caption:=fmt(SX*VoltsScale)+' '; stResult.Caption:=fmt(SX*CoeffK+CoeffB)+' '; end else stX.Caption:='-'; end; function TFrameSensor.Validate: Boolean; var Tmp:Integer; begin Result:=False; ValidConfig:=False; try try Tmp:=StrToInt(edPeriod.Text); if(Tmp<1)or(100<Tmp)then raise Exception.Create(''); CS.Acquire; Period:=Tmp; CS.Release; except edPeriod.SetFocus; raise; end; CS.Acquire; QueryCmd:=edQueryCmd.Text; QueryCmd:=QueryCmd+StrCheckSum(QueryCmd[1],SizeOf(QueryCmd)); CS.Release; except exit; end; Result:=True; ValidConfig:=True; end; procedure TFrameSensor.cbOnClick(Sender: TObject); begin if cbOn.Checked then cbOn.Checked:=Validate; CS.Acquire; isSensorOn:=cbOn.Checked; CS.Release; end; procedure TFrameSensor.WriteToIni(Ini: TIniFile); begin Ini.WriteInteger(Section,'On',Integer(cbOn.Checked)); if ValidConfig then begin Ini.WriteString(Section,'Period',edPeriod.Text); Ini.WriteString(Section,'QueryCmd',edQueryCmd.Text); end; // ADC & conversion parameters Ini.WriteInteger(Section,'VoltageMode',Integer(VoltageMode)); Ini.WriteInteger(Section,'ADCRange',ADCRange); if VoltageMode then begin Ini.WriteFloat(Section,'Ua',Ua); Ini.WriteFloat(Section,'Ub',Ub); end else begin Ini.WriteFloat(Section,'Ia',Ia); Ini.WriteFloat(Section,'Ib',Ib); Ini.WriteFloat(Section,'R',R); end; Ini.WriteFloat(Section,'Xm',Xm); Ini.WriteFloat(Section,'Xa',Xa); Ini.WriteFloat(Section,'Xb',Xb); end; constructor TFrameSensor.Create(AOwner: TComponent); begin inherited; CS:=TCriticalSection.Create; end; procedure TFrameSensor.CalcCoeffs; begin while not getADCRangeParams(ADCRange,PhysScale,VoltsScale) do ADCRange:=9; CoeffK:=VoltsScale*(Xb-Xa)/(Ub-Ua); CoeffB:=VoltsScale*Xa-CoeffK*Ua; end; procedure TFrameSensor.BtnConversionClick(Sender: TObject); var CF:TFormConversion; MR:Integer; begin CF:=TFormConversion.Create(Self); CF.VoltageMode:=VoltageMode; CF.ADCRange:=ADCRange; CF.Ia:=Ia; CF.Ib:=Ib; CF.R:=R; CF.Ua:=Ua; CF.Ub:=Ub; CF.Xm:=Xm; CF.Xa:=Xa; CF.Xb:=Xb; while True do begin MR:=CF.ShowModal; case MR of mrOK,mrYes: begin CS.Enter; VoltageMode:=CF.VoltageMode; ADCRange:=CF.ADCRange; Ia:=CF.Ia; Ib:=CF.Ib; R:=CF.R; Ua:=CF.Ua; Ub:=CF.Ub; Xm:=CF.Xm; Xa:=CF.Xa; Xb:=CF.Xb; CalcCoeffs; CS.Leave; if MR=mrOK then break; end; mrCancel: break; end; end; CF.Free; end; { procedure TFrameSensor.TimerShow; begin if CntP=0 then P:=0; stStatus.Caption:=Format('%3d | %7.3f ',[CntP,P]);; CntP:=0; end; } { TAddress } constructor TAddress.Create(const Host: String; Port: Integer); begin inherited Create; Self.Host:=Host; Self.Port:=Port; end; end.
unit View.LancamentosExtratosExpressas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinsDefaultPainters, cxClasses, dxLayoutContainer, dxLayoutControl, cxContainer, cxEdit, dxLayoutcxEditAdapters, cxLabel, cxTextEdit, Vcl.ComCtrls, dxCore, cxDateUtils, cxMaskEdit, cxDropDownEdit, cxCalendar, cxButtonEdit, cxCalc, cxCheckBox, cxSpinEdit, dxLayoutControlAdapters, Vcl.Menus, Vcl.StdCtrls, cxButtons, System.Actions, Vcl.ActnList, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, dxDateRanges, cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB, cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Common.ENum, Control.EntregadoresExpressas, Control.Lancamentos, System.DateUtils; type Tview_LancamentosExtratosExpressas = class(TForm) layoutControlPadraoGroup_Root: TdxLayoutGroup; layoutControlPadrao: TdxLayoutControl; labelTitle: TcxLabel; layoutItemLabelTitle: TdxLayoutItem; layoutGroupLancamento: TdxLayoutGroup; textEditDescricao: TcxTextEdit; layoutItemDescricao: TdxLayoutItem; dateEditData: TcxDateEdit; layoutItemData: TdxLayoutItem; buttonEditCodigoEntregador: TcxButtonEdit; layoutItemCodigoEntregador: TdxLayoutItem; dxLayoutAutoCreatedGroup1: TdxLayoutAutoCreatedGroup; textEditNomeEntregador: TcxTextEdit; layoutItemNomeEntregador: TdxLayoutItem; comboBoxTipo: TcxComboBox; layoutItemTipoLancamento: TdxLayoutItem; dxLayoutAutoCreatedGroup2: TdxLayoutAutoCreatedGroup; calcEditValor: TcxCalcEdit; layoutItemValor: TdxLayoutItem; layoutGroupHistorico: TdxLayoutGroup; checkBoxProcessado: TcxCheckBox; layoutItemProcessado: TdxLayoutItem; maskEditDataProcessamento: TcxMaskEdit; layoutItemDataProcessamento: TdxLayoutItem; textEditExtrato: TcxTextEdit; layoutItemExtrato: TdxLayoutItem; maskEditDataCadastro: TcxMaskEdit; layoutItemDataCadastro: TdxLayoutItem; buttonEditReferencia: TcxButtonEdit; layoutItemReferencia: TdxLayoutItem; TextEditUsuario: TcxTextEdit; layoutItemUsuario: TdxLayoutItem; layoutGroupParcelamento: TdxLayoutGroup; spinEditIntervaloDias: TcxSpinEdit; layoutItemIntervalo: TdxLayoutItem; dxLayoutAutoCreatedGroup3: TdxLayoutAutoCreatedGroup; dateEditDataInicial: TcxDateEdit; layoutItemDataInicial: TdxLayoutItem; buttonProcessar: TcxButton; layoutItemProcessar: TdxLayoutItem; actionListLancamentos: TActionList; actionNovo: TAction; actionEditar: TAction; actionCancelar: TAction; actionExcluir: TAction; actionGravar: TAction; actionLocalizar: TAction; actionFechar: TAction; actionProcessar: TAction; gridParcelamentoDBTableView1: TcxGridDBTableView; gridParcelamentoLevel1: TcxGridLevel; gridParcelamento: TcxGrid; layoutItemGridParcelamento: TdxLayoutItem; memTableParcelamento: TFDMemTable; memTableParcelamentonum_parcela: TIntegerField; memTableParcelamentodat_parcela: TDateField; memTableParcelamentoval_parcela: TCurrencyField; fdParcelamentos: TDataSource; gridParcelamentoDBTableView1num_parcela: TcxGridDBColumn; gridParcelamentoDBTableView1dat_parcela: TcxGridDBColumn; gridParcelamentoDBTableView1val_parcela: TcxGridDBColumn; comboBoxProcessamento: TcxComboBox; layoutItemProcessamento: TdxLayoutItem; actionReferencia: TAction; layoutGroupOpcoes: TdxLayoutGroup; buttonGravar: TcxButton; layoutItemGravar: TdxLayoutItem; buttonFechar: TcxButton; layoutItemFechar: TdxLayoutItem; actionPesquisaEntregadores: TAction; spinEditParcelas: TcxSpinEdit; layoutItemParcelas: TdxLayoutItem; maskEditID: TcxMaskEdit; dxLayoutItem1: TdxLayoutItem; procedure actionEditarExecute(Sender: TObject); procedure actionExcluirExecute(Sender: TObject); procedure actionNovoExecute(Sender: TObject); procedure actionCancelarExecute(Sender: TObject); procedure actionFecharExecute(Sender: TObject); procedure buttonEditCodigoEntregadorPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure comboBoxTipoPropertiesChange(Sender: TObject); procedure comboBoxProcessamentoPropertiesChange(Sender: TObject); procedure actionProcessarExecute(Sender: TObject); procedure actionPesquisaEntregadoresExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure actionGravarExecute(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } procedure Modo; procedure LimpaCampos; procedure PesquisaEntregadores; procedure ProcessaParcelamento; procedure SetupForm(iID: integer); procedure SetupClass; function SaveData(): boolean; function VerificaProcesso(): Boolean; function RetornaNomeEntregador(iCodigo: integer): String; function ValidateData(): boolean; public { Public declarations } iID: integer; FAcao: TAcao; end; var view_LancamentosExtratosExpressas: Tview_LancamentosExtratosExpressas; Lancamentos: TLancamentosControl; iCadastro: integer; implementation {$R *.dfm} uses Data.SisGeF, View.PesquisaEntregadoresExpressas, Common.Utils, View.PesquisarPessoas, Global.Parametros; procedure Tview_LancamentosExtratosExpressas.actionCancelarExecute (Sender: TObject); begin FAcao := tacIndefinido; LimpaCampos; Modo; end; procedure Tview_LancamentosExtratosExpressas.actionEditarExecute (Sender: TObject); begin SetupForm(iID); if not VerificaProcesso() then begin Application.MessageBox ('Lançamento já processado (Descontato ou creditado). A edição não é permitida!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); FAcao := tacPesquisa; end; Modo; end; procedure Tview_LancamentosExtratosExpressas.actionExcluirExecute (Sender: TObject); begin if not VerificaProcesso() then begin Application.MessageBox ('Lançamento já processado (Descontato ou creditado). A exclusão não é permitida!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); FAcao := tacPesquisa; end; Modo; end; procedure Tview_LancamentosExtratosExpressas.actionFecharExecute (Sender: TObject); begin ModalResult := mrCancel; end; procedure Tview_LancamentosExtratosExpressas.actionGravarExecute(Sender: TObject); begin if SaveData() then ModalResult := mrOk; end; procedure Tview_LancamentosExtratosExpressas.actionNovoExecute(Sender: TObject); begin LimpaCampos; Modo; textEditDescricao.SetFocus; end; procedure Tview_LancamentosExtratosExpressas.actionPesquisaEntregadoresExecute (Sender: TObject); begin PesquisaEntregadores; end; procedure Tview_LancamentosExtratosExpressas.actionProcessarExecute (Sender: TObject); begin ProcessaParcelamento; end; procedure Tview_LancamentosExtratosExpressas.buttonEditCodigoEntregadorPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin if (FAcao <> tacIncluir) and (FAcao <> tacAlterar) then begin Exit end; textEditNomeEntregador.Text := RetornaNomeEntregador(DisplayValue); end; procedure Tview_LancamentosExtratosExpressas. comboBoxProcessamentoPropertiesChange(Sender: TObject); begin if FAcao = tacIncluir then begin if comboBoxProcessamento.ItemIndex >= 2 then begin dateEditDataInicial.Date := dateEditData.Date; layoutGroupParcelamento.Visible := True; end else begin layoutGroupParcelamento.Visible := False; end; end; end; procedure Tview_LancamentosExtratosExpressas.comboBoxTipoPropertiesChange (Sender: TObject); begin if comboBoxTipo.ItemIndex = 2 then begin comboBoxTipo.Style.Font.Color := clRed; calcEditValor.Style.Font.Color := clRed; end else begin comboBoxTipo.Style.Font.Color := clNone; calcEditValor.Style.Font.Color := clNone; end; end; procedure Tview_LancamentosExtratosExpressas.FormKeyPress(Sender: TObject; var Key: Char); begin if gridParcelamento.Focused then Exit; If Key = #13 then begin Key := #0; Perform(Wm_NextDlgCtl, 0, 0); end; end; procedure Tview_LancamentosExtratosExpressas.FormShow(Sender: TObject); begin labelTitle.Caption := Self.Caption; if FAcao = tacIncluir then actionNovoExecute(Sender) else if FAcao = tacAlterar then actionEditarExecute(Sender); end; procedure Tview_LancamentosExtratosExpressas.LimpaCampos; begin iID := 0; textEditDescricao.EditValue := ''; dateEditData.Clear; iCadastro := 0; buttonEditCodigoEntregador.EditValue := 0; comboBoxTipo.ItemIndex := 0; calcEditValor.Value := 0; spinEditIntervaloDias.Value := 15; dateEditDataInicial.Clear; if memTableParcelamento.Active then memTableParcelamento.Close; checkBoxProcessado.EditValue := 'N'; maskEditDataProcessamento.Clear; textEditExtrato.Clear; maskEditDataCadastro.Clear; buttonEditReferencia.EditValue := 0; TextEditUsuario.Clear; end; procedure Tview_LancamentosExtratosExpressas.Modo; begin if FAcao = tacIndefinido then begin actionNovo.Enabled := True; actionEditar.Enabled := False; actionLocalizar.Enabled := True; actionCancelar.Enabled := False; actionGravar.Enabled := False; actionReferencia.Enabled := False; actionPesquisaEntregadores.Enabled := False; textEditDescricao.Properties.ReadOnly := True; dateEditData.Properties.ReadOnly := True; buttonEditCodigoEntregador.Properties.ReadOnly := True; comboBoxTipo.Properties.ReadOnly := True; calcEditValor.Properties.ReadOnly := True; layoutItemProcessamento.Visible := False; layoutGroupParcelamento.Visible := False; layoutGroupHistorico.Visible := False; layoutGroupHistorico.Visible := False; end else if FAcao = tacIncluir then begin actionNovo.Enabled := False; actionEditar.Enabled := False; actionLocalizar.Enabled := False; actionCancelar.Enabled := True; actionGravar.Enabled := True; actionReferencia.Enabled := False; actionPesquisaEntregadores.Enabled := True; textEditDescricao.Properties.ReadOnly := False; dateEditData.Properties.ReadOnly := False; buttonEditCodigoEntregador.Properties.ReadOnly := False; comboBoxTipo.Properties.ReadOnly := False; calcEditValor.Properties.ReadOnly := False; layoutItemProcessamento.Visible := True; layoutGroupParcelamento.Visible := False; layoutGroupHistorico.Visible := False; end else if FAcao = tacAlterar then begin actionNovo.Enabled := False; actionEditar.Enabled := False; actionLocalizar.Enabled := False; actionCancelar.Enabled := True; actionGravar.Enabled := True; actionReferencia.Enabled := False; actionPesquisaEntregadores.Enabled := True; textEditDescricao.Properties.ReadOnly := False; dateEditData.Properties.ReadOnly := False; buttonEditCodigoEntregador.Properties.ReadOnly := False; comboBoxTipo.Properties.ReadOnly := False; calcEditValor.Properties.ReadOnly := False; layoutItemProcessamento.Visible := False; layoutGroupParcelamento.Visible := False; layoutGroupHistorico.Visible := True; end else if FAcao = tacPesquisa then begin actionNovo.Enabled := False; actionEditar.Enabled := True; actionLocalizar.Enabled := False; actionCancelar.Enabled := True; actionGravar.Enabled := False; actionReferencia.Enabled := False; actionPesquisaEntregadores.Enabled := False; textEditDescricao.Properties.ReadOnly := True; dateEditData.Properties.ReadOnly := True; buttonEditCodigoEntregador.Properties.ReadOnly := True; comboBoxTipo.Properties.ReadOnly := True; calcEditValor.Properties.ReadOnly := True; layoutItemProcessamento.Visible := False; layoutGroupParcelamento.Visible := False; layoutGroupHistorico.Visible := True; end; end; procedure Tview_LancamentosExtratosExpressas.PesquisaEntregadores; begin if not Assigned(view_PesquisaEntregadoresExpressas) then view_PesquisaEntregadoresExpressas := Tview_PesquisaEntregadoresExpressas.Create(Application); if view_PesquisaEntregadoresExpressas.ShowModal = mrOk then begin buttonEditCodigoEntregador.EditValue := view_PesquisaEntregadoresExpressas.fdPesquisacod_entregador.AsInteger; iCadastro := view_PesquisaEntregadoresExpressas.fdPesquisacod_cadastro.AsInteger; textEditNomeEntregador.Text := view_PesquisaEntregadoresExpressas.fdPesquisanom_entregador.AsString; end; FreeAndNil(view_PesquisaEntregadoresExpressas); end; procedure Tview_LancamentosExtratosExpressas.ProcessaParcelamento; var dtData: TDate; i, iDias, iParcelas: integer; dValor: Double; begin if memTableParcelamento.Active then begin memTableParcelamento.Close; end; memTableParcelamento.Open; iParcelas := spinEditParcelas.Value; if comboBoxProcessamento.ItemIndex = 2 then dValor := calcEditValor.Value / iParcelas else dValor := calcEditValor.Value; dtData := dateEditDataInicial.Date; iDias := spinEditIntervaloDias.Value; for i := 1 to iParcelas do begin memTableParcelamento.Insert; memTableParcelamentonum_parcela.AsInteger := i; memTableParcelamentodat_parcela.AsDateTime := dtData; memTableParcelamentoval_parcela.AsFloat := dValor; memTableParcelamento.Post; dtData := IncDay(dtData,iDias); end; if not memTableParcelamento.IsEmpty then begin memTableParcelamento.First; end; end; function Tview_LancamentosExtratosExpressas.RetornaNomeEntregador(iCodigo: integer): String; var entregador: TEntregadoresExpressasControl; sRetorno, sCadastro: String; begin try Result := ''; sRetorno := ''; sCadastro := ''; iCadastro := 0; entregador := TEntregadoresExpressasControl.Create; if iCodigo <> 0 then begin sRetorno := entregador.GetField('NOM_FANTASIA', 'COD_ENTREGADOR', iCodigo.ToString); sCadastro := entregador.GetField('COD_CADASTRO', 'COD_ENTREGADOR', iCodigo.ToString); iCadastro := StrToIntDef(sCadastro,0); end; if sRetorno.IsEmpty then begin sRetorno := 'NONE'; end; Result := sRetorno; finally entregador.Free; end; end; function Tview_LancamentosExtratosExpressas.SaveData: boolean; var aParam : Array of variant; sDescricao, sParcelamento: String; begin try lancamentos := TLancamentosControl.Create; Result := False; if not ValidateData then Exit; if Application.MessageBox('Confirma gravar os dados ?', 'Gravar', MB_YESNO + MB_ICONQUESTION) = IDNO then Exit; if FAcao = tacIncluir then begin SetupClass; if not memTableParcelamento.IsEmpty then memTableParcelamento.First; if comboBoxProcessamento.ItemIndex > 1 then begin sDescricao := Lancamentos.Lancamentos.Descricao; while not memTableParcelamento.Eof do begin sParcelamento := ''; if comboBoxProcessamento.ItemIndex = 2 then sParcelamento := ' - ' + memTableParcelamentonum_parcela.AsString + '/' + spinEditParcelas.Text; Lancamentos.Lancamentos.Descricao := sDescricao + sParcelamento; Lancamentos.Lancamentos.Data := memTableParcelamentodat_parcela.AsDateTime; Lancamentos.Lancamentos.Valor := memTableParcelamentoval_parcela.AsCurrency; if not Lancamentos.Gravar then begin Application.MessageBox(PChar('Ocorreu um problema ao tentar salvar a parcela ' + memTableParcelamentonum_parcela.AsString + '!'), 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; memTableParcelamento.Next; end; if not memTableParcelamento.IsEmpty then memTableParcelamento.First; end else begin if not Lancamentos.Gravar then begin Application.MessageBox('Ocorreu um problema ao tentar salvar o registro!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; end; end else if FAcao = tacAlterar then begin SetLength(aParam,2); aParam := ['CODIGO', maskEditID.EditValue]; if Lancamentos.Localizar(aParam).IsEmpty then begin Application.MessageBox('Ocorreu um problema ao tentar localizar o registro para alterar!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end else begin SetupClass; if not Lancamentos.Gravar then begin Application.MessageBox('Ocorreu um problema ao tentar salvar o registro!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; end; end; Result := True; finally lancamentos.Free; end; end; procedure Tview_LancamentosExtratosExpressas.SetupClass; var iReferencia : Integer; begin if FAcao = tacIncluir then iReferencia := Lancamentos.GetId; Lancamentos.Lancamentos.Descricao := textEditDescricao.Text; Lancamentos.Lancamentos.Data := dateEditData.Date; Lancamentos.Lancamentos.Cadastro := iCadastro; Lancamentos.Lancamentos.entregador := buttonEditCodigoEntregador.EditValue; if comboBoxTipo.ItemIndex = 1 then begin Lancamentos.Lancamentos.Tipo := 'CREDITO'; end else begin Lancamentos.Lancamentos.Tipo := 'DEBITO'; end; Lancamentos.Lancamentos.Valor := calcEditValor.Value; if FAcao = tacIncluir then begin Lancamentos.Lancamentos.Desconto := 'N'; Lancamentos.Lancamentos.DataDesconto := 0; Lancamentos.Lancamentos.Extrato := ''; Lancamentos.Lancamentos.Referencia := iReferencia; Lancamentos.Lancamentos.DataCadastro := Now; Lancamentos.Lancamentos.Usuario := Global.Parametros.pUser_Name; end; Lancamentos.Lancamentos.Persistir := 'N'; Lancamentos.Lancamentos.Acao := FAcao; end; procedure Tview_LancamentosExtratosExpressas.SetupForm(iID: integer); var aParam: array of Variant; begin Lancamentos := TLancamentosControl.Create; SetLength(aParam, 2); aParam := ['CODIGO', iID]; if not Lancamentos.Localizar(aParam).IsEmpty then begin maskEditID.EditValue := Lancamentos.Lancamentos.Codigo; textEditDescricao.Text := Lancamentos.Lancamentos.Descricao; dateEditData.Date := Lancamentos.Lancamentos.Data; buttonEditCodigoEntregador.EditValue := Lancamentos.Lancamentos.entregador; textEditNomeEntregador.Text := RetornaNomeEntregador(Lancamentos.Lancamentos.entregador); if Lancamentos.Lancamentos.Tipo = 'CREDITO' then begin comboBoxTipo.ItemIndex := 1; end else if Lancamentos.Lancamentos.Tipo = 'DEBITO' then begin comboBoxTipo.ItemIndex := 2; end else begin comboBoxTipo.ItemIndex := 0; end; calcEditValor.EditValue := Lancamentos.Lancamentos.Valor; if Lancamentos.Lancamentos.Desconto = 'S' then begin checkBoxProcessado.Checked := True; end else begin checkBoxProcessado.Checked := False; end; maskEditDataProcessamento.Text := FormatDateTime('dd/mm/yyyy', Lancamentos.Lancamentos.DataDesconto); textEditExtrato.Text := Lancamentos.Lancamentos.Extrato; maskEditDataCadastro.Text := FormatDateTime('dd/mm/yyyy', Lancamentos.Lancamentos.DataCadastro); buttonEditReferencia.Text := Lancamentos.Lancamentos.Codigo.ToString; textEditUsuario.Text := Lancamentos.Lancamentos.Usuario; iCadastro := Lancamentos.Lancamentos.Cadastro; end; end; function Tview_LancamentosExtratosExpressas.ValidateData: boolean; begin Result:= False; if textEditDescricao.Text = '' then begin Application.MessageBox('Informe uma descrição para o lançamento!', 'Atenção', MB_OK + MB_ICONWARNING); textEditDescricao.SetFocus; Exit; end; if dateEditData.Text = '' then begin Application.MessageBox('Informe a data do lançamento!', 'Atenção', MB_OK + MB_ICONWARNING); dateEditData.SetFocus; Exit; end; if buttonEditCodigoEntregador.EditValue = 0 then begin Application.MessageBox('Informe o código do entregador!', 'Atenção', MB_OK + MB_ICONWARNING); buttonEditCodigoEntregador.SetFocus; Exit; end; if comboBoxTipo.ItemIndex = 0 then begin Application.MessageBox('Informe o tipo do lançamento!', 'Atenção', MB_OK + MB_ICONWARNING); comboBoxTipo.SetFocus; Exit; end; if calcEditValor.Value = 0 then begin Application.MessageBox('Informe o valor do lançamento!', 'Atenção', MB_OK + MB_ICONWARNING); calcEditValor.SetFocus; Exit; end; if FAcao = tacIncluir then begin if comboBoxProcessamento.ItemIndex = 0 then begin Application.MessageBox('Informe o tipo de processo do lançamento!', 'Atenção', MB_OK + MB_ICONWARNING); comboBoxProcessamento.SetFocus; Exit; end; if comboBoxProcessamento.ItemIndex > 1 then begin if spinEditIntervaloDias.Value = 0 then begin Application.MessageBox('Informe o intervalo de dias do parcelamento!', 'Atenção', MB_OK + MB_ICONWARNING); spinEditIntervaloDias.SetFocus; Exit; end; if spinEditParcelas.Value = 0 then begin Application.MessageBox('Informe a quantidade de parcelas!', 'Atenção', MB_OK + MB_ICONWARNING); spinEditParcelas.SetFocus; Exit; end; if dateEditDataInicial.Text = '' then begin Application.MessageBox('Informe a data inicial do parcelamento!', 'Atenção', MB_OK + MB_ICONWARNING); dateEditDataInicial.SetFocus; Exit; end; if dateEditDataInicial.Date < dateEditData.Date then begin Application.MessageBox('Data inicial do parcelamento menor que a data do lançamento!', 'Atenção', MB_OK + MB_ICONWARNING); dateEditDataInicial.SetFocus; Exit; end; end; end; Result := True; end; function Tview_LancamentosExtratosExpressas.VerificaProcesso: Boolean; begin Result := False; if Lancamentos.Lancamentos.Desconto = 'S' then begin Exit; end; Result := True; end; end.
unit TestUnmarshalMultipleArrayUnit; interface uses TestFramework, System.JSON, SysUtils; type TTestUnmarshalMultipleArray = class(TTestCase) private function Etalon: String; published procedure TestUnmarshal(); end; implementation { TTestUnmarshalMultipleArray } uses GetOrdersWithCustomFieldsResponseUnit, MarshalUnMarshalUnit; function TTestUnmarshalMultipleArray.Etalon: String; begin Result := '{"results": [[7205711, 1],[7205710, 2],[7205709, 3],[7205708, 4]],"total": 148,"fields": ["order_id","member_id"]}'; end; procedure TTestUnmarshalMultipleArray.TestUnmarshal; var Actual: TGetOrdersWithCustomFieldsResponse; JsonValue: TJSONValue; begin JsonValue := TJSONObject.ParseJSONValue(Etalon); try Actual := TMarshalUnMarshal.FromJson( TGetOrdersWithCustomFieldsResponse, JsonValue) as TGetOrdersWithCustomFieldsResponse; CheckEquals(148, Actual.Total); CheckEquals(2, Length(Actual.Fields)); CheckEquals('order_id', Actual.Fields[0]); CheckEquals('member_id', Actual.Fields[1]); CheckEquals(4, Actual.ResultCount); CheckEquals('7205711', Actual.GetResult(0, 'order_id')); CheckEquals('1', Actual.GetResult(0, 'member_id')); CheckEquals('7205710', Actual.GetResult(1, 'order_id')); CheckEquals('2', Actual.GetResult(1, 'member_id')); CheckEquals('7205709', Actual.GetResult(2, 'order_id')); CheckEquals('3', Actual.GetResult(2, 'member_id')); CheckEquals('7205708', Actual.GetResult(3, 'order_id')); CheckEquals('4', Actual.GetResult(3, 'member_id')); finally FreeAndNil(JsonValue); end; end; initialization RegisterTest('JSON\Unmarshal\', TTestUnmarshalMultipleArray.Suite); end.
unit d03.mocking.DriverTests; interface uses DUnitX.TestFramework, d03.mocking.ManualMock, d03.mocking.Driver, d03.mocking.Car; type [TestFixture] TDriverTests_ManualMock = class public [Test] procedure cannot_drive_a_running_car(); end; implementation procedure TDriverTests_ManualMock.cannot_drive_a_running_car; var mockRunningCar : TMockRunningCar; driver : TDriver; begin mockRunningCar := TMockRunningCar.Create(); driver := TDriver.Create(mockRunningCar); Assert.IsFalse(driver.CanDrive()); end; end.
// Filename : EventConsumer.pas // Version : 1.1 (Delphi) // Date : July 4, 2003 // Author : Jeff Rafter // Details : http://xml.defined.net/SAX/aelfred2 // License : Please read License.txt unit EventConsumer; interface uses Classes, SAX; type IEventConsumer = interface(IUnknown) ['{2129F823-B408-4B1F-A9EC-577EFE95946C}'] function getContentHandler() : IContentHandler; function getDTDHandler() : IDTDHandler; function getProperty(const propertyId: SAXString): IProperty; procedure setErrorHandler(const handler : IErrorHandler); end; implementation end.
unit uCheckValiable; interface const ALARMCONTROL = 1; //알람제어 ALARMSTATECHECK = 2; //방범상태체크 ALERTLAMPSIREN = 3; //비상알람시램프사이렌 ALERTLAMPTIME = 4; // ALERTSIRENTIME = 5; // ARMDSCHECK = 6; //경계시 DS체크 ARMRELAYTYPE = 7; //경계시 릴레이타입 CARDDOWNLOADACK = 8; //카드다운로드 CARDLIST = 10; //등록카드리스트 CARDLISTCANCEL = 11; //카드리스트 조회 취소 CARDREADERCALLTIME = 12; //카드리더 통화시간 CARDREADERINFO = 13; //카드리더 정보 CARDREADERSOUNDUSE = 14; //카드리더 음성송출유무 CARDREADERTELNUMBERCHECK = 15; //카드리더 전화번호 체크 CARDREADERTYPE = 16; //카드리더 타입 CARDREADERVERSION = 17; //카드리더 버젼정보 conARMAREAUSE = 18; //방범구역 사용 유무 conCARDREADERExitSOUNDUSE = 19; //카드리더 퇴실음성송출유무 conCARDREADERSTATE = 20; //카드리더 통신상태 conCARDRegCardCnt = 21; //등록카드리스트 conCCCInfoCHECK = 22; //CCC 정보 체크 conCCCStartTimeCheck = 23; conCCCTimeIntervalCheck = 24; conDDNSQueryServer = 30; conDDNSServer = 31; conDOORARMAREA = 32; //출입문 방범구역 conDOORDSCHECKTIME = 33; //데드볼트시 문검사 수행시 검사 시간 conDOORDSCHECKUSE = 34; //데드볼트시 문검사 항상수행 여부 conDoorTimeCodeUse = 35; //타임코드 사용유무 conExtentionVERSION = 36; //존 확장기 버젼정보 conEventServer = 37; conKTTMUXID = 40; //Mux ID conLineCheckStart = 41; conLineCheckTime = 42; conLineShortCheck = 43; //선로 쇼트 체크 conMaxCardCountCheck = 44; //최종 카드번지 conJaeJungDlayUseCheck = 45; //재중 딜레이 체크 conJavaraArmClose = 46; //자바라경계시닫힘 conJavaraAutoClose = 47; //자바라자동닫힘 conJavaraSchedule = 48; //자바라 스케줄 conJavaraStopTime = 49; //자바라스톱시간 conPrimaryKTTType = 60; //주통신 타입 conPoliceTel = 61; conServerCardNF = 62; conTCPServerPort = 63; conTimeCode = 64; conRegisterClear = 65; //메모리지움 제어 conZoneExtensionPortInfo = 70; //감지기존 설정 conZoneExtensionUse = 71; //존확장기 사용유무 conZONEEXTENTIONNETWORK = 72; //존확장기 통신상태 conZONEUSEDREMOTECONTROL = 73; //존확장기 통신상태 DEVICECODECHECK = 74; //기기코드 조회 DEVICERESET = 75; //컨트롤러 리셋 DEVICETYPECHECK = 76; //ECU/ICU Check DEVICEVERSIONCHECK = 77; //기기버젼체크 DOORCONTROL = 78; //출입문제어 DOORSTATECHECK = 79; //출입문상태체크 DOORSYSTEMCHECK = 80; //출입문시스템체크 DVRInfoCHECK = 81; //DVR정보 ECUSTATE = 90; //확장기 통신상태 FIRERECOVERY = 91; //화재복구 FTPFUNCTION = 92; //FTP기능 체크 HOLIDAY = 93; //특정일 IDCHECK = 94; //ID Check KTTRINGCOUNT = 95; //관제데코더전화번호 KTTSYSTEMID = 96; //관제시스템아이디 KTTTELNUM = 97; //관제데코더전화번호 LOCKSTATECHECK = 100; //락 상태 체크 MACINFO = 101; MAINTOLOCALARM = 102; //메인에서 로컬 경계시키는 기능 MAINFROMLOCALARM = 103; //로컬이 경계 된 후 메인이 경계 되는 기능 PORTSTATE = 104; //현재 포트의 쇼트/단선체크 RELAY2TYPE = 105; //812 출입문 2 사용여부 SCHEDULE = 106; //스케줄 조회 SERIALWIZNET = 107; //랜정보 SYSINFOCHECK = 110; //시스템정보 SYSTEMFUNCTION = 111; //기기기능 체크 TIME = 112; //시간 USECDMACHECK = 113; //CDMA사용 유무 체크 USEDEVICECHECK = 114; //사용확장기체크 USEDVRCHECK = 115; //DVR사용 유무 체크 WIZNETMODULECHECK = 116; //랜모듈 정보 ZONESENSECHECK = 117; //알람 상태 체크 var G_bResponseChecking : Boolean; //현재 응답 대기 중인지 여부 - 대기중이면 패킷 송신을 보류 하자 G_bDeviceResponse: Array [0..200] of Boolean; //기기 설정 정보 응답 여부 G_bCardReaderResponse: Array [0..512] of Boolean; //카드리더 정보 응답 여부 G_bCardReaderVersionResponse: Array [0..512] of Boolean; //카드리더 정보 응답 여부 G_bExtentionVersionResponse: Array [0..512] of Boolean; //존확장기 정보 응답 여부 G_bPortResponse: Array [0..768] of Boolean; //포트 정보 응답 여부 G_stDeviceType: Array [0..200] of string; //기기 타입 implementation end.
unit ZombieController; interface uses Graphics, PositionRecord, Animation, AnimationArchive, Frame, ZombieAction, ZombieDirection, ZombieCharacter; type TZombieController = class protected fAnimationArchive : TAnimationArchive; procedure MakeAnimation_stance(); procedure MakeAnimation_lurch(); procedure MakeAnimation_slam(); procedure MakeAnimation_bite(); procedure MakeAnimation_block(); procedure MakeAnimation_hitndie(); procedure MakeAnimation_criticaldeath(); procedure MakeAnimation_selected(); procedure MakeAnimation_destination(); public constructor Create(aAnimationArchive : TAnimationArchive); destructor Destroy(); function GetAnimationArchive() : TAnimationArchive; procedure DrawCharacter(aZombie : TZombieCharacter; aCanvas : TCanvas; aMapPosition : TPositionRecord); function PositionCollisionWithCharacter(aZombie : TZombieCharacter; aMapPosition : TPositionRecord; collisionPosition : TPositionRecord) : Boolean; function RectangleCollisionWithCharacter(aZombie: TZombieCharacter; aMapPosition, aLeftTopPosition, aRightBottomPosition: TPositionRecord): Boolean; end; const CHARACTER_WIDTH = 128; CHARACTER_HEIGHT = 128; implementation procedure TZombieController.MakeAnimation_stance(); var animation : TAnimation; i : Integer; begin for i := 0 to 7 do begin animation := fAnimationArchive.AddAnimation(ZombieAnimationAction[Ord(TZombieAction.Stance)] + ZombieAnimationDirection[i]); animation.AddFrame(TFrame.Create(0 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(1 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(2 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(3 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(2 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(1 + i *36,TPositionRecord.Create(0,0),0.11)); end; end; procedure TZombieController.MakeAnimation_lurch(); var animation : TAnimation; i : Integer; begin for i := 0 to 7 do begin animation := fAnimationArchive.AddAnimation(ZombieAnimationAction[Ord(TZombieAction.Lurch)] + ZombieAnimationDirection[i]); animation.AddFrame(TFrame.Create(4 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(5 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(6 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(7 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(8 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(9 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(10 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(11 + i *36,TPositionRecord.Create(0,0),0.11)); end; end; procedure TZombieController.MakeAnimation_slam(); var animation : TAnimation; i : Integer; begin for i := 0 to 7 do begin animation := fAnimationArchive.AddAnimation(ZombieAnimationAction[Ord(TZombieAction.Slam)] + ZombieAnimationDirection[i]); animation.AddFrame(TFrame.Create(12 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(13 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(14 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(15 + i *36,TPositionRecord.Create(0,0),0.11)); end; end; procedure TZombieController.MakeAnimation_bite(); var animation : TAnimation; i : Integer; begin for i := 0 to 7 do begin animation := fAnimationArchive.AddAnimation(ZombieAnimationAction[Ord(TZombieAction.Bite)] + ZombieAnimationDirection[i]); animation.AddFrame(TFrame.Create(16 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(17 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(18 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(19 + i *36,TPositionRecord.Create(0,0),0.11)); end; end; procedure TZombieController.MakeAnimation_block(); var animation : TAnimation; i : Integer; begin for i := 0 to 7 do begin animation := fAnimationArchive.AddAnimation(ZombieAnimationAction[Ord(TZombieAction.Block)] + ZombieAnimationDirection[i]); animation.AddFrame(TFrame.Create(20 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(20 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(20 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(21 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(21 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(21 + i *36,TPositionRecord.Create(0,0),0.11)); end; end; procedure TZombieController.MakeAnimation_hitndie(); var animation : TAnimation; i : Integer; begin for i := 0 to 7 do begin animation := fAnimationArchive.AddAnimation(ZombieAnimationAction[Ord(TZombieAction.Hitndie)] + ZombieAnimationDirection[i]); animation.AddFrame(TFrame.Create(22 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(23 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(24 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(25 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(26 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(27 + i *36,TPositionRecord.Create(0,0),0.11)); end; end; procedure TZombieController.MakeAnimation_criticaldeath(); var animation : TAnimation; i : Integer; begin for i := 0 to 7 do begin animation := fAnimationArchive.AddAnimation(ZombieAnimationAction[Ord(TZombieAction.Criticaldeath)] + ZombieAnimationDirection[i]); animation.AddFrame(TFrame.Create(28 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(29 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(30 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(31 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(32 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(33 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(34 + i *36,TPositionRecord.Create(0,0),0.11)); animation.AddFrame(TFrame.Create(35 + i *36,TPositionRecord.Create(0,0),0.11)); end; end; procedure TZombieController.MakeAnimation_selected(); var animation : TAnimation; begin animation := fAnimationArchive.AddAnimation(ZombieAnimationSelected); animation.AddFrame(TFrame.Create(36 + 7 * 36,TPositionRecord.Create(0,0),0.11)); end; procedure TZombieController.MakeAnimation_destination(); var animation : TAnimation; begin animation := fAnimationArchive.AddAnimation(ZombieAnimationDestination); animation.AddFrame(TFrame.Create(37 + 7 * 36,TPositionRecord.Create(0,0),0.11)); end; function TZombieController.PositionCollisionWithCharacter(aZombie: TZombieCharacter; aMapPosition, collisionPosition: TPositionRecord): Boolean; var x,y : Integer; begin x := aZombie.GetPosition().X - aMapPosition.X + (CHARACTER_WIDTH div 2); y := aZombie.GetPosition().Y - aMapPosition.Y + (CHARACTER_HEIGHT div 2); Result := (x - 20 < collisionPosition.X) and (collisionPosition.X < x + 20) and (y - 50 < collisionPosition.Y) and (collisionPosition.Y < y + 50); end; function TZombieController.RectangleCollisionWithCharacter(aZombie: TZombieCharacter; aMapPosition, aLeftTopPosition, aRightBottomPosition: TPositionRecord): Boolean; var swap : Integer; x,y : Integer; begin //Assure the corner positions are correct if(aLeftTopPosition.X > aRightBottomPosition.X) then begin swap := aLeftTopPosition.X; aLeftTopPosition.X := aRightBottomPosition.X; aRightBottomPosition.X := swap; end; if(aLeftTopPosition.Y > aRightBottomPosition.Y) then begin swap := aLeftTopPosition.Y; aLeftTopPosition.Y := aRightBottomPosition.Y; aRightBottomPosition.Y := swap; end; x := aZombie.GetPosition().X - aMapPosition.X + (CHARACTER_WIDTH div 2); y := aZombie.GetPosition().Y - aMapPosition.Y + (CHARACTER_HEIGHT div 2); Result := (x > aLeftTopPosition.X - 20) and ( x < aRightBottomPosition.X + 20) and (y > aLeftTopPosition.Y - 20) and ( y < aRightBottomPosition.Y + 20); end; constructor TZombieController.Create(aAnimationArchive: TAnimationArchive); begin fAnimationArchive := aAnimationArchive; MakeAnimation_stance(); MakeAnimation_lurch(); MakeAnimation_slam(); MakeAnimation_bite(); MakeAnimation_block(); MakeAnimation_hitndie(); MakeAnimation_criticaldeath(); MakeAnimation_selected(); MakeAnimation_destination(); end; destructor TZombieController.Destroy; begin fAnimationArchive.Free(); end; procedure TZombieController.DrawCharacter(aZombie: TZombieCharacter; aCanvas: TCanvas; aMapPosition: TPositionRecord); var animationName : string; x,y : Integer; begin animationName := ZombieAnimationAction[Ord(aZombie.GetAction())] + ZombieAnimationDirection[Ord(aZombie.GetDirection())]; x := aZombie.GetPosition().X - aMapPosition.X; y := aZombie.GetPosition().Y - aMapPosition.Y; if(aZombie.GetSelected())then begin if(aZombie.GetState() = TZombieState.Ordered) then fAnimationArchive.DrawAnimation(ZombieAnimationDestination,aCanvas,aZombie.GetDestination().X - aMapPosition.X,aZombie.GetDestination().Y - aMapPosition.Y, aZombie.GetTotalElapsedSeconds()); fAnimationArchive.DrawAnimation(ZombieAnimationSelected,aCanvas,x,y, aZombie.GetTotalElapsedSeconds()); end; fAnimationArchive.DrawAnimation(animationName,aCanvas,x,y, aZombie.GetTotalElapsedSeconds()); end; function TZombieController.GetAnimationArchive: TAnimationArchive; begin Result := fAnimationArchive; end; end.
unit RasHelperClasses; interface uses Windows, Messages, Classes, SysUtils, Forms, Contnrs, Ras, RasError, RasUtils; type TRasBaseList = class(TPersistent) private FOnRefresh: TNotifyEvent; function GetCount: Integer; protected FItems: TObjectList; procedure DoRefresh; dynamic; public constructor Create; destructor Destroy; override; procedure Refresh; dynamic; abstract; property Count: Integer read GetCount; property OnRefresh: TNotifyEvent read FOnRefresh write FOnRefresh; end; TRasPhonebook = class; TRasConnectionItem = class; TRasConnection = class private const MAX_BUSYTIMEOUT: Cardinal = 30000; private FBusy: Boolean; FRasConn: TRasConn; FChanged: Boolean; FBusyEndTime: Cardinal; private function GetHandle: THandle; procedure SetHandle(const Value: THandle); private function GetDeviceName: String; function GetDeviceType: String; function GetName: String; function GetIsConnected: Boolean; function GetConnStatus: TRasConnStatus; function GetConnStatusStr: String; function GetIPAddress: string; procedure SetRasConn(const Value: TRasConn); procedure SetBusy(const Value: Boolean); function GetBusy: Boolean; public constructor Create; public property Busy: Boolean read GetBusy write SetBusy; property Handle: THandle read GetHandle write SetHandle; public procedure HangUp(WaitToCompleteSec: Integer = 5); property ConnStatus: TRasConnStatus read GetConnStatus; property ConnStatusStr: String read GetConnStatusStr; property DeviceName: String read GetDeviceName; property DeviceType: String read GetDeviceType; property Connected: Boolean read GetIsConnected; property Name: String read GetName; property RasConn: TRasConn read FRasConn write SetRasConn; property IPAddress: string read GetIPAddress; property Changed: Boolean read FChanged write FChanged; end; TRasPhonebookEntry = class(TPersistent) private FName: String; FOwner: TRasPhonebook; FPasswordStored: Boolean; FConnection: TRasConnection; FNeedConnect: Boolean; procedure SetCallbackNumber(const Value: String); procedure SetDomain(const Value: String); procedure SetPassword(const Value: String); procedure SetPhoneNumber(const Value: String); procedure SetUserName(const Value: String); function GetCallbackNumber: String; function GetDomain: String; function GetPassword: String; function GetPhoneNumber: String; function GetUserName: String; function GetDialParams: TRasDialParams; procedure SetDialParams(const Value: TRasDialParams); function GetPhoneBook: String; public constructor Create(AOwner: TRasPhonebook; const AName: String); destructor Destroy; override; procedure DeleteEntry; procedure EditEntry(Wnd: HWND = 0); function GetProperties(var Value: PRasEntry): DWORD; procedure RenameEntry(const NewName: String); function SetProperties(const Value: PRasEntry; Size: DWORD; FreeValue: Boolean = False): DWORD; property CallbackNumber: String read GetCallbackNumber write SetCallbackNumber; property DialParams: TRasDialParams read GetDialParams write SetDialParams; property Domain: String read GetDomain write SetDomain; property Password: String read GetPassword write SetPassword; property PasswordStored: Boolean read FPasswordStored write FPasswordStored; property PhoneBook: String read GetPhoneBook; property PhoneNumber: String read GetPhoneNumber write SetPhoneNumber; property Name: String read FName; property UserName: String read GetUserName write SetUserName; property NeedConnect: Boolean read FNeedConnect write FNeedConnect; property Connection: TRasConnection read FConnection write FConnection; end; TRasPhonebook = class(TRasBaseList) private FPBK: PChar; FPhoneBook: String; function GetItems(Index: Integer): TRasPhonebookEntry; procedure SetPhoneBook(const Value: String); protected procedure AssignTo(Dest: TPersistent); override; public procedure CreateEntryInteractive(Wnd: HWND = 0); procedure Refresh; override; function ValidateName(const EntryName: String): Boolean; property Items[Index: Integer]: TRasPhonebookEntry read GetItems; default; property PhoneBook: String read FPhoneBook write SetPhoneBook; end; TRasConnectionsList = class; TRasConnectionItem = class(TObject) private FOwner: TRasConnectionsList; FRasConn: TRasConn; function GetDeviceName: String; function GetDeviceType: String; function GetName: String; function GetIsConnected: Boolean; function GetConnStatus: TRasConnStatus; function GetConnStatusStr: String; function GetIPAddress: string; public constructor Create(AOwner: TRasConnectionsList; ARasConn: TRasConn); procedure HangUp(WaitToCompleteSec: Integer = 5); property ConnStatus: TRasConnStatus read GetConnStatus; property ConnStatusStr: String read GetConnStatusStr; property DeviceName: String read GetDeviceName; property DeviceType: String read GetDeviceType; property IsConnected: Boolean read GetIsConnected; property Name: String read GetName; property RasConn: TRasConn read FRasConn; property IPAddress: string read GetIPAddress; end; TRasConnectionsList = class(TRasBaseList) private function GetItems(Index: Integer): TRasConnectionItem; protected procedure AssignTo(Dest: TPersistent); override; public procedure Refresh; override; property Items[Index: Integer]: TRasConnectionItem read GetItems; default; end; TRasDialerEvent = procedure(Sender: TObject; State: TRasConnState; ErrorCode: DWORD) of object; TRasDialer = class(TPersistent) private FConnHandle: THRasConn; FNotifyMessage: DWORD; FNotifyWnd: HWND; FParams: TRasDialParams; FOnNotify: TRasDialerEvent; function GetActive: Boolean; function GetPassword: String; function GetPhoneNumber: String; function GetUserName: String; procedure SetPassword(const Value: String); procedure SetPhoneNumber(const Value: String); procedure SetUserName(const Value: String); protected procedure DoDialEvent(Message: TMessage); procedure WndProc(var Message: TMessage); public procedure Assign(Source: TPersistent); override; constructor Create; destructor Destroy; override; procedure Dial; procedure HangUp; property Active: Boolean read GetActive; property ConnHandle: THRasConn read FConnHandle; property Params: TRasDialParams read FParams write FParams; property Password: String read GetPassword write SetPassword; property PhoneNumber: String read GetPhoneNumber write SetPhoneNumber; property UserName: String read GetUserName write SetUserName; property OnNotify: TRasDialerEvent read FOnNotify write FOnNotify; end; TRasDevicesList = array of TRasDevInfo; function GetRasDevicesList: TRasDevicesList; implementation function GetRasDevicesList: TRasDevicesList; var BufSize, NumberOfEntries, Res: DWORD; begin SetLength(Result, 1); Result[0].dwSize := Sizeof(TRasDevInfo); BufSize := Sizeof(TRasDevInfo); Res := RasEnumDevices(@Result[0], BufSize, NumberOfEntries); if Res = ERROR_BUFFER_TOO_SMALL then begin SetLength(Result, BufSize div Sizeof(TRasDevInfo)); Result[0].dwSize := Sizeof(TRasDevInfo); Res := RasEnumDevices(@Result[0], BufSize, NumberOfEntries); end; RasCheck(Res); end; procedure ConnectionHangUp(ConnHandle: THRasConn; WaitToCompleteSec: Integer); var Status: TRasConnStatus; Res: DWORD; begin RasCheck(RasHangUp(ConnHandle)); ZeroMemory(@Status, Sizeof(Status)); Status.dwSize := Sizeof(Status); WaitToCompleteSec := WaitToCompleteSec * 10; repeat Sleep(100); Dec(WaitToCompleteSec); Res := RasGetConnectStatus(ConnHandle, Status); until (WaitToCompleteSec = 0) or (Res = ERROR_INVALID_HANDLE); end; { TRasBaseList } constructor TRasBaseList.Create; begin inherited Create; FItems := TObjectList.Create(True); Refresh; end; destructor TRasBaseList.Destroy; begin FItems.Free; inherited; end; procedure TRasBaseList.DoRefresh; begin if Assigned(FOnRefresh) then FOnRefresh(Self); end; function TRasBaseList.GetCount: Integer; begin Result := FItems.Count; end; { TRasPhonebookEntry } constructor TRasPhonebookEntry.Create(AOwner: TRasPhonebook; const AName: String); begin inherited Create; FName := AName; FOwner := AOwner; FConnection := TRasConnection.Create; FNeedConnect := False; end; procedure TRasPhonebookEntry.DeleteEntry; begin RasCheck(RasDeleteEntry(FOwner.FPBK, PChar(FName))); FOwner.Refresh; end; destructor TRasPhonebookEntry.Destroy; begin FreeAndNil(FConnection); inherited; end; procedure TRasPhonebookEntry.EditEntry(Wnd: HWND); begin RasCheck(RasEditPhonebookEntry(Wnd, FOwner.FPBK, PChar(FName))); FOwner.Refresh; end; function TRasPhonebookEntry.GetCallbackNumber: String; begin Result := GetDialParams.szCallbackNumber; end; function TRasPhonebookEntry.GetDialParams: TRasDialParams; var B: BOOL; begin ZeroMemory(@Result, Sizeof(Result)); Result.dwSize := Sizeof(Result); StrPCopy(Result.szEntryName, FName); RasCheck(RasGetEntryDialParams(FOwner.FPBK, Result, B)); FPasswordStored := B; end; function TRasPhonebookEntry.GetDomain: String; begin Result := GetDialParams.szDomain; end; function TRasPhonebookEntry.GetPassword: String; begin Result := GetDialParams.szPassword; end; function TRasPhonebookEntry.GetPhoneBook: String; begin Result := FOwner.FPhoneBook; end; function TRasPhonebookEntry.GetPhoneNumber: String; var Prop: PRasEntry; begin GetProperties(Prop); Result := Prop^.szLocalPhoneNumber; FreeMem(Prop); end; function TRasPhonebookEntry.GetProperties(var Value: PRasEntry): DWORD; var Res: DWORD; begin Result := 0; Res := RasGetEntryProperties(FOwner.FPBK, PWideChar(FName), nil, Result, nil, nil); if Res <> ERROR_BUFFER_TOO_SMALL then RasCheck(Res); Value := AllocMem(Result); Value^.dwSize := Sizeof(TRasEntry); Res := RasGetEntryProperties(FOwner.FPBK, PWideChar(FName), Value, Result, nil, nil); if Res <> SUCCESS then begin FreeMem(Value); RasCheck(Res); end; end; function TRasPhonebookEntry.GetUserName: String; begin Result := GetDialParams.szUserName; end; procedure TRasPhonebookEntry.RenameEntry(const NewName: String); begin RasCheck(RasRenameEntry(FOwner.FPBK, PChar(FName), PChar(NewName))); FOwner.Refresh; end; procedure TRasPhonebookEntry.SetCallbackNumber(const Value: String); var P: TRasDialParams; begin P := GetDialParams; StrPCopy(P.szCallbackNumber, Value); SetDialParams(P); end; procedure TRasPhonebookEntry.SetDialParams(const Value: TRasDialParams); begin RasCheck(RasSetEntryDialParams(FOwner.FPBK, @Value, FPasswordStored)); end; procedure TRasPhonebookEntry.SetDomain(const Value: String); var P: TRasDialParams; begin P := GetDialParams; StrPCopy(P.szDomain, Value); SetDialParams(P); end; procedure TRasPhonebookEntry.SetPassword(const Value: String); var P: TRasDialParams; begin P := GetDialParams; StrPCopy(P.szPassword, Value); SetDialParams(P); end; procedure TRasPhonebookEntry.SetPhoneNumber(const Value: String); var Prop: PRasEntry; Size: DWORD; begin Size := GetProperties(Prop); StrPCopy(Prop^.szLocalPhoneNumber, Value); SetProperties(Prop, Size, True); end; function TRasPhonebookEntry.SetProperties(const Value: PRasEntry; Size: DWORD; FreeValue: Boolean): DWORD; begin Result := RasSetEntryProperties(FOwner.FPBK, PChar(FName), Value, Size, nil, 0); if FreeValue then begin FreeMem(Value); RasCheck(Result); end; end; procedure TRasPhonebookEntry.SetUserName(const Value: String); var P: TRasDialParams; begin P := GetDialParams; StrPCopy(P.szUserName, Value); SetDialParams(P); end; { TRasPhonebook } procedure TRasPhonebook.AssignTo(Dest: TPersistent); var I: Integer; begin if Dest is TStrings then begin with TStrings(Dest) do begin BeginUpdate; try Clear; for I := 0 to FItems.Count - 1 do AddObject(Items[I].Name, Items[I]); finally EndUpdate; end; end; end else inherited; end; procedure TRasPhonebook.CreateEntryInteractive(Wnd: HWND); begin RasCheck(RasCreatePhonebookEntry(Wnd, FPBK)); Refresh; end; function TRasPhonebook.GetItems(Index: Integer): TRasPhonebookEntry; begin Result := TRasPhonebookEntry(FItems[Index]); end; procedure TRasPhonebook.Refresh; var Entries, P: PRasEntryName; BufSize, NumberOfEntries, Res: DWORD; I: Integer; procedure InitFirstEntry; begin ZeroMemory(Entries, BufSize); Entries^.dwSize := Sizeof(TRasEntryName); NumberOfEntries := 0; end; begin FItems.Clear; New(Entries); BufSize := Sizeof(TRasEntryName); InitFirstEntry; Res := RasEnumEntries(nil, FPBK, Entries, BufSize, NumberOfEntries); if Res = ERROR_BUFFER_TOO_SMALL then begin ReallocMem(Entries, BufSize); InitFirstEntry; Res := RasEnumEntries(nil, FPBK, Entries, BufSize, NumberOfEntries); end; try RasCheck(Res); P := Entries; for I := 1 to NumberOfEntries do begin FItems.Add(TRasPhonebookEntry.Create(Self, P^.szEntryName)); Inc(P); end; DoRefresh; finally FreeMem(Entries); end; end; procedure TRasPhonebook.SetPhoneBook(const Value: String); begin if FPhoneBook <> Value then begin FPhoneBook := Value; FPBK := PChar(FPhoneBook); if FPBK^ = #0 then FPBK := nil; Refresh; end; end; function TRasPhonebook.ValidateName(const EntryName: String): Boolean; var Res: DWORD; begin Result := False; Res := RasValidateEntryName(FPBK, PChar(EntryName)); case Res of ERROR_SUCCESS, ERROR_ALREADY_EXISTS: Result := True; ERROR_INVALID_NAME: Result := False; else RasCheck(Res); end; end; { TRasConnectionItem } constructor TRasConnectionItem.Create(AOwner: TRasConnectionsList; ARasConn: TRasConn); begin inherited Create; FOwner := AOwner; FRasConn := ARasConn; end; function TRasConnectionItem.GetConnStatus: TRasConnStatus; begin ZeroMemory(@Result, Sizeof(Result)); Result.dwSize := Sizeof(Result); RasCheck(RasGetConnectStatus(FRasConn.hrasconn, Result)); end; function TRasConnectionItem.GetConnStatusStr: String; begin with GetConnStatus do Result := RasConnStatusString(rasconnstate, dwError); end; function TRasConnectionItem.GetDeviceName: String; begin Result := FRasConn.szDeviceName; end; function TRasConnectionItem.GetDeviceType: String; begin Result := FRasConn.szDeviceType; end; function TRasConnectionItem.GetIsConnected: Boolean; begin Result := (GetConnStatus.rasconnstate = RASCS_DeviceConnected); end; function TRasConnectionItem.GetName: String; begin Result := FRasConn.szEntryName; end; function TRasConnectionItem.GetIPAddress: string; var dwSize: Cardinal; RASpppIP: TPRasPppIP; begin Result := ''; dwSize := Sizeof(RASpppIP); RASpppIP.dwSize := Sizeof(RASpppIP); If RASGetProjectionInfo(FRasConn.hrasconn, RASP_PPPIP, @RASpppIP, dwSize) = 0 Then Result := strPas(RASpppIP.szIPAddress); end; procedure TRasConnectionItem.HangUp(WaitToCompleteSec: Integer); begin ConnectionHangUp(FRasConn.hrasconn, WaitToCompleteSec); FOwner.Refresh; end; { TRasConnectionsList } procedure TRasConnectionsList.AssignTo(Dest: TPersistent); var I: Integer; begin if Dest is TStrings then begin with TStrings(Dest) do begin BeginUpdate; try Clear; for I := 0 to FItems.Count - 1 do AddObject(Items[I].Name, Items[I]); finally EndUpdate; end; end; end else inherited; end; function TRasConnectionsList.GetItems(Index: Integer): TRasConnectionItem; begin Result := TRasConnectionItem(FItems[Index]); end; procedure TRasConnectionsList.Refresh; var Entries, P: PRasConn; BufSize, NumberOfEntries, Res: DWORD; I: Integer; procedure InitFirstEntry; begin ZeroMemory(Entries, BufSize); Entries^.dwSize := Sizeof(Entries^); end; begin FItems.Clear; New(Entries); BufSize := Sizeof(Entries^); InitFirstEntry; Res := RasEnumConnections(Entries, BufSize, NumberOfEntries); if Res = ERROR_BUFFER_TOO_SMALL then begin ReallocMem(Entries, BufSize); InitFirstEntry; Res := RasEnumConnections(Entries, BufSize, NumberOfEntries); end; try RasCheck(Res); P := Entries; for I := 1 to NumberOfEntries do begin FItems.Add(TRasConnectionItem.Create(Self, P^)); Inc(P); end; DoRefresh; finally FreeMem(Entries); end; end; { TRasDialer } procedure TRasDialer.Assign(Source: TPersistent); begin if Source is TRasPhonebookEntry then with TRasPhonebookEntry(Source) do begin FParams := DialParams; FParams.szEntryName := ''; Self.PhoneNumber := PhoneNumber; end else inherited; end; constructor TRasDialer.Create; begin inherited Create; FNotifyMessage := RegisterWindowMessage(RASDIALEVENT); if FNotifyMessage = 0 then FNotifyMessage := WM_RASDIALEVENT; FNotifyWnd := AllocateHWnd(WndProc); ZeroMemory(@FParams, Sizeof(FParams)); FParams.dwSize := Sizeof(FParams); end; destructor TRasDialer.Destroy; begin DeallocateHWnd(FNotifyWnd); inherited; end; procedure TRasDialer.Dial; begin FConnHandle := 0; RasCheck(RasDial(nil, nil, @FParams, $FFFFFFFF, Pointer(FNotifyWnd), FConnHandle)); end; procedure TRasDialer.DoDialEvent(Message: TMessage); begin with Message do begin if WParam = RASCS_Disconnected then FConnHandle := 0; if Assigned(FOnNotify) then FOnNotify(Self, WParam, LParam); end; end; function TRasDialer.GetActive: Boolean; begin Result := FConnHandle <> 0; end; function TRasDialer.GetPassword: String; begin Result := FParams.szPassword; end; function TRasDialer.GetPhoneNumber: String; begin Result := FParams.szPhoneNumber; end; function TRasDialer.GetUserName: String; begin Result := FParams.szUserName; end; procedure TRasDialer.HangUp; begin ConnectionHangUp(FConnHandle, 3); end; procedure TRasDialer.SetPassword(const Value: String); begin StrPCopy(FParams.szPassword, Value); end; procedure TRasDialer.SetPhoneNumber(const Value: String); begin StrPCopy(FParams.szPhoneNumber, Value); end; procedure TRasDialer.SetUserName(const Value: String); begin StrPCopy(FParams.szUserName, Value); end; procedure TRasDialer.WndProc(var Message: TMessage); begin with Message do if Msg = FNotifyMessage then try DoDialEvent(Message); except Application.HandleException(Self); end else Result := DefWindowProc(FNotifyWnd, Msg, WParam, LParam); end; { TRasConnection } constructor TRasConnection.Create; begin FBusy := False; FRasConn.hrasconn := 0; FChanged := False; end; function TRasConnection.GetBusy: Boolean; begin if FBusy and (GetTickCount > FBusyEndTime) then FBusy := False; Result := FBusy; end; function TRasConnection.GetConnStatus: TRasConnStatus; begin ZeroMemory(@Result, Sizeof(Result)); Result.dwSize := Sizeof(Result); RasCheck(RasGetConnectStatus(FRasConn.hrasconn, Result)); end; function TRasConnection.GetConnStatusStr: String; begin with GetConnStatus do Result := RasConnStatusString(rasconnstate, dwError); end; function TRasConnection.GetDeviceName: String; begin Result := FRasConn.szDeviceName; end; function TRasConnection.GetDeviceType: String; begin Result := FRasConn.szDeviceType; end; function TRasConnection.GetHandle: THandle; begin Result := FRasConn.hrasconn; end; function TRasConnection.GetIPAddress: string; var dwSize: Cardinal; RASpppIP: TPRasPppIP; begin Result := ''; dwSize := Sizeof(RASpppIP); RASpppIP.dwSize := Sizeof(RASpppIP); If RASGetProjectionInfo(FRasConn.hrasconn, RASP_PPPIP, @RASpppIP, dwSize) = 0 Then Result := strPas(RASpppIP.szIPAddress); end; function TRasConnection.GetIsConnected: Boolean; begin Result := Handle <> 0; end; function TRasConnection.GetName: String; begin Result := FRasConn.szEntryName; end; procedure TRasConnection.HangUp(WaitToCompleteSec: Integer); begin if Handle <> 0 then begin ConnectionHangUp(Handle, WaitToCompleteSec); Handle := 0; end; end; procedure TRasConnection.SetBusy(const Value: Boolean); begin FBusy := Value; FBusyEndTime := GetTickCount + MAX_BUSYTIMEOUT; end; procedure TRasConnection.SetHandle(const Value: THandle); begin if Value <> FRasConn.hrasconn then FChanged := True; FRasConn.hrasconn := Value; end; procedure TRasConnection.SetRasConn(const Value: TRasConn); begin Handle := Value.hrasconn; FRasConn := Value; end; end.
unit LaySwitch; interface uses Windows, Messages, SysUtils, Classes, Controls, StdCtrls, Forms, Dialogs, extctrls, typinfo; Const BELARUSSIAN = LANG_BELARUSIAN; RUS = LANG_RUSSIAN; ENG = LANG_ENGLISH; BLR = LANG_BELARUSIAN; type TOnLayoutChange = procedure(Sender: tobject;Lang: string) of object; TLanguageKeyBord = (NONE, ENGLISH, RUSSIAN, BELARUSIAN); TEvent = class private FNotifyEvent: TNotifyEvent; public constructor Create(ANotifyEvent: TNotifyEvent); property NotifyEvent: TNotifyEvent read FNotifyEvent; end; TOnEnterList = class(TStringList) public function AddObject(const S: string; const ANotifyEvent: TNotifyEvent): Integer; reintroduce;virtual; procedure Delete(Index: Integer);override; end; TOnExitList = TOnEnterList; TLayoutSwitcher = Class(TComponent) private FCompsList: TStringList; FOnEnterList: TOnEnterList; FOnExitList: TOnExitList; FOnLayoutChange: TOnLayoutChange; FRestoreLayoutOnExit: boolean; class var CurentLanguage: Hkl; class var OldOnActivate: TNotifyEvent; class var OldOnDeactivate: TNotifyEvent; class var HLANG_ENGLISH: HKL; class var HLANG_RUSSIAN: HKL; class var HLANG_BELARUSIAN: HKL; class var LangDefault: integer; protected class Function GetKblLayoutName: String; procedure SetSwitch(Sender: TWinControl; Lang: integer); procedure SetRussianLayout(Sender: Tobject); procedure SetBelaRusianLayout(Sender: Tobject); procedure SetEnglishLayout(Sender: Tobject); procedure RestoreLayout(Sender: Tobject); class Function PrimaryLangId(Lang: Integer): Integer; Function SubLangId(Lang: Integer): Integer; class Function GetLangId: Integer; class Function MakeLangId(PLang, SLang: Integer): String; procedure DoOldOnEnter(Sender: TObject); procedure DoOldOnExit(Sender: TObject); class procedure OnApplicationDeactivate(Sender: TObject); class procedure OnApplicationActivate(Sender: TObject); public Constructor Create(AOwner: TComponent); override; Destructor Destroy; override; procedure Add(Accessor: TWinControl; Lang: integer); overload; procedure Add(Accessor: TWinControl; Lang: TLanguageKeyBord); overload; procedure Remove(Accessor: TWinControl); class procedure SwitchToRussian; class procedure SwitchToBelarusian; class procedure SwitchToEnglish; function GetActiveLang: string; published Property RestoreLayoutOnExit: boolean read FRestoreLayoutOnExit write FRestoreLayoutOnExit; property OnLayoutChange: TOnLayoutChange read FOnLayoutChange write FOnLayoutChange; end; function isList(AList: array of HKL;Lang: HKL): boolean; implementation var AList: array[0..254] of Hkl; const KLF_SETFORPROCESS = $100; function HexToInt(HexNum: string): LongInt; begin Result := StrToInt('$' + HexNum); end; function MakeLangId(PLang, SLang: byte): string; begin MakeLangId := IntToHex(((SLang shl 10) or PLang), 8); end; function TOnEnterList.AddObject(const S: string;const ANotifyEvent: TNotifyEvent): Integer; begin result := inherited AddObject(S,TEvent.Create(ANotifyEvent)); end; constructor TEvent.Create(ANotifyEvent: TNotifyEvent); begin FNotifyEvent := ANotifyEvent; end; procedure TOnEnterList.Delete(Index: Integer); begin (Objects[Index] as TEvent).Free; inherited; end; procedure TLayoutSwitcher.Add(Accessor: TWinControl; Lang: TLanguageKeyBord); begin case Lang of ENGLISH: Add(Accessor, LANG_ENGLISH); RUSSIAN: Add(Accessor, LANG_RUSSIAN); BELARUSIAN: Add(Accessor, LANG_BELARUSIAN); else begin Raise Exception.Create('Не определен язык!'); end; end; end; Constructor TLayoutSwitcher.Create(AOwner: TComponent); begin inherited Create(Aowner); FCompsList := TStringList.Create; FCompsList.Sorted := true; FCompsList.Duplicates := dupError; FOnEnterList := TOnEnterList.create; FOnEnterList.Sorted := true; FOnEnterList.Duplicates := dupError; FOnExitList := TOnExitList.create; FOnExitList.Sorted := true; FOnExitList.Duplicates := dupError; end; class Function TLayoutSwitcher.MakeLangId(PLang, SLang: Integer): String; begin MakeLangId := IntToHex(((SLang Shl 10) OR PLang), 8); end; class procedure TLayoutSwitcher.OnApplicationActivate(Sender: TObject); begin case CurentLanguage of BLR: SwitchToBelarusian; RUS: SwitchToRussian; ENG: SwitchToEnglish; end; if Assigned(OldOnActivate) then OldOnActivate(Sender); end; class procedure TLayoutSwitcher.OnApplicationDeactivate(Sender: TObject); begin CurentLanguage := GetLangId; case LangDefault of BLR: SwitchToBelarusian; RUS: SwitchToRussian; ENG: SwitchToEnglish; end; if not isList(AList,HLANG_ENGLISH) then begin HLANG_ENGLISH := 0; UnloadKeyboardLayout(HLANG_ENGLISH); end; if not isList(AList,HLANG_RUSSIAN) then begin UnloadKeyboardLayout(HLANG_RUSSIAN); HLANG_RUSSIAN := 0; end; if not isList(AList,HLANG_BELARUSIAN) then begin UnloadKeyboardLayout(HLANG_BELARUSIAN); HLANG_BELARUSIAN := 0; end; if Assigned(OldOnDeactivate) then OldOnDeactivate(Sender); end; function TLayoutSwitcher.GetActiveLang: string; var id: integer; begin id := getlangid; case id of BLR: getactivelang := 'BE'; RUS: getactivelang := 'RU'; ENG: getactivelang := 'EN'; end; end; class Function TLayoutSwitcher.PrimaryLangId(Lang: Integer): Integer; begin PrimaryLangId := Lang AND $3FF; end; Function TLayoutSwitcher.SubLangId(Lang: Integer): Integer; begin SubLangId := Lang Shr 10; end; class Function TLayoutSwitcher.GetLangId: Integer; begin GetLangId := PrimaryLangId(HexToInt(GetKblLayoutName)); end; procedure TLayoutSwitcher.RestoreLayout; var lang: HKL; begin case getlangid of ENG: lang := HLANG_ENGLISH; RUS: lang := HLANG_RUSSIAN; BLR: lang := HLANG_BELARUSIAN; else lang := HLANG_ENGLISH; end; ActivateKeyboardLayout(lang, KLF_SETFORPROCESS); DoOldOnExit(Sender); end; procedure TLayoutSwitcher.SetRussianLayout(Sender: Tobject); begin SwitchToRussian; DoOldOnEnter(Sender); if Assigned(FOnLayoutChange) then FOnLayoutChange(Self, 'RU'); end; procedure TLayoutSwitcher.SetBelaRusianLayout(Sender: Tobject); begin SwitchToBelarusian; DoOldOnEnter(Sender); end; procedure TLayoutSwitcher.SetEnglishLayout(Sender: Tobject); begin SwitchToEnglish; DoOldOnEnter(Sender); if Assigned(FOnLayoutChange) then FOnLayoutChange(Self,'EN'); end; Destructor TLayoutSwitcher.Destroy; begin fcompslist.free; fonenterlist.free; fonexitlist.free; inherited Destroy; end; class procedure TLayoutSwitcher.SwitchToRussian; begin if HLANG_RUSSIAN = 0 then HLANG_RUSSIAN := LoadKeyboardLayout(pchar(makelangid(integer(LANG_RUSSIAN), sublang_default)), KLF_SETFORPROCESS ); ActivateKeyboardLayout(HLANG_RUSSIAN, KLF_SETFORPROCESS); end; class procedure TLayoutSwitcher.SwitchToBelarusian; begin if HLANG_BELARUSIAN=0 then HLANG_BELARUSIAN := LoadKeyboardLayout(pchar(makelangid(integer(LANG_BELARUSIAN), sublang_default)), KLF_SETFORPROCESS ); ActivateKeyboardLayout(HLANG_BELARUSIAN, KLF_SETFORPROCESS); end; class procedure TLayoutSwitcher.SwitchToEnglish; begin if HLANG_ENGLISH=0 then HLANG_ENGLISH := LoadKeyboardLayout(pchar(makelangid(integer(LANG_ENGLISH), sublang_default)), KLF_SETFORPROCESS); ActivateKeyboardLayout(HLANG_ENGLISH, KLF_SETFORPROCESS); end; class Function TLayoutSwitcher.GetKblLayoutName: String; Var KLN: PChar; begin KLN := StrAlloc(KL_NAMELENGTH+1); GetKeyboardLayoutName(KLN); GetKblLayoutName := StrPas(KLN); StrDispose(KLN); end; procedure TLayoutSwitcher.SetSwitch(Sender: TWinControl; Lang: integer); Var a: integer; sender1: tcomponent; begin Case Lang of lang_russian: begin if (sender is tcustomform) or (sender is tcustompanel) then begin for a := 0 to sender.Componentcount-1 do begin sender1 := sender.components[a]; if (getpropinfo(sender1,'OnEnter')<>nil) and (getpropinfo(sender1,'OnExit')<>nil) then begin TEdit(Sender1).OnEnter := SetRussianLayout; if FRestoreLayoutOnExit then TEdit(Sender1).OnExit := RestoreLayout; end; end; end else if (getpropinfo(sender,'OnEnter')<>nil) and (getpropinfo(sender,'OnExit')<>nil) then begin TEdit(Sender).OnEnter := setRussianLayout; if FRestoreLayoutOnExit then TEdit(Sender).OnExit := RestoreLayout; end; end; lang_belarusian: begin if (sender is tcustomform) or (sender is tcustompanel) then begin for a := 0 to sender.ComponentCount-1 do begin sender1 := sender.components[a]; if (getpropinfo(sender1,'OnEnter')<>nil) and (getpropinfo(sender1,'OnExit')<>nil) then begin TEdit(Sender1).OnEnter := setBelarusianLayout; if FRestoreLayoutOnExit then TEdit(Sender1).OnExit := RestoreLayout; end; end; end else if (getpropinfo(sender,'OnEnter')<>nil) and (getpropinfo(sender,'OnExit')<>nil) then begin TEdit(Sender).OnEnter := setBelarusianLayout; if FRestoreLayoutOnExit then TEdit(Sender).OnExit := RestoreLayout; end; end; lang_English: begin if (sender is tcustomform) or (sender is tcustompanel) then begin for a := 0 to sender.ComponentCount-1 do begin sender1 := sender.components[a]; if (getpropinfo(sender1,'OnEnter')<>nil) and (getpropinfo(sender1,'OnExit')<>nil) then begin TEdit(Sender1).OnEnter := setEnglishLayout; if FRestoreLayoutOnExit then TEdit(Sender1).OnExit := RestoreLayout; end; end; end else if (getpropinfo(sender,'OnEnter')<>nil) and (getpropinfo(sender,'OnExit')<>nil) then begin TEdit(Sender).OnEnter := setEnglishLayout; if FRestoreLayoutOnExit then TEdit(Sender).OnExit := RestoreLayout; end; end; end; end; procedure TLayoutSwitcher.Add(Accessor: TWinControl; Lang: integer); Var EdTmp: TEdit; index: integer; begin if (lang<>lang_russian) and (lang<>lang_english) and (lang<>lang_belarusian) then begin messagedlg('Неизвестный язык для '+accessor.name+'! ('+inttostr(lang)+')',mterror,[mbok],0); exit; end; if FCompsList.Find(accessor.name, index) then exit; EdTmp := TEdit(accessor); FCompsList.add(accessor.name); if assigned(edtmp.OnEnter) then FOnEnterList.AddObject(accessor.name,edtmp.OnEnter); if assigned(edtmp.OnExit) then FOnExitList.AddObject(accessor.name,edtmp.OnExit); SetSwitch(Accessor, Lang); end; procedure TLayoutSwitcher.Remove(Accessor: TWinControl); Var EdTmp: TEdit; ind: integer; begin EdTmp := TEdit(Accessor); if FCompsList.Find(EdTmp.Name,ind) then begin EdTmp.OnEnter := nil; FCompsList.Delete(ind); end; if FonenterList.Find(EdTmp.Name,ind) then FonenterList.Delete(ind); if FonexitList.Find(EdTmp.Name,ind) then FonexitList.Delete(ind); end; procedure TLayoutSwitcher.DoOldOnEnter(sender: TObject); Var oldonenter: TNotifyEvent; index: integer; begin if FonenterList.Find(TWinControl(Sender).Name,index) then begin oldonenter := (FonenterList.Objects[index] as TEvent).NotifyEvent; if Assigned(oldonenter) then oldonenter(Sender); end; end; procedure TLayoutSwitcher.DoOldOnExit(sender: TObject); Var oldonexit: TNotifyEvent; index: integer; begin if FonexitList.Find(TWinControl(Sender).Name,index) then begin oldonexit := (FonexitList.Objects[Index] as TEvent).NotifyEvent;; if Assigned(oldonexit) then oldonexit(Sender); end; end; function isList(AList: array of HKL;Lang: HKL): boolean; var I: integer; begin result := false; for I := 0 to Length(AList)-1 do if AList[i]=Lang then result := true; end; initialization TLayoutSwitcher.LangDefault := TLayoutSwitcher.GetLangId ; GetKeyboardLayoutList(255, AList); TLayoutSwitcher.HLANG_RUSSIAN := 0; TLayoutSwitcher.HLANG_BELARUSIAN := 0; TLayoutSwitcher.HLANG_ENGLISH := 0; TLayoutSwitcher.OldOnActivate := Application.OnActivate; TLayoutSwitcher.OldOnDeactivate := Application.OnDeactivate; Application.OnDeactivate := TLayoutSwitcher.OnApplicationDeactivate; Application.OnActivate := TLayoutSwitcher.OnApplicationActivate; finalization if not isList(AList,TLayoutSwitcher.HLANG_ENGLISH) then UnloadKeyboardLayout(TLayoutSwitcher.HLANG_ENGLISH); if not isList(AList,TLayoutSwitcher.HLANG_RUSSIAN) then UnloadKeyboardLayout(TLayoutSwitcher.HLANG_RUSSIAN); if not isList(AList,TLayoutSwitcher.HLANG_BELARUSIAN) then UnloadKeyboardLayout(TLayoutSwitcher.HLANG_BELARUSIAN); Application.OnActivate := TLayoutSwitcher.OldOnActivate; Application.OnDeactivate := TLayoutSwitcher.OldOnDeactivate; end.
unit MFichas.Model.Usuario.Interfaces; interface uses MFichas.Controller.Usuario.Operacoes.Interfaces, MFichas.Model.Entidade.USUARIO, ORMBR.Container.ObjectSet.Interfaces, ORMBR.Container.DataSet.interfaces, FireDAC.Comp.Client; type iModelUsuario = interface; iModelUsuarioMetodos = interface; iModelUsuarioFuncoes = interface; iModelUsuarioFuncoesCadastrar = interface; iModelUsuarioFuncoesEditar = interface; iModelUsuarioFuncoesBuscar = interface; iModelUsuarioFuncoesValidarUES = interface; iModelUsuario = interface ['{CEAD7FDD-AE0F-4254-891E-7B61C3DDA754}'] function Metodos(AValue: iModelUsuarioMetodos): iModelUsuarioMetodos; function Funcoes : iModelUsuarioFuncoes; function Entidade : TUSUARIO; overload; function EntidadeFiscal : TUSUARIO; function Entidade(AEntidade: TUSUARIO): iModelUsuario; overload; function DAO : iContainerObjectSet<TUSUARIO>; function DAODataSet : iContainerDataSet<TUSUARIO>; end; iModelUsuarioMetodos = interface ['{86A4A224-05F9-43FF-A3BE-4D6C3760FC1E}'] function SetOperacoes(AOperacoes: iControllerUsuarioOperacoes): iModelUsuarioMetodos; function NextReponsibility(AValue: iModelUsuarioMetodos): iModelUsuarioMetodos; function LogoENomeDaFesta : iModelUsuarioMetodos; function AbrirCaixa : iModelUsuarioMetodos; function FecharCaixa : iModelUsuarioMetodos; function Suprimento : iModelUsuarioMetodos; function Sangria : iModelUsuarioMetodos; function CadastrarProdutos : iModelUsuarioMetodos; function CadastrarGrupos : iModelUsuarioMetodos; function CadastrarUsuarios : iModelUsuarioMetodos; function AcessarRelatorios : iModelUsuarioMetodos; function AcessarConfiguracoes : iModelUsuarioMetodos; function ExcluirProdutosPosImpressao: iModelUsuarioMetodos; function &End : iModelUsuario; end; iModelUsuarioFuncoes = interface ['{994A0965-45DD-434E-B0FF-65535C4ADED5}'] function Cadastrar : iModelUsuarioFuncoesCadastrar; function Editar : iModelUsuarioFuncoesEditar; function Buscar : iModelUsuarioFuncoesBuscar; function ValidarUsuarioESenha: iModelUsuarioFuncoesValidarUES; function &End : iModelUsuario; end; iModelUsuarioFuncoesCadastrar = interface ['{0AD7A26C-CDB9-4FB0-B935-B4ACBF1241F5}'] function Login(ALogin: String) : iModelUsuarioFuncoesCadastrar; function Nome(ANomeUsuario: String) : iModelUsuarioFuncoesCadastrar; function Senha(ASenha: String) : iModelUsuarioFuncoesCadastrar; function TipoUsuario(ABoolean: Integer): iModelUsuarioFuncoesCadastrar; function &End : iModelUsuarioFuncoes; end; iModelUsuarioFuncoesEditar = interface ['{BC9607BA-F6B5-4D6E-B6C7-C28A73E224DA}'] function GUUID(AGUUID: String) : iModelUsuarioFuncoesEditar; function Login(ALogin: String) : iModelUsuarioFuncoesEditar; function Nome(ANomeUsuario: String) : iModelUsuarioFuncoesEditar; function Senha(ASenha: String) : iModelUsuarioFuncoesEditar; function TipoUsuario(ABoolean: Integer) : iModelUsuarioFuncoesEditar; function AtivoInativo(ABoolean: Integer): iModelUsuarioFuncoesEditar; function &End : iModelUsuarioFuncoes; end; iModelUsuarioFuncoesBuscar = interface ['{396E689B-7567-4C97-8860-49D73952F598}'] function FDMemTable(AFDMemTable: TFDMemTable): iModelUsuarioFuncoesBuscar; function BuscarTodos : iModelUsuarioFuncoesBuscar; function BuscarTodosAtivos : iModelUsuarioFuncoesBuscar; function BuscarCaixas : iModelUsuarioFuncoesBuscar; function BuscarFiscais : iModelUsuarioFuncoesBuscar; function BuscarProprietarios : iModelUsuarioFuncoesBuscar; function BuscarPorCodigo(AGUUID: String) : iModelUsuarioFuncoesBuscar; function &End : iModelUsuarioFuncoes; end; iModelUsuarioFuncoesValidarUES = interface ['{59FC6597-F0A8-41D5-87F4-C7E89A0BC5C7}'] function NomeDoUsuario(AValue: String): iModelUsuarioFuncoesValidarUES; function Senha(AValue: String) : iModelUsuarioFuncoesValidarUES; function &End : iModelUsuarioFuncoes; end; implementation end.
{$include lem_directives.inc} unit LemCore; interface const GAME_BMPWIDTH = 1584; (* { TODO : find good settings } we cannot get a nice minimapscale 1/16 so instead we chose the following: image width of game = 1584 imagewidth of minimap = 104 width of white rectangle in minimap = 25 // GAME_BMPWIDTH = 1664; // this is too far I think, but now it fits with the minimap! { the original dos lemmings show pixels 0 through 1583 (so including pixel 1583) so the imagewidth should be 1584, which means 80 pixels less then 1664 MiniMapBounds: TRect = ( Left: 208; // width =about 100 Top: 18; Right: 311; // height =about 20 Bottom: 37 ); *) clMask32 = $00FF00FF; // color used for "shape-only" masks {•} type TBasicLemmingAction = ( baNone, baWalking, baJumping, baDigging, baClimbing, baDrowning, baHoisting, baBuilding, baBashing, baMining, baFalling, baFloating, baSplatting, baExiting, baVaporizing, baBlocking, baShrugging, baOhnoing, baExploding ); TSkillPanelButton = ( spbNone, spbSlower, spbFaster, spbClimber, spbUmbrella, spbExplode, spbBlocker, spbBuilder, spbBasher, spbMiner, spbDigger, spbPause, spbNuke ); const AssignableSkills = [ baDigging, baClimbing, baBuilding, baBashing, baMining, baFloating, baBlocking, baExploding ]; const ActionToSkillPanelButton: array[TBasicLemmingAction] of TSkillPanelButton = ( spbNone, spbNone, spbNone, spbDigger, spbClimber, spbNone, spbNone, spbBuilder, spbBasher, spbMiner, spbNone, spbUmbrella, spbNone, spbNone, spbNone, spbBlocker, spbNone, spbNone, spbExplode ); const SkillPanelButtonToAction: array[TSkillPanelButton] of TBasicLemmingAction = ( baNone, baNone, baNone, baClimbing, baFloating, baExploding, baBlocking, baBuilding, baBashing, baMining, baDigging, baNone, baNone ); implementation end.
unit modShapes; interface USES Windows, WinGraph, sysutils; (* for HDC *) const MAX = 254; type pointRec = record x : integer; y : integer; end; shape = ^shapeObj; shapeObj = object visible : boolean; name : string; procedure move(mx, my : integer); virtual; abstract; (* abstract methods have no definition *) procedure write; virtual; abstract; procedure draw(dc : HDC); virtual; abstract; function contains(ident : string) : shape; virtual; procedure setVisible(visible : boolean); virtual; end; shapeArray = array[1..MAX] of shape; line = ^lineObj; lineObj = object(shapeObj) private startP, endP : PointRec; public constructor init(tStartP, tEndP : pointRec; ident : string); procedure move(mx, my : integer); virtual; procedure write; virtual; procedure draw(dc : HDC); virtual; end; rectangle = ^rectangleObj; rectangleObj = object(shapeObj) private p0, p1, p2, p3 : pointRec; public constructor init(lt, rb : pointRec; ident : string); procedure move(mx, my : integer); virtual; procedure write; virtual; procedure draw(dc : HDC); virtual; end; circle = ^circleObj; circleObj = object(shapeObj) private center : pointRec; radius : integer; public constructor init(c : pointRec; r : integer; ident : string ); procedure move(mx, my : integer); virtual; procedure write; virtual; procedure draw(dc : HDC); virtual; end; picture = ^pictureObj; pictureObj = object(shapeObj) private shapes : shapeArray; numShapes : integer; public constructor init(ident : string); procedure move(mx, my : integer); virtual; procedure add(s : shape); procedure write; virtual; procedure draw(dc : HDC); virtual; function contains(ident : string) : shape; virtual; procedure setVisible(visible : boolean); virtual; end; implementation procedure addToPoint(var p : pointRec; x, y : integer); begin p.x := p.x + x; p.y := p.y + y; end; (***************Shape**************) function shapeObj.contains(ident : string) : shape; begin ident := upperCase(ident); if(name = ident) then contains := @self else contains := NIL; end; procedure shapeObj.setVisible(visible : boolean); begin self.visible := visible; end; (***************Line***************) constructor lineObj.init(tStartP, tEndP : PointRec; ident : string); begin self.name := upperCase(ident); self.startP := tStartP; self.endP := tEndP; visible := TRUE; end; procedure lineObj.move(mx, my : integer); begin addToPoint(startP, mx, my); addToPoint(endP, mx, my); end; procedure lineObj.write; begin //writeLn('Line from ', startP.x, ',', startP.y, ') to (', endP.x, ',' endP.y, ')'); end; procedure lineObj.draw(dc : HDC); begin if not visible then exit; moveTo(dc, startP.x, startP.y); lineTo(dc, endP.x, endP.y); end; (************************RECTANGLE*****************) constructor rectangleObj.init(lt, rb : PointRec; ident : string); begin self.name := ident; p0 := lt; p2 := rb; p1.x := p2.x; p1.y := p0.y; p3.x := p0.x; p3.y := p2.y; end; procedure rectangleObj.move(mx, my : integer); begin addToPoint(p0, mx, my); addToPoint(p1, mx, my); addToPoint(p2, mx, my); addToPoint(p3, mx, my); end; procedure rectangleObj.write; begin writeLn('Rectangle: '); writeLn('(', p0.x,',', p0.y,')'); end; procedure rectangleObj.draw(dc : HDC); begin if not visible then exit; moveTo(dc, p0.x, p0.y); lineTo(dc, p1.x, p1.y); lineTo(dc, p2.x, p2.y); lineTo(dc, p3.x, p3.y); lineTo(dc, p0.x, p0.y); end; (*********************Circle****************************) constructor circleObj.init(c: pointRec; r : integer; ident : string); begin self.name := ident; self.center := c; self.radius := r; visible := TRUE; end; procedure circleObj.move(mx, my : integer); begin addToPoint(center, mx, my); end; procedure circleObj.write; begin writeLn('Circle with center: (', center.x, ',', center.y, ') radius: ', radius); end; procedure circleObj.draw(dc : HDC); begin if not visible then exit; Ellipse(dc, center.x - radius, center.y - radius, center.x + radius, center.y + radius); end; (********************PICTURE**************************) constructor pictureObj.init(ident : string); begin self.name := ident; numShapes := 0; visible := TRUE; end; procedure pictureObj.move(mx, my : integer); var i : integer; begin for i := 1 to numShapes do shapes[i]^.move(mx, my); end; procedure pictureObj.add(s : shape); begin if numShapes >= MAX then begin writeLn('Picture is full'); halt; end; if s = @self then begin writeLn('Cannot add picture to itself'); halt; end; inc(numShapes); shapes[numShapes] := s; end; procedure pictureObj.write; var i : integer; begin writeLn('Picture with ', numShapes, ' shapes: '); for i := 1 to numShapes do shapes[i]^.write; end; procedure pictureObj.draw(dc : HDC); var i : integer; begin if not visible then exit; for i := 1 to numShapes do begin shapes[i]^.draw(dc); (* forward all messages *) end; sleep(1); end; procedure pictureObj.setVisible(visible : boolean); var i : integer; begin i := 1; while (i <= numShapes) do begin shapes[i]^.setVisible(visible); inc(i); end; end; function pictureObj.contains(ident : string) : shape; var i : integer; tPointer : shape; begin tPointer := inherited contains(ident); if(tPointer = NIL) then begin i := 1; while (i <= numShapes) and (tPointer = NIL) do begin tPointer := shapes[i]^.contains(ident); (* forward all messages *) inc(i); end; end; contains := tPointer; end; begin end.
unit StdResPrim; { Библиотека "vcm" } { Автор: Люлин А.В. © } { Модуль: StdResPrim - } { Начат: 26.04.2011 14:15 } { $Id: StdResPrim.pas,v 1.7 2016/08/04 17:44:49 lulin Exp $ } // $Log: StdResPrim.pas,v $ // Revision 1.7 2016/08/04 17:44:49 lulin // - перегенерация. // // Revision 1.6 2016/08/03 09:37:12 lulin // - перегенерация. // // Revision 1.5 2016/07/15 14:35:18 lulin // - собираем DesignTime. // // Revision 1.4 2016/07/15 11:25:22 lulin // - выпрямляем зависимости. // // Revision 1.3 2016/07/15 09:53:34 lulin // - выпрямляем зависимости. // // Revision 1.2 2015/08/26 15:19:25 lulin // {RequestLink:606128535} // // Revision 1.1 2013/09/11 16:12:57 lulin // - добавляем операции для возможности определения состояний операций. // // Revision 1.10 2013/09/11 10:51:47 lulin // - добавляем операции для возможности определения состояний операций. // // Revision 1.9 2013/02/19 16:53:37 lulin // {RequestLink:358352192} // // Revision 1.8 2013/02/19 15:37:05 lulin // {RequestLink:358352192} // // Revision 1.7 2012/11/02 09:23:51 lulin // - выкидываем лишнее. // // Revision 1.6 2012/11/02 09:16:34 lulin // - выкидываем лишнее. // // Revision 1.5 2012/03/22 11:43:51 lulin // - заготовочка. // // Revision 1.4 2012/03/22 10:52:49 lulin // - чиним за Мишей. // // Revision 1.3 2011/10/04 11:52:26 lulin // {RequestLink:289933577}. // // Revision 1.2 2011/06/03 09:53:39 dinishev // Переносим общие слова из F1 // // Revision 1.1 2011/04/26 13:19:07 lulin // {RequestLink:265391857}. // {$IfNDef NoVCM} {$Include vcmDefine.inc } {$EndIf NoVCM} interface {$IfNDef NoVCM} uses // !!! добавлять модули можно ДО этой строчки !!! {$IfDef NewGen} {$IfDef nsTest} NemesisRes {$Else nsTest} NewGenRes {$EndIf nsTest} {$Else NewGen} {$IfDef Nemesis} {$IfDef Admin} {$IfDef InsiderTest} AdminTestRes {$Else InsiderTest} AdminAppRes {$EndIf InsiderTest} {$Else Admin} {$IfDef Monitorings} {$IfDef InsiderTest} PrimeTestRes {$Else InsiderTest} MonitoringsRes {$EndIf InsiderTest} {$Else Monitorings} {$IfDef InsiderTest} NemesisTestRes {$Else InsiderTest} NemesisRes {$EndIf InsiderTest} {$EndIf Monitorings} {$EndIf Admin} {$Else Nemesis} {$IFDEF Archi} ArchiAppRes {$Else} //NemesisRes vcmApplication {$ENDIF Archi} {$EndIf Nemesis} {$EndIf NewGen} ; {$EndIf NoVCM} {$IfNDef NoVCM} type TvcmApplicationRunner = {$IfDef NewGen} {$IfDef nsTest} TNemesisRes {$Else nsTest} TNewGenRes {$EndIf nsTest} {$Else NewGen} {$IfDef Nemesis} {$IfDef Admin} {$IfDef InsiderTest} TAdminTestRes {$Else InsiderTest} TAdminAppRes {$EndIf InsiderTest} {$Else Admin} {$IfDef Monitorings} {$IfDef InsiderTest} TPrimeTestRes {$Else InsiderTest} TMonitoringsRes {$EndIf InsiderTest} {$Else Monitorings} {$IfDef InsiderTest} TNemesisTestRes {$Else InsiderTest} TNemesisRes {$EndIf InsiderTest} {$EndIf Monitorings} {$EndIf Admin} {$Else Nemesis} {$IFDEF Archi} {$IfNDef NoVCM} TArchiAppRes {$EndIf NoVCM} {$ELSE} //TNemesisRes TvcmApplication {$ENDIF Archi} {$EndIf Nemesis} {$EndIf NewGen} ; {$EndIf NoVCM} implementation uses f1VersionInfoService ; end.
unit UPascalCoinBank; // blabla ;) interface uses Classes, UStorage, UPCOperationsComp, UOperationBlock, UPCBankLog, UThread, UStorageClass, UBlockAccount, ULog; type { TPCBank } TPCBank = Class private FStorage : TStorage; FLastBlockCache : TPCOperationsComp; FLastOperationBlock: TOperationBlock; FIsRestoringFromFile: Boolean; FUpgradingToV2: Boolean; FOnLog: TPCBankLog; FBankLock: TPCCriticalSection; FNotifyList : TList; FStorageClass: TStorageClass; function GetStorage: TStorage; procedure SetStorageClass(const Value: TStorageClass); public Constructor Create; Destructor Destroy; Override; function GetActualTargetSecondsAverage(BackBlocks : Cardinal): Real; function GetTargetSecondsAverage(FromBlock,BackBlocks : Cardinal): Real; function LoadBankFromStream(Stream : TStream; useSecureLoad : Boolean; var errors : AnsiString) : Boolean; Procedure Clear; Function LoadOperations(Operations : TPCOperationsComp; Block : Cardinal) : Boolean; Function AddNewBlockChainBlock(Operations: TPCOperationsComp; MaxAllowedTimestamp : Cardinal; var newBlock: TBlockAccount; var errors: AnsiString): Boolean; Procedure DiskRestoreFromOperations(max_block : Int64); Procedure UpdateValuesFromSafebox; Procedure NewLog(Operations: TPCOperationsComp; Logtype: TLogType; Logtxt: AnsiString); Property OnLog: TPCBankLog read FOnLog write FOnLog; Property LastOperationBlock : TOperationBlock read FLastOperationBlock; // TODO: Use Property Storage : TStorage read GetStorage; Property StorageClass : TStorageClass read FStorageClass write SetStorageClass; Function IsReady(Var CurrentProcess : AnsiString) : Boolean; Property LastBlockFound : TPCOperationsComp read FLastBlockCache; Property UpgradingToV2 : Boolean read FUpgradingToV2; // Skybuck: added property for NotifyList so TPCBankNotify can access it property NotifyList : TList read FNotifyList; End; var PascalCoinBank : TPCBank; implementation uses SysUtils, UCrypto, UPCBankNotify, UConst, UPascalCoinSafeBox; { TPCBank } function TPCBank.AddNewBlockChainBlock(Operations: TPCOperationsComp; MaxAllowedTimestamp : Cardinal; var newBlock: TBlockAccount; var errors: AnsiString): Boolean; Var buffer, pow: AnsiString; i : Integer; begin TPCThread.ProtectEnterCriticalSection(Self,FBankLock); Try Result := False; errors := ''; Operations.Lock; // New Protection Try If Not Operations.ValidateOperationBlock(errors) then begin exit; end; if (Operations.OperationBlock.block > 0) then begin if ((MaxAllowedTimestamp>0) And (Operations.OperationBlock.timestamp>MaxAllowedTimestamp)) then begin errors := 'Invalid timestamp (Future time: New timestamp '+Inttostr(Operations.OperationBlock.timestamp)+' > max allowed '+inttostr(MaxAllowedTimestamp)+')'; exit; end; end; // Ok, include! // WINNER !!! // Congrats! if Not Operations.SafeBoxTransaction.Commit(Operations.OperationBlock,errors) then begin exit; end; newBlock := PascalCoinSafeBox.Block(PascalCoinSafeBox.BlocksCount-1); // Initialize values FLastOperationBlock := Operations.OperationBlock; // log it! NewLog(Operations, ltupdate, Format('New block height:%d nOnce:%d timestamp:%d Operations:%d Fee:%d SafeBoxBalance:%d=%d PoW:%s Operations previous Safe Box hash:%s Future old Safe Box hash for next block:%s', [ Operations.OperationBlock.block,Operations.OperationBlock.nonce,Operations.OperationBlock.timestamp, Operations.Count, Operations.OperationBlock.fee, PascalCoinSafeBox.TotalBalance, Operations.SafeBoxTransaction.TotalBalance, TCrypto.ToHexaString(Operations.OperationBlock.proof_of_work), TCrypto.ToHexaString(Operations.OperationBlock.initial_safe_box_hash), TCrypto.ToHexaString(PascalCoinSafeBox.SafeBoxHash)])); // Save Operations to disk if Not FIsRestoringFromFile then begin Storage.SaveBlockChainBlock(Operations); end; FLastBlockCache.CopyFrom(Operations); Operations.Clear(true); Result := true; Finally if Not Result then begin NewLog(Operations, lterror, 'Invalid new block '+inttostr(Operations.OperationBlock.block)+': ' + errors+ ' > '+TPCOperationsComp.OperationBlockToText(Operations.OperationBlock)); end; Operations.Unlock; End; Finally FBankLock.Release; End; if Result then begin for i := 0 to FNotifyList.Count - 1 do begin TPCBankNotify(FNotifyList.Items[i]).NotifyNewBlock; end; end; end; procedure TPCBank.Clear; begin PascalCoinSafeBox.Clear; FLastOperationBlock := TPCOperationsComp.GetFirstBlock; FLastOperationBlock.initial_safe_box_hash := TCrypto.DoSha256(CT_Genesis_Magic_String_For_Old_Block_Hash); // Genesis hash FLastBlockCache.Clear(true); NewLog(Nil, ltupdate, 'Clear Bank'); end; constructor TPCBank.Create; begin inherited; FStorage := Nil; FStorageClass := Nil; FBankLock := TPCCriticalSection.Create('TPCBank_BANKLOCK'); FIsRestoringFromFile := False; FOnLog := Nil; PascalCoinSafeBox := TPCSafeBox.Create; FNotifyList := TList.Create; FLastBlockCache := TPCOperationsComp.Create; FIsRestoringFromFile:=False; FUpgradingToV2:=False; Clear; end; destructor TPCBank.Destroy; var step : String; begin Try step := 'Deleting critical section'; FreeAndNil(FBankLock); step := 'Clear'; Clear; step := 'Destroying LastBlockCache'; FreeAndNil(FLastBlockCache); step := 'Destroying SafeBox'; FreeAndNil(PascalCoinSafeBox); step := 'Destroying NotifyList'; FreeAndNil(FNotifyList); step := 'Destroying Storage'; FreeAndNil(FStorage); step := 'inherited'; inherited; Except On E:Exception do begin TLog.NewLog(lterror,Classname,'Error destroying Bank step: '+step+' Errors ('+E.ClassName+'): ' +E.Message); Raise; end; End; end; procedure TPCBank.DiskRestoreFromOperations(max_block : Int64); Var errors: AnsiString; newBlock: TBlockAccount; Operations: TPCOperationsComp; n : Int64; begin if FIsRestoringFromFile then begin TLog.NewLog(lterror,Classname,'Is Restoring!!!'); raise Exception.Create('Is restoring!'); end; TPCThread.ProtectEnterCriticalSection(Self,FBankLock); try FUpgradingToV2 := NOT Storage.HasUpgradedToVersion2; FIsRestoringFromFile := true; try Clear; Storage.Initialize; If (max_block<Storage.LastBlock) then n := max_block else n := Storage.LastBlock; Storage.RestoreBank(n); // Restore last blockchain if (PascalCoinSafeBox.BlocksCount>0) And (PascalCoinSafeBox.CurrentProtocol=CT_PROTOCOL_1) then begin if Not Storage.LoadBlockChainBlock(FLastBlockCache,PascalCoinSafeBox.BlocksCount-1) then begin NewLog(nil,lterror,'Cannot find blockchain '+inttostr(PascalCoinSafeBox.BlocksCount-1)+' so cannot accept bank current block '+inttostr(PascalCoinSafeBox.BlocksCount)); Clear; end else begin FLastOperationBlock := FLastBlockCache.OperationBlock; end; end; NewLog(Nil, ltinfo,'Start restoring from disk operations (Max '+inttostr(max_block)+') BlockCount: '+inttostr(PascalCoinSafeBox.BlocksCount)+' Orphan: ' +Storage.Orphan); Operations := TPCOperationsComp.Create; try while ((PascalCoinSafeBox.BlocksCount<=max_block)) do begin if Storage.BlockExists(PascalCoinSafeBox.BlocksCount) then begin if Storage.LoadBlockChainBlock(Operations,PascalCoinSafeBox.BlocksCount) then begin SetLength(errors,0); if Not AddNewBlockChainBlock(Operations,0,newBlock,errors) then begin NewLog(Operations, lterror,'Error restoring block: ' + Inttostr(PascalCoinSafeBox.BlocksCount)+ ' Errors: ' + errors); Storage.DeleteBlockChainBlocks(PascalCoinSafeBox.BlocksCount); break; end else begin // To prevent continuous saving... If (PascalCoinSafeBox.BlocksCount MOD (CT_BankToDiskEveryNBlocks*10))=0 then begin Storage.SaveBank; end; end; end else break; end else break; end; if FUpgradingToV2 then Storage.CleanupVersion1Data; finally Operations.Free; end; NewLog(Nil, ltinfo,'End restoring from disk operations (Max '+inttostr(max_block)+') Orphan: ' + Storage.Orphan+' Restored '+Inttostr(PascalCoinSafeBox.BlocksCount)+' blocks'); finally FIsRestoringFromFile := False; FUpgradingToV2 := false; end; finally FBankLock.Release; end; end; procedure TPCBank.UpdateValuesFromSafebox; Var aux : AnsiString; i : Integer; begin { Will update current Bank state based on Safbox state Used when commiting a Safebox or rolling back } Try TPCThread.ProtectEnterCriticalSection(Self,FBankLock); try FLastBlockCache.Clear(True); FLastOperationBlock := TPCOperationsComp.GetFirstBlock; FLastOperationBlock.initial_safe_box_hash := TCrypto.DoSha256(CT_Genesis_Magic_String_For_Old_Block_Hash); // Genesis hash If PascalCoinSafeBox.BlocksCount>0 then begin Storage.Initialize; If Storage.LoadBlockChainBlock(FLastBlockCache,PascalCoinSafeBox.BlocksCount-1) then begin FLastOperationBlock := FLastBlockCache.OperationBlock; end else begin aux := 'Cannot read last operations block '+IntToStr(PascalCoinSafeBox.BlocksCount-1)+' from blockchain'; TLog.NewLog(lterror,ClassName,aux); Raise Exception.Create(aux); end; end; TLog.NewLog(ltinfo,ClassName,Format('Updated Bank with Safebox values. Current block:%d ',[FLastOperationBlock.block])); finally FBankLock.Release; end; finally for i := 0 to FNotifyList.Count - 1 do begin TPCBankNotify(FNotifyList.Items[i]).NotifyNewBlock; end; end; end; function TPCBank.GetActualTargetSecondsAverage(BackBlocks: Cardinal): Real; Var ts1, ts2: Int64; begin if PascalCoinSafeBox.BlocksCount>BackBlocks then begin ts1 := PascalCoinSafeBox.Block(PascalCoinSafeBox.BlocksCount-1).blockchainInfo.timestamp; ts2 := PascalCoinSafeBox.Block(PascalCoinSafeBox.BlocksCount-BackBlocks-1).blockchainInfo.timestamp; end else if (PascalCoinSafeBox.BlocksCount>1) then begin ts1 := PascalCoinSafeBox.Block(PascalCoinSafeBox.BlocksCount-1).blockchainInfo.timestamp; ts2 := PascalCoinSafeBox.Block(0).blockchainInfo.timestamp; BackBlocks := PascalCoinSafeBox.BlocksCount-1; end else begin Result := 0; exit; end; Result := (ts1 - ts2) / BackBlocks; end; function TPCBank.GetTargetSecondsAverage(FromBlock, BackBlocks: Cardinal): Real; Var ts1, ts2: Int64; begin If FromBlock>=PascalCoinSafeBox.BlocksCount then begin Result := 0; exit; end; if FromBlock>BackBlocks then begin ts1 := PascalCoinSafeBox.Block(FromBlock-1).blockchainInfo.timestamp; ts2 := PascalCoinSafeBox.Block(FromBlock-BackBlocks-1).blockchainInfo.timestamp; end else if (FromBlock>1) then begin ts1 := PascalCoinSafeBox.Block(FromBlock-1).blockchainInfo.timestamp; ts2 := PascalCoinSafeBox.Block(0).blockchainInfo.timestamp; BackBlocks := FromBlock-1; end else begin Result := 0; exit; end; Result := (ts1 - ts2) / BackBlocks; end; function TPCBank.GetStorage: TStorage; begin if Not Assigned(FStorage) then begin if Not Assigned(FStorageClass) then raise Exception.Create('StorageClass not defined'); FStorage := FStorageClass.Create; end; Result := FStorage; end; function TPCBank.IsReady(Var CurrentProcess: AnsiString): Boolean; begin Result := false; CurrentProcess := ''; if FIsRestoringFromFile then begin if FUpgradingToV2 then CurrentProcess := 'Migrating to version 2 format' else CurrentProcess := 'Restoring from file' end else Result := true; end; function TPCBank.LoadBankFromStream(Stream: TStream; useSecureLoad : Boolean; var errors: AnsiString): Boolean; Var LastReadBlock : TBlockAccount; i : Integer; auxSB : TPCSafeBox; begin auxSB := Nil; Try If useSecureLoad then begin // When on secure load will load Stream in a separate SafeBox, changing only real SafeBox if successfully auxSB := TPCSafeBox.Create; Result := auxSB.LoadSafeBoxFromStream(Stream,true,LastReadBlock,errors); If Not Result then Exit; end; TPCThread.ProtectEnterCriticalSection(Self,FBankLock); try If Assigned(auxSB) then begin PascalCoinSafeBox.CopyFrom(auxSB); end else begin Result := PascalCoinSafeBox.LoadSafeBoxFromStream(Stream,false,LastReadBlock,errors); end; If Not Result then exit; If PascalCoinSafeBox.BlocksCount>0 then FLastOperationBlock := PascalCoinSafeBox.Block(PascalCoinSafeBox.BlocksCount-1).blockchainInfo else begin FLastOperationBlock := TPCOperationsComp.GetFirstBlock; FLastOperationBlock.initial_safe_box_hash := TCrypto.DoSha256(CT_Genesis_Magic_String_For_Old_Block_Hash); // Genesis hash end; finally FBankLock.Release; end; for i := 0 to FNotifyList.Count - 1 do begin TPCBankNotify(FNotifyList.Items[i]).NotifyNewBlock; end; finally If Assigned(auxSB) then auxSB.Free; end; end; function TPCBank.LoadOperations(Operations: TPCOperationsComp; Block: Cardinal): Boolean; begin TPCThread.ProtectEnterCriticalSection(Self,FBankLock); try if (Block>0) AND (Block=FLastBlockCache.OperationBlock.block) then begin // Same as cache, sending cache Operations.CopyFrom(FLastBlockCache); Result := true; end else begin Result := Storage.LoadBlockChainBlock(Operations,Block); end; finally FBankLock.Release; end; end; procedure TPCBank.NewLog(Operations: TPCOperationsComp; Logtype: TLogType; Logtxt: AnsiString); var s : AnsiString; begin if Assigned(Operations) then s := Operations.ClassName else s := Classname; TLog.NewLog(Logtype,s,Logtxt); if Assigned(FOnLog) then FOnLog(Self, Operations, Logtype, Logtxt); end; procedure TPCBank.SetStorageClass(const Value: TStorageClass); begin if FStorageClass=Value then exit; FStorageClass := Value; if Assigned(FStorage) then FreeAndNil(FStorage); end; end.
unit InsertionSort; interface uses StrategyInterface; type TInsertionSort = class(TInterfacedObject, ISorter) procedure Sort(var A : Array of Integer); destructor Destroy; override; end; implementation procedure TInsertionSort.Sort(var A: array of Integer); var i, j : Integer; cur : Integer; begin for i := Low(A)+1 to High(A) do begin cur := A[i]; j := i - 1; while (j >= Low(A)) and (A[j] > cur) do begin A[j+1] := A[j]; j := j-1; end; A[j+1] := cur; end; end; destructor TInsertionSort.Destroy; begin WriteLn('Insertion sort destr'); inherited; end; end.
unit gm_generator; interface uses gm_engine, gm_patterns, gm_map, gm_creature, gm_item, PathFind; type PRoom = ^TRoom; TRoom = record TX, TY : Integer; W, H : Integer; Walls : array of array of Byte; end; procedure GenerateWalls(M: TMap); procedure ClearSmallRooms(M: TMap); procedure GenerateDoors(M: TMap); procedure GenerateObjects(M: TMap); procedure GenerateTreasures(M: TMap); procedure TreasuresConvert(M: TMap); procedure GenerateCreatures(M: TMap); implementation uses SysUtils, Utils; procedure InitRoom(Room : PRoom); var i, j, x1, y1, w, h, k : Integer; begin Room.W := Random(8) + 5; Room.H := Random(8) + 5; SetLength(Room.Walls, Room.W, Room.H); for j := 0 to Room.H - 1 do for i := 0 to Room.W - 1 do begin Room.Walls[i, j] := 1; if (i = 0) or (j = 0) or (i = Room.W - 1) or (j = Room.H - 1) then Room.Walls[i, j] := 2; end; w := Random(Room.W - 3); h := Random(Room.H - 3); if (w <= 1) or (h <= 1) then Exit; x1 := 0; y1 := 0; k := Random(3); if (k = 0) or (k = 2) then x1 := Room.W - w; if (k = 1) or (k = 2) then y1 := Room.H - h; if Random(5) = 0 then begin x1 := Random(Room.W - w); y1 := Random(Room.H - h); end; for j := y1 to y1 + h do for i := x1 to x1 + w do begin if (i < 0) or (j < 0) or (i >= Room.W) or (j >= Room.H) then Continue; Room.Walls[i, j] := 0; if (i = 0) or (j = 0) or (i = w) or (j = h) then if not((i = 0) or (j = 0) or (i = Room.W - 1) or (j = Room.H - 1)) then Room.Walls[i, j] := 2; end; end; procedure GenerateWalls(M : TMap); var i, j, n, l, x, y, dx, dy, k, napr : Integer; WallPat : TObjPat; Room : TRoom; Walls : array of array of Byte; bool : Boolean; con : Integer; Tnl : array of TPoint; TnlLen : Integer; begin WallPat := TObjPat(GetPattern('OBJECT', 'Wall')); SetLength(Walls, M.Width, M.Height); for j := 0 to M.Height - 1 do for i := 0 to M.Width - 1 do Walls[i, j] := 0; for n := 0 to 1500 do begin InitRoom(@Room); Room.TX := Random(M.Width - Room.W + 1); Room.TY := Random(M.Height - Room.H + 1); con := 0; bool := True; for j := 0 to Room.H - 1 do begin for i := 0 to Room.W - 1 do begin if (Walls[i + Room.TX, j + Room.TY] = 1) and (Room.Walls[i, j] = 2) then bool := False; if (Room.Walls[i, j] = 2) and (Walls[i + Room.TX, j + Room.TY] = 2) then con := con + 1; if bool = False then Break; end; if bool = False then Break; end; if (n > 0) and (con < 4) then Continue; if bool = False then Continue; for j := 0 to Room.H - 1 do for i := 0 to Room.W - 1 do Walls[i + Room.TX, j + Room.TY] := Room.Walls[i, j]; end; for n := 0 to 300 do begin x := Random(M.Width); y := Random(M.Height); if Walls[x, y] <> 2 then Continue; TnlLen := 1; SetLength(Tnl, TnlLen); Tnl[TnlLen - 1] := Point(x, y); k := Random(4) + 1; for j := 0 to k do begin l := Random(5) + 3; napr := Random(4); dx := 0; dy := 0; if Napr = 0 then dx := -1; if Napr = 1 then dx := 1; if Napr = 2 then dy := -1; if Napr = 3 then dy := 1; for i := 0 to l do begin x := x + dx; y := y + dy; if (x < 0) or (y < 0) or (x >= M.Width) or (y >= M.Height) then Break; if Walls[x, y] <> 0 then Break; TnlLen := TnlLen + 1; SetLength(Tnl, TnlLen); Tnl[TnlLen - 1] := Point(x, y); end; if TnlLen < 3 then Break; x := Tnl[TnlLen - 1].X; Y := Tnl[TnlLen - 1].Y; end; if TnlLen > 5 then for i := 0 to TnlLen - 1 do Walls[Tnl[i].X, Tnl[i].Y] := 1; end; for j := 0 to M.Height - 1 do for i := 0 to M.Width - 1 do if Walls[i, j] = 1 then Walls[i, j] := 0 else Walls[i, j] := 1; n := 0; for j := 1 to M.Height - 2 do for i := 0 to M.Width - 1 do begin l := n; if (Walls[i, j] = 1) and (Walls[i, j - 1] = 0) and (Walls[i, j + 1] = 0) then n := n + 1 else n := 0; if (l > 0) and (n = 0) then begin l := Random(l) + 1; Walls[i - l, j] := 0; end; if i = M.Width - 1 then n := 0; end; n := 0; for i := 1 to M.Width - 2 do for j := 0 to M.Height - 1 do begin l := n; if (Walls[i, j] = 1) and (Walls[i - 1, j] = 0) and (Walls[i + 1, j] = 0) then n := n + 1 else n := 0; if (l > 0) and (n = 0) then begin l := Random(l) + 1; Walls[i, j - l] := 0; end; if j = M.Height - 1 then n := 0; end; for j := 0 to M.Height - 1 do for i := 0 to M.Width - 1 do if (i = 0) or (j = 0) or (i = M.Width - 1) or (j = M.Height - 1 ) then Walls[i, j] := 1; for k := 0 to 5 do for j := 1 to M.Height - 2 do for i := 1 to M.Width - 2 do begin if (Walls[i, j] = 0) and (Walls[i + 1, j + 1] = 0) and (Walls[i + 1, j] = 1) and (Walls[i, j + 1] = 1) then Walls[i, j] := 1; if (Walls[i, j] = 1) and (Walls[i + 1, j + 1] = 1) and (Walls[i + 1, j] = 0) and (Walls[i, j + 1] = 0) then Walls[i + 1, j] := 1; if (Walls[i, j] = 0) and (Walls[i - 1, j] = 0) and (Walls[i + 1, j] = 1) and (Walls[i, j - 1] = 1) and (Walls[i, j + 1] = 1) then Walls[i, j] := 1; if (Walls[i, j] = 0) and (Walls[i - 1, j] = 1) and (Walls[i + 1, j] = 0) and (Walls[i, j - 1] = 1) and (Walls[i, j + 1] = 1) then Walls[i, j] := 1; if (Walls[i, j] = 0) and (Walls[i - 1, j] = 1) and (Walls[i + 1, j] = 1) and (Walls[i, j - 1] = 0) and (Walls[i, j + 1] = 1) then Walls[i, j] := 1; if (Walls[i, j] = 0) and (Walls[i - 1, j] = 1) and (Walls[i + 1, j] = 1) and (Walls[i, j - 1] = 1) and (Walls[i, j + 1] = 0) then Walls[i, j] := 1; end; for j := 0 to M.Height - 1 do for i := 0 to M.Width - 1 do begin if Walls[i, j] = 1 then M.Objects.ObjCreate(i, j, WallPat); end; end; procedure ClearSmallRooms(M : TMap); var WallPat : TObjPat; i, j : Integer; begin WallPat := TObjPat(GetPattern('OBJECT', 'Wall')); for j := 0 to M.Height - 1 do for i := 0 to M.Width - 1 do if Wave[i, j] = 0 then M.Objects.ObjCreate(i, j, WallPat); end; procedure GenerateDoors(M : TMap); var i, j, k : Integer; DoorPat : TObjPat; WallPat : TObjPat; begin DoorPat := TObjPat(GetPattern('OBJECT', 'Door')); WallPat := TObjPat(GetPattern('OBJECT', 'Wall')); for j := 1 to M.Height - 2 do for i := 1 to M.Width - 2 do if M.Objects.Obj[i, j] = nil then begin k := 0; if (M.Objects.Obj[i - 1, j] = nil) and (M.Objects.Obj[i + 1, j] = nil) and (M.Objects.Obj[i, j - 1] <> nil) and (M.Objects.Obj[i, j + 1] <> nil) then begin if M.Objects.Obj[i - 1, j - 1] = nil then k := k + 1; if M.Objects.Obj[i + 1, j - 1] = nil then k := k + 1; if M.Objects.Obj[i - 1, j + 1] = nil then k := k + 1; if M.Objects.Obj[i + 1, j + 1] = nil then k := k + 1; if k > 1 then if Random(10) > 0 then M.Objects.ObjCreate(i, j, DoorPat); end; if M.Objects.Obj[i, j] <> nil then Continue; k := 0; if (M.Objects.Obj[i - 1, j] <> nil) and (M.Objects.Obj[i + 1, j] <> nil) and (M.Objects.Obj[i, j - 1] = nil) and (M.Objects.Obj[i, j + 1] = nil) then begin if M.Objects.Obj[i - 1, j - 1] = nil then k := k + 1; if M.Objects.Obj[i + 1, j - 1] = nil then k := k + 1; if M.Objects.Obj[i - 1, j + 1] = nil then k := k + 1; if M.Objects.Obj[i + 1, j + 1] = nil then k := k + 1; if k > 1 then if Random(10) > 0 then M.Objects.ObjCreate(i, j, DoorPat); end; end; for j := 0 to M.Height - 2 do for i := 0 to M.Width - 2 do begin if M.Objects.Obj[i, j] = nil then Continue; if M.Objects.Obj[i, j].Pat <> DoorPat then Continue; k := 0; if M.Objects.Obj[i + 1, j] <> nil then if M.Objects.Obj[i + 1, j].Pat = DoorPat then k := 1; if M.Objects.Obj[i, j + 1] <> nil then if M.Objects.Obj[i, j + 1].Pat = DoorPat then k := 1; {if M.Objects.Obj[i + 1, j + 1] <> nil then if M.Objects.Obj[i + 1, j + 1].Pat = DoorPat then k := 1;} if k = 1 then begin M.Objects.Obj[i, j].Free; M.Objects.Obj[i, j] := nil; end; end; for j := 1 to M.Height - 2 do for i := 1 to M.Width - 2 do begin if M.Objects.Obj[i, j] = nil then Continue; if M.Objects.Obj[i, j].Pat <> DoorPat then Continue; if (M.Objects.Obj[i - 1, j] = nil) and (M.Objects.Obj[i + 1, j] = nil) then begin if M.Objects.Obj[i, j - 1] = nil then M.Objects.ObjCreate(i, j - 1, WallPat); if M.Objects.Obj[i, j + 1] = nil then M.Objects.ObjCreate(i, j + 1, WallPat); end; if (M.Objects.Obj[i, j - 1] = nil) and (M.Objects.Obj[i, j + 1] = nil) then begin if M.Objects.Obj[i - 1, j] = nil then M.Objects.ObjCreate(i - 1, j, WallPat); if M.Objects.Obj[i + 1, j] = nil then M.Objects.ObjCreate(i + 1, j, WallPat); end; end; for j := 1 to M.Height - 2 do for i := 1 to M.Width - 2 do begin if M.Objects.Obj[i, j] = nil then Continue; if M.Objects.Obj[i, j].Pat.Name <> 'DOOR' then Continue; if M.Objects.Obj[i - 1, j] = nil then begin CreateWave(M, i - 1, j, -1, 0, True); if Wave[i + 1, j] <> 0 then begin M.Objects.Obj[i, j].Free; M.Objects.Obj[i, j] := nil; Continue; end; end; if M.Objects.Obj[i, j - 1] = nil then begin CreateWave(M, i, j - 1, -1, 0, True); if Wave[i, j + 1] <> 0 then begin M.Objects.Obj[i, j].Free; M.Objects.Obj[i, j] := nil; Continue; end; end; end; for j := 1 to M.Height - 2 do for i := 1 to M.Width - 2 do begin if M.Objects.Obj[i, j] = nil then Continue; if M.Objects.Obj[i, j].Pat.Name <> 'DOOR' then Continue; M.Objects.Obj[i, j].BlockWalk := False; end; for j := 1 to M.Height - 2 do for i := 1 to M.Width - 2 do begin if M.Objects.Obj[i, j] = nil then Continue; if M.Objects.Obj[i, j].Pat.Name <> 'DOOR' then Continue; M.Objects.Obj[i, j].BlockWalk := True; if M.Objects.Obj[i - 1, j] = nil then begin CreateWave(M, i - 1, j, -1, 0, True); if (Wave[i + 1, j] > 0) and (Wave[i + 1, j] < 20) and (Random(3) = 0) then begin M.Objects.Obj[i, j].Free; M.Objects.Obj[i, j] := nil; M.Objects.ObjCreate(i, j, WallPat); end; end; if M.Objects.Obj[i, j - 1] = nil then begin CreateWave(M, i, j - 1, -1, 0, True); if (Wave[i, j + 1] > 0) and (Wave[i, j + 1] < 20) and (Random(3) = 0) then begin M.Objects.Obj[i, j].Free; M.Objects.Obj[i, j] := nil; M.Objects.ObjCreate(i, j, WallPat); end; end; if M.Objects.Obj[i, j].Pat.Name = 'DOOR' then M.Objects.Obj[i, j].BlockWalk := False; end; for j := 1 to M.Height - 2 do for i := 1 to M.Width - 2 do begin if M.Objects.Obj[i, j] = nil then Continue; if M.Objects.Obj[i, j].Pat.Name <> 'DOOR' then Continue; M.Objects.Obj[i, j].BlockWalk := True; end; end; procedure GenerateObjects(M: TMap); procedure AddMapObject(ObjName: string; Count: Byte); var P: TObjPat; I, J, X, Y, C: Integer; B: Boolean; begin P := TObjPat(GetPattern('OBJECT', ObjName)); C := Count; repeat X := Random(M.Width - 3) + 2; Y := Random(M.Height - 3) + 2; B := True; for I := X - 1 to X + 1 do for J := Y - 1 to Y + 1 do if M.Objects.Obj[I, J] <> nil then begin B := False; Break; end; if B then begin M.Objects.ObjCreate(X, Y, P); Dec(C); end; until C = 0; end; begin AddMapObject('LifeShrine', 5); AddMapObject('ManaShrine', 5); end; procedure GenerateTreasures(M : TMap); var i, j, k, i1, j1, cnt : Integer; ChestPat : TObjPat; bool : Boolean; PatNames : array [0..3] of String; begin ChestPat := TObjPat(GetPattern('OBJECT', 'Chest')); cnt := Random(10) + 20; repeat i := Random(M.Width - 2) + 1; j := Random(M.Height - 2) + 1; if M.Objects.Obj[i, j] <> nil then Continue; PatNames[0] := M.Objects.PatName(i - 1, j); PatNames[1] := M.Objects.PatName(i + 1, j); PatNames[2] := M.Objects.PatName(i, j - 1); PatNames[3] := M.Objects.PatName(i, j + 1); bool := True; if bool = True then begin for j1 := j - 2 to j + 2 do begin for i1 := i - 2 to i + 2 do if M.Objects.PatName(i1, j1) = 'DOOR' then begin bool := False; Break; end; if bool = False then Break; end; if ((PatNames[0] <> '') and (PatNames[1] <> '')) or ((PatNames[2] <> '') and (PatNames[3] <> '')) then bool := False; end; if bool = True then begin k := 0; for j1 := j - 1 to j + 1 do for i1 := i - 1 to i + 1 do if M.Objects.PatName(i1, j1) = 'WALL' then k := k + 1; if (k = 0) and (Random(3) > 0) then bool := False; end; if bool = True then if (M.Objects.PatName(i, j + 1) = '') and (M.Objects.PatName(i - 1, j + 1) = 'WALL') and (M.Objects.PatName(i + 1, j + 1) = 'WALL') then bool := False; if bool = True then if (M.Objects.PatName(i, j - 1) = '') and (M.Objects.PatName(i - 1, j - 1) = 'WALL') and (M.Objects.PatName(i + 1, j - 1) = 'WALL') then bool := False; if bool = True then if (M.Objects.PatName(i + 1, j) = '') and (M.Objects.PatName(i + 1, j + 1) = 'WALL') and (M.Objects.PatName(i + 1, j - 1) = 'WALL') then bool := False; if bool = True then if (M.Objects.PatName(i - 1, j) = '') and (M.Objects.PatName(i - 1, j + 1) = 'WALL') and (M.Objects.PatName(i - 1, j - 1) = 'WALL') then bool := False; if bool = True then begin k := 0; for j1 := j - 7 to j + 7 do for i1 := i - 7 to i + 7 do if M.Objects.PatName(i1, j1) = 'CHEST' then k := k + 1; if k > 2 then bool := False; if (k = 2) and (Random(10) = 0) then bool := False; if (k = 1) and (Random(5) = 0) then bool := False; end; if bool = True then begin M.Objects.ObjCreate(i, j, ChestPat); cnt := cnt - 1; end; until cnt = 0; for j := 1 to M.Height - 2 do for i := 1 to M.Width - 2 do begin if M.Objects.Obj[i, j] <> nil then Continue; k := 0; if M.Objects.PatName(i - 1, j) = 'WALL' then k := k + 1; if M.Objects.PatName(i + 1, j) = 'WALL' then k := k + 1; if M.Objects.PatName(i, j - 1) = 'WALL' then k := k + 1; if M.Objects.PatName(i, j + 1) = 'WALL' then k := k + 1; if (k = 3) and (Random(5) > 0) then M.Objects.ObjCreate(i, j, ChestPat); end; end; function GetRandSuffix(ItemPat: TItemPat): string; var S: string; SufPat: TSuffixPat; begin Result := ''; if ItemPat.CanGroup then Exit; S := Trim(ItemPat.AllowedSuf); if (S = '') then Exit; S := UpperCase(RandStr(',', S)); SufPat := nil; SufPat := TSuffixPat(GetPattern('SUFFIX', S)); if (S <> '') and (SufPat <> nil) and (SufPat.Rarity > 0) and (SufPat.Rarity > Rand(0, 1000)) then Result := S else Result := ''; end; function GetRandMaterial(ItemPat: TItemPat): string; var S, M: string; MatPat: TMaterialPat; begin Result := ''; if ItemPat.CanGroup then Exit; S := Trim(ItemPat.AllowedMat); if (S = '') then Exit; M := UpperCase(RandStr(',', S)); MatPat := nil; MatPat := TMaterialPat(GetPattern('MATERIAL', M)); if (M <> '') and (MatPat <> nil) and (MatPat.Rarity > 0) and (MatPat.Rarity > Rand(0, 1000)) then Result := M else Result := ''; if (S <> '') and (Result = '') then Result := UpperCase(FirstStr(',', S)); end; function CreateItem(ItemID: string; X, Y: Integer): Boolean; var Count: Byte; ItemPat: TItemPat; begin Count := 1; ItemPat := nil; Result := False; ItemPat := TItemPat(GetPattern('ITEM', ItemID)); if (ItemPat <> nil) and (ItemPat.Chance > 0) and (ItemPat.Chance > Rand(0, 1000)) then begin Result := True; Count := Rand(ItemPat.MinCount, ItemPat.MaxCount); if (Map.Objects.Obj[X, Y] <> nil) and (Map.Objects.Obj[X, Y].Pat.Name = 'CHEST') then Map.Objects.Obj[X, Y].CreateItem(ItemPat, Count, GetRandSuffix(ItemPat), GetRandMaterial(ItemPat)) else Map.CreateItem(ItemPat, Count, X, Y, GetRandSuffix(ItemPat), GetRandMaterial(ItemPat)); end; end; function GetRandItemName: string; begin Result := ''; if (AllItemsID = '') then Exit; Result := RandStr(',', AllItemsID); end; procedure RandomItem(X, Y: Integer); begin if not CreateItem(GetRandItemName, X, Y) then RandomItem(X, Y); end; procedure TreasuresConvert(M: TMap); var X, Y, Z: Integer; begin for Y := 0 to M.Height - 1 do for X := 0 to M.Width - 1 do begin if (M.Objects.Obj[X, Y] <> nil) and (M.Objects.Obj[X, Y].Pat.Name = 'CHEST') then for Z := 1 to Rand(3, 8) do RandomItem(X, Y) else if (Rand(1, 500) = 1) then RandomItem(X, Y); end; end; procedure GenerateCreatures(M : TMap); var P: TPoint; B: Boolean; Cr: TCreature; Cnt, K: Integer; ItemPat: TItemPat; begin cnt := Random(10) + 25; repeat P.X := Random(M.Width - 2) + 1; P.Y := Random(M.Height - 2) + 1; if M.GetCreature(P) <> nil then Continue; B := True; for k := 0 to M.Creatures.Count - 1 do begin Cr := TCreature(M.Creatures[k]); if (ABS(Cr.Pos.X - P.X) < 7) and (ABS(Cr.Pos.Y - P.Y) < 7) then if Random(2) = 0 then B := False; if not B then Break; end; if not B then Continue; if (Wave[P.X, P.Y] = 0) or (Wave[P.X, P.Y] > 8) then begin Cr := nil; case Random(5) of 0..1: Cr := Map.CreateCreature('Skelet', P); 2..3: Cr := Map.CreateCreature('Darkeye', P); 4: Cr := Map.CreateCreature('Necromancer', P); end; if (Cr = nil) then Continue; Cr.Team := 1; if (Cr.Pat.Name = 'SKELET') and (Random(2) = 0) then begin k := Random(6); ItemPat := nil; if k = 0 then ItemPat := TItemPat(GetPattern('ITEM', 'Sword')); if k = 1 then ItemPat := TItemPat(GetPattern('ITEM', 'Axe')); if k = 2 then ItemPat := TItemPat(GetPattern('ITEM', 'Rock')); if k = 3 then ItemPat := TItemPat(GetPattern('ITEM', 'Bow')); if k = 4 then ItemPat := TItemPat(GetPattern('ITEM', 'Shuriken')); if k = 5 then ItemPat := TItemPat(GetPattern('ITEM', 'Knife')); if ItemPat <> nil then begin Cr.SlotItem[slRHand].Item.Pat := ItemPat; Cr.SlotItem[slRHand].Item.Count := 1; if ItemPat.Throw then Cr.SlotItem[slRHand].Item.Count := Random(3) + 3; if ItemPat.Bow = True then begin Cr.SlotItem[slLHand].Item.Pat := TItemPat(GetPattern('ITEM', 'Arrow')); Cr.SlotItem[slLHand].Item.Count := Random(3) + 4; end; end; end; RandomItem(Cr.Pos.X, Cr.Pos.Y); cnt := cnt - 1; end; until cnt = 0; end; end.
unit MdiChilds.CheckPricesCECT; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.CustomDialog, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, DocumentViewer, GlobalData, GsDocument, MdiChilds.ProgressForm, MdiChilds.reg, MdiChilds.DocList, System.RegularExpressions, ActionHandler; type TFmCheckPricesCECT = class(TFmProcess) pcMain: TPageControl; tsMain: TTabSheet; tsResult: TTabSheet; frmDocumentViewer: TfrmDocumentViewer; btnDocLoad: TButton; gpOptions: TGroupBox; chkPriceCE: TCheckBox; chkPriceBT: TCheckBox; mLog: TMemo; Label2: TLabel; edtDocument: TLabeledEdit; OpenDialog: TOpenDialog; edtFilter: TLabeledEdit; procedure btnDocLoadClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private FResultDocument: TGsDocument; CurrentDocument: TGsDocument; FChapter: TGsChapter; procedure Debug(Mes: string); procedure CheckCost(Row: TGsRow; Cost: TGsCost); procedure AddRowToResult(Row: TGsRow); procedure ReleaseDocs; protected procedure BeforeExecute; override; procedure AfterExecute; override; procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; procedure DoCancel(Sender: TObject); override; public procedure AfterConstruction; override; function IsPriceChecked: Boolean; function IsPriceBTChecked: Boolean; function GetMask: string; end; TCheckPricesCECTActionHandler = class (TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var FmCheckPricesCECT: TFmCheckPricesCECT; implementation {$R *.dfm} { TFmCheckPricesCECT } procedure TFmCheckPricesCECT.AddRowToResult(Row: TGsRow); var NewRow: TGsRow; begin NewRow := TGsRow.CreateCompatibleObject(Row) as TGsRow; NewRow.Assign(Row); FChapter.Add(NewRow); end; procedure TFmCheckPricesCECT.AfterConstruction; begin inherited; mLog.Clear; FreeAndNil(FResultDocument); end; procedure TFmCheckPricesCECT.AfterExecute; begin frmDocumentViewer.Document := FResultDocument; pcMain.ActivePage := tsResult; end; procedure TFmCheckPricesCECT.BeforeExecute; begin mLog.Clear; if CurrentDocument <> nil then if CurrentDocument.BaseDataType <> GsDocument.bdtMaterial then raise Exception.Create('Этот тип документа не является материалами') else begin FResultDocument := NewGsDocument; FResultDocument.DocumentType := dtBaseData; FResultDocument.BaseDataType := bdtMaterial; FResultDocument.TypeName := CurrentDocument.TypeName; FResultDocument.Zones.Assign(CurrentDocument.Zones); FChapter := FResultDocument.CreateChapter(FResultDocument.Chapters); FChapter.Caption := 'Материалы с нулевыми ценами'; end; end; procedure TFmCheckPricesCECT.btnDocLoadClick(Sender: TObject); begin if OpenDialog.Execute then begin mLog.Clear; FreeAndNil(FResultDocument); frmDocumentViewer.Document := nil; FreeAndNil(CurrentDocument); edtDocument.Text := OpenDialog.FileName; CurrentDocument := NewGsDocument; CurrentDocument.LoadFromFile(edtDocument.Text); ShowMessage('Документ загружен'); end; end; procedure TFmCheckPricesCECT.CheckCost(Row: TGsRow; Cost: TGsCost); var I: Integer; Mes: string; priceName: string; begin priceName := 'сметная'; if Cost.Kind = cstPriceBT then priceName := 'оптовая'; Mes := ''; if Cost.IsCommon then begin if Cost.CommonValue = 0 then begin Debug('Цена (' + priceName + ') не найдена: ' + Row.Number(True)); AddRowToResult(Row); end; end else begin for I := 1 to Cost.Document.Zones.Count do if Cost.Value[I] = 0 then Mes := Mes + IntToStr(I) + ', '; if Mes <> '' then begin Debug('Цена (' + priceName + ') не найдена в зонах: ' + Mes + Row.Number(True)); AddRowToResult(Row); end; end; end; procedure TFmCheckPricesCECT.Debug(Mes: string); begin mLog.Lines.Add(Mes); end; procedure TFmCheckPricesCECT.DoCancel(Sender: TObject); begin frmDocumentViewer.Document := nil; FreeAndNil(CurrentDocument); FreeAndNil(FResultDocument); inherited; end; procedure TFmCheckPricesCECT.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var L: TList; I: Integer; Row: TGsRow; Price: TGsCost; PriceBT: TGsCost; begin if CurrentDocument = nil then raise Exception.Create('Документ не определен.'); ShowMessage := True; L := TList.Create; try CurrentDocument.Chapters.EnumItems(L, TGsRow, True); ProgressForm.InitPB(L.Count); ProgressForm.Show; for I := 0 to L.Count - 1 do begin Row := TGsRow(L[I]); if not ProgressForm.InProcess then Break; if (GetMask <> '*' ) and TRegEx.IsMatch(Row.Number(True), GetMask) then Continue; Price := Row.GetCost(cstPrice); PriceBT := Row.GetCost(cstPriceBT); if IsPriceChecked then begin if (Price = nil) then begin Debug('Цена (сметная) не найдена: ' + Row.Number(True)); AddRowToResult(Row); end else CheckCost(Row, Price); end; if IsPriceBTChecked then begin if (PriceBT = nil) then begin Debug('Цена (оптовая) не найдена: ' + Row.Number(True)); AddRowToResult(Row); end else CheckCost(Row, PriceBT); end; ProgressForm.StepIt(Row.Number(True)); end; finally L.Free; end; end; procedure TFmCheckPricesCECT.FormClose(Sender: TObject; var Action: TCloseAction); begin ReleaseDocs; inherited; end; function TFmCheckPricesCECT.GetMask: string; begin Result := Trim(edtFilter.Text); if Result = '' then Result := '*'; end; function TFmCheckPricesCECT.IsPriceBTChecked: Boolean; begin Result := chkPriceBT.Checked; end; function TFmCheckPricesCECT.IsPriceChecked: Boolean; begin Result := chkPriceCE.Checked; end; procedure TFmCheckPricesCECT.ReleaseDocs; begin FreeAndNil(FResultDocument); FreeAndNil(CurrentDocument); frmDocumentViewer.Document := nil; end; { TCheckPricesCECTActionHandler } procedure TCheckPricesCECTActionHandler.ExecuteAction; begin TFmCheckPricesCECT.Create(Application).Show; end; begin ActionHandlerManager.RegisterActionHandler('Проверка наличия сметной и оптовой цен в материалах', hkDefault, TCheckPricesCECTActionHandler); end.
{---------------------------------------------------------------------------- | | Library: Envision | | Module: EnMsg | | Description: Centralization of exceptions and messages. | | History: Nov 28, 1998. Michel Brazeau, first version | |---------------------------------------------------------------------------} unit EnMsg; {$I Envision.Inc} interface const {$J+} msgInvalidBitmap = 'Invalid bitmap'; msgTiffCompressionNotSupported = '%s compression not supported with %s images'; msgLZWCompressionNotSupported = 'LZW compression not supported'; msgUnsupportedCompressionTag = 'Unsupported compression tag, %d'; msgInvalidImageFormat = 'Internal error: Invalid image format'; msgMethodNotImplemented = 'Method %s not implemented for %s class'; msgImageDoesNotHavePalette = 'The image does not have a palette'; msgUseNewImageToChangeSize = 'Dimensions must be change with the NewImage method'; msgNotAGrayScaleFormat = 'Not a gray scale image format'; msgCannotAssign = 'Cannot assign a %s to a %s'; msgNotAValidPngFile = 'PNG file is not valid or corrupted'; msgInvalidColorTypeForBitDepth = 'Invalid color type for bit depth'; msgInvalidBitDepth = 'Invalid bit depth'; msgInvalidSampleCount = 'Invalid number of samples'; msgJpegMustBeTrueColorOrGrayscale = 'JPEG image must be gray scale or true color'; msgTGAMustBeTrueColorOr8Bit = 'TARGA image must be true color or 8 bit with palette'; msgFileFormatNotSupported = 'Graphic files of %s format are not supported or not registered'; msgGifCannotBeTrueColor = 'GIF image cannot be a true color image'; msgUnsupportedClipboardFormat = 'Unknown clipboard format, %d'; msgFrameDoesNotExist = 'Frame %d does not exist'; msgScannerIsBusy = 'Scanner is busy'; msgOnlyOneScannerObjectPermitted = 'Only one scanner object is permitted'; msgUnableToOpenTWAINSourceManager = 'Unable to open TWAIN source manager'; msgInvalidCropParameters = 'Invalid crop parameters'; msgOutOfResources = 'Out of resources'; msgSourceTooSmall = 'Source graphic too small'; msgDestTooSmall = 'Destination graphic too small'; msgSingleImageFileFormat = 'The %s format does not support multiple images'; msgInvalidDcxHeader = 'The DCX file header is not valid'; msgDcxHeaderIsFull = 'The DCX file header is full'; {--------------------------------------------------------------------------} implementation {--------------------------------------------------------------------------} end.
{ This file is part of the Free Pascal run time library. A file in Amiga system run time library. Copyright (c) 1998-2003 by Nils Sjoholm member of the Amiga RTL development team. See the file COPYING.FPC, included in this distribution, for details about the copyright. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. **********************************************************************} { History: Added the defines use_amiga_smartlink and use_auto_openlib. Implemented autoopening of the library. 14 Jan 2003. Changed startcode for unit. nils.sjoholm@mailbox.swipnet.se Nils Sjoholm } {$I useamigasmartlink.inc} {$ifdef use_amiga_smartlink} {$smartlink on} {$endif use_amiga_smartlink} UNIT translator; INTERFACE USES exec; Const TR_NotUsed = -1; { This is an oft used system rc } TR_NoMem = -2; { Can't allocate memory } TR_MakeBad = -4; { Error in MakeLibrary call } VAR TranslatorBase : pLibrary; const TRANSLATORNAME : PChar = 'translator.library'; FUNCTION Translate(const inputString : pCHAR; inputLength : LONGINT; outputBuffer : pCHAR; bufferSize : LONGINT) : LONGINT; {Here we read how to compile this unit} {You can remove this include and use a define instead} {$I useautoopenlib.inc} {$ifdef use_init_openlib} procedure InitTRANSLATORLibrary; {$endif use_init_openlib} {This is a variable that knows how the unit is compiled} var TRANSLATORIsCompiledHow : longint; IMPLEMENTATION {$ifndef dont_use_openlib} uses msgbox; {$endif dont_use_openlib} FUNCTION Translate(const inputString : pCHAR; inputLength : LONGINT; outputBuffer : pCHAR; bufferSize : LONGINT) : LONGINT; BEGIN ASM MOVE.L A6,-(A7) MOVEA.L inputString,A0 MOVE.L inputLength,D0 MOVEA.L outputBuffer,A1 MOVE.L bufferSize,D1 MOVEA.L TranslatorBase,A6 JSR -030(A6) MOVEA.L (A7)+,A6 MOVE.L D0,@RESULT END; END; const { Change VERSION and LIBVERSION to proper values } VERSION : string[2] = '0'; LIBVERSION : longword = 0; {$ifdef use_init_openlib} {$Info Compiling initopening of translator.library} {$Info don't forget to use InitTRANSLATORLibrary in the beginning of your program} var translator_exit : Pointer; procedure ClosetranslatorLibrary; begin ExitProc := translator_exit; if TranslatorBase <> nil then begin CloseLibrary(TranslatorBase); TranslatorBase := nil; end; end; procedure InitTRANSLATORLibrary; begin TranslatorBase := nil; TranslatorBase := OpenLibrary(TRANSLATORNAME,LIBVERSION); if TranslatorBase <> nil then begin translator_exit := ExitProc; ExitProc := @ClosetranslatorLibrary; end else begin MessageBox('FPC Pascal Error', 'Can''t open translator.library version ' + VERSION + #10 + 'Deallocating resources and closing down', 'Oops'); halt(20); end; end; begin TRANSLATORIsCompiledHow := 2; {$endif use_init_openlib} {$ifdef use_auto_openlib} {$Info Compiling autoopening of translator.library} var translator_exit : Pointer; procedure ClosetranslatorLibrary; begin ExitProc := translator_exit; if TranslatorBase <> nil then begin CloseLibrary(TranslatorBase); TranslatorBase := nil; end; end; begin TranslatorBase := nil; TranslatorBase := OpenLibrary(TRANSLATORNAME,LIBVERSION); if TranslatorBase <> nil then begin translator_exit := ExitProc; ExitProc := @ClosetranslatorLibrary; TRANSLATORIsCompiledHow := 1; end else begin MessageBox('FPC Pascal Error', 'Can''t open translator.library version ' + VERSION + #10 + 'Deallocating resources and closing down', 'Oops'); halt(20); end; {$endif use_auto_openlib} {$ifdef dont_use_openlib} begin TRANSLATORIsCompiledHow := 3; {$Warning No autoopening of translator.library compiled} {$Warning Make sure you open translator.library yourself} {$endif dont_use_openlib} END. (* UNIT TRANSLATOR *)
unit LibMoney; {$I defines.inc} interface (* c=0 - 21.05 -> "Двадцать один рубль 05 копеек." с=1 - 21.05 -> "двадцать один" c=2 - 21.05 -> "21-05", 21.00 -> "21=" *) function MoneyToStr(n: double; c: byte = 0): string; function NumToStr(n: double; c: byte = 0): string; function F2W(number: Currency): String; stdcall; implementation uses SysUtils; function F2W(number: Currency): String; stdcall; // у меня эта функция реализована в DLL var FiguresInWord: string; const s1: array [0 .. 19] of string = ('ноль', 'один', 'два', 'три', 'четыре', 'пять', 'шесть', 'семь', 'восемь', 'девять', 'десять', 'одиннадцать', 'двенадцать', 'тринадцать', 'четырнадцать', 'пятнадцать', 'шестнадцать', 'семнадцать', 'восемнадцать', 'девятнадцать'); s10: array [2 .. 9] of string = ('двадцать', 'тридцать', 'сорок', 'пятьдесят', 'шестьдесят', 'семьдесят', 'восемьдесят', 'девяносто'); s100: array [1 .. 9] of string = ('сто', 'двести', 'триста', 'четыреста', 'пятьсот', 'шестьсот', 'семьсот', 'восемьсот', 'девятьсот'); function f(s: string; t: Boolean): Integer; var i: Integer; r: string; begin FiguresInWord := ''; i := StrToInt(s); s := IntToStr(i); // убираем нули впереди if i > 99 then begin r := r + s100[StrToInt(s[1])] + ' '; Delete(s, 1, 1); i := StrToInt(s); end; if i > 19 then begin r := r + s10[StrToInt(s[1])] + ' '; Delete(s, 1, 1); i := StrToInt(s); end; if (i > 9) and (i < 20) then r := r + s1[i] else if i <> 0 then if t then begin if i = 1 then r := r + 'одна' else if i = 2 then r := r + 'две' else r := r + s1[i]; end else r := r + s1[i]; FiguresInWord := FiguresInWord + r; result := i; end; var i, l, n, c: Integer; s, r: string; fs : TFormatSettings; begin fs := TFormatSettings.Create; r := ''; { ---------------------------- отбрасываем дробную часть } number := number * 100; number := System.Round(number); number := number / 100; s := FloatToStr(number); i := Pos(fs.DecimalSeparator, s); l := Length(s); Delete(s, i, l - i + 1); l := Length(s); i := StrToInt(s); { ---------------------------- } c := l mod 3; if (c = 0) and (l > 0) then c := 3; if i > 999999999 then i := 0; if i > 999999 then begin n := f(Copy(s, 1, c), false); r := r + FiguresInWord; if n = 1 then r := r + ' миллион ' else if (n = 2) or (n = 3) or (n = 4) then r := r + ' миллиона ' else r := r + ' миллионов '; Delete(s, 1, c); c := 3; end; if i > 999 then begin n := f(Copy(s, 1, c), true); r := r + FiguresInWord; if n = 1 then r := r + ' тысяча ' else if (n = 2) or (n = 3) or (n = 4) then r := r + ' тысячи ' else if Copy(s, 1, c) <> '000' then r := r + ' тысяч '; Delete(s, 1, c); end; n := f(s, false); r := r + FiguresInWord; if n < 5 then begin if n = 1 then r := r + ' рубль ' else if (n = 2) or (n = 3) or (n = 4) then r := r + ' рубля ' else r := r + ' рублей '; end else r := r + ' рублей '; s := FloatToStrF(number, ffCurrency, 15, 2); i := Pos(fs.DecimalSeparator, s); r := r + Copy(s, i + 1, 2); n := StrToInt(Copy(s, i + 1, 2)); if (n > 4) and (n < 21) then r := r + ' копеек' else begin n := StrToInt(Copy(s, i + 2, 1)); if n = 1 then r := r + ' копейка' else if (n = 2) or (n = 3) or (n = 4) then r := r + ' копейки' else r := r + ' копеек'; end; s := AnsiUpperCase(Copy(r, 1, 1)); Delete(r, 1, 1); r := Concat(s, r); result := r; end; // Еще одна function NumToStr(n: double; c: byte = 0): string; (* c=0 - 21.05 -> 'Двадцать один рубль 05 копеек.' с=1 - 21.05 -> 'двадцать один' c=2 - 21.05 -> '21-05', 21.00 -> '21=' *) const digit: array [0 .. 9] of string = ('ноль', 'оди', 'два', 'три', 'четыр', 'пят', 'шест', 'сем', 'восем', 'девят'); var ts, mln, mlrd, SecDes: Boolean; len: byte; summa: string; function NumberString(const number: string): string; var d, Pos: byte; function DigitToStr: string; begin result := ''; if (d <> 0) and ((Pos = 11) or (Pos = 12)) then mlrd := true; if (d <> 0) and ((Pos = 8) or (Pos = 9)) then mln := true; if (d <> 0) and ((Pos = 5) or (Pos = 6)) then ts := true; if SecDes then begin case d of 0: result := 'десять '; 2: result := 'двенадцать ' else result := digit[d] + 'надцать ' end; case Pos of 4: result := result + 'тысяч '; 7: result := result + 'миллионов '; 10: result := result + 'миллиардов ' end; SecDes := false; mln := false; mlrd := false; ts := false end else begin if (Pos = 2) or (Pos = 5) or (Pos = 8) or (Pos = 11) then case d of 1: SecDes := true; 2, 3: result := digit[d] + 'дцать '; 4: result := 'сорок '; 9: result := 'девяносто '; 5 .. 8: result := digit[d] + 'ьдесят ' end; if (Pos = 3) or (Pos = 6) or (Pos = 9) or (Pos = 12) then case d of 1: result := 'сто '; 2: result := 'двести '; 3: result := 'триста '; 4: result := 'четыреста '; 5 .. 9: result := digit[d] + 'ьсот ' end; if (Pos = 1) or (Pos = 4) or (Pos = 7) or (Pos = 10) then case d of 1: result := 'один '; 2, 3: result := digit[d] + ' '; 4: result := 'четыре '; 5 .. 9: result := digit[d] + 'ь ' end; if Pos = 4 then begin case d of 0: if ts then result := 'тысяч '; 1: result := 'одна тысяча '; 2: result := 'две тысячи '; 3, 4: result := result + 'тысячи '; 5 .. 9: result := result + 'тысяч ' end; ts := false end; if Pos = 7 then begin case d of 0: if mln then result := 'миллионов '; 1: result := result + 'миллион '; 2, 3, 4: result := result + 'миллиона '; 5 .. 9: result := result + 'миллионов ' end; mln := false end; if Pos = 10 then begin case d of 0: if mlrd then result := 'миллиардов '; 1: result := result + 'миллиард '; 2, 3, 4: result := result + 'миллиарда '; 5 .. 9: result := result + 'миллиардов ' end; mlrd := false end end end; begin result := ''; ts := false; mln := false; mlrd := false; SecDes := false; len := Length(number); if (len = 0) or (number = '0') then result := digit[0] else for Pos := len downto 1 do begin d := StrToInt(Copy(number, len - Pos + 1, 1)); result := result + DigitToStr end end; function MoneyString(const number: string): string; var s: string; n: string; begin len := Length(number); n := Copy(number, 1, len - 3); result := NumberString(n); s := AnsiUpperCase(result[1]); Delete(result, 1, 1); result := s + result; if len < 2 then begin if len = 0 then n := '0'; len := 2; n := '0' + n end; result := trim(result); if Copy(n, len - 1, 1) = '1' then result := '(' + result + ') рублей' else begin case StrToInt(Copy(n, len, 1)) of 1: result := '(' + result + ') рубль'; 2, 3, 4: result := '(' + result + ') рубля' else result := '(' + result + ') рублей' end end; len := Length(number); n := Copy(number, len - 1, len); if Copy(n, 1, 1) = '1' then n := n + ' копеек.' else begin case StrToInt(Copy(n, 2, 1)) of 1: n := n + ' копейка.'; 2, 3, 4: n := n + ' копейки.' else n := n + ' копеек.' end end; result := result + ' ' + n end; // Основная часть begin case c of 0: result := MoneyString(FormatFloat('0.00', n)); 1: result := NumberString(FormatFloat('0', n)); 2: begin summa := FormatFloat('0.00', n); len := Length(summa); if Copy(summa, len - 1, 2) = '00' then begin Delete(summa, len - 2, 3); result := summa + '=' end else begin Delete(summa, len - 2, 1); insert('-', summa, len - 2); result := summa; end; end end; end; function MoneyToStr(n: double; c: byte = 0): string; begin result := NumToStr(n, c); end; end.
unit dev_base_form; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, extdev_driver, ext_global; { Это класс базовой формы и базового объекта Формы должны быть Inherited от TfrmBase } type TGetTime = function : TDateTime of Object; TArcRecord = record InfoByte: Byte; RecTime: TDateTime; Rec_number: Byte; end; TfrmBase = class(TForm) private { Private declarations } FCallBack: TPGUSensorCallBack; FDeviceTime : TGetTime; function GetCurrentDeviceTime: TDateTime; public { Public declarations } property CallBack: TPGUSensorCallBack read FCallBack; property CurrentDeviceTime : TDateTime read GetCurrentDeviceTime; end; TFrmBaseClass = class of TfrmBase; TBaseDevice = class(TInterfacedObject, IRSDevice) private FCB: TPGUSensorCallBack; FormClass: TFrmBaseClass; FCreateDevCompTime: TDateTime; function GetCurrentDeviceTime: TDateTime; public MyForm: TfrmBase; FDevTime: TDateTime; FCompTime: TDateTime; FDevTimeSync: Boolean; // флаг валидности установленного времени FS : TFormatSettings; FDeviceSettingsList : TStringList; constructor Create(F: TFrmBaseClass); function RegisterCallback(CBF: TPGUSensorCallBack): HResult; stdcall; function CreateDeviceWindow(parentHWND: HWND; var createHWND: HWND): Hresult; stdcall; function DestroyDevice: HRESULT; stdcall; function OnDataReceive(pd: PByte; PacketSize: Integer; MaxSize: Integer; var AnswerSize: Integer): HRESULT; virtual; stdcall; function Serialize (LoadSave: Integer; P: PChar; var PSize : DWORD): HRESULT; virtual; stdcall; property CallBack: TPGUSensorCallBack read FCB; // время создания устройсва по часам компьютера property CreateDeviceCompTime: TDateTime read FCreateDevCompTime; // текущее время устройство по "внутренним часам" property CurrentDeviceTime : TDateTime read GetCurrentDeviceTime; end; implementation {$R *.dfm} { TBaseDevice } constructor TBaseDevice.Create(F: TFrmBaseClass); begin FormClass := F; FDevTime := EncodeDate(2001, 1, 1) + EncodeTime(0, 0, 0, 0); FCompTime := Now; FCreateDevCompTime := Now; FDevTimeSync := False; FS := TFormatSettings.Create; FDeviceSettingsList := TStringList.Create; end; function TBaseDevice.CreateDeviceWindow(parentHWND: HWND; var createHWND: HWND): Hresult; begin MyForm := FormClass.Create(nil); MyForm.ParentWindow := parentHWND; createHWND := MyForm.Handle; MyForm.Visible := True; MyForm.FCallBack := FCB; MyForm.FDeviceTime := GetCurrentDeviceTime; Result := 0; end; function TBaseDevice.DestroyDevice: HRESULT; begin MyForm.Free; FDeviceSettingsList.Free; Result := 0; end; function TBaseDevice.GetCurrentDeviceTime: TDateTime; begin Result := (Now - FCompTime) + FDevTime; end; function TBaseDevice.OnDataReceive(pd: PByte; PacketSize, MaxSize: Integer; var AnswerSize: Integer): HRESULT; begin AnswerSize := 0; Result := 0; end; function TBaseDevice.RegisterCallback(CBF: TPGUSensorCallBack): HResult; begin FCB := CBF; Result := 0; end; function TBaseDevice.Serialize(LoadSave: Integer; P: PChar; var PSize : DWORD): HRESULT; begin if LoadSave = 0 then begin FDeviceSettingsList.CommaText := P; end else begin if Length (FDeviceSettingsList.CommaText) + 1 > PSize then begin PSize := Length (FDeviceSettingsList.CommaText) + 1; Exit (1); end else StrPCopy(P,FDeviceSettingsList.CommaText); end; Result := 0; end; { TfrmBase } function TfrmBase.GetCurrentDeviceTime: TDateTime; begin Result := FDeviceTime; end; end.
unit MdiChilds.SetNRSPIndex; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.CustomDialog, JvComponentBase, JvDragDrop, Vcl.StdCtrls, Vcl.ExtCtrls, MdiChilds.ProgressForm, GsDocument, Parsers.Excel.Tools, StrUtils, ActionHandler; type TFmSetNRSPIndex = class(TFmProcess) edtFile: TLabeledEdit; btnOpen: TButton; lbFiles: TListBox; lblComment: TLabel; JvDragDrop: TJvDragDrop; OpenDialog: TOpenDialog; JvDragDropFile: TJvDragDrop; RadioGroup1: TRadioGroup; procedure JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); procedure btnOpenClick(Sender: TObject); procedure JvDragDropFileDrop(Sender: TObject; Pos: TPoint; Value: TStrings); private { Private declarations } protected procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; public procedure ExecuteDocument(Doc: TGsDocument; S: TStringList); procedure ExecuteIndex(Index: TGsIndexElement; S: TStringList); function InInterval(Code: string; Interval: string): Boolean; function GetGlava(Code: string): Integer; function GetTable(Code: string): Integer; function GetPos(Code: string): Integer; function GetChapter(Code: string): Integer; end; TSetNRSPActionHandler = class (TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var FmSetNRSPIndex: TFmSetNRSPIndex; implementation {$R *.dfm} procedure TFmSetNRSPIndex.btnOpenClick(Sender: TObject); begin if OpenDialog.Execute then edtFile.Text := OpenDialog.FileName; end; procedure TFmSetNRSPIndex.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var I: Integer; S: TStringList; Doc: TGsDocument; begin S := TStringList.Create; try ProgressForm.InitPB(lbFiles.Count); ProgressForm.Show; S.LoadFromFile(edtFile.Text); for I := 0 to lbFiles.Count - 1 do begin if not ProgressForm.InProcess then Break; ProgressForm.StepIt(lbFiles.Items[I]); Doc := TGsDocument.Create; try Doc.LoadFromFile(lbFiles.Items[I]); ExecuteDocument(Doc, S); Doc.Save; finally Doc.Free; end; end; finally S.Free; end; end; procedure TFmSetNRSPIndex.ExecuteDocument(Doc: TGsDocument; S: TStringList); var L: TList; I: Integer; Index: TGsIndexElement; begin L := TList.Create; try Doc.Chapters.EnumItems(L, TGsIndexElement, True); for I := 0 to L.Count - 1 do begin Index := TGsIndexElement(L[I]); Index.AddOn.Clear; ExecuteIndex(Index, S); end; finally L.Free; end; end; procedure TFmSetNRSPIndex.ExecuteIndex(Index: TGsIndexElement; S: TStringList); var I: Integer; A: TArray<string>; AddOn: TGsIndexAddOn; Interval: string; const Stroy: array [0 .. 3] of Integer = (3, 4, 5, 6); Rem: array [0 .. 3] of Integer = (7, 8, 9, 10); begin // Index.AddOn.Clear; for I := 0 to S.Count - 1 do begin A := S[I].Split(['#']); Interval := A[1] + '.' + StringReplace(A[2], ':', ':' + A[1] + '.', []); if (A[1] <> '2') then begin if InInterval(Index.Code, Interval) and (Index.IntTag <> 1) then begin Index.IntTag := 1; if RadioGroup1.ItemIndex = 0 then begin if (TParserTools.ConvertToFloat(A[Stroy[0]]) <> 1) and (TParserTools.ConvertToFloat(A[Stroy[0]]) <> 0) then begin AddOn := TGsIndexAddOn.Create(Index.Document); AddOn.Kind := iNR; Index.AddOn.Add(AddOn); AddOn.OZ := TParserTools.ConvertToFloat(A[Stroy[0]]) / 100; AddOn.ZM := AddOn.OZ; end; if (TParserTools.ConvertToFloat(A[Stroy[1]]) <> 1) and (TParserTools.ConvertToFloat(A[Stroy[1]]) <> 0) then begin AddOn := TGsIndexAddOn.Create(Index.Document); AddOn.Kind := iSP; Index.AddOn.Add(AddOn); AddOn.OZ := TParserTools.ConvertToFloat(A[Stroy[1]]) / 100; AddOn.ZM := AddOn.OZ; end; if (TParserTools.ConvertToFloat(A[Stroy[2]]) <> 0) and (TParserTools.ConvertToFloat(A[Stroy[2]]) <> 1) or (TParserTools.ConvertToFloat(A[Stroy[3]]) <> 0) and (TParserTools.ConvertToFloat(A[Stroy[3]]) <> 1) then begin AddOn := TGsIndexAddOn.Create(Index.Document); AddOn.Kind := iZU; Index.AddOn.Add(AddOn); AddOn.OZ := TParserTools.ConvertToFloat(A[Stroy[2]]); AddOn.EM := AddOn.OZ; AddOn.ZM := AddOn.OZ; AddOn.MAT := TParserTools.ConvertToFloat(A[Stroy[3]]); end; end else begin if (TParserTools.ConvertToFloat(A[Rem[0]]) <> 0) and (TParserTools.ConvertToFloat(A[Rem[0]]) <> 1) then begin AddOn := TGsIndexAddOn.Create(Index.Document); AddOn.Kind := iNR; Index.AddOn.Add(AddOn); AddOn.OZ := TParserTools.ConvertToFloat(A[Rem[0]]) / 100; AddOn.ZM := AddOn.OZ; end; if (TParserTools.ConvertToFloat(A[Rem[1]]) <> 0) and (TParserTools.ConvertToFloat(A[Rem[1]]) <> 1) then begin AddOn := TGsIndexAddOn.Create(Index.Document); AddOn.Kind := iSP; Index.AddOn.Add(AddOn); AddOn.OZ := TParserTools.ConvertToFloat(A[Rem[1]]) / 100; AddOn.ZM := AddOn.OZ; end; if (TParserTools.ConvertToFloat(A[Rem[2]]) <> 0) and (TParserTools.ConvertToFloat(A[Rem[2]]) <> 1) or (TParserTools.ConvertToFloat(A[Rem[3]]) <> 0) and (TParserTools.ConvertToFloat(A[Rem[3]]) <> 1) then begin AddOn := TGsIndexAddOn.Create(Index.Document); AddOn.Kind := iZU; Index.AddOn.Add(AddOn); AddOn.OZ := TParserTools.ConvertToFloat(A[Rem[2]]); AddOn.EM := AddOn.OZ; AddOn.ZM := AddOn.OZ; AddOn.MAT := TParserTools.ConvertToFloat(A[Rem[3]]); end; end; end; end else if AnsiStartsText('2.', Index.Code) then begin AddOn := TGsIndexAddOn.Create(Index.Document); AddOn.Kind := iNR; Index.AddOn.Add(AddOn); AddOn.OZ := TParserTools.ConvertToFloat(A[3]) / 100; AddOn.ZM := AddOn.OZ; AddOn := TGsIndexAddOn.Create(Index.Document); AddOn.Kind := iSP; Index.AddOn.Add(AddOn); AddOn.OZ := TParserTools.ConvertToFloat(A[4]) / 100; AddOn.ZM := AddOn.OZ; end; end; end; function TFmSetNRSPIndex.GetChapter(Code: string): Integer; var A: TStringArray; begin A := Code.Split(['-', '.']); if Length(A) = 4 then Result := StrToInt(Trim(A[1])) else Result := -1; end; function TFmSetNRSPIndex.GetGlava(Code: string): Integer; begin Result := StrToInt(Trim(System.Copy(Code, 1, Pos('.', Code) - 1))); end; function TFmSetNRSPIndex.GetPos(Code: string): Integer; var A: TStringArray; begin A := Code.Split(['-']); if Length(A) > 0 then begin Result := StrToInt(Trim(A[Length(A) - 1])); end else Result := -1; end; function TFmSetNRSPIndex.GetTable(Code: string): Integer; var A: TStringArray; begin A := Code.Split(['-']); if Length(A) = 3 then begin Result := StrToInt(Trim(A[1])); end else Result := -1; end; function TFmSetNRSPIndex.InInterval(Code, Interval: string): Boolean; var Left, Right: string; begin Result := AnsiSameText(Code, Interval); if not Result and (Pos(':', Interval) > 0) then begin Left := System.Copy(Interval, 1, Pos(':', Interval) - 1); Right := System.Copy(Interval, Pos(':', Interval) + 1, 255); if (GetGlava(Left) <= GetGlava(Code)) and (GetGlava(Code) <= GetGlava(Right)) then begin if (GetChapter(Left) <= GetChapter(Code)) and (GetChapter(Code) <= GetChapter(Right)) then begin if (GetTable(Left) = GetTable(Code)) then begin if GetTable(Code) = GetTable(Right) then begin Result := (GetPos(Left) <= GetPos(Code)) and (GetPos(Code) <= GetPos(Right)); end else if GetTable(Code) < GetTable(Right) then Result := True; end else if GetTable(Left) < GetTable(Code) then begin if GetTable(Code) = GetTable(Right) then begin Result := (GetPos(Code) <= GetPos(Right)); end else if GetTable(Code) < GetTable(Right) then Result := True; end; end; end; end; end; procedure TFmSetNRSPIndex.JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); begin lbFiles.Items.Assign(Value); end; procedure TFmSetNRSPIndex.JvDragDropFileDrop(Sender: TObject; Pos: TPoint; Value: TStrings); begin if Value.Count = 1 then edtFile.Text := Value[0]; end; { TSetNRSPActionHandler } procedure TSetNRSPActionHandler.ExecuteAction(UserData: Pointer); begin TFmSetNRSPIndex.Create(Application).Show; end; begin ActionHandlerManager.RegisterActionHandler('Óñòàíîâêà ÍÐ è ÑÏ äëÿ èíäåêñîâ ÒÑÍ', hkDefault, TSetNRSPActionHandler); end.
unit Dates; interface type TDate = class private fDate: TDateTime; procedure SetDay(const Value: Integer); procedure SetMonth(const Value: Integer); procedure SetYear(const Value: Integer); function GetDay: Integer; function GetMonth: Integer; function GetYear: Integer; public constructor Create; overload; constructor Create (y, m, d: Integer); overload; procedure SetValue (y, m, d: Integer); overload; procedure SetValue (NewDate: TDateTime); overload; procedure Assign(Source: TDate); function LeapYear: Boolean; procedure Increase (NumberOfDays: Integer = 1); procedure Decrease (NumberOfDays: Integer = 1); function GetText: string; property Year: Integer read GetYear write SetYear; property Month: Integer read GetMonth write SetMonth; property Day: Integer read GetDay write SetDay; end; TNewDate = class (TDate) public function GetText: string; end; implementation uses SysUtils, DateUtils; procedure TDate.Assign (Source: TDate); begin fDate := Source.fDate; end; procedure TDate.SetValue (y, m, d: Integer); begin fDate := EncodeDate (y, m, d); end; function TDate.LeapYear: Boolean; begin Result := IsInLeapYear(fDate); end; procedure TDate.Increase (NumberOfDays: Integer = 1); begin fDate := fDate + NumberOfDays; end; function TDate.GetText: string; begin GetText := DateToStr (fDate); end; procedure TDate.Decrease (NumberOfDays: Integer = 1); begin fDate := fDate - NumberOfDays; end; constructor TDate.Create (y, m, d: Integer); begin fDate := EncodeDate (y, m, d); end; constructor TDate.Create; begin fDate := Date; end; procedure TDate.SetValue(NewDate: TDateTime); begin fDate := NewDate; end; procedure TDate.SetDay(const Value: Integer); begin fDate := RecodeDay (fDate, Value); end; procedure TDate.SetMonth(const Value: Integer); begin fDate := RecodeMonth (fDate, Value); end; procedure TDate.SetYear(const Value: Integer); begin fDate := RecodeYear (fDate, Value); end; function TDate.GetDay: Integer; begin Result := DayOf (fDate); end; function TDate.GetMonth: Integer; begin Result := MonthOf (fDate); end; function TDate.GetYear: Integer; begin Result := YearOf (fDate); end; { TNewDate } function TNewDate.GetText: string; begin GetText := FormatDateTime ('dddddd', fDate); end; end.
unit Model.PenalizacaoAtrasos; interface type TPenalizacaoAtrasos = class private var FId: System.Integer; FData: System.TDate; FAtraso: System.Integer; FValor: System.Double; FPercentual: System.Double; FLog: System.string; public property ID: System.Integer read FId write FId; property Data: System.TDate read FData write FData; property Atraso: System.Integer read FAtraso write FAtraso; property Valor: System.Double read FValor write FValor; property Percentual: System.Double read FPercentual write FPercentual; property Log: System.string read FLog write FLog; constructor Create; overload; constructor Create(pFId: System.Integer; pFData: System.TDate; pFAtraso: System.Integer; pFValor: System.Double; pFPercentual: System.Double; pFLog: System.string); overload; end; implementation constructor TPenalizacaoAtrasos.Create; begin inherited Create; end; constructor TPenalizacaoAtrasos.Create(pFId: System.Integer; pFData: System.TDate; pFAtraso: System.Integer; pFValor: System.Double; pFPercentual: System.Double; pFLog: System.string); begin FId := pFId; FData := pFData; FAtraso := pFAtraso; FValor := pFValor; FPercentual := pFPercentual; FLog := pFLog; end; end.
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François Piette Creation: Aug 27, 2002 Description: Version: 1.02 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 2002-2010 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. History: Dec 28, 2004 V1.01 F. Piette added DeleteItem method and replaced code where needed Added RemoveItemIfAged method Apr 04, 2009 V1.02 F. Piette cleanup code * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsTimeList; {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$H+} { Use long strings } {$J+} { Allow typed constant to be modified } {$I OverbyteIcsDefs.inc} {$IFDEF COMPILER14_UP} {$IFDEF NO_EXTENDED_RTTI} {$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])} {$ENDIF} {$ENDIF} interface uses Windows, SysUtils, Classes, Controls; type TTimeRecFreeFct = procedure (var P : Pointer); TTimeRec = record Value : String; TimeMark : TDateTime; Count : Integer; Data : Pointer; FreeFct : TTimeRecFreeFct; end; PTimeRec = ^TTimeRec; TTimeListDeleteEvent = procedure (Sender: TObject; PItem : PTimeRec) of object; TTimeList = class(TComponent) private FData : TList; FMaxItems : Integer; FVersion : Integer; // Change each time content change FMaxAge : Integer; // Seconds FOnChange : TNotifyEvent; FOnDelete : TTimeListDeleteEvent; function GetCount: Integer; function GetItems(Index: Integer): PTimeRec; procedure SetMaxItems(const Value: Integer); procedure SetMaxAge(const Value: Integer); procedure TriggerChange; virtual; procedure TriggerDelete(PItem : PTimeRec); virtual; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; function Add(const Value : String) : PTimeRec; virtual; function AddWithData(const Value : String; Data : Pointer; FreeFct : TTimeRecFreeFct) : PTimeRec; virtual; function Delete(const Value: String) : Integer; virtual; procedure DeleteItem(Index : Integer); virtual; function IndexOf(const Value: String): Integer; procedure RemoveAged; virtual; function RemoveItemIfAged(Index: Integer): Boolean; virtual; procedure Clear; virtual; property Count : Integer read GetCount; property Items[Index: Integer]: PTimeRec read GetItems; default; property Version : Integer read FVersion; published property MaxItems : Integer read FMaxItems write SetMaxItems; property MaxAge : Integer read FMaxAge write SetMaxAge; property OnChange : TNotifyEvent read FOnChange write FOnChange; property OnDelete : TTimeListDeleteEvent read FOnDelete write FOnDelete; end; implementation {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TTimeList.Create(AOwner : TComponent); begin inherited Create(AOwner); FData := TList.Create; FMaxItems := 100; FMaxAge := 300; // Seconds FVersion := 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TTimeList.Destroy; var I : Integer; begin if Assigned(FData) then begin // delete all items stored in the list for I := FData.Count - 1 downto 0 do DeleteItem(I); FreeAndNil(FData); end; inherited; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTimeList.DeleteItem(Index : Integer); var PItem : PTimeRec; begin PItem := FData.Items[Index]; FData.Delete(Index); // Remove item from list TriggerDelete(PItem); // Free data object if associated properly if (PItem^.Data <> nil) and Assigned(PItem^.FreeFct) then PItem^.FreeFct(PItem^.Data); Dispose(PItem); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTimeList.IndexOf(const Value: String) : Integer; var PItem : PTimeRec; begin if not Assigned(FData) then begin Result := -1; Exit; end; // Search if item "Value" already exists Result := FData.Count - 1; // Start with last item (most recent) while Result >= 0 do begin PItem := FData.Items[Result]; if CompareText(PItem.Value, Value) = 0 then // We found existing item Exit; Dec(Result); end; // The item is not existing in the list Result := -1; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTimeList.Add(const Value: String) : PTimeRec; var I : Integer; PItem : PTimeRec; begin Result := nil; if Value = '' then Exit; // Ignore empty value if not Assigned(FData) then FData := TList.Create; PItem := nil; // Makes compiler happy // Search if item "Value" already exists I := FData.Count - 1; // Start with last item (most recent) while I >= 0 do begin PItem := FData.Items[I]; if CompareText(PItem.Value, Value) = 0 then begin // We found existing item // Remove it from where it is, to add it later at the end FData.Delete(I); break; end; Dec(I); end; if I < 0 then begin // The item is not existing in the list, create a new item New(PItem); PItem.Value := Value; PItem.Count := 0; PItem.Data := nil; PItem.FreeFct := nil; end; // Remove older entry if too much items. if FData.Count >= FMaxItems then DeleteItem(0); // Add existing or new item at the end of the list FData.Add(PItem); // Set new TimeMark PItem.TimeMark := Now; // Increment the use count Inc(PItem.Count); // Increment version number, wrapping to 0 when largest integer is reached FVersion := (Cardinal(FVersion) + 1) and High(Integer); TriggerChange; Result := PItem; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTimeList.AddWithData( const Value : String; Data : Pointer; FreeFct : TTimeRecFreeFct) : PTimeRec; begin Result := Add(Value); if Result <> nil then begin if (Result^.Data <> nil) and Assigned(Result^.FreeFct) then Result^.FreeFct(Result^.Data); Result^.Data := Data; Result^.FreeFct := FreeFct; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTimeList.GetCount: Integer; begin if not Assigned(FData) then Result := 0 else Result := FData.Count; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTimeList.GetItems(Index: Integer): PTimeRec; begin if not Assigned(FData) then Result := nil else if (Index < 0) or (Index >= FData.Count) then Result := nil else Result := FData.Items[Index]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTimeList.SetMaxItems(const Value: Integer); begin if FMaxItems = Value then Exit; FMaxItems := Value; if not Assigned(FData) then Exit; // No items at all if FData.Count > FMaxItems then begin // Adjust number of items in the list while FData.Count > FMaxItems do DeleteItem(0); // Inc version number, wrapping to 0 when largest integer is reached FVersion := (Cardinal(FVersion) + 1) and High(Integer); TriggerChange; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTimeList.TriggerChange; begin if Assigned(FOnChange) then FOnChange(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTimeList.TriggerDelete(PItem : PTimeRec); begin if Assigned(FOnDelete) then FOnDelete(Self, PItem); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} // Delete an item if it is aged // Return TRUE if item removed function TTimeList.RemoveItemIfAged(Index : Integer) : Boolean; var TimeLimit : TDateTime; PItem : PTimeRec; begin Result := FALSE; if not Assigned(FData) then Exit; if FData.Count <= 0 then Exit; TimeLimit := Now - FMaxAge * EncodeTime(0, 0, 1, 0); PItem := FData.Items[Index]; if PItem.TimeMark < TimeLimit then begin DeleteItem(Index); Result := TRUE; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTimeList.RemoveAged; var TimeLimit : TDateTime; I : Integer; PItem : PTimeRec; Changed : Boolean; begin if not Assigned(FData) then Exit; if FData.Count <= 0 then Exit; TimeLimit := Now - FMaxAge * EncodeTime(0, 0, 1, 0); Changed := FALSE; I := FData.Count - 1; // Start with last item (most recent) while I >= 0 do begin PItem := FData.Items[I]; if PItem.TimeMark < TimeLimit then begin DeleteItem(I); Changed := TRUE; end; Dec(I); end; if Changed then begin // Inc version number, wrapping to 0 when largest integer is reached FVersion := (Cardinal(FVersion) + 1) and High(Integer); TriggerChange; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTimeList.SetMaxAge(const Value: Integer); begin if FMaxAge = Value then Exit; FMaxAge := Value; RemoveAged; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTimeList.Clear; var I : Integer; begin if not Assigned(FData) then Exit; if FData.Count <= 0 then Exit; I := FData.Count - 1; // Start with last item (most recent) while I >= 0 do begin DeleteItem(I); Dec(I); end; // Inc version number, wrapping to 0 when largest integer is reached FVersion := (Cardinal(FVersion) + 1) and High(Integer); TriggerChange; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTimeList.Delete(const Value: String) : Integer; begin if not Assigned(FData) then begin Result := -1; Exit; end; Result := IndexOf(Value); if Result < 0 then Exit; // Not found DeleteItem(Result); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit bomba; interface uses SysUtils, DateUtils; type T_Bomba = class(TObject) private F_Id: Integer; F_Tanque_Id: Integer; F_Numero: Integer; // F_Id function getId(): Integer; procedure setId(pId: Integer); // F_Tanque_Id function getTanque_Id(): Integer; procedure setTanque_Id(pTanque_Id: Integer); // F_Numero function getNumero(): Integer; procedure setNumero(pNumero: Integer); public constructor Create( pId: Integer; pTanque_Id: Integer; pNumero: Integer); overload; constructor Create(); overload; published property Id: Integer read getId write setId; property Tanque_Id: Integer read getTanque_Id write setTanque_Id; property Numero: Integer read getNumero write setNumero; end; implementation constructor T_Bomba.Create( pId: Integer; pTanque_Id: Integer; pNumero: Integer); begin F_Id := pId; F_Tanque_Id := pTanque_Id; F_Numero := pNumero; end; constructor T_Bomba.Create(); begin end; function T_Bomba.getId(): Integer; begin result := F_Id; end; procedure T_Bomba.setId(pId: Integer); begin F_Id := pId; end; // F_Tanque_Id function T_Bomba.getTanque_Id(): Integer; begin result := F_Tanque_Id; end; procedure T_Bomba.setTanque_Id(pTanque_Id: Integer); begin F_Tanque_Id := pTanque_Id; end; // F_Numero function T_Bomba.getNumero(): Integer; begin result := F_Numero; end; procedure T_Bomba.setNumero(pNumero: Integer); begin F_Numero := pNumero; end; end.
unit MappedFiles; interface uses Windows; const usgReadOnly = 0; usgReadWrite = 1; usgWriteCopy = 2; type TMemoryMappedFile = class public constructor Create( const aFileName : string; Usage : integer ); destructor Destroy; override; protected fFileHandle : THandle; fFileMap : THandle; fAddress : pointer; fLockCount : integer; fViewAccess : integer; function GetAddress : pointer; public property Address : pointer read GetAddress; function Lock( Offset : integer ) : pointer; procedure Unlock( Addr : pointer ); end; resourcestring sCantOpenFile = 'File to be mapped cannot be opened!!'; sCantMapFile = 'File cannot be mapped!!'; sCantViewMapFile = 'Cannot get a view of mapped file!!'; implementation uses SysUtils; function TMemoryMappedFile.GetAddress : pointer; begin if fAddress = nil then fAddress := Lock( 0 ); Result := fAddress; end; function TMemoryMappedFile.Lock( Offset : integer ) : pointer; begin Result := MapViewOfFile( fFileMap, FILE_MAP_READ, 0, 0, 0 ); if Assigned( Result ) then inc( fLockCount ) else raise Exception.Create( sCantViewMapFile ); end; procedure TMemoryMappedFile.Unlock( Addr : pointer ); begin if UnmapViewOfFile( Addr ) then dec( fLockCount ); end; constructor TMemoryMappedFile.Create( const aFileName : string; Usage : integer ); var xShareMode : integer; xAccess : integer; xMapProtection : integer; begin inherited Create; case Usage of usgReadOnly : begin xAccess := GENERIC_READ; xShareMode := FILE_SHARE_READ; xMapProtection := PAGE_READONLY; fViewAccess := FILE_MAP_READ; end; usgReadWrite : begin xAccess := GENERIC_READ or GENERIC_WRITE; xShareMode := 0; xMapProtection := PAGE_READWRITE; fViewAccess := FILE_MAP_WRITE; end; else // usgWriteCopy begin xAccess := GENERIC_READ or GENERIC_WRITE; xShareMode := FILE_SHARE_READ; xMapProtection := PAGE_WRITECOPY; fViewAccess := FILE_MAP_COPY; end; end; try fFileHandle := CreateFile( pchar(aFilename), xAccess, xShareMode, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); if fFileHandle = INVALID_HANDLE_VALUE then raise Exception.Create( sCantOpenFile ) else begin fFileMap := CreateFileMapping( fFileHandle, nil, xMapProtection, 0, 0, nil ); if fFileMap = 0 then raise Exception.Create( sCantMapFile ); end; except CloseHandle( fFileHandle ); raise; end; end; destructor TMemoryMappedFile.Destroy; begin if Assigned( fAddress ) then Unlock( fAddress ); assert( fLockCount = 0, 'Unmatched Lock/Unlock calls!! in MappedFiles.TMemoryMappedFile.Destroy!!' ); CloseHandle( fFileMap ); CloseHandle( fFileHandle ); inherited; end; end.
unit DibRle; interface uses Windows, Dibs, NumUtils; procedure UnpackRle4( DibWidth : integer; RlePixels : pointer; DibPixels : pointer ); procedure UnpackRle8( DibWidth : integer; RlePixels : pointer; DibPixels : pointer ); procedure PackRle8( DibHeader : PDib; DibPixels, RlePixels, PrevFramePixels : pointer; MinJumpLength : integer ); function Rle8DeltaFrame( DibHeader : PDib; DibPixels, RlePixels, PrevFramePixels : pchar; Start, Len : integer; MinJump : integer ) : PDib; const RLE_ESCAPE = 0; RLE_EOL = 0; RLE_EOF = 1; RLE_JMP = 2; RLE_MINABS = 3; const rleJump = RLE_ESCAPE + RLE_JMP shl 8; rleEndOfLine = RLE_ESCAPE + RLE_EOL shl 8; rleEndOfBitmap = RLE_ESCAPE + RLE_EOF shl 8; procedure DibUnpackRle( SourcePixels : pointer; DibHeader : PDib; DibPixels : pointer; ForceTopDown : boolean ); procedure RegisterRleDibIoHooks; procedure UnregisterRleDibIoHooks; implementation procedure RegisterRleDibIoHooks; begin RegisterDibIOHooks( [ BI_RLE4, BI_RLE8 ], DibUnpackRle ); end; procedure UnregisterRleDibIoHooks; begin UnregisterDibIOHooks( [ BI_RLE4, BI_RLE8 ] ); end; procedure DibUnpackRle( SourcePixels : pointer; DibHeader : PDib; DibPixels : pointer; ForceTopDown : boolean ); begin case DibHeader.biCompression of BI_RLE4 : UnpackRle4( DibHeader.biWidth, SourcePixels, DibPixels ); BI_RLE8 : UnpackRle8( DibHeader.biWidth, SourcePixels, DibPixels ); end; end; procedure UnpackRle4( DibWidth : integer; RlePixels : pointer; DibPixels : pointer ); // // On entry: // // EAX: DibWidth // EDX: RlePixels // ECX: DibPixels var OddX : boolean; asm (* push esi push edi push ebx add eax, 3 mov esi, edx // esi = RlePixels and eax, not 3 mov edi, ecx // edi = DibPixels mov ebx, eax // ebx = scanline width xor ecx, ecx xor eax, eax mov OddX, 0 // Start of RLE decoding @RleBltStart: mov edx, edi // save start of scan @RleBltNext: lodsw // al := count ah := color or al, al // is it a escape? jz @RleBltEscape // We have found a encoded run (al <> 0) @RleBltEncodedRun: mov cl, al // al - run length mov al, ah // ah - run colors 1 & 2 mov ah, OddX shr ecx, 1 jnc @RleEncodedEvenCount @RleEncodedOddCount: xor OddX, 1 @RleEncodedEvenCount: or ah, ah // Is X odd? jnz @EvenEncodedRun @OddEncodedRun: rol al, 4 // Swap color1 & color2 in AL rep stosb jnc @RleBltNext jmp @RleBltNext // We have found a RLE escape code (al = 0) // Possibilities are: // . End of Line - ah = 0 // . End of RLE - ah = 1 // . Delta - ah = 2 // . Unencoded run - ah = 3 or more @RleBltEscape: cmp ah, al je @RleBltEOL inc al cmp ah, al je @RleBltEOF inc al cmp ah, al je @RleBltDelta // We have found a un-encoded run (ah >= 3) @RleBltUnencodedRun: xchg al, ah // ah is pixel count mov cl, al // ESI --> pixels shr ecx, 1 rep movsb jnc @UnencodedCont xor OddX, 1 jz // !!! @MoveOddPixel: jmp @UnencodedCont @MoveEvenPixel: @UnencodedCont: inc esi // !!! re-align source and si, not 1 jmp @RleBltNext // We have found a delta jump, the next two bytes contain the jump values // note the the jump values are unsigned bytes, x first then y @RleBltDelta: lodsw // al = deltaX, ah = deltaY or ah, ah jnz @RleBltDeltaXY @RleBltDeltaX: shr eax, 1 jc @RleBltDeltaXYHalf @RleBltDeltaXYFull: add edi, eax jmp @RleBltNext @RleBltDeltaXY: add edi, ebx add edx, ebx dec ah jnz @RleBltDeltaXY @RleBltDeltaXYHalf: add edi, eax xor OddX, 1 jnz @RleBltNext inc edi jmp @RleBltNext // We have found a end of line marker, point ES:DI to the begining of the // next scan @RleBltEOL: mov edi, edx // go back to start of scan add edi, ebx // advance to next scan jmp @RleBltStart // go get some more // We have found a end of rle marker, clean up and exit @RleBltEOF: @Exit: pop ebx pop edi pop esi *) end; procedure UnpackRle8( DibWidth : integer; RlePixels : pointer; DibPixels : pointer ); // // On entry: // // EAX: DibWidth // EDX: RlePixels // ECX: DibPixels asm push esi push edi push ebx add eax, 3 mov esi, edx // esi = RlePixels and eax, not 3 mov edi, ecx // edi = DibPixels mov ebx, eax // ebx = scanline width xor ecx, ecx xor eax, eax // Start of RLE decoding @RleBltStart: mov edx, edi // save start of scan @RleBltNext: lodsw // al := count ah := color or al, al // is it a escape? jz @RleBltEscape // We have found a encoded run (al <> 0) @RleBltEncodedRun: mov cl, al // al - run length mov al, ah // ah - run color shr ecx, 1 rep stosw adc cl, cl rep stosb jmp @RleBltNext // We have found a RLE escape code (al = 0) // Possibilities are: // . End of Line - ah = 0 // . End of RLE - ah = 1 // . Delta - ah = 2 // . Unencoded run - ah = 3 or more @RleBltEscape: cmp ah, al je @RleBltEOL inc al cmp ah, al je @RleBltEOF inc al cmp ah, al je @RleBltDelta // We have found a un-encoded run (ah >= 3) @RleBltUnencodedRun: xchg al, ah // ah is pixel count mov cl, al // ESI --> pixels shr ecx, 2 and eax, 3 rep movsd mov ecx, eax rep movsb inc esi // !!! re-align source and si, not 1 jmp @RleBltNext // We have found a delta jump, the next two bytes contain the jump values // note the the jump values are unsigned bytes, x first then y @RleBltDelta: lodsw // al = deltaX, ah = deltaY or ah, ah jnz @RleBltDeltaXY @RleBltDeltaX: add edi, eax jmp @RleBltNext @RleBltDeltaXY: add edi, ebx add edx, ebx dec ah jnz @RleBltDeltaXY // !!! add edi, eax jmp @RleBltNext // We have found a end of line marker, point ES:DI to the begining of the // next scan @RleBltEOL: mov edi, edx // go back to start of scan add edi, ebx // advance to next scan jmp @RleBltStart // go get some more // We have found a end of rle marker, clean up and exit @RleBltEOF: @Exit: pop ebx pop edi pop esi end; procedure PackRle8( DibHeader : PDib; DibPixels, RlePixels, PrevFramePixels : pointer; MinJumpLength : integer ); // // On entry: // // EAX: DibHeader // EDX: DibPixels // ECX: RlePixels var tDibHeader : PDib; tDibPixels : pointer; tRlePixels : pointer; CurX, CurY : word; ImageWidth, ImageHeight : word; JumpX, JumpY : smallint; NextScan : integer; WidthBytes : integer; asm push esi push edi push ebx mov tDibHeader, eax mov tDibPixels, edx mov tRlePixels, ecx mov edx, TDib( [eax] ).biWidth mov esi, TDib( [eax] ).biHeight cmp esi, 0 jge @DibBottomUp neg esi // Make sure height > 0 @DibBottomUp: mov ImageWidth, dx mov ImageHeight, si mov eax, edx add eax, 3 // Compute scanline width and eax, not 3 mov WidthBytes, eax sub eax, edx mov NextScan, eax xor esi, esi mov CurX, si mov CurY, si mov JumpX, si mov JumpY, si // init pointers into buffers, the following registers will be constant // for the entire DeltaFrame process. mov esi, tDibPixels // esi = DibPixels mov edi, tRlePixels // edi = RlePixels mov ebx, PrevFramePixels // ebx = PrevFramePixels or ebx, ebx // if PrevFramePixels is NULL, no Temporal compression is wanted, just RLE jnz @DeltaFrameTemporal // the DIB and return // Spatial Compression // -------------------------------------------------------------------- // the frame is to be compressed without relying on the previous frame @DeltaFrameSpatial: @DeltaFrameSpatialLoop: mov cx, ImageWidth // encode entire line call @EncodeFragment // ...go do it add esi, NextScan // point pbDib to next scan dec ImageHeight // another scan to do? jz @DeltaFrameDone // ...no generate EOF and exit mov ax, rleEndOfLine // generate EOL, and go for more stosw jmp @DeltaFrameSpatialLoop // Temporal Compression // -------------------------------------------------------------------- // the frame is to be compressed assuming the previous frame is visible // any pixels that are the same in both frames will be skiped over @DeltaFrameTemporal: xchg edi, PrevFramePixels // edi --> previous DIB @DeltaFrameTemporalLoop: mov cx, ImageWidth // compute amount of pixels left sub cx, curX // on the scanline jz @DeltaFrameEOL // are we at EOL? call @FindFragmentLength // calc frag length and jump value or ax, ax jz @DeltaFrameJump // we have a fragment (ie a part of the image that changed) to encode // // first thing we need to do is generate any outstanding jumps we have // in (jump.x, jump.y) // // AX is fragment length // BX is jump length // add edi, eax xchg edi, PrevFramePixels // edi --> RLE bits push bx // save jump size push ax // save fragment size xor cx, cx xor bx, bx xchg cx, JumpX // check if we need to gen a jump xchg bx, JumpY @DeltaFrameDoJump: mov ax, cx // check if we need to gen a jump or ax, bx jz @DeltaFrameFragment // no jump needed generate a frag. js @DeltaFrameNegY // negative, need a EOL mov ax, rleJump stosw mov ax, 255 // ax = 255 sub ax, cx // ax = min( ax, cx ) (255 = maximum run) cwd and ax, dx add ax, cx stosb sub cx, ax mov ax, 255 // ax = 255 sub ax, bx // ax = min( ax, bx ) (255 = maximum run) cwd and ax, dx add ax, bx stosb sub bx, ax jmp @DeltaFrameDoJump @DeltaFrameNegY: mov ax, rleEndOfLine stosw mov cx, curX dec bx jmp @DeltaFrameDoJump @DeltaFrameFragment: pop cx add curX, cx call @EncodeFragment xchg edi, PrevFramePixels // edi --> Prev DIB pop bx @DeltaFrameJump: add jumpX, bx add curX, bx add esi, ebx add edi, ebx jmp @DeltaFrameTemporalLoop @DeltaFrameEOL: inc jumpY dec ImageHeight jz @DeltaFrameTemporalDone mov eax, NextScan add esi, eax add edi, eax mov ax, curX // jumpX -= curX sub jumpX, ax xor eax, eax mov curX, ax jmp @DeltaFrameTemporalLoop @DeltaFrameTemporalDone: xchg edi, PrevFramePixels // edi --> rle data // we are all done! // // generate the final EOF and update the biSizeImage field in passed // bitmapinfo and return. @DeltaFrameDone: mov ax, rleEndOfBitmap stosw mov esi, tDibHeader // ESI --> BITMAPINFO sub edi, tRlePixels // compute length mov TBitmapInfoHeader([esi]).biSizeImage, edi // and store it. mov TBitmapInfoHeader([esi]).biCompression, BI_RLE8 jmp @Exit // RLE encodes a run of 8 bit pixels, no Temporal compression is done. // // Entry: // CX --> number of pixels to RLE // ESI --> DIB pixels to RLE // EDI --> place to store RLE data @EncodeFragment: or cx, cx // anything at all to do? jnz @EncodeFragmentLoop jmp @EncodeFragmentExit @EncodeFragmentLoop: mov bx, dx mov ax, cx // eax = pixels left sub ax, 255 // eax = min( eax, 255 ) (255 = maximum run) cwd and ax, dx add ax, 255 shl ecx, 16 // save old ecx mov cx, ax // ecx = maximum run allowed mov dx, bx // look for a run of same pixels and generate a single RLE run. @EncodeFragmentSolid: xor ebx, ebx // ebx = 0 (run count) mov ah, [esi] // get first pixel @EncodeFragmentSolidScan: inc bx cmp bx, cx je @EncodeFragmentSolidRun cmp ah, [esi + ebx] // get pixel je @EncodeFragmentSolidScan @EncodeFragmentSolidRun: cmp bx, 1 // is run greater than one? jbe @EncodeFragmentAbs @EncodeFragmentSolidEncode: mov al, bl // store solid run (cnt, color) stosw add esi, ebx // advance pbDib shr ecx, 16 // restore cx (length) sub cx, bx jz @EncodeFragmentExit // any pixels left to encode? jmp @EncodeFragmentLoop // look for a run of pixels that are not the same // note. we cant generate a abs run less than 3 pixels, so if we have // a abs run <3 encode it as a bunch of count=1 rle runs @EncodeFragmentAbs: cmp cx, RLE_MINABS // enough room left for a min abs run? jb @EncodeFragmentSolidEncode mov bx, RLE_MINABS - 1 @EncodeFragmentAbsScan: inc bx // add another pixel to the run // we want at least 4 pixels in a row to be the same before we // stop ABS mode. otherwise leaving ABS mode to do a short run // then re-entering ABS mode would be bigger // // if there are not 4 pixels left on the line, encode the max // amount, else the four pixels must be the same mov ax, cx // get remaining length sub ax, bx xchg bx, cx // cx = run, bx = max cmp ax, 4 // are there 4 or more pixels left? jb @EncodeFragmentAbsRun // no encode the max amount xchg bx, cx // cx = max, bx = run mov al, [esi + ebx + 0] // get first pixel cmp al, [esi + ebx + 1] // are they the same? jne @EncodeFragmentAbsScan cmp al, [esi + ebx + 2] // are they the same? jne @EncodeFragmentAbsScan cmp al, [esi + ebx + 3] // are they the same? jne @EncodeFragmentAbsScan @EncodeFragmentAbsRun: xor al, al // store abs run (0, cnt) mov ah, bl stosw shr ecx, 16 // restore cx (length) sub cx, bx // subtract run length from total xchg cx, bx shr cx, 1 rep movsw adc cx, cx rep movsb mov cx, bx inc edi // word align RLE data and edi, not 1 // !!! store a zero? jcxz @EncodeFragmentExit // any pixels left to encode? jmp @EncodeFragmentLoop // and do it again. @EncodeFragmentExit: ret // determine the number of pixels that are not the same // as the previous frame, this run of pixels need to be encoded. // // a fragment ends when we run out of pixels or we find a run of similar // pixels greater than MinJumpLength // // Entry: // CX --> number of pixels in line // ESI --> DIB pixels to RLE // EDI --> Previous DIB image @FindFragmentLength: xor eax, eax xor ebx, ebx jcxz @FindFragmentLengthExit // look for a run of pixels that are not the same // to the previous frame, we must find MinJumpLength pixels that // are the same before we stop. mov ax, cx mov cx, word ptr MinJumpLength // put MinJumpLength in HIWORD(ecx) shl ecx, 16 mov cx, ax push ebp // save bp mov ebp, $FFFF @FindFragmentLengthLoop1: mov bx, -1 @FindFragmentLengthLoop: inc bx inc bp // another one not the same cmp bp, cx // do we got enough? je @FindFragmentLengthDone // ...yes all done mov ah, [edi + ebp] // !!!use words!!! cmp ah, [esi + ebp] // is it exact? je @FindFragmentLengthLoop // the same keep going (and counting) rol ecx, 16 // ax = HIWORD(ecx) = MinJumpLength mov ax, cx rol ecx, 16 cmp bx, ax // big enough run to stop? jb @FindFragmentLengthLoop1 // no, zero "same" count and keep going @FindFragmentLengthDone: sub cx, bp mov ax, bp // return length - jump sub ax, bx pop ebp @FindFragmentLengthExit: movzx ecx, cx ret @Exit: pop ebx pop edi pop esi end; function Rle8DeltaFrame( DibHeader : PDib; DibPixels, RlePixels, PrevFramePixels : pchar; Start, Len : integer; MinJump : integer ) : PDib; var AllocRle : boolean; Height : integer; JumpCount : integer; DeltaY : integer; begin assert( ( DibHeader.biBitCount = 8 ) and ( DibHeader.biCompression <> BI_RGB ), 'Non-8bpp DIB in DibRle.DibRle8DeltaFrame' ); with DibHeader^ do begin JumpCount := 0; if MinJump = 0 then MinJump := 4; Height := abs( DibHeader.biHeight ); if Len <= 0 then Len := Height; Len := min( Height - Start, Len ); if DibPixels = nil then DibPixels := DibPtr( DibHeader ); // create an RLE buffer to place the RLE bits in Result := DibNewHeader( biWidth, biHeight, 8 ); AllocRle := not Assigned( RlePixels ); if AllocRle then begin ReallocMem( Result, DibSize( Result ) ); RlePixels := DibPtr( Result ); end; Result.biSizeImage := 0; DibPixels := DibScanLine( DibHeader, DibPixels, Start ); while Start > 0 do begin DeltaY := min( Start, 255 ); dec( Start, DeltaY ); byte( RlePixels[0] ) := RLE_ESCAPE; byte( RlePixels[1] ) := RLE_JMP; byte( RlePixels[2] ) := 0; byte( RlePixels[3] ) := DeltaY; inc( RlePixels, 4 ); dec( JumpCount, 4 ); end; Swap4( Result.biHeight, Len ); PackRle8( Result, DibPixels, RlePixels, PrevFramePixels, MinJump ); Swap4( Result.biHeight, Len ); inc( Result.biSizeImage, JumpCount ); // adjust size to include JUMP! // Hey we are done! Unlock the buffers and get out if AllocRle then ReallocMem( Result, DibSize( Result ) ); end; end; end.
unit UStudent; interface type TStudent = class private FName: string; FAge: Integer; procedure SetAge(const Value: Integer); procedure SetName(const Value: string); public property Name: string read FName write SetName; property Age: Integer read FAge write SetAge; constructor Create(FName: string; FAge: Integer);overload; end; implementation { TStudent } constructor TStudent.Create(FName: string; FAge: Integer); begin Self.FName := FName; Self.FAge := FAge; end; procedure TStudent.SetAge(const Value: Integer); begin FAge := Value; end; procedure TStudent.SetName(const Value: string); begin FName := Value; end; end.
program ViewWith; { Test program for ViewDoc unit. } {$IFDEF FPC} {$MODE Delphi} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} {$R+,Q+} uses SysUtils, ViewDoc; var VwrIdx : Integer; Viewer : Integer; Options : TViewerOptions; InStr : string; ErrorMsg : string; Done : Boolean; begin if ParamCount < 2 then begin WriteLn('Usage: ViewWith viewername docfilename [-t] [-d]'); Exit; end; Viewer := 0; for VwrIdx := 1 to GetViewerCount do begin if SameText(ParamStr(1), GetViewerName(VwrIdx)) then Viewer := VwrIdx; end; if Viewer = 0 then WriteLn('Specified viewer not supported - using first viewer found'); Options := []; if FindCmdLineSwitch('t', ['-'], True) then {Treat file as template?} Options := Options + [ovwUseAsTemplate]; if FindCmdLineSwitch('d', ['-'], True) then {Delete file before exiting?} begin Options := Options + [ovwAddToDeleteList]; Write('File will be deleted when done viewing - is this okay (Y/N)? '); ReadLn(InStr); if CompareText(InStr, 'y') <> 0 then Exit; end; if not ViewDocument(ParamStr(2), Viewer, Options, ErrorMsg) then begin WriteLn(ErrorMsg); Exit; end; if FindCmdLineSwitch('d', ['-'], True) and FileExists(ParamStr(2)) then begin repeat Write('Press Enter when ready to delete file (or Ctrl+C to exit): '); ReadLn(InStr); Done := DeleteViewedDocs; if not Done then WriteLn(' Unable to delete file - may still be open in viewer'); until Done; end; end.
unit TileU; interface uses System.Math, System.UITypes, System.SysUtils, System.StrUtils; type TIncScoreEvent = procedure(const aScore: Integer) of object; TTile = class strict private const COLOR_DEFAULT: TColor = $B4C0CD; COLORS: array [1 .. 11] of TColor = ($DAE4EE, $C8E0ED, $79B1F2, $6395F5, $5F7CF6, $3B5EF6, $72CFED, $61CCED, $50C8ED, $3FC5ED, $2EC2ED); BASE: Integer = 2; DEFAULT_POWER: Integer = 0; INITIAL_POWER: Integer = 1; MAX_POWER: Integer = 11; private FChanged: Boolean; FCol: Integer; FDownTile: TTile; FLeftTile: TTile; FOnIncScore: TIncScoreEvent; FPower: Integer; FRightTile: TTile; FRow: Integer; FUpTile: TTile; procedure DoMerge(aTile: TTile); function GetContrastColor(aColor: TColor): TColor; procedure Clear; procedure DoOnIncScore(const aScore: Integer); function GetCanMerge: Boolean; function GetCaption: String; inline; function GetColor: TColor; function GetValue: Integer; function HasSamePower(const aTile: TTile): Boolean; function DoMove(aTile: TTile): Boolean; procedure MoveDown; procedure MoveLeft; procedure MoveRight; procedure MoveUp; procedure MergeDown; procedure MergeLeft; procedure MergeRight; procedure MergeUp; procedure RecursiveMergeDown; procedure RecursiveMergeLeft; procedure RecursiveMergeRight; procedure RecursiveMergeUp; procedure RecursiveMoveDown; procedure RecursiveMoveLeft; procedure RecursiveMoveRight; procedure RecursiveMoveUp; function GetTextColor: TColor; function HasDownTile: Boolean; {$IFNDEF DEBUG}inline; {$ENDIF} function HasLeftTile: Boolean; {$IFNDEF DEBUG}inline; {$ENDIF} function HasRightTile: Boolean; {$IFNDEF DEBUG}inline; {$ENDIF} function HasUpTile: Boolean; {$IFNDEF DEBUG}inline; {$ENDIF} function IsDownTile: Boolean; {$IFNDEF DEBUG}inline; {$ENDIF} function IsLeftTile: Boolean; {$IFNDEF DEBUG}inline; {$ENDIF} function IsRightTile: Boolean; {$IFNDEF DEBUG}inline; {$ENDIF} function IsUpTile: Boolean; {$IFNDEF DEBUG}inline; {$ENDIF} public constructor Create(const aRow: Integer; const aCol: Integer); overload; constructor Create(const aTile: TTile); overload; procedure AlignDown; procedure AlignLeft; procedure AlignRight; procedure AlignUp; procedure Fill; function IsMax: Boolean; {$IFNDEF DEBUG}inline; {$ENDIF} function IsEmpty: Boolean; {$IFNDEF DEBUG}inline; {$ENDIF} function ToString: String; override; property CanMerge: Boolean read GetCanMerge; property Caption: String read GetCaption; property TilePower: Integer read FPower write FPower; property Changed: Boolean read FChanged write FChanged; property Col: Integer read FCol write FCol; property Color: TColor read GetColor; property DownTile: TTile read FDownTile write FDownTile; property LeftTile: TTile read FLeftTile write FLeftTile; property RightTile: TTile read FRightTile write FRightTile; property Row: Integer read FRow write FRow; property UpTile: TTile read FUpTile write FUpTile; property Value: Integer read GetValue; property OnIncScore: TIncScoreEvent read FOnIncScore write FOnIncScore; property TextColor: TColor read GetTextColor; end; implementation uses VCL.GraphUtil; constructor TTile.Create(const aRow: Integer; const aCol: Integer); begin FPower := DEFAULT_POWER; FRow := aRow; FCol := aCol; FLeftTile := nil; FRightTile := nil; FUpTile := nil; FDownTile := nil; FOnIncScore := nil; end; constructor TTile.Create(const aTile: TTile); begin FPower := aTile.FPower; FRow := aTile.FRow; FCol := aTile.FCol; FLeftTile := aTile.FLeftTile; FRightTile := aTile.FRightTile; FUpTile := aTile.FUpTile; FDownTile := aTile.FDownTile; FOnIncScore := aTile.FOnIncScore; end; procedure TTile.AlignDown; begin if not IsDownTile then exit; RecursiveMoveDown; RecursiveMergeDown; RecursiveMoveDown; end; procedure TTile.AlignLeft; begin if not IsLeftTile then exit; RecursiveMoveLeft; RecursiveMergeLeft; RecursiveMoveLeft; end; procedure TTile.AlignRight; begin if not IsRightTile then exit; RecursiveMoveRight; RecursiveMergeRight; RecursiveMoveRight; end; procedure TTile.AlignUp; begin if not IsUpTile then exit; RecursiveMoveUp; RecursiveMergeUp; RecursiveMoveUp; end; procedure TTile.Clear; begin FPower := DEFAULT_POWER; FChanged := True; end; procedure TTile.DoMerge(aTile: TTile); begin if not Assigned(aTile) then exit; if aTile.IsEmpty then exit; if FPower <> aTile.TilePower then exit; Inc(FPower); aTile.Clear; DoOnIncScore(Value); end; function TTile.DoMove(aTile: TTile): Boolean; begin if (not Assigned(aTile)) or (IsEmpty or (not aTile.IsEmpty)) then exit(false); Result := True; aTile.TilePower := FPower; Clear; end; procedure TTile.DoOnIncScore(const aScore: Integer); begin FChanged := True; if Assigned(FOnIncScore) then FOnIncScore(aScore); end; procedure TTile.Fill; begin FPower := INITIAL_POWER; FChanged := false; end; function TTile.GetCanMerge: Boolean; begin Result := IsEmpty; if (not Result) and HasLeftTile then Result := HasSamePower(FLeftTile); if (not Result) and HasRightTile then Result := HasSamePower(FRightTile); if (not Result) and HasUpTile then Result := HasSamePower(FUpTile); if (not Result) and HasDownTile then Result := HasSamePower(FDownTile); end; function TTile.GetCaption: String; begin Result := IfThen(IsEmpty, String.Empty, Value.ToString); end; function TTile.GetColor: TColor; begin if IsEmpty then Result := COLOR_DEFAULT else Result := COLORS[FPower]; end; function TTile.GetContrastColor(aColor: TColor): TColor; var Hue, Luminance, Saturation: Word; begin // convert the color in hue, luminance, saturation ColorRGBToHLS(aColor, Hue, Luminance, Saturation); if (Luminance < 120) or ((Luminance = 120) and (Hue > 120)) then Result := TColors.White else Result := TColors.Black; end; function TTile.GetTextColor: TColor; begin Result := GetContrastColor(Color); end; function TTile.GetValue: Integer; begin Result := Round(Power(BASE, FPower)); end; function TTile.HasDownTile: Boolean; begin Result := Assigned(FDownTile); end; function TTile.HasLeftTile: Boolean; begin Result := Assigned(FLeftTile); end; function TTile.HasRightTile: Boolean; begin Result := Assigned(FRightTile); end; function TTile.HasSamePower(const aTile: TTile): Boolean; begin Result := false; if Assigned(aTile) then Result := FPower = aTile.TilePower; end; function TTile.HasUpTile: Boolean; begin Result := Assigned(FUpTile); end; function TTile.IsDownTile: Boolean; begin Result := not HasDownTile; end; function TTile.IsEmpty: Boolean; begin Result := FPower = DEFAULT_POWER; end; function TTile.IsLeftTile: Boolean; begin Result := not HasLeftTile; end; function TTile.IsMax: Boolean; begin Result := FPower >= MAX_POWER; end; function TTile.IsRightTile: Boolean; begin Result := not HasRightTile; end; function TTile.IsUpTile: Boolean; begin Result := not HasUpTile; end; procedure TTile.MergeDown; begin DoMerge(FUpTile); end; procedure TTile.MergeLeft; begin DoMerge(FRightTile); end; procedure TTile.MergeRight; begin DoMerge(FLeftTile); end; procedure TTile.MergeUp; begin DoMerge(FDownTile); end; procedure TTile.MoveDown; begin if DoMove(FDownTile) then FDownTile.MoveDown; end; procedure TTile.MoveLeft; begin if DoMove(FLeftTile) then FLeftTile.MoveLeft; end; procedure TTile.MoveRight; begin if DoMove(FRightTile) then FRightTile.MoveRight; end; procedure TTile.MoveUp; begin if DoMove(FUpTile) then FUpTile.MoveUp; end; procedure TTile.RecursiveMergeDown; begin MergeDown; if HasUpTile then FUpTile.RecursiveMergeDown; end; procedure TTile.RecursiveMergeLeft; begin MergeLeft; if HasRightTile then FRightTile.RecursiveMergeLeft; end; procedure TTile.RecursiveMergeRight; begin MergeRight; if HasLeftTile then FLeftTile.RecursiveMergeRight; end; procedure TTile.RecursiveMergeUp; begin MergeUp; if HasDownTile then FDownTile.RecursiveMergeUp; end; procedure TTile.RecursiveMoveDown; begin MoveDown; if HasUpTile then FUpTile.RecursiveMoveDown; end; procedure TTile.RecursiveMoveLeft; begin MoveLeft; if HasRightTile then FRightTile.RecursiveMoveLeft; end; procedure TTile.RecursiveMoveRight; begin MoveRight; if HasLeftTile then FLeftTile.RecursiveMoveRight; end; procedure TTile.RecursiveMoveUp; begin MoveUp; if HasDownTile then FDownTile.RecursiveMoveUp; end; function TTile.ToString: String; begin Result := Caption; end; end.
unit DAO.CadastroRH; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.CadastroRH; type TCadastroRHDAO = class private FConexao : TConexao; public constructor Create; function Inserir(ACadastro: TCadastroRH): Boolean; function Alterar(ACadastro: TCadastroRH): Boolean; function Excluir(ACadastro: TCadastroRH): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; end; const TABLENAME = 'cadastro_rh'; implementation { TCadastroRHDAO } function TCadastroRHDAO.Alterar(ACadastro: TCadastroRH): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET ' + 'NUM_PIS = :PNUM_PIS, NUM_CTPS = :PNUM_CTPS, NUM_SERIE_CTPS = :PNUM_SERIE_CTPS, ' + 'UF_CTPS = :PUF_CTPS, NUM_TITULO_ELEITOR = :PNUM_TITULO_ELEITOR, DES_ZONA_ELEITORAL = :PDES_ZONA_ELEITORAL, ' + 'DES_SECAO_ELEITORAL = :PDES_SECAO_ELEITORAL, NOM_MUNICIPIO_ELEITORAL = :PNOM_MUNICIPIO_ELEITORAL, ' + 'UF_ELEITORAL = :PUF_ELEITORAL, NUM_RESERVISTA = :PNUM_RESERVISTA, ID_FUNCAO = :PID_FUNCAO, ' + 'DAT_ADMISSAO = :PDAT_ADMISSAO, DAT_DEMISSAO = :PDAT_DEMISSAO, ID_FOLHA = :PID_FOLHA, ' + 'ID_STATUS = :PID_STATUS, DES_OBS = :PDES_OBS ' + 'WHERE ID_CADASTRO = :PID_CADASTRO', [ACadastro.PIS, ACadastro.NumeroCTPS, ACadastro.SerieCTPS, ACadastro.UFCTPS, ACadastro.NumeroTituloEleitor, ACadastro.ZonaTituloEleitor, ACadastro.SecaoTituloEleitor, ACadastro.MunicipioTituloEleitor, ACadastro.UFTituloEleitor, ACadastro.NumeroReservista, ACadastro.Funcao, ACadastro.Adminissao, ACadastro.Demissao, ACadastro.IDFolha, ACadastro.Status, ACadastro.OBS, ACadastro.ID]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TCadastroRHDAO.Create; begin FConexao := TConexao.Create; end; function TCadastroRHDAO.Excluir(ACadastro: TCadastroRH): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('DELETE FROM ' + TABLENAME + ' where WHERE ID_CADASTRO = :PID_CADASTRO', [ACadastro.ID]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TCadastroRHDAO.Inserir(ACadastro: TCadastroRH): Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + '(ID_CADASTRO, NUM_PIS, NUM_CTPS, NUM_SERIE_CTPS, UF_CTPS, NUM_TITULO_ELEITOR, DES_ZONA_ELEITORAL, ' + 'DES_SECAO_ELEITORAL, NOM_MUNICIPIO_ELEITORAL, UF_ELEITORAL, NUM_RESERVISTA, ID_FUNCAO, DAT_ADMISSAO, ' + 'DAT_DEMISSAO, ID_FOLHA, ID_STATUS, DES_OBS) ' + 'VALUES ' + '(:PID_CADASTRO, :PNUM_PIS, :PNUM_CTPS, :PNUM_SERIE_CTPS, :PUF_CTPS, :PNUM_TITULO_ELEITOR, ' + ':PDES_ZONA_ELEITORAL, :PDES_SECAO_ELEITORAL, :PNOM_MUNICIPIO_ELEITORAL, :PUF_ELEITORAL, :PNUM_RESERVISTA, ' + ':PID_FUNCAO, DAT_ADMISSAO, :PDAT_DEMISSAO, :PID_FOLHA, :PID_STATUS, :PDES_OBS) ', [ACadastro.ID, ACadastro.PIS, ACadastro.NumeroCTPS, ACadastro.SerieCTPS, ACadastro.UFCTPS, ACadastro.NumeroTituloEleitor, ACadastro.ZonaTituloEleitor, ACadastro.SecaoTituloEleitor, ACadastro.MunicipioTituloEleitor, ACadastro.UFTituloEleitor, ACadastro.NumeroReservista, ACadastro.Funcao, ACadastro.Adminissao, ACadastro.Demissao, ACadastro.IDFolha, ACadastro.Status, ACadastro.OBS]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroRHDAO.Pesquisar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('WHERE ID_CADASTRO = :ID_CADASTRO'); FDQuery.ParamByName('ID_CADASTRO').AsInteger := aParam[1]; end; if aParam[0] = 'PIS' then begin FDQuery.SQL.Add('WHERE NUM_PIS = :NUM_PIS'); FDQuery.ParamByName('NUM_PIS').AsString := aParam[1]; end; if aParam[0] = 'CTPS' then begin FDQuery.SQL.Add('WHERE NUM_CTPS LIKE :NUM_CTPS'); FDQuery.ParamByName('NUM_CTPS').AsString := aParam[1]; end; if aParam[0] = 'TITULO' then begin FDQuery.SQL.Add('WHERE NUM_TITULO_ELEITOR = :NUM_TITULO_ELEITOR'); FDQuery.ParamByName('NUM_TITULO_ELEITOR').AsString := aParam[1]; end; if aParam[0] = 'RESERVISTA' then begin FDQuery.SQL.Add('WHERE NUM_RESERVISTA = :NUM_RESERVISTA'); FDQuery.ParamByName('NUM_RESERVISTA').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; FDQuery.Open(); Result := FDQuery; end; end.
unit sn_76496; interface uses {$IFDEF WINDOWS}windows,{$else}main_engine,{$ENDIF}sound_engine; type SN76496_chip=class(snd_chip_class) constructor Create(clock:dword;amp:single=1); destructor free; public UpdateStep:dword; VolTable:array[0..15] of single; // volume table Registers:array[0..7] of word; // registers LastRegister:byte; // last register written Volume:array [0..3] of single; Period,Count:array [0..3] of integer; // volume of voice 0-2 and noise Output:array [0..3] of byte; RNG:cardinal; // noise generator */ NoiseFB:integer; // noise feedback mask */ procedure Write(data:byte); procedure update; procedure reset; function save_snapshot(data:pbyte):word; procedure load_snapshot(data:pbyte); procedure change_clock(clock:dword); private procedure set_gain(gain:integer); procedure resample; end; var sn_76496_0,sn_76496_1,sn_76496_2,sn_76496_3:sn76496_chip; implementation const REGS_SIZE=161; MAX_OUTPUT=$7fff; SN_STEP=$10000; FB_WNOISE=$14002; FB_PNOISE=$8000; NG_PRESET=$0f35; constructor sn76496_chip.Create(clock:dword;amp:single=1); begin self.amp:=amp; self.set_gain(0); self.clock:=clock; self.tsample_num:=init_channel; self.resample; self.reset; end; destructor sn76496_chip.free; begin end; type tsn76496=packed record UpdateStep:dword; VolTable:array[0..15] of single; Registers:array[0..7] of word; LastRegister:byte; Volume:array [0..3] of single; Period,Count:array [0..3] of integer; Output:array [0..3] of byte; RNG:cardinal; NoiseFB:integer; end; procedure sn76496_chip.change_clock(clock:dword); begin self.clock:=clock; self.resample; end; function sn76496_chip.save_snapshot(data:pbyte):word; var sn76496:^tsn76496; begin getmem(sn76496,sizeof(tsn76496)); sn76496.UpdateStep:=self.UpdateStep; copymemory(@sn76496.VolTable,@self.VolTable,16*sizeof(single)); copymemory(@sn76496.Registers,@self.Registers,8*2); sn76496.LastRegister:=self.LastRegister; copymemory(@sn76496.Volume,@self.Volume,4*sizeof(single)); copymemory(@sn76496.Period,@self.Period,4*4); copymemory(@sn76496.Count,@self.Count,4*4); copymemory(@sn76496.Output,@self.Output,4); sn76496.RNG:=self.RNG; sn76496.NoiseFB:=self.NoiseFB; copymemory(data,sn76496,REGS_SIZE); freemem(sn76496); save_snapshot:=REGS_SIZE; end; procedure sn76496_chip.load_snapshot(data:pbyte); var sn76496:^tsn76496; begin getmem(sn76496,sizeof(tsn76496)); copymemory(sn76496,data,REGS_SIZE); self.UpdateStep:=sn76496.UpdateStep; copymemory(@self.VolTable,@sn76496.VolTable,16*sizeof(single)); copymemory(@self.Registers,@sn76496.Registers,8*2); self.LastRegister:=sn76496.LastRegister; copymemory(@self.Volume,@sn76496.Volume,4*sizeof(single)); copymemory(@self.Period,@sn76496.Period,4*4); copymemory(@self.Count,@sn76496.Count,4*4); copymemory(@self.Output,@sn76496.Output,4); self.RNG:=sn76496.RNG; self.NoiseFB:=sn76496.NoiseFB; freemem(sn76496); end; procedure sn76496_chip.Write(data:byte); var r,c,n:integer; begin // update the output buffer before changing the registers //SN76496update(num); if (data and $80)<>0 then begin r:=(data and $70) shr 4; c:=r div 2; self.LastRegister:=r; self.Registers[r]:=(self.Registers[r] and $3f0) or (data and $0f); case r of 0,2,4:begin // tone 0 : frequency,tone 1 : frequency,tone 2 : frequency */ self.Period[c]:=self.UpdateStep*self.Registers[r]; if (self.Period[c]=0) then self.Period[c]:=self.UpdateStep; if (r=4) then begin //update noise shift frequency */ if ((self.Registers[6] and $03)=$03) then self.Period[3]:=self.Period[2]*2; end; end; 1,3,5,7:begin // tone 0 : volume,tone 1 : volume,tone 2 : volume,noise : volume */ self.Volume[c]:=self.VolTable[data and $0f]; end; 6:begin // noise : frequency, mode */ n:=self.Registers[6]; if (n and 4)<>0 then self.NoiseFB:=FB_WNOISE else self.NoiseFB:=FB_PNOISE; n:=n and 3; //* N/512,N/1024,N/2048,Tone #3 output */ if ((n and 3)=3) then self.Period[3]:=self.Period[2]*2 else self.Period[3]:=self.UpdateStep shl (5+(n and 3)); // reset noise shifter */ self.RNG:=NG_PRESET; self.Output[3]:=self.RNG and 1; end; end; //del case end else begin //del if r:=self.LastRegister; c:=r div 2; case r of 0,2,4:begin // tone 0 : frequency,tone 1 : frequency,tone 2 : frequency */ self.Registers[r]:= (self.Registers[r] and $0f) or ((data and $3f) shl 4); self.Period[c]:=self.UpdateStep*self.Registers[r]; if (self.Period[c]=0) then self.Period[c]:=self.UpdateStep; if (r=4) then begin // update noise shift frequency */ if ((self.Registers[6] and $03) = $03) then self.Period[3]:=self.Period[2]*2; end; end; 1,3,5,7:begin //* tone 0 : volume,tone 1 : volume,tone 2 : volume,noise : volume */ self.volume[c]:= self.VolTable[data and $0f]; self.Registers[r]:=(self.Registers[r] and $3f0) or (data and $0f); end; 6:begin // noise : frequency, mode */ self.Registers[r]:= (self.Registers[r] and $3f0) or (data and $0f); n:= self.Registers[6]; if (n and 4)<>0 then self.NoiseFB:=FB_WNOISE else self.NoiseFB:=FB_PNOISE; n:=n and 3; // N/512,N/1024,N/2048,Tone #3 output */ if ((n and 3)=3) then self.Period[3]:=2 * self.Period[2] else self.Period[3]:=self.UpdateStep shl (5+(n and 3)); // reset noise shifter */ self.RNG:=NG_PRESET; self.Output[3]:= self.RNG and 1; end; end; //del case end; end; procedure sn76496_chip.set_gain(gain:integer); var i:integer; out_sn:single; begin // increase max output basing on gain (0.2 dB per step) */ out_sn:=MAX_OUTPUT/3; while (gain> 0) do begin gain:=gain-1; out_sn:=out_sn*1.023292992; // = (10 ^ (0.2/20)) */ end; // build volume table (2dB per step) */ for i:=0 to 14 do begin // limit volume to avoid clipping */ if (out_sn>(MAX_OUTPUT/3)) then self.VolTable[i]:=MAX_OUTPUT/3 else self.VolTable[i]:=out_sn; out_sn:=out_sn/1.258925412; // = 10 ^ (2/20) = 2dB */ end; self.VolTable[15]:=0; end; procedure sn76496_chip.reset; var i:byte; begin for i:=0 to 3 do self.Volume[i]:=0; self.LastRegister:= 0; for i:=0 to 3 do begin self.Registers[i*2]:=0; self.Registers[(i*2) + 1]:=$0f; // volume = 0 */ end; for i:=0 to 3 do begin self.Output[i]:=0; self.Period[i]:=self.UpdateStep; self.Count[i]:=self.UpdateStep; end; self.RNG:=NG_PRESET; self.Output[3]:=self.RNG and 1; end; procedure sn76496_chip.resample; var tmp:uint64; begin { the base clock for the tone generators is the self clock divided by 16 for the noise generator, it is clock / 256. Here we calculate the number of steps which happen during one sample at the given sample rate. No. of events = sample rate / (clock/16). STEP is a multiplier used to turn the fraction into a fixed point number. } tmp:=SN_STEP*16; tmp:=tmp*FREQ_BASE_AUDIO; self.UpdateStep:=round(tmp/self.clock); end; procedure sn76496_chip.update; Var i,left,nextevent:Integer; out_sn:single; vol:array[0..3] of integer; begin // If the volume is 0, increase the counter */ for i:=0 to 3 do begin if (self.Volume[i]=0) then begin { note that I do count += length, NOT count = length + 1. You might think */ it's the same since the volume is 0, but doing the latter could cause */ interferencies when the program is rapidly modulating the volume. } if (self.Count[i]<=SN_STEP) then inc(self.Count[i],SN_STEP); end; end; { vol[] keeps track of how long each square wave stays in the 1 position during the sample period. } for i:=0 to 3 do vol[i]:=0; for i:=0 to 2 do begin if (self.Output[i])<>0 then inc(vol[i],self.Count[i]); dec(self.Count[i],SN_STEP); { Period[i] is the half period of the square wave. Here, in each */ loop I add Period[i] twice, so that at the end of the loop the */ square wave is in the same status (0 or 1) it was at the start. */ vol[i] is also incremented by Period[i], since the wave has been 1 */ exactly half of the time, regardless of the initial position. */ If we exit the loop in the middle, Output[i] has to be inverted */ and vol[i] incremented only if the exit status of the square */ wave is 1. } while (self.Count[i] <= 0) do begin inc(self.Count[i],self.Period[i]); if (self.Count[i] > 0) then begin self.Output[i]:=self.Output[i] xor 1; if (self.Output[i])<>0 then inc(vol[i],self.Period[i]); break; end; inc(self.Count[i],self.Period[i]); inc(vol[i],self.Period[i]); end; //del while if (self.Output[i])<>0 then dec(vol[i],self.Count[i]); end; //del for left:=SN_STEP; repeat if (self.Count[3] < left) then nextevent:=self.Count[3] else nextevent:=left; if (self.Output[3])<>0 then inc(vol[3],self.Count[3]); dec(self.Count[3],nextevent); if (self.Count[3] <= 0) then begin if (self.RNG and 1)<>0 then self.RNG:=self.RNG xor self.NoiseFB; self.RNG:=self.RNG shr 1; self.Output[3]:=self.RNG and 1; inc(self.Count[3],self.Period[3]); if (self.Output[3])<>0 then inc(vol[3],self.Period[3]); end; if (self.Output[3])<>0 then dec(vol[3],self.Count[3]); dec(left,nextevent); until (left=0); out_sn:= vol[0] * self.Volume[0] + vol[1] * self.Volume[1] + vol[2] * self.Volume[2] + vol[3] * self.Volume[3]; if (out_sn>MAX_OUTPUT*SN_STEP) then out_sn:=MAX_OUTPUT*SN_STEP; tsample[self.tsample_num,sound_status.posicion_sonido]:=trunc((out_sn/SN_STEP)*self.amp); if sound_status.stereo then tsample[self.tsample_num,sound_status.posicion_sonido+1]:=trunc((out_sn/SN_STEP)*self.amp); end; end.
PROGRAM Demo1; {******************************************************* ** ** ** DEMO1: Show mouse in text and graphics modes ** ** ** *******************************************************} USES Crt, VESA256; PROCEDURE WaitForUser; {returns the moment something changes (mouse buttons and keyboard)} BEGIN ShowMouse; REPEAT MoveMouse UNTIL NOT IsMouseButtonDown; REPEAT MoveMouse; IF KeyPressed THEN BEGIN ReadKey; BREAK; END; UNTIL IsMouseButtonDown; HideMouse; END; {WaitForUser} BEGIN TextColor(Yellow); WriteLn; WriteLn('Welcome to this simple VESA256 DEMO.'); WriteLn; WriteLn('Notice that the mouse is already working'); WriteLn; WriteLn('Simply push a key or a mouse button to continue the demo...'); WaitForUser; IF StartVESA256(VESA640x480,Black) THEN BEGIN PutText(100,100,'And the mouse works here too....', TRUE,1,Yellow,Black,CopyBlit); WaitForUser; IF StartVESA256(VESA800x600,Black) THEN BEGIN PutText(200,200,'And the mouse still works....', TRUE,1,Yellow,Black,CopyBlit); WaitForUser; END ELSE WriteLn('Your video card does not support VESA800x600.'); END ELSE WriteLn('Your video card does not support VESA640x480.'); FinishVESA256; TextColor(Yellow); WriteLn; WriteLn('And back in text mode we still have a mouse....'); WriteLn; WaitForUser; END.
//Exercicio 23: Faça um algoritmo que leia dois valores inteiros A e B. Se os valores forem iguais deverão se somar os //dois, caso contrário multiplique A por B e exiba o resultado na tela. { Solução em Portugol Algoritmo Exercicio 23; Var A,B: inteiro; Inicio exiba("Programa que faz operações com 2 números."); exiba("Digite um valor para A: "); leia(A); exiba("Digite um valor para B: "); leia(B); se(A = B) então exiba("Como A = B, então A + B = ", A + B,".") senão exiba("Como A <> B, então A x B = ", A * B,"."); fimse; Fim. } // Solução em Pascal Program Exercicio23; uses crt; var A,B: integer; begin clrscr; writeln('Programa que faz operações com 2 números.'); writeln('Digite um valor para A: '); readln(A); writeln('Digite um valor para B: '); readln(B); if(A = B) then writeln('Como A = B, então A + B = ', A + B,'.') else writeln('Como A <> B, então A x B = ', A * B,'.'); repeat until keypressed; end.
{!DOCTOPIC}{ Standard functions } {!DOCREF} { @method: function se.IndexOf(var Haystack, Needle; HaystkLen:UInt32; ElmntSize:SizeInt): Int32; @desc: Finds the position of the Needle in the Haystack. Both needle and haystack can be [u]any data-type[/u], tho haystack should always be an Array. Requres information about the array, and the size of the elements in the array | Use: `SizeOf(<DataType>)`. [b]Example:[/b] [code=pascal] var Arr:TIntArray; Item:Int32; begin Arr := [0,2,4,6,8,10]; Item := 8; WriteLn( se.IndexOf(Arr[0], Item, Length(Arr), SizeOf(Integer)) ); end; [/code]>> `4` [params] [b]Haystack:[/b] Referance to the haystack position. [b]Needle:[/b] The needle. [b]HaystkLen:[/b] Number of elements in haystack [b]ElmntSize:[/b] Size of each element. [/params] } function SimbaExt.IndexOf(var Haystack,Needle; HaystkLen:UInt32; ElmntSize:SizeInt): Int32; var i,hi,lo,ss:Int32; PBData,PBSeek,P,Q:PChar; begin PBData := PChar(@Haystack); PBSeek := PChar(@Needle); P := PBData[0]; Q := PBSeek[0]; lo := Int32(PBData[0]); hi := Int32(PBData[HaystkLen*ElmntSize] - ElmntSize); while hi > UInt32(P) do begin if (Q^ <> P^) then begin inc(p,ElmntSize); continue; end; if CompareMem(Q, P, ElmntSize) then Exit((UInt32(P)-lo) div ElmntSize); inc(p,ElmntSize); end; Exit(-1); end; {!DOCREF} { @method: function se.Reduce(Func:Pointer; Arr:<1d array type>): <data type>; @desc: Returns a single value constructed by calling the function `func` on the first two items of the sequence, then on the result and the next item, and so on.[br] For example, to compute the sum of the numbers 1 through 10: [code=pascal] function F(x,y:Int32): Int32; begin Result := x + y; end; [br] WriteLn( se.Reduce(@F, [1,2,3,4,5,6,7,8,9,10]) ); [/code] Output: `55` [params] [b]Func:[/b] function that takes two parameters (same type as array items), and returns the same type as the array items. [b]Arr:[/b] TByteArray, TIntArray, TFloatArray, TDoubleArray, TExtArray, TPointArray, TBoxArray [b]func64:[/b] [Byte, Int, Single]: if `True` then params of the given functions must be 64bit, meaning `Double`, or `Int64`, used to avoid overflowing. [/params] } {$IFNDEF CODEINSIGHT} type __TReduceTBtA = function (x,y:Byte): Int64; __TReduceTIA = function (x,y:Int32): Int64; __TReduceTFA = function (x,y:Single): Extended; __TReduceTDA = function (x,y:Double): Extended; __TReduceTEA = function (x,y:Extended): Extended; __TReduceTPA = function (x,y:TPoint): TPoint; __TReduceTBA = function (x,y:TBox): TBox; __TReduceTBtA64 = function (x,y:Int64): Int64; __TReduceTIA64 = function (x,y:Int64): Int64; __TReduceTFA64 = function (x,y:Single): Extended; {$ENDIF} //---| TBtA |---\\ function SimbaExt.Reduce(Func:Pointer; Arr:TByteArray; func64:Boolean=False): Int64; overload; var i,l:Int32; Def:__TReduceTBtA; Def2: __TReduceTBtA64; begin l := High(Arr); if l < 0 then Exit(0); if l = 0 then Exit(Arr[0]); case func64 of False: begin Def := Func; Result := Def(Arr[0],Arr[1]); for i:=2 to High(Arr) do Result := Def(Result,Arr[i]); end; True: begin Def2 := Func; Result := Def2(Arr[0],Arr[1]); for i:=2 to High(Arr) do Result := Def2(Result,Arr[i]); end; end; end; //---| TIA |---\\ function SimbaExt.Reduce(Func:Pointer; Arr:TIntArray; func64:Boolean=False): Int64; overload; {inline} var i,l:Int32; Def:__TReduceTIA; Def2: __TReduceTIA64; begin l := High(Arr); if l < 0 then Exit(0); if l = 0 then Exit(Arr[0]); case func64 of False: begin Def := Func; Result := Def(Arr[0],Arr[1]); for i:=2 to High(Arr) do Result := Def(Result,Arr[i]); end; True: begin Def2 := Func; Result := Def2(Arr[0],Arr[1]); for i:=2 to High(Arr) do Result := Def2(Result,Arr[i]); end; end; end; //---| TFA |---\\ function SimbaExt.Reduce(Func:Pointer; Arr:TFloatArray; func64:Boolean=False): Double; overload; var i,l:Int32; Def:__TReduceTFA; Def2:__TReduceTFA64; begin l := High(Arr); if l < 0 then Exit(0); if l = 0 then Exit(Arr[0]); case func64 of False: begin Def := Func; Result := Def(Arr[0],Arr[1]); for i:=2 to High(Arr) do Result := Def(Result,Arr[i]); end; True: begin Def2 := Func; Result := Def2(Arr[0],Arr[1]); for i:=2 to High(Arr) do Result := Def2(Result,Arr[i]); end; end; end; //---| TDA |---\\ function SimbaExt.Reduce(Func:Pointer; Arr:TDoubleArray): Extended; overload; var i,l:Int32; Def:__TReduceTDA; begin l := High(Arr); if l < 0 then Exit(0); if l = 0 then Exit(Arr[0]); Def := Func; Result := Def(Arr[0],Arr[1]); for i:=2 to High(Arr) do Result := Def(Result,Arr[i]); end; //---| TEA |---\\ function SimbaExt.Reduce(Func:Pointer; Arr:TExtArray): Extended; overload; var i,l:Int32; Def:__TReduceTEA; begin l := High(Arr); if l < 0 then Exit(0); if l = 0 then Exit(Arr[0]); Def := Func; Result := Def(Arr[0],Arr[1]); for i:=2 to High(Arr) do Result := Def(Result,Arr[i]); end; //---| TPA |---\\ function SimbaExt.Reduce(Func:Pointer; Arr:TPointArray): TPoint; overload; var i,l:Int32; Def:__TReduceTPA; begin l := High(Arr); if l < 0 then Exit(Point(0,0)); if l = 0 then Exit(Arr[0]); Def := Func; Result := Def(Arr[0],Arr[1]); for i:=2 to High(Arr) do Result := Def(Result,Arr[i]); end; //---| TBA |---\\ function SimbaExt.Reduce(Func:Pointer; Arr:TBoxArray): TBox; overload; var i,l:Int32; Def:__TReduceTBA; begin l := High(Arr); if l < 0 then Exit(TBox([0,0,0,0])); if l = 0 then Exit(Arr[0]); Def := Func; Result := Def(Arr[0],Arr[1]); for i:=2 to High(Arr) do Result := Def(Result,Arr[i]); end; {!DOCREF} { @method: function se.Filter(Func:Pointer; Arr:<1d array type>): <1d array type>; @desc: Returns a array consisting of those items from the array for which `func(item)` is True. The result will always be of the same type as Arr.[br] For example, to compute a sequence of numbers not divisible by 2 or 3: [code=pascal] function F(x:Int32): Boolean; begin Result := (x mod 2 <> 0) and (x mod 3 <> 0); end; [br] WriteLn( se.Filter(@F, [1,2,3,4,5,6,7,8,9,10]) ); [/code] Output: `[1, 5, 7]` [params] [b]Func:[/b] function that takes 1 parameter (same type as array items), and returns a boolean [b]Arr:[/b] TByteArray, TIntArray, TFloatArray, TDoubleArray, TExtArray, TPointArray, TBoxArray [/params] } {$IFNDEF CODEINSIGHT} type __TFilterTBtA = function (x:Byte): Boolean; __TFilterTIA = function (x:Int32): Boolean; __TFilterTFA = function (x:Single): Boolean; __TFilterTDA = function (x:Double): Boolean; __TFilterTEA = function (x:Extended): Boolean; __TFilterTPA = function (x:TPoint): Boolean; __TFilterTBA = function (x:TBox): Boolean; {$ENDIF} //---| TBtA |---\\ function SimbaExt.Filter(Func:Pointer; Arr:TByteArray): TByteArray; overload; var i,l,j:Int32; Def:__TFilterTBtA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); j := 0; for i:=0 to High(Arr) do if Def(Arr[i]) then begin Result[j] := Arr[i]; Inc(j); end; SetLength(Result, j); end; //---| TIA |---\\ function SimbaExt.Filter(Func:Pointer; Arr:TIntArray): TIntArray; overload; var i,l,j:Int32; Def:__TFilterTIA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); j := 0; for i:=0 to High(Arr) do if Def(Arr[i]) then begin Result[j] := Arr[i]; Inc(j); end; SetLength(Result, j); end; //---| TFA |---\\ function SimbaExt.Filter(Func:Pointer; Arr:TFloatArray): TFloatArray; overload; var i,l,j:Int32; Def:__TFilterTFA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); j := 0; for i:=0 to High(Arr) do if Def(Arr[i]) then begin Result[j] := Arr[i]; Inc(j); end; SetLength(Result, j); end; //---| TDA |---\\ function SimbaExt.Filter(Func:Pointer; Arr:TDoubleArray): TDoubleArray; overload; var i,l,j:Int32; Def:__TFilterTDA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); j := 0; for i:=0 to High(Arr) do if Def(Arr[i]) then begin Result[j] := Arr[i]; Inc(j); end; SetLength(Result, j); end; //---| TEA |---\\ function SimbaExt.Filter(Func:Pointer; Arr:TExtArray): TExtArray; overload; var i,l,j:Int32; Def:__TFilterTEA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); j := 0; for i:=0 to High(Arr) do if Def(Arr[i]) then begin Result[j] := Arr[i]; Inc(j); end; SetLength(Result, j); end; //---| TPA |---\\ function SimbaExt.Filter(Func:Pointer; Arr:TPointArray): TPointArray; overload; var i,l,j:Int32; Def:__TFilterTPA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); j := 0; for i:=0 to High(Arr) do if Def(Arr[i]) then begin Result[j] := Arr[i]; Inc(j); end; SetLength(Result, j); end; //---| TBA |---\\ function SimbaExt.Filter(Func:Pointer; Arr:TBoxArray): TBoxArray; overload; var i,l,j:Int32; Def:__TFilterTBA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); j := 0; for i:=0 to High(Arr) do if Def(Arr[i]) then begin Result[j] := Arr[i]; Inc(j); end; SetLength(Result, j); end; {!DOCREF} { @method: function se.Filter(Func:Pointer; Arr:<1d array type>; Args:TVaraintArray): <1d array type>; overload; @desc: Returns a array consisting of those items from the array for which `func(item)` is True. The result will always be of the same type as Arr.[br] For example, to filter out points not within a circle: [code=pascal] function FilterDist(Pt:TPoint; Args:TVariantArray): Boolean; begin Result := Math.DistEuclidean( pt, Point(Args[0],Args[1]) ) < Args[2]; end; [br] var TPA:TPointArray; BMP:TRafBitmap; begin TPA := TPAFromBox(ToBox(0,0,250,250)); TPA := se.Filter( @FilterDist, TPA, TVariantArray([100,100,100.0]) ); [br] BMP.Create(300,300); BMP.SetPixels(TPA,255); BMP.Debug(); BMP.Free(); end. [/code] Output: [i]run the code to see[/i] [params] [b]Func:[/b] function that takes 2 parameter `x`:same type as array items | `Args`:TVariantArray | Return a boolean [b]Arr:[/b] TByteArray, TIntArray, TFloatArray, TDoubleArray, TExtArray, TPointArray, TBoxArray [b]Args:[/b] TVaraintArray used to pass extra infomation to the filter function. [/params] } {$IFNDEF CODEINSIGHT} type __TFilterExTBtA = function (x:Byte; Args:TVariantArray): Boolean; __TFilterExTIA = function (x:Int32; Args:TVariantArray): Boolean; __TFilterExTFA = function (x:Single; Args:TVariantArray): Boolean; __TFilterExTDA = function (x:Double; Args:TVariantArray): Boolean; __TFilterExTEA = function (x:Extended; Args:TVariantArray): Boolean; __TFilterExTPA = function (x:TPoint; Args:TVariantArray): Boolean; __TFilterExTBA = function (x:TBox; Args:TVariantArray): Boolean; {$ENDIF} //---| TBtA |---\\ function SimbaExt.Filter(Func:Pointer; Arr:TByteArray; Args:TVariantArray): TByteArray; overload; var i,l,j:Int32; Def:__TFilterExTBtA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); j := 0; for i:=0 to High(Arr) do if Def(Arr[i], Args) then begin Result[j] := Arr[i]; Inc(j); end; SetLength(Result, j); end; //---| TIA |---\\ function SimbaExt.Filter(Func:Pointer; Arr:TIntArray; Args:TVariantArray): TIntArray; overload; var i,l,j:Int32; Def:__TFilterExTIA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); j := 0; for i:=0 to High(Arr) do if Def(Arr[i],Args) then begin Result[j] := Arr[i]; Inc(j); end; SetLength(Result, j); end; //---| TFA |---\\ function SimbaExt.Filter(Func:Pointer; Arr:TFloatArray; Args:TVariantArray): TFloatArray; overload; var i,l,j:Int32; Def:__TFilterExTFA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); j := 0; for i:=0 to High(Arr) do if Def(Arr[i],Args) then begin Result[j] := Arr[i]; Inc(j); end; SetLength(Result, j); end; //---| TDA |---\\ function SimbaExt.Filter(Func:Pointer; Arr:TDoubleArray; Args:TVariantArray): TDoubleArray; overload; var i,l,j:Int32; Def:__TFilterExTDA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); j := 0; for i:=0 to High(Arr) do if Def(Arr[i],Args) then begin Result[j] := Arr[i]; Inc(j); end; SetLength(Result, j); end; //---| TEA |---\\ function SimbaExt.Filter(Func:Pointer; Arr:TExtArray; Args:TVariantArray): TExtArray; overload; var i,l,j:Int32; Def:__TFilterExTEA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); j := 0; for i:=0 to High(Arr) do if Def(Arr[i],Args) then begin Result[j] := Arr[i]; Inc(j); end; SetLength(Result, j); end; //---| TPA |---\\ function SimbaExt.Filter(Func:Pointer; Arr:TPointArray; Args:TVariantArray): TPointArray; overload; var i,l,j:Int32; Def:__TFilterExTPA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); j := 0; for i:=0 to High(Arr) do if Def(Arr[i],Args) then begin Result[j] := Arr[i]; Inc(j); end; SetLength(Result, j); end; //---| TBA |---\\ function SimbaExt.Filter(Func:Pointer; Arr:TBoxArray; Args:TVariantArray): TBoxArray; overload; var i,l,j:Int32; Def:__TFilterExTBA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); j := 0; for i:=0 to High(Arr) do if Def(Arr[i],Args) then begin Result[j] := Arr[i]; Inc(j); end; SetLength(Result, j); end; {!DOCREF} { @method: function se.Map(Func:Pointer; Arr:<1d array type>): <1d array type>; @desc: Calls `Func(item)` for each of the array's items and returns an array of the return values. The result type will always be the same as the input type.[br] For example, to compute some cubes: [code=pascal] function F(x:Int32): Int32; begin Result := x*x*x; end; [br] WriteLn( se.Map(@F, [1,2,3,4,5,6,7,8,9,10]) ); [/code] Output: `[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]` [params] [b]Func:[/b] function that takes 1 parameter (same type as array items), and returns a the same type as the array items. [b]Arr:[/b] TByteArray, TIntArray, TFloatArray, TDoubleArray, TExtArray, TPointArray, TBoxArray [/params] } {$IFNDEF CODEINSIGHT} type __TMapTBtA = function (x:Byte): Int32; __TMapTIA = function (x:Int32): Int32; __TMapTFA = function (x:Single): Extended; __TMapTDA = function (x:Double): Extended; __TMapTEA = function (x:Extended): Extended; __TMapTPA = function (x:TPoint): TPoint; __TMapTBA = function (x:TBox): TBox; {$ENDIF} //---| TBtA |---\\ function SimbaExt.Map(Func:Pointer; Arr:TByteArray): TByteArray; overload; var i,l:Int32; Def:__TMapTBtA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); for i:=0 to High(Arr) do Result[i] := Def(Arr[i]); end; //---| TIA |---\\ function SimbaExt.Map(Func:Pointer; Arr:TIntArray): TIntArray; overload; var i,l:Int32; Def:__TMapTIA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); for i:=0 to High(Arr) do Result[i] := Def(Arr[i]); end; //---| TFA |---\\ function SimbaExt.Map(Func:Pointer; Arr:TFloatArray): TFloatArray; overload; var i,l:Int32; Def:__TMapTFA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); for i:=0 to High(Arr) do Result[i] := Def(Arr[i]); end; //---| TDA |---\\ function SimbaExt.Map(Func:Pointer; Arr:TDoubleArray): TDoubleArray; overload; var i,l:Int32; Def:__TMapTDA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); for i:=0 to High(Arr) do Result[i] := Def(Arr[i]); end; //---| TEA |---\\ function SimbaExt.Map(Func:Pointer; Arr:TExtArray): TExtArray; overload; var i,l:Int32; Def:__TMapTEA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); for i:=0 to High(Arr) do Result[i] := Def(Arr[i]); end; //---| TPA |---\\ function SimbaExt.Map(Func:Pointer; Arr:TPointArray): TPointArray; overload; var i,l:Int32; Def:__TMapTPA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); for i:=0 to High(Arr) do Result[i] := Def(Arr[i]); end; //---| TBA |---\\ function SimbaExt.Map(Func:Pointer; Arr:TBoxArray): TBoxArray; overload; var i,l:Int32; Def:__TMapTBA; begin l := High(Arr); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr)); for i:=0 to High(Arr) do Result[i] := Def(Arr[i]); end; {!DOCREF} { @method: function se.Map(Func:Pointer; Arr1, Arr2:<1d array type>): <1d array type>; @desc: Calls `Func(item)` for each of the array's items and returns an array of the return values. The result type will always be the same as the input type.[br] For example, to multiply all values in arr1 with values in arr2: [code=pascal] function F(x,y:Int32): Int32; begin Result := x*y; end; [br] WriteLn( se.Map(@F, [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10]) ); [/code] Output: `[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]` [params] [b]Func:[/b] function that takes two parameters (same type as array items), and returns a the same type as the array items. [b]Arr1:[/b] TByteArray, TIntArray, TFloatArray, TDoubleArray, TExtArray, TPointArray, TBoxArray [b]Arr2:[/b] Same array type as array 1. [/params] } {$IFNDEF CODEINSIGHT} type __TMapExTBtA = function (x,y:Byte): Int32; __TMapExTIA = function (x,y:Int32): Int32; __TMapExTFA = function (x,y:Single): Extended; __TMapExTDA = function (x,y:Double): Extended; __TMapExTEA = function (x,y:Extended): Extended; __TMapExTPA = function (x,y:TPoint): TPoint; __TMapExTBA = function (x,y:TBox): TBox; {$ENDIF} //---| TBtA |---\\ function SimbaExt.Map(Func:Pointer; Arr1,Arr2:TByteArray): TByteArray; overload; var i,l:Int32; Def:__TMapExTBtA; begin l := High(Arr1); if High(Arr1) > l then RaiseException('se.Map: Out Of Range'); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr1)); for i:=0 to High(Arr1) do Result[i] := Def(Arr1[i],Arr2[i]); end; //---| TIA |---\\ function SimbaExt.Map(Func:Pointer; Arr1,Arr2:TIntArray): TIntArray; overload; var i,l:Int32; Def:__TMapExTIA; begin l := High(Arr1); if High(Arr1) > l then RaiseException('se.Map: Out Of Range'); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr1)); for i:=0 to High(Arr1) do Result[i] := Def(Arr1[i],Arr2[i]); end; //---| TFA |---\\ function SimbaExt.Map(Func:Pointer; Arr1,Arr2:TFloatArray): TFloatArray; overload; var i,l:Int32; Def:__TMapExTFA; begin l := High(Arr1); if High(Arr1) > l then RaiseException('se.Map: Out Of Range'); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr1)); for i:=0 to High(Arr1) do Result[i] := Def(Arr1[i],Arr2[i]); end; //---| TDA |---\\ function SimbaExt.Map(Func:Pointer; Arr1,Arr2:TDoubleArray): TDoubleArray; overload; var i,l:Int32; Def:__TMapExTDA; begin l := High(Arr1); if High(Arr1) > l then RaiseException('se.Map: Out Of Range'); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr1)); for i:=0 to High(Arr1) do Result[i] := Def(Arr1[i],Arr2[i]); end; //---| TEA |---\\ function SimbaExt.Map(Func:Pointer; Arr1,Arr2:TExtArray): TExtArray; overload; var i,l:Int32; Def:__TMapExTEA; begin l := High(Arr1); if High(Arr1) > l then RaiseException('se.Map: Out Of Range'); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr1)); for i:=0 to High(Arr1) do Result[i] := Def(Arr1[i],Arr2[i]); end; //---| TPA |---\\ function SimbaExt.Map(Func:Pointer; Arr1,Arr2:TPointArray): TPointArray; overload; var i,l:Int32; Def:__TMapExTPA; begin l := High(Arr1); if High(Arr1) > l then RaiseException('se.Map: Out Of Range'); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr1)); for i:=0 to High(Arr1) do Result[i] := Def(Arr1[i],Arr2[i]); end; //---| TBA |---\\ function SimbaExt.Map(Func:Pointer; Arr1,Arr2:TBoxArray): TBoxArray; overload; var i,l:Int32; Def:__TMapExTBA; begin l := High(Arr1); if High(Arr1) > l then RaiseException('se.Map: Out Of Range'); if l < 0 then Exit(); Def := Func; SetLength(Result, Length(Arr1)); for i:=0 to High(Arr1) do Result[i] := Def(Arr1[i],Arr2[i]); end; {!DOCREF} { @method: function se.Range(lo,hi:Int32; step:Int32=1): TIntArray; @desc: Generates an array ranging from `lo` to `hi`, with the given `step`. Negative `step` will result in a reversed result. Alternative methods to return other arraytypes: `RangeB` | `RangeF` | `RangeD` | `RangeE`[br] Examples: [code=pascal]WriteLn( se.Range(0,10) );[/code] Output: `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`[br] [code=pascal]WriteLn( se.Range(-100,0,-20) );[/code] Output: `[0, -20, -40, -60, -80, -100]` } function SimbaExt.Range(lo,hi:Int32; step:Int32=1): TIntArray; var i,j:Int32; begin j := -1; case (step > 0) and True of True: begin SetLength(Result, ((hi-lo) div step) + 1); for i:=lo to hi with step do Result[Inc(j)] := i; end; False: begin step := abs(step); SetLength(Result, ((hi-lo) div step) + 1); for i:=hi downto lo with step do Result[Inc(j)] := i; end; end; end; function SimbaExt.RangeB(lo,hi:Int32; step:Int32=1): TByteArray; var i,j:Int32; begin j := -1; case (step > 0) and True of True: begin SetLength(Result, ((hi-lo) div step) + 1); for i:=lo to hi with step do Result[Inc(j)] := i; end; False: begin step := abs(step); SetLength(Result, ((hi-lo) div step) + 1); for i:=hi downto lo with step do Result[Inc(j)] := i; end; end; end; function SimbaExt.RangeF(lo,hi:Int32; step:Int32=1): TFloatArray; var i,j:Int32; begin j := -1; case (step > 0) and True of True: begin SetLength(Result, ((hi-lo) div step) + 1); for i:=lo to hi with step do Result[Inc(j)] := i; end; False: begin step := abs(step); SetLength(Result, ((hi-lo) div step) + 1); for i:=hi downto lo with step do Result[Inc(j)] := i; end; end; end; function SimbaExt.RangeD(lo,hi:Int32; step:Int32=1): TDoubleArray; var i,j:Int32; begin j := -1; case (step > 0) and True of True: begin SetLength(Result, ((hi-lo) div step) + 1); for i:=lo to hi with step do Result[Inc(j)] := i; end; False: begin step := abs(step); SetLength(Result, ((hi-lo) div step) + 1); for i:=hi downto lo with step do Result[Inc(j)] := i; end; end; end; function SimbaExt.RangeE(lo,hi:Int32; step:Int32=1): TExtArray; var i,j:Int32; begin j := -1; case (step > 0) and True of True: begin SetLength(Result, ((hi-lo) div step) + 1); for i:=lo to hi with step do Result[Inc(j)] := i; end; False: begin step := abs(step); SetLength(Result, ((hi-lo) div step) + 1); for i:=hi downto lo with step do Result[Inc(j)] := i; end; end; end;
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpAsn1Tags; {$I ..\Include\CryptoLib.inc} interface type TAsn1Tags = class sealed(TObject) public const &Boolean = Int32($01); &Integer = Int32($02); BitString = Int32($03); OctetString = Int32($04); Null = Int32($05); ObjectIdentifier = Int32($06); &External = Int32($08); Enumerated = Int32($0A); Sequence = Int32($10); SequenceOf = Int32($10); // for completeness &Set = Int32($11); SetOf = Int32($11); // for completeness NumericString = Int32($12); PrintableString = Int32($13); T61String = Int32($14); VideotexString = Int32($15); IA5String = Int32($16); UtcTime = Int32($17); GeneralizedTime = Int32($18); GraphicString = Int32($19); VisibleString = Int32($1A); GeneralString = Int32($1B); UniversalString = Int32($1C); BmpString = Int32($1E); Utf8String = Int32($0C); Constructed = Int32($20); Application = Int32($40); Tagged = Int32($80); end; implementation end.
unit FoldersKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы Folders } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Folders\FoldersKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "FoldersKeywordsPack" MUID: (CEAC79654954) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3IntfUses , vtProportionalPanel , vtPanel , vtSizeablePanel ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3ImplUses , Folders_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_Folders = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы Folders ---- *Пример использования*: [code] 'aControl' форма::Folders TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_Folders Tkw_Folders_Control_BackgroundPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола BackgroundPanel ---- *Пример использования*: [code] контрол::BackgroundPanel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Folders_Control_BackgroundPanel Tkw_Folders_Control_BackgroundPanel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола BackgroundPanel ---- *Пример использования*: [code] контрол::BackgroundPanel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Folders_Control_BackgroundPanel_Push Tkw_Folders_Control_ParentZone = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ParentZone ---- *Пример использования*: [code] контрол::ParentZone TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Folders_Control_ParentZone Tkw_Folders_Control_ParentZone_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола ParentZone ---- *Пример использования*: [code] контрол::ParentZone:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Folders_Control_ParentZone_Push Tkw_Folders_Control_ChildZone = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ChildZone ---- *Пример использования*: [code] контрол::ChildZone TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Folders_Control_ChildZone Tkw_Folders_Control_ChildZone_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола ChildZone ---- *Пример использования*: [code] контрол::ChildZone:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Folders_Control_ChildZone_Push TkwCfFoldersBackgroundPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TcfFolders.BackgroundPanel } private function BackgroundPanel(const aCtx: TtfwContext; acfFolders: TcfFolders): TvtProportionalPanel; {* Реализация слова скрипта .TcfFolders.BackgroundPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwCfFoldersBackgroundPanel TkwCfFoldersParentZone = {final} class(TtfwPropertyLike) {* Слово скрипта .TcfFolders.ParentZone } private function ParentZone(const aCtx: TtfwContext; acfFolders: TcfFolders): TvtPanel; {* Реализация слова скрипта .TcfFolders.ParentZone } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwCfFoldersParentZone TkwCfFoldersChildZone = {final} class(TtfwPropertyLike) {* Слово скрипта .TcfFolders.ChildZone } private function ChildZone(const aCtx: TtfwContext; acfFolders: TcfFolders): TvtSizeablePanel; {* Реализация слова скрипта .TcfFolders.ChildZone } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwCfFoldersChildZone function Tkw_Form_Folders.GetString: AnsiString; begin Result := 'cfFolders'; end;//Tkw_Form_Folders.GetString class function Tkw_Form_Folders.GetWordNameForRegister: AnsiString; begin Result := 'форма::Folders'; end;//Tkw_Form_Folders.GetWordNameForRegister function Tkw_Folders_Control_BackgroundPanel.GetString: AnsiString; begin Result := 'BackgroundPanel'; end;//Tkw_Folders_Control_BackgroundPanel.GetString class procedure Tkw_Folders_Control_BackgroundPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtProportionalPanel); end;//Tkw_Folders_Control_BackgroundPanel.RegisterInEngine class function Tkw_Folders_Control_BackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel'; end;//Tkw_Folders_Control_BackgroundPanel.GetWordNameForRegister procedure Tkw_Folders_Control_BackgroundPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('BackgroundPanel'); inherited; end;//Tkw_Folders_Control_BackgroundPanel_Push.DoDoIt class function Tkw_Folders_Control_BackgroundPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel:push'; end;//Tkw_Folders_Control_BackgroundPanel_Push.GetWordNameForRegister function Tkw_Folders_Control_ParentZone.GetString: AnsiString; begin Result := 'ParentZone'; end;//Tkw_Folders_Control_ParentZone.GetString class procedure Tkw_Folders_Control_ParentZone.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_Folders_Control_ParentZone.RegisterInEngine class function Tkw_Folders_Control_ParentZone.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ParentZone'; end;//Tkw_Folders_Control_ParentZone.GetWordNameForRegister procedure Tkw_Folders_Control_ParentZone_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ParentZone'); inherited; end;//Tkw_Folders_Control_ParentZone_Push.DoDoIt class function Tkw_Folders_Control_ParentZone_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ParentZone:push'; end;//Tkw_Folders_Control_ParentZone_Push.GetWordNameForRegister function Tkw_Folders_Control_ChildZone.GetString: AnsiString; begin Result := 'ChildZone'; end;//Tkw_Folders_Control_ChildZone.GetString class procedure Tkw_Folders_Control_ChildZone.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtSizeablePanel); end;//Tkw_Folders_Control_ChildZone.RegisterInEngine class function Tkw_Folders_Control_ChildZone.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ChildZone'; end;//Tkw_Folders_Control_ChildZone.GetWordNameForRegister procedure Tkw_Folders_Control_ChildZone_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ChildZone'); inherited; end;//Tkw_Folders_Control_ChildZone_Push.DoDoIt class function Tkw_Folders_Control_ChildZone_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ChildZone:push'; end;//Tkw_Folders_Control_ChildZone_Push.GetWordNameForRegister function TkwCfFoldersBackgroundPanel.BackgroundPanel(const aCtx: TtfwContext; acfFolders: TcfFolders): TvtProportionalPanel; {* Реализация слова скрипта .TcfFolders.BackgroundPanel } begin Result := acfFolders.BackgroundPanel; end;//TkwCfFoldersBackgroundPanel.BackgroundPanel class function TkwCfFoldersBackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := '.TcfFolders.BackgroundPanel'; end;//TkwCfFoldersBackgroundPanel.GetWordNameForRegister function TkwCfFoldersBackgroundPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtProportionalPanel); end;//TkwCfFoldersBackgroundPanel.GetResultTypeInfo function TkwCfFoldersBackgroundPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwCfFoldersBackgroundPanel.GetAllParamsCount function TkwCfFoldersBackgroundPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TcfFolders)]); end;//TkwCfFoldersBackgroundPanel.ParamsTypes procedure TkwCfFoldersBackgroundPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству BackgroundPanel', aCtx); end;//TkwCfFoldersBackgroundPanel.SetValuePrim procedure TkwCfFoldersBackgroundPanel.DoDoIt(const aCtx: TtfwContext); var l_acfFolders: TcfFolders; begin try l_acfFolders := TcfFolders(aCtx.rEngine.PopObjAs(TcfFolders)); except on E: Exception do begin RunnerError('Ошибка при получении параметра acfFolders: TcfFolders : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(BackgroundPanel(aCtx, l_acfFolders)); end;//TkwCfFoldersBackgroundPanel.DoDoIt function TkwCfFoldersParentZone.ParentZone(const aCtx: TtfwContext; acfFolders: TcfFolders): TvtPanel; {* Реализация слова скрипта .TcfFolders.ParentZone } begin Result := acfFolders.ParentZone; end;//TkwCfFoldersParentZone.ParentZone class function TkwCfFoldersParentZone.GetWordNameForRegister: AnsiString; begin Result := '.TcfFolders.ParentZone'; end;//TkwCfFoldersParentZone.GetWordNameForRegister function TkwCfFoldersParentZone.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwCfFoldersParentZone.GetResultTypeInfo function TkwCfFoldersParentZone.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwCfFoldersParentZone.GetAllParamsCount function TkwCfFoldersParentZone.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TcfFolders)]); end;//TkwCfFoldersParentZone.ParamsTypes procedure TkwCfFoldersParentZone.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ParentZone', aCtx); end;//TkwCfFoldersParentZone.SetValuePrim procedure TkwCfFoldersParentZone.DoDoIt(const aCtx: TtfwContext); var l_acfFolders: TcfFolders; begin try l_acfFolders := TcfFolders(aCtx.rEngine.PopObjAs(TcfFolders)); except on E: Exception do begin RunnerError('Ошибка при получении параметра acfFolders: TcfFolders : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ParentZone(aCtx, l_acfFolders)); end;//TkwCfFoldersParentZone.DoDoIt function TkwCfFoldersChildZone.ChildZone(const aCtx: TtfwContext; acfFolders: TcfFolders): TvtSizeablePanel; {* Реализация слова скрипта .TcfFolders.ChildZone } begin Result := acfFolders.ChildZone; end;//TkwCfFoldersChildZone.ChildZone class function TkwCfFoldersChildZone.GetWordNameForRegister: AnsiString; begin Result := '.TcfFolders.ChildZone'; end;//TkwCfFoldersChildZone.GetWordNameForRegister function TkwCfFoldersChildZone.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtSizeablePanel); end;//TkwCfFoldersChildZone.GetResultTypeInfo function TkwCfFoldersChildZone.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwCfFoldersChildZone.GetAllParamsCount function TkwCfFoldersChildZone.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TcfFolders)]); end;//TkwCfFoldersChildZone.ParamsTypes procedure TkwCfFoldersChildZone.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ChildZone', aCtx); end;//TkwCfFoldersChildZone.SetValuePrim procedure TkwCfFoldersChildZone.DoDoIt(const aCtx: TtfwContext); var l_acfFolders: TcfFolders; begin try l_acfFolders := TcfFolders(aCtx.rEngine.PopObjAs(TcfFolders)); except on E: Exception do begin RunnerError('Ошибка при получении параметра acfFolders: TcfFolders : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ChildZone(aCtx, l_acfFolders)); end;//TkwCfFoldersChildZone.DoDoIt initialization Tkw_Form_Folders.RegisterInEngine; {* Регистрация Tkw_Form_Folders } Tkw_Folders_Control_BackgroundPanel.RegisterInEngine; {* Регистрация Tkw_Folders_Control_BackgroundPanel } Tkw_Folders_Control_BackgroundPanel_Push.RegisterInEngine; {* Регистрация Tkw_Folders_Control_BackgroundPanel_Push } Tkw_Folders_Control_ParentZone.RegisterInEngine; {* Регистрация Tkw_Folders_Control_ParentZone } Tkw_Folders_Control_ParentZone_Push.RegisterInEngine; {* Регистрация Tkw_Folders_Control_ParentZone_Push } Tkw_Folders_Control_ChildZone.RegisterInEngine; {* Регистрация Tkw_Folders_Control_ChildZone } Tkw_Folders_Control_ChildZone_Push.RegisterInEngine; {* Регистрация Tkw_Folders_Control_ChildZone_Push } TkwCfFoldersBackgroundPanel.RegisterInEngine; {* Регистрация cfFolders_BackgroundPanel } TkwCfFoldersParentZone.RegisterInEngine; {* Регистрация cfFolders_ParentZone } TkwCfFoldersChildZone.RegisterInEngine; {* Регистрация cfFolders_ChildZone } TtfwTypeRegistrator.RegisterType(TypeInfo(TcfFolders)); {* Регистрация типа TcfFolders } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtProportionalPanel)); {* Регистрация типа TvtProportionalPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtSizeablePanel)); {* Регистрация типа TvtSizeablePanel } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) end.
unit uFuncoesApp; interface uses uClassPODO, System.IniFiles, System.SysUtils, CCR.PrefsIniFile, Datasnap.DSClientRest; type TConfiguraREST = class(TObject) public class procedure configuracaoREST(poDadosConfig: TConfiguracaoApp; var poRestConnection: TDSRestConnection); end; type TGravaConfiguracoesINI = Class(Tobject) class procedure pcdGravaConfigApp(poDadosConfig: TConfiguracaoApp); class function pcdLerConfigApp : TConfiguracaoApp; End; implementation { TGravaConfiguracoesINI } class procedure TGravaConfiguracoesINI.pcdGravaConfigApp( poDadosConfig: TConfiguracaoApp); var Settings: TCustomIniFile; begin Settings := CreateUserPreferencesIniFile; try Settings.WriteString('ConfigApp', 'Endereco', poDadosConfig.psEnderecoIP); Settings.WriteString('ConfigApp', 'Porta', poDadosConfig.psPortaConexao); finally FreeAndNil(Settings); end; end; class function TGravaConfiguracoesINI.pcdLerConfigApp: TConfiguracaoApp; var Settings : TCustomIniFile; vloConfigApp : TConfiguracaoApp; begin Settings := CreateUserPreferencesIniFile; try vloConfigApp := TConfiguracaoApp.Create; vloConfigApp.psEnderecoIP := Settings.ReadString('ConfigApp', 'Endereco', vloConfigApp.psEnderecoIP); vloConfigApp.psPortaConexao := Settings.ReadString('ConfigApp', 'Porta', vloConfigApp.psPortaConexao); result := vloConfigApp; finally FreeAndNil(Settings); end; end; { TConfiguraREST } class procedure TConfiguraREST.configuracaoREST(poDadosConfig: TConfiguracaoApp; var poRestConnection: TDSRestConnection); begin poRestConnection.Host := poDadosConfig.psEnderecoIP; poRestConnection.Port := StrToInt(poDadosConfig.psPortaConexao); end; end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2016 * } { ----------------------------------------------------------- } { * # Standard secure pseudorandom generator * } { *********************************************************** } unit tfRandEngines; interface {$I TFL.inc} uses tfTypes, tfSalsa20, {$IFDEF TFL_WINDOWS}tfWindows{$ELSE}tfStubOS{$ENDIF}; type PRandEngine = ^TRandEngine; TRandEngine = record private const BUF_SIZE = 1024; private FVTable: Pointer; FRefCount: Integer; FState: TChaChaPRG; FCount: Integer; FHave: Integer; FBuffer: array[0..BUF_SIZE - 1] of Byte; function Reset: TF_RESULT; public class function Release(Inst: PRandEngine): Integer; stdcall; static; class procedure Burn(Inst: PRandEngine); static; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} class function GetRand(Inst: PRandEngine; Buf: PByte; BufSize: Cardinal): TF_RESULT; static; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} end; function GetRandInstance(var Inst: PRandEngine): TF_RESULT; function GetRand(Buf: PByte; BufSize: Cardinal): TF_RESULT; implementation uses tfRecords; const PRGVTable: array[0..4] of Pointer = ( @TForgeInstance.QueryIntf, @TForgeInstance.Addref, @TRandEngine.Release, @TRandEngine.Burn, @TRandEngine.GetRand ); var RandGen: TRandEngine; // GetRand is threadsafe function GetRand(Buf: PByte; BufSize: Cardinal): TF_RESULT; begin {$IFDEF TFL_WINDOWS} Result:= CryptLock.Acquire; if Result = TF_S_OK then begin if RandGen.FVTable = nil then begin RandGen.FVTable:= @PRGVTable; RandGen.FRefCount:= -1; end; Result:= TRandEngine.GetRand(@RandGen, Buf, BufSize); CryptLock.Resease; end; {$ELSE} Result:= TF_E_NOTIMPL; {$ENDIF} end; function GetRandInstance(var Inst: PRandEngine): TF_RESULT; var P: PRandEngine; begin try GetMem(P, SizeOf(TRandEngine)); P^.FVTable:= @PRGVTable; P^.FRefCount:= 1; // P^.FState:= P^.FCount:= 0; P^.FHave:= 0; if Inst <> nil then TRandEngine.Release(Inst); Inst:= P; Result:= TF_S_OK; except Result:= TF_E_OUTOFMEMORY; end; end; { TPRGEngine } class procedure TRandEngine.Burn(Inst: PRandEngine); var BurnSize: Integer; begin BurnSize:= SizeOf(TRandEngine) - Integer(@PRandEngine(nil)^.FState); FillChar(Inst^.FState, BurnSize, 0); end; class function TRandEngine.Release(Inst: PRandEngine): Integer; begin if Inst.FRefCount > 0 then begin Result:= tfDecrement(Inst.FRefCount); if Result = 0 then begin FillChar(Inst^, SizeOf(TRandEngine), 0); FreeMem(Inst); end; end else Result:= Inst.FRefCount; end; class function TRandEngine.GetRand(Inst: PRandEngine; Buf: PByte; BufSize: Cardinal): TF_RESULT; var N: Cardinal; P: PByte; begin while (BufSize > 0) do begin if Inst.FHave = 0 then begin Result:= Inst.Reset; if Result <> TF_S_OK then Exit; end; // here Inst.FHave > 0 N:= Inst.FHave; if BufSize < N then N:= BufSize; P:= PByte(@Inst.FBuffer) + BUF_SIZE - Inst.FHave; Move(P^, Buf^, N); FillChar(P^, N, 0); Inc(Buf, N); Dec(BufSize, N); Dec(Inst.FHave, N); end; Result:= TF_S_OK; end; function TRandEngine.Reset: TF_RESULT; const SEED_SIZE = 40; BUF_COUNT = 10000; // number of buffers generated until reseed var Seed: array[0..SEED_SIZE-1] of Byte; begin if FCount = 0 then begin Result:= GenRandom(Seed, SizeOf(Seed)); if Result = TF_S_OK then begin Result:= FState.Init(@Seed, SizeOf(Seed)); FillChar(Seed, SizeOf(Seed), 0); end; if Result <> TF_S_OK then Exit; FCount:= BUF_COUNT; end; Result:= FState.GetKeyStream(@FBuffer, SizeOf(FBuffer)); // immediately reinit for backtracking resistance if Result = TF_S_OK then begin FState.Init(@FBuffer, SEED_SIZE); FillChar(FBuffer, SEED_SIZE, 0); FHave:= SizeOf(FBuffer) - SEED_SIZE; end; Dec(FCount); end; end.
{ query FreeDB for audio cd title informations written by Sebastian Kraft sebastian_kraft@gmx.de This software is free under the GNU Public License (c)2005 } unit cddb; {$mode objfpc}{$H+} {$ifndef Darwin}{$define HAS_CDROM}{$endif} interface uses Classes, SysUtils, {$ifdef HAS_CDROM}cdrom, discid,{$endif} lnet, config, debug; type {$ifndef HAS_CDROM} TTocEntry = Record min, sec, frame : Integer; end; PTocEntry = ^TTocEntry; {$endif} { TCddbObject } TCddbObject = class year, genre, artist, album: string; title: array[1..99] of string; ErrorMsg, Status, QueryString: string; CDromDrives : Array[1..10] of String; DriveCount, NrTracks: byte; Device: string; ErrorCode: Integer; Data: TStringList; TOCEntries: array[1..99] of TTocEntry; DiscID: integer; query_send, data_ready, receiving_data:boolean; function connect(server:string; port: word):boolean; procedure callevents; procedure query(drive, server:string; port: word); procedure Parsedata; function ReadTOC(drive:string):boolean; constructor create; destructor destroy; private { private declarations } orphantext: string; Connection: TLTcp; FServer, FUser, FSoftware, FVersion, FHostname: string; FPort: word; procedure OnReceiveProc(asocket: TLSocket); procedure OnErrorProc(const msg: string; asocket: TLSocket); procedure OnDisconnectProc(asocket: TLSocket); procedure OnConnectProc(asocket: TLSocket); public { public declarations } end; implementation uses functions; type { TLEvents } TLEvents = class public procedure DsProc(aSocket: TLSocket); procedure ReProc(aSocket: TLSocket); procedure ErProc(const msg: string; aSocket: TLSocket); end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ { TLEvents } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TLEvents.DsProc(aSocket: TLSocket); begin end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TLEvents.ReProc(aSocket: TLSocket); begin end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TLEvents.ErProc(const msg: string; aSocket: TLSocket); begin end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ { TCddbObject } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TCddbObject.connect(server: string; port: word): boolean; begin end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TCddbObject.OnReceiveProc(asocket: TLSocket); var s, s1, s2, tmp: string; deleted: boolean; posi: integer; Errorcode2: integer; begin ErrorCode:=0; s:=''; asocket.GetMessage(s); DebugOutLn(Format('Socket message length: %d', [Length(s)]), 1); if s<>'' then begin if length(s)>3 then begin posi:=pos(#13, s); s1:=Copy(s, 1, 3); if (posi<>0) then s2:=Copy(s, posi+2, 3); try TryStrToInt(s1, ErrorCode); TryStrToInt(s2, ErrorCode2); if Errorcode2 > 0 then Errorcode := Errorcode2; except end; end; DebugOutLn('-------------------------------------------------', 0); DebugOutLn(s, 0); DebugOutLn(errorcode, 0); DebugOutLn(s1, 0); DebugOutLn(s2, 0); DebugOutLn('-------------------------------------------------', 0); end; if (ErrorCode=200) and query_send then begin delete(s, 1, 4); tmp:=copy(s, 1, pos(' ',s)); delete(s, 1, pos(' ', s)); s1:=copy(s, 1, pos(' ',s)); Connection.SendMessage('cddb read '+tmp+' '+s1+' '+#13+#10); DebugOutLn('cddb read '+tmp+' '+s1+' ', 0); end; if (ErrorCode=211) and query_send then begin // delete(s, 1, 4); delete(s, 1, pos(#10, s)); tmp:=copy(s, 1, pos(' ',s)); delete(s, 1, pos(' ', s)); s1:=copy(s, 1, pos(' ',s)); Connection.SendMessage('cddb read '+tmp+' '+s1+' '+#10+#13); DebugOutLn('cddb read '+tmp+' '+s1+' ', 0); end; if (ErrorCode=200) and (not query_send) then begin Connection.SendMessage('cddb query '+QueryString+#10+#13); DebugOutLn('cddb query '+QueryString, 0); query_send:=true; end; if (ErrorCode=210) and (query_send) then begin artist:=''; album:=''; delete(s, 1, pos(#10, s)); receiving_data := true; Data.Clear; orphantext := ''; end; if receiving_data then begin Data.Text := Data.Text + orphantext + s; if not (s[Length(s)] in [#10,#13]) then begin orphantext := Data[Data.Count-1]; Data.Delete(Data.Count-1); end; // writeln(' v v v v v v v v v v v v v v v'); // writeln(Data.Text); // writeln(' ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^'); if Data[Data.Count-1]= '.' then // End of data (".") in Count-1 begin Parsedata; album:=copy(artist, pos(' / ', artist)+3, length(artist)-pos(' / ', artist)+3); delete(artist, pos(' / ', artist), length(artist)-pos(' / ', artist)+1); album:=Latin1toUTF8(album); data_ready:=true; receiving_data := false; DebugOutLn('CDDB data ready...', 0); end; end; s:=''; s1:=''; tmp:='' end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TCddbObject.OnErrorProc(const msg: string; asocket: TLSocket); begin ErrorMsg:=msg; DebugOutLn(ErrorMsg, 0); end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TCddbObject.OnDisconnectProc(asocket: TLSocket); begin DebugOutLn('[TCddbObject.OnDisconnectProc] lost connection', 0); end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TCddbObject.OnConnectProc(asocket: TLSocket); var s:string; begin asocket.GetMessage(s); DebugOutLn(s, 0); Connection.CallAction; DebugOutLn('connected to cddb server, sending hello...', 0); asocket.SendMessage('cddb hello '+FUser+' '+FHostname+' '+FSoftware+' '+FVersion+#13+#10); end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TCddbObject.callevents; begin Connection.CallAction; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TCddbObject.query(drive, server: string; port: word); begin if NrTracks>0 then begin {$ifdef HAS_CDROM} discid:=(CDDBDiscID(TOCEntries, NrTracks)); querystring:=GetCDDBQueryString(TOCEntries, NrTracks); DebugOutLn(QueryString, 0); DebugOutLn(hexStr(discid, 8), 0); {$endif} FServer:=server; FPort:=port; query_send:=false; Connection.Connect(FServer, FPort); end; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TCddbObject.Parsedata; var c: integer; s: string; i: integer; begin // TODO: initialize year, genre, artist, album, and title[n] to '' for c := 0 to Data.Count-1 do begin s := Data[c]; { deleted:=false; if pos('#', s)=1 then begin delete(s, 1, pos(#10, s)); deleted:=true; end; if pos('DISCID=', s)=1 then begin delete(s, 1, pos(#10, s)); deleted:=true; end; } if (pos('DTITLE=', s)=1) and (artist='') then begin artist:=Copy(s, 8, MaxInt); artist:=Latin1toUTF8(artist); delete(s, 1, pos(#10, s)); //deleted:=true; end; if pos('TTITLE', s)=1 then begin TryStrToInt(Copy(s,7, Pos('=',s)-7 ), i); inc(i); title[i]:=Copy(s, pos('=', s)+1, MaxInt); title[i]:=Latin1toUTF8(title[i]); delete(s, 1, pos(#10, s)); if i>8 then DebugOutLn('title ---> '+title[i], 0); // deleted:=true; end; if (pos('EXTD=', s)=1) and (pos('YEAR:', s)<>0) then begin year:=Copy(s, pos('YEAR:', s)+6, 4); { delete(s, 1, pos(#10, s)); deleted:=true; } end; { if (pos('EXTD=', s)=1) then begin delete(s, 1, pos(#10, s)); deleted:=true; end; if (pos('PLAYORDER', s)=1)then begin delete(s, 1, pos(#10, s)); deleted:=true; end; if (pos('EXTT', s)=1)then begin delete(s, 1, pos(#10, s)); deleted:=true; end; } { if not deleted then delete(s, 1, pos(#10, s));} end; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TCddbObject.ReadTOC(drive: string):boolean; begin NrTracks:=0; Device:=drive; Try {$ifdef HAS_CDROM} NrTracks:= ReadCDTOC(drive, TOCEntries); {$endif} except result:=false; end; if NrTracks>100 then NrTracks:=0; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ constructor TCddbObject.create; var b: byte; begin Connection:=TLTcp.Create(nil); Connection.OnConnect:=@OnConnectProc; Connection.OnReceive:=@OnReceiveProc; Connection.OnDisconnect:=@OnDisconnectProc; Connection.OnError:=@OnErrorProc; Data := TStringList.Create; data_ready:=false; receiving_data := false; FUser:='cddbuser'; FSoftware:='cddbobject'; FVersion:='v0.1'; FHostname:='localhost'; DriveCount:=0; Try {$ifdef HAS_CDROM} DriveCount:=GetCDRomDevices(CDromDrives); {$endif} DebugOutLn(Format('%d CD-ROM drives autodetected', [DriveCount]), 0); For b:=1 to DriveCount do DebugOutLn(Format('Drive %d on device: %s',[b, CDRomDrives[b]]), 0); Except On E : exception do DebugOutLn('[TCddbObject.create] exception caught with message: '+E.Message, 0); end; if DriveCount=0 then begin CDromDrives[1]:=CactusConfig.CDRomDevice; inc(DriveCount); end; Connection.CallAction; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ destructor TCddbObject.destroy; begin Connection.destroy; Data.Destroy; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ begin end.
unit Unbound.Game.Renderer; interface uses Pengine.Camera, Pengine.VAO, Pengine.GLState, Pengine.ResourceManager, Pengine.GLProgram, Pengine.ICollections, Pengine.GLEnums, Pengine.MarchingCubes, Pengine.Vector, Pengine.IntMaths, Pengine.Color, Pengine.EventHandling, Unbound.Shaders, Unbound.Game; type TChunkRenderable = class(TRenderable) private FChunk: TChunk; FTerrainShader: IResource<TGLProgram>; FTerrainChanged: Boolean; FTerrainVAO: TVAOMutable<TTerrainShader.TData>; FTerrainChangeSubscription: IEventSubscription; procedure BuildTerrainVAO; procedure TerrainChange; public constructor Create(AGLState: TGLState; AChunk: TChunk); property Chunk: TChunk read FChunk; procedure Render; override; end; TGameRenderer = class private FGame: TGame; FCamera: TCamera; public constructor Create(AGame: TGame); destructor Destroy; override; property Camera: TCamera read FCamera; end; implementation { TChunkRenderable } procedure TChunkRenderable.BuildTerrainVAO; function Mix(F: Single; A, B: TColorRGBA): TColorRGBA; begin F := A.A * (F * B.A - 1) + 1; Result := A + F * (B - A); end; function ColorAt(ATerrain: TTerrain; APos: TIntVector3; AOffset: TVector3): TColorRGB; begin Result := Mix(AOffset.Z, Mix(AOffset.Y, Mix(AOffset.X, ATerrain[APos { + 0 } ].Color, ATerrain[APos + IVec3(1, 0, 0)].Color), Mix(AOffset.X, ATerrain[APos + IVec3(0, 1, 0)].Color, ATerrain[APos + IVec3(1, 1, 0)].Color)), Mix(AOffset.Y, Mix(AOffset.X, ATerrain[APos + IVec3(0, 0, 1)].Color, ATerrain[APos + IVec3(1, 0, 1)].Color), Mix(AOffset.X, ATerrain[APos + IVec3(0, 1, 1)].Color, ATerrain[APos + IVec3(1, 1, 1)].Color))); end; var Data: TTerrainShader.TData; VBOData: IList<TTerrainShader.TData>; Terrain: TTerrain; P: TIntVector3; Plane: TPlane3; TexCoord: TVector2; Corners: TCorners3; Corner: TCorner3; begin Terrain := Chunk.Terrain; for P in Terrain.Size - 1 do begin Corners := []; for Corner := Low(TCorner3) to High(TCorner3) do if Terrain[P + Corner3Pos[Corner]] <> nil then Include(Corners, Corner); for Plane in TMarchingCubes.GetTriangles(Corners) do begin for TexCoord in TriangleTexCoords do begin Data.Pos := Plane[TexCoord]; Data.Color := ColorAt(Terrain, P, Data.Pos); VBOData.Add(Data); end; end; end; FTerrainVAO.VBO.Generate(VBOData.Count, buDynamicDraw, VBOData.DataPointer); FTerrainChanged := False; end; constructor TChunkRenderable.Create(AGLState: TGLState; AChunk: TChunk); begin FChunk := AChunk; FTerrainShader := TTerrainShader.Get(AGLState); FTerrainVAO := TVAOMutable<TTerrainShader.TData>.Create(FTerrainShader.Data); FTerrainChangeSubscription := AChunk.Terrain.OnChange.Subscribe(TerrainChange); FTerrainChanged := True; end; procedure TChunkRenderable.Render; begin if FTerrainChanged then BuildTerrainVAO; FTerrainVAO.Render; end; procedure TChunkRenderable.TerrainChange; begin FTerrainChanged := True; end; { TGameRenderer } constructor TGameRenderer.Create(AGame: TGame); begin FGame := AGame; FCamera := TCamera.Create(75, 1, 0.01, 1000); end; destructor TGameRenderer.Destroy; begin FCamera.Free; inherited; end; end.
unit GX_IdeBaseDock; interface {$UNDEF DoNotCompileThis} {$IFDEF DoNotCompileThis} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DockForm, IDEMessages, ActnList, ecoHackDockForm; type TBaseDockHostForm = class(TDockableForm) procedure FormClose(Sender: TObject; var Action: TCloseAction); private FLastFocusedClient: TDockableForm; procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; function GetVisibleClientCount: Integer; procedure UMFinalUndock(var Message: TMessage); message UM_FINALUNDOCK; procedure UMNewClientFocused(var Message: TMessage); message UM_NEWCLIENTFOCUSED; procedure WMActivate(var Message: TWMActivate); message WM_ACTIVATE; protected function CreateDockParent(var Message: TCMDockClient): Boolean; override; procedure DoAddDockClient(Client: TControl; const ARect: TRect); override; procedure DoRemoveDockClient(Client: TControl); override; function DoUnDock(NewTarget: TWinControl; Client: TControl): Boolean; override; function GetDialogCharParentClass: TWinControlClass; virtual; abstract; function GetDockSiteControl: TWinControl; virtual; procedure SetDockable(const Value: Boolean); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ManualDockClient(Client: TControl; DropControl: TControl; ControlSide: TAlign; Replace: Boolean); virtual; procedure ResetCaption; procedure ResetStayOnTop; property VisibleClientCount: Integer read GetVisibleClientCount; end; TBaseDockHostFormClass = class of TBaseDockHostForm; var HostDockFormList: TList; procedure DestroyDockHosts; {$ENDIF DoNotCompileThis} implementation {$R *.dfm} end.
// AKTools akDataCvt unit. // Модуль, содержащий функции по преобразованию формата данных. //============================================================================= unit akDataCvt; interface uses SysUtils, Windows, Graphics, akSysCover; resourcestring exRectCoordWrong = 'Unable to convert ''%s'' in TRECT'; exPointCoordWrong = 'Unable to convert ''%s'' in TPOINT'; exFontStrWrong = 'Unable to convert ''%s'' in TFONT'; exColorStrWrong = 'Unable to convert ''%s'' in TCOLOR'; exIntArrayWrong = 'Unable to convert ''%s'' in Array[%d..%d] of Integer'; const MAXCHARSET = 41; IECharSets: array[0..MAXCHARSET, 0..1] of string = ( ('Arabic (ASMO 708)', 'ASMO-708'), ('Arabic (ISO)', 'iso-8859-6'), ('Arabic (Windows)', 'windows-1256'), ('Baltic (ISO)', 'iso-8859-4'), ('Baltic (Windows)', 'windows-1257'), ('Central European (ISO)', 'iso-8859-2'), ('Central European (Windows)', 'windows-1250'), ('Cyrillic (ISO)', 'iso-8859-5'), ('Cyrillic (KOI8-R)', 'koi8-r'), ('Cyrillic (KOI8-U)', 'koi8-u'), ('Cyrillic (Windows)', 'windows-1251'), ('German (IA5)', 'x-IA5-German'), ('Greek (ISO)', 'iso-8859-7'), ('Greek (Windows)', 'windows-1253'), ('Hebrew (ISO-Logical)', 'iso-8859-8-i'), ('Hebrew (Windows)', 'windows-1255'), ('ISCII Assamese', 'x-iscii-as'), ('ISCII Bengali', 'x-iscii-be'), ('ISCII Devanagari', 'x-iscii-de'), ('ISCII Gujarathi', 'x-iscii-gu'), ('ISCII Kannada', 'x-iscii-ka'), ('ISCII Malayalam', 'x-iscii-ma'), ('Japanese (EUC)', 'euc-jp'), ('Japanese (JIS)', 'iso-2022-jp'), ('Japanese (Shift-JIS)', 'shift_jis'), ('Korean', 'ks_c_5601-1987'), ('Korean (EUC)', 'euc-kr'), ('Korean (ISO)', 'iso-2022-kr'), ('Korean (Johab)', 'Johab'), ('Latin 3 (ISO)', 'iso-8859-3'), ('Latin 9 (ISO)', 'iso-8859-15'), ('Norwegian (IA5)', 'x-IA5-Norwegian'), ('OEM United States', 'IBM437'), ('Swedish (IA5)', 'x-IA5-Swedish'), ('Thai (Windows)', 'windows-874'), ('Turkish (ISO)', 'iso-8859-9'), ('Turkish (Windows)', 'windows-1254'), ('US-ASCII', 'us-ascii'), ('Vietnamese (Windows)', 'windows-1258'), ('Western European (IA5)', 'x-IA5'), ('Western European (ISO)', 'iso-8859-1'), ('Western European (Windows)', 'Windows-1252') ); const MaxColors = 17; MaxSpColors = 24; INT_TRUE = 1; INT_FALSE = 0; // Названия цветов. const CColorNames: array[0..MaxColors] of string = ('Black', 'Maroon', 'Green', 'Olive', 'Navy', 'Purple', 'Teal', 'Gray', 'Silver', 'Red', 'Lime', 'Yellow', 'Blue', 'Fuchsia', 'Aqua', 'LtGray', 'DkGray', 'White'); // Названия стандартных системных цветов const CSpColorNames: array[0..MaxSpColors] of string = ('ScrollBar', 'Background', 'ActiveCaption', 'InactiveCaption', 'Menu', 'Window', 'WindowFrame', 'MenuText', 'WindowText', 'CaptionText', 'ActiveBorder', 'InactiveBorder', 'AppWorkSpace', 'Highlight', 'HighlightText', 'BtnFace', 'BtnShadow', 'GrayText', 'BtnText', 'InactiveCaptionText', 'BtnHighlight', '3DDkShadow', '3DLight', 'InfoText', 'InfoBk'); // Значения цветов const CColorValues: array[0..MaxColors] of TColor = (clBlack, clMaroon, clGreen, clOlive, clNavy, clPurple, clTeal, clGray, clSilver, clRed, clLime, clYellow, clBlue, clFuchsia, clAqua, clLtGray, clDkGray, clWhite); // Значения стандартных системных цветов const CSpColorValues: array[0..MaxSpColors] of TColor = (clScrollBar, clBackground, clActiveCaption, clInactiveCaption, clMenu, clWindow, clWindowFrame, clMenuText, clWindowText, clCaptionText, clActiveBorder, clInactiveBorder, clAppWorkSpace, clHighlight, clHighlightText, clBtnFace, clBtnShadow, clGrayText, clBtnText, clInactiveCaptionText, clBtnHighlight, cl3DDkShadow, cl3DLight, clInfoText, clInfoBk); type TGradient = record fromc: TColor; // source color toc: TColor; // target color hor: boolean; // horisontal gradient aqua: boolean; // стиль градиента end; //////////////////////////////////////////////////////////////////////////////// function FriendlyIECodePageToCodePage(friendlynm: string): string; function IECodePageToFriendlyCodePage(cp: string): string; // Преобразует строку вида "10,5,20,30" в TRECT function StrToTRECT(str: string; Sep: char = ','): TRect; function TRECTToStr(rect: TRect; Sep: char = ','): string; // Преобразует строку вида "10,51" в TPOINT function StrToTPOINT(str: string; Sep: char = ','): TPoint; // Преобразует строку вида "font_name,BIU,Size,Color" в TFONT procedure StrToTFONT(str: string; const Font: TFont; Sep: char = ','); // Преобразует строку вида "Black" или "#FFFFFF"(Цвет в RGB) в TCOLOR. // Возможные строковые значения смотрите в CSpColorNames и CColorNames. function StrToTCOLOR(str: string): TColor; // Преобразует строку вида "Black:#FF2A44:v:g" или "Black:#FF2A44:h:a" в градиент. // h - horizontal // v - vertical // g - gradient // a - aqua function StrToGradient(str: string): TGradient; // Преобразует массив в строку, разделяя элементы запятыми function ArrayToStr(const ar: array of Integer): string; overload; function ArrayToStr(const ar: array of string): string; overload; // Возвращает дату преобразованную в строку. Если даты нет (=0), то вернется def. function DateTimeToStrDef(dt: TDateTime; def: string = ''): string; function StrToDateTimeDef(str: string; def: TDateTime = 0): TDateTime; // Преобразует строку в массив интеджеров. // ar - указатель на массив // max - максимальное количество элементов массива (Count-1) procedure StrToArray(str: string; ar: PIntArray; max: Integer); overload; // возвращает порядковый номер (с нуля) записи с мнимальным порядковым номером function MinOfArray(const Args: array of integer): Integer; // Преобразует время, указанное в секундах, в строку типа 124:23:45 // (часы:минуты:секунды) function SecToHoursDgt(sec: Integer; ShowSecs: Boolean = true): string; // Преобразует TColor в Color для html: function ToHTMLColor(tcol: TColor): string; // Работает с датой в unix-формате const FirstOfYear1970 = 25569; // EncodeDate(1970, 1, 1); function DateTimeToUnix(ADate: TDateTime): LongInt; function UnixToDateTime(Atime: LongInt): TDateTime; function UnixIsZeroDate(ADate: TDateTime): Boolean; // Конвертирует строку в дату и наоборот. Не зависит от настроек даты в системе function DateTimeToStrFixed(dt: TDateTime): string; function StrToDateTimeFixed(str: string): TDateTime; // Преобразует строку Accented Symbols в нормальную function AccStrToNormal(str: string): string; //------------------------------------------------------------------------------ var Time_ZoneC: Integer; shsFmtDay, shsFmtHr, shsFmtMin, shsFmtSec: string; shsFmtMode: Integer; // Указывает уровень подробности вывода. // Например, если здесь указано 4, то будет выводится "2 дня 10 час", // а если 3, то "58 час 12 мин"... и т.п. // Преобразует число секунд в годы, дни, часы и т.п., используя // правила форматирование из переменных shs*. {!}function SecToHoursStr(sec: Integer; ShowSecs: Boolean = true): string; // Устанавливает стандартные правила форматирования для SecToHoursStr. procedure DefaultShsFormat; implementation uses akStrUtils, akDataUtils, Classes; function FriendlyIECodePageToCodePage(friendlynm: string): string; var i: Integer; begin Result := ''; for i := 0 to MAXCHARSET do if AnsiCompareText(IECharSets[i, 0], friendlynm) = 0 then begin Result := IECharSets[i, 1]; break; end; end; function IECodePageToFriendlyCodePage(cp: string): string; var i: Integer; begin Result := ''; for i := 0 to MAXCHARSET do if AnsiCompareText(IECharSets[i, 1], cp) = 0 then begin Result := IECharSets[i, 0]; break; end; end; function DateTimeToStrFixed(dt: TDateTime): string; var y, m, d, h, n, s, z: Word; begin DecodeDate(dt, y, m, d); DecodeTime(dt, h, n, s, z); Result := Format('%2.2d/%2.2d/%2.4d %2.2d:%2.2d:%2.2d:%3.3d', [m, d, y, h, n, s, z]); end; function StrToDateTimeFixed(str: string): TDateTime; var y, m, d, h, n, s, z: Integer; begin m := StrToIntDef(Copy(str, 1, 2), 1); d := StrToIntDef(Copy(str, 4, 2), 1); y := StrToIntDef(Copy(str, 7, 4), 1); h := StrToIntDef(Copy(str, 12, 2), 0); n := StrToIntDef(Copy(str, 15, 2), 0); s := StrToIntDef(Copy(str, 18, 2), 0); z := StrToIntDef(Copy(str, 21, 3), 0); Result := EncodeDate(y, m, d) + EncodeTime(h, n, s, z); end; function DateTimeToUnix(ADate: TDateTime): LongInt; var Hour, Min, Sec, MSec: Word; begin if (ADate = 0) or (ADate < FirstOfYear1970) then begin Result := 0; exit; end; DecodeTime(ADate, Hour, Min, Sec, MSec); Result := TRUNC(ADate - FirstOfYear1970) * SecsPerDay + (((Hour - 1) * 60) + Min) * 60 + Sec + Time_ZoneC; end; function UnixToDateTime(Atime: LongInt): TDateTime; begin Result := FirstOfYear1970 + ((ATime - Time_ZoneC + 3600) / SecsPerDay); end; function UnixIsZeroDate(ADate: TDateTime): Boolean; begin Result := DateTimeToUnix(ADate) = 0; end; function DateTimeToStrDef(dt: TDateTime; def: string): string; begin Result := iifs((dt = 0) or (UnixIsZeroDate(dt)), def, DateTimeToStr(dt)); end; function StrToDateTimeDef(str: string; def: TDateTime = 0): TDateTime; begin try Result := StrToDateTime(str); except Result := def; end; end; function MinOfArray(const Args: array of integer): Integer; var i: Integer; minval: Integer; begin Result := -1; minval := maxint; for i := 0 to High(Args) do begin if minval > Args[i] then begin minval := Args[i]; Result := i; end; end; end; function ArrayToStr(const ar: array of string): string; overload; var i: Integer; begin Result := ''; with TStringList.Create do try for i := Low(ar) to High(ar) do Add(ar[i]); Result := CommaText; finally Free; end; end; procedure StrToArray(str: string; ar: PIntArray; max: Integer); overload; var i: Integer; begin with TStringList.Create do try CommaText := str; for i := 0 to max do if i > Count - 1 then ar^[i] := 0 else ar^[i] := StrToIntDef(Strings[i], 0); finally Free; end; end; function ArrayToStr(const ar: array of Integer): string; overload; var i: Integer; begin Result := ''; for i := Low(ar) to High(ar) do begin Result := Result + IntToStr(ar[i]); if i <> High(ar) then Result := Result + ','; end; end; procedure DefaultShsFormat; begin shsFmtDay := ' %d day'; shsFmtHr := ' %d h'; shsFmtMin := ' %d min'; shsFmtSec := ' %d sec'; shsFmtMode := 3; end; function SecToHoursStr(sec: Integer; ShowSecs: Boolean = true): string; var d, h, m, s: integer; td, th, tm, ts: Integer; begin Result := ''; s := sec; if shsFmtMode >= 4 then td := Trunc(s / 24 / 60 / 60) else td := 0; d := td; th := Trunc(s / 60 / 60); h := th - td * 24; tm := Trunc(s / 60); m := tm - th * 60; ts := s; s := ts - tm * 60; if not ShowSecs then s := 0; if shsFmtMode >= 4 then if d <> 0 then result := result + Format(shsFmtDay, [d]); if h <> 0 then result := result + Format(shsFmtHr, [h]); if (m <> 0) and (d = 0) then result := result + Format(shsFmtMin, [m]); if (s <> 0) and (d = 0) and (h = 0) then result := result + Format(shsFmtSec, [s]); if result = '' then result := Format(shsFmtSec, [0]); result := Trim(Result); end; function SecToHoursDgt(sec: Integer; ShowSecs: Boolean = true): string; var th, tm, ts, h, m, s: Integer; begin s := sec; th := Trunc(s / 60 / 60); h := th; tm := Trunc(s / 60); m := tm - th * 60; ts := s; s := ts - tm * 60; if not ShowSecs then s := 0; Result := Format('%d:%.2d', [h, m]); if ShowSecs then Result := Format('%s:%.2d', [Result, s]); end; function StrToTRECT(str: string; Sep: char = ','): TRect; var i: Integer; res, st: string; begin st := TrimIn(str, [' ', '(', ')', '[', ']']); try for i := 0 to 3 do begin Res := GetLeftSegment(i, St, Sep); if Res <> Sep then begin case i of 0: Result.Left := StrToInt(Res); 1: Result.Top := StrToInt(Res); 2: Result.Right := StrToInt(Res); 3: Result.Bottom := StrToInt(Res); end; end else raise EConvertError.Create('Str uncomplete'); end; except raise EConvertError.CreateFmt(exRectCoordWrong, [Str]); end; end; function StrToTPOINT(str: string; Sep: char = ','): TPoint; var i: Integer; res, st: string; begin st := TrimIn(str, [' ', '(', ')', '[', ']']); try for i := 0 to 1 do begin Res := GetLeftSegment(i, St, Sep); if Res <> Sep then begin case i of 0: Result.x := StrToInt(Res); 1: Result.y := StrToInt(Res); end; end else raise EConvertError.Create('Str uncomplete'); end; except raise EConvertError.CreateFmt(exPointCoordWrong, [Str]); end; end; procedure StrToTFONT(str: string; const Font: TFont; Sep: char = ','); var i: Integer; res, st: string; begin st := TrimIn(str, [' ', '(', ')', '[', ']']); try for i := 0 to 3 do begin Res := GetLeftSegment(i, St, Sep); if Res <> Sep then begin case i of 0: Font.Name := Res; 1: begin Font.Style := []; if Pos('B', Res) <> 0 then Font.Style := Font.Style + [fsBold]; if Pos('I', Res) <> 0 then Font.Style := Font.Style + [fsItalic]; if Pos('U', Res) <> 0 then Font.Style := Font.Style + [fsUnderline]; end; 2: Font.Height := -StrToInt(Res); 3: Font.Color := StrToTCOLOR(Res); end; end else raise EConvertError.Create('Str uncomplete'); end; except raise EConvertError.CreateFmt(exFontStrWrong, [Str]); end; end; function StrToGradient(str: string): TGradient; var tmp: string; begin Result.fromc := StrToTCOLOR(GetLeftSegment(0, str, ':')); tmp := GetLeftSegment(1, str, ':'); if tmp = ':' then Result.toc := Result.fromc else Result.toc := StrToTCOLOR(tmp); tmp := UpperCase(GetLeftSegment(2, str, ':')); Result.hor := (tmp = 'H') or (tmp = ':'); tmp := UpperCase(GetLeftSegment(3, str, ':')); Result.aqua := (tmp <> 'G'); end; function StrToTCOLOR(str: string): TColor; var el: Integer; st: string; R, G, B: Byte; begin Result := clNone; try st := Trim(str); if Pos('#', st) = 1 then begin R := StrToInt('$' + Copy(st, 2, 2)); G := StrToInt('$' + Copy(st, 4, 2)); B := StrToInt('$' + Copy(st, 6, 2)); Result := RGB(R, G, B); end else begin el := DataInArray(st, CColorNames, true); if el <> -1 then Result := CColorValues[el]; if el = -1 then begin el := DataInArray(st, CSpColorNames, true); if el <> -1 then Result := CSpColorValues[el]; end; if el = -1 then raise EConvertError.Create('Str uncomplete'); end; except ///raise EConvertError.CreateFmt(exColorStrWrong, [Str]); end; end; function TRECTToStr(rect: TRect; Sep: char = ','): string; begin with Rect do Result := Format('%d' + sep + '%d' + sep + '%d' + sep + '%d', [Left, Top, Right, Bottom]); end; function AccStrToNormal(str: string): string; const CharTable: array[128..255] of string = (#128, #129, #130, #131, #132, #133, #134, #135, #136, #137, #138, #139, #140, #141, #142, #143, #144, #145, #146, #147, #148, #149, #150, #151, #152, '&trade;', #154, #155, #156, #157, #158, #159, '&nbsp;', '&iexcl;', '&cent;', '&pound;', '&curren;', '&yen;', '&brkbar;', '&sect;', '&die;', '&copy;', '&ordf;', '&laquo;', '&not;', '&shy;', '&reg;', '&hibar;', '&deg;', '&plusmn;', '&sup2;', '&sup3;', '&acute;', '&micro;', '&para;', '&middot;', '&cedil;', '&sup1;', '&ordm;', '&raquo;', '&frac14;', '&frac12;', '&frac34;', '&iquest;', '&Agrave;', '&Aacute;', '&Acirc;', '&Atilde;', '&Auml;', '&Aring;', '&AElig;', '&Ccedil;', '&Egrave;', '&Eacute;', '&Ecirc;', '&Euml;', '&Igrave;', '&Iacute;', '&Icirc;', '&Iuml;', '&Dstrok;', '&Ntilde;', '&Ograve;', '&Oacute;', '&Ocirc;', '&Otilde;', '&Ouml;', '&times;', '&Oslash;', '&Ugrave;', '&Uacute;', '&Ucirc;', '&Uuml;', '&Yacute;', '&THORN;', '&szlig;', '&agrave;', '&aacute;', '&acirc;', '&atilde;', '&auml;', '&aring;', '&aelig;', '&ccedil;', '&egrave;', '&eacute;', '&ecirc;', '&euml;', '&igrave;', '&iacute;', '&icirc;', '&iuml;', '&eth;', '&ntilde;', '&ograve;', '&oacute;', '&ocirc;', '&otilde;', '&ouml;', '&divide;', '&oslash;', '&ugrave;', '&uacute;', '&ucirc;', '&uuml;', '&yacute;', '&thorn;', '&yuml;'); function AccCharToNormal(acc: string): string; var ln, i: Integer; cht, ch: string; Res: string; begin Result := ''; ln := Length(acc); if ln <= 1 then begin Result := acc; exit; end else begin if (acc[1] = '&') and (acc[ln] = ';') then begin ch := Copy(acc, 2, 1); Res := ''; for i := 128 to 255 do begin cht := Copy(CharTable[i], 2, 1); if (CompareStr(lowercase(CharTable[i]), lowercase(acc)) = 0) then begin if (cht = ch) then begin Result := chr(i); exit; end else begin Res := chr(i); end; end; end; if Res <> '' then begin if AnsiLowerCase(ch) = ch then Result := AnsiLowerCase(Res) else Result := AnsiUpperCase(Res); end else Result := acc; end; end; end; var org, trg, tln, ln: Integer; acc: string; begin ln := Length(str); SetLength(Result, ln); org := 1; trg := 0; while org <= ln do begin inc(trg); if str[org] = '&' then begin tln := PosL(org + 1, ';', str); if (tln <> 0) and (tln - org <= 10) then begin acc := Copy(str, org, tln - org + 1); acc := AccCharToNormal(acc); CopyMem(@Result[trg], @acc[1], Length(acc)); inc(trg, Length(acc) - 1); org := tln + 1; continue; end; end; Result[trg] := str[org]; inc(org); end; SetLength(Result, trg); end; function ToHTMLColor(tcol: TColor): string; var tmpRGB: TColorRef; begin tmpRGB := ColorToRGB(tcol); Result := Format('#%.2x%.2x%.2x', [GetRValue(tmpRGB), GetGValue(tmpRGB), GetBValue(tmpRGB)]); end; var Timezone: TIME_ZONE_INFORMATION; initialization GetTimeZoneInformation(TimeZone); Time_ZoneC := (Timezone.Bias*60); DefaultShsFormat; end.
unit UABMProfesores; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UABMGeneral, DB, IBCustomDataSet, dxMasterView, StdCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxDBEdit, Grids, DBGrids, Buttons, ExtCtrls, UDatosDB, jpeg, IBQuery, UPrincipal, cxLookAndFeelPainters, cxButtons; type TFABMProfesores = class(TFABMGeneral) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; cxNombre: TcxTextEdit; cxApellido: TcxTextEdit; cxEdad: TcxTextEdit; cxDNI: TcxTextEdit; cxSueldo: TcxTextEdit; RGTipoSueldo: TRadioGroup; procedure FormCreate(Sender: TObject); procedure BInsertarClick(Sender: TObject); procedure EliminarClick(Sender: TObject); procedure BModificarClick(Sender: TObject); procedure BGuardarClick(Sender: TObject); procedure BEliminarClick(Sender: TObject); private procedure CargarParametrosInsertar(); override; procedure CargarParametrosModificacion(); override; public { Public declarations } end; var FABMProfesores: TFABMProfesores; implementation {$R *.dfm} procedure TFABMProfesores.FormCreate(Sender: TObject); begin inherited; DMGimnasio.IBTPersonal.Active := true; end; procedure TFABMProfesores.BInsertarClick(Sender: TObject); begin inherited; cxNombre.Clear; cxApellido.Clear; cxEdad.Clear; cxDNI.Clear; cxSueldo.Clear; end; procedure TFABMProfesores.EliminarClick(Sender: TObject); begin inherited; DMGimnasio.IBTPersonal.Delete; end; procedure TFABMProfesores.BModificarClick(Sender: TObject); begin inherited; cxNombre.Text := DMGimnasio.IBTPersonal.FieldValues['nombre']; cxApellido.Text := DMGimnasio.IBTPersonal.FieldValues['apellido']; cxEdad.Text := DMGimnasio.IBTPersonal.FieldValues['edad']; cxDNI.Text := DMGimnasio.IBTPersonal.FieldValues['dni']; cxSueldo.Text := DMGimnasio.IBTPersonal.FieldValues['sueldo']; if (DMGimnasio.IBTPersonal.FieldValues['tipo_sueldo'] = 'C') then RGTipoSueldo.ItemIndex := 0 else RGTipoSueldo.ItemIndex := 1; end; procedure TFABMProfesores.CargarParametrosInsertar(); begin IBQInsert.ParamByName('nombre').AsString := Trim(cxNombre.EditValue); IBQInsert.ParamByName('apellido').AsString := Trim(cxApellido.EditValue); IBQInsert.ParamByName('edad').AsInteger := cxEdad.EditValue; IBQInsert.ParamByName('dni').AsInteger := cxDNI.EditValue; IBQInsert.ParamByName('sueldo').AsFloat := cxSueldo.EditValue; IBQInsert.ParamByName('esta').AsInteger := FPrincipal.Establecimiento; if (RGTipoSueldo.ItemIndex = 0) then IBQInsert.ParamByName('TS').AsString := 'C' else IBQInsert.ParamByName('TS').AsString := 'P'; end; procedure TFABMProfesores.CargarParametrosModificacion(); begin IBQModificar.ParamByName('nombre').AsString := Trim(cxNombre.EditValue); IBQModificar.ParamByName('apellido').AsString := Trim(cxApellido.EditValue); IBQModificar.ParamByName('edad').AsInteger := cxEdad.EditValue; IBQModificar.ParamByName('dni').AsInteger := cxDNI.EditValue; IBQModificar.ParamByName('sueldo').AsFloat := cxSueldo.EditValue; if (RGTipoSueldo.ItemIndex = 0) then IBQModificar.ParamByName('TS').AsString := 'C' else IBQModificar.ParamByName('TS').AsString := 'P'; IBQModificar.ParamByName('id').AsInteger := DMGimnasio.IBTPersonal.FieldValues['id_personal']; IBQModificar.ParamByName('esta').AsInteger := FPrincipal.Establecimiento; end; procedure TFABMProfesores.BGuardarClick(Sender: TObject); begin inherited; DMGimnasio.IBTPersonal.Active := false; DMGimnasio.IBTPersonal.Active := true; end; procedure TFABMProfesores.BEliminarClick(Sender: TObject); begin inherited; try DMGimnasio.IBTPersonal.Delete; DMGimnasio.IBTGimnasio.CommitRetaining; except DMGimnasio.IBTGimnasio.RollbackRetaining; MessageDlg('El Profesor tiene datos relacionados y no se puede borrar',mtError,[mbOk],0); end; end; end.
{ Subroutine SST_ORDVAL (VAL,ORDVAL,STAT) * * Find the ordinal integer value from the constant value descriptor VAL. * The ordinal value is returned in ORDVAL. STAT is the returned completion * status code. It is set to an error if the value in VAL does not have an * ordinal value. } module sst_ORDVAL; define sst_ordval; %include 'sst2.ins.pas'; procedure sst_ordval ( {find ordinal value from value descriptor} in val: sst_var_value_t; {input constant value descriptor} out ordval: sys_int_max_t; {returned ordinal value} out stat: sys_err_t); {set to error if ordinal value not exist} begin sys_error_none (stat); {init to no error finding ordinal value} case val.dtype of {what base data type is this constant ?} sst_dtype_int_k: begin {integer} ordval := val.int_val; end; sst_dtype_enum_k: begin {enumerated type} ordval := val.enum_p^.enum_ordval; end; sst_dtype_bool_k: begin {boolean} if val.bool_val then ordval := 1 else ordval := 0; end; sst_dtype_char_k: begin {character} ordval := ord(val.char_val); end; otherwise sys_stat_set (sst_subsys_k, sst_stat_no_ordval_k, stat); end; end;
{ Модуль компонента управления файлом XML. Версия: 0.0.2 } unit ICXMLConfig; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, XMLConf; type TICXMLConfig = class(TXMLConfig) private { Имя XML файла по умолчанию. В случае если не определено основное имя } FDefaultFileName: AnsiString; procedure SetDefaultFileName(ADefaultFileName: AnsiString); protected public { Получить значение как целое @param APath: Путь до элемента. Например /L1/L2/L3 @param ADefault: Значение по умолчанию в случае не существующего элемента или не корректных данных. } function GetValueAsInteger(APath: WideString; ADefault: Integer=0): Integer; { Получить значение как вещественное @param APath: Путь до элемента. Например /L1/L2/L3 @param ADefault: Значение по умолчанию в случае не существующего элемента или не корректных данных. } function GetValueAsFloat(APath: WideString; ADefault: Double=0.0): Double; { Получить значение как логическое @param APath: Путь до элемента. Например /L1/L2/L3 @param ADefault: Значение по умолчанию в случае не существующего элемента или не корректных данных. } function GetValueAsBoolean(APath: WideString; ADefault: Boolean=False): Boolean; { Получить значение как строку @param APath: Путь до элемента. Например /L1/L2/L3 @param ADefault: Значение по умолчанию в случае не существующего элемента или не корректных данных. } function GetValueAsString(APath: WideString; ADefault: AnsiString=''): AnsiString; { Запуск редактора конфигурационного файла XML } function Edit(): Boolean; published property DefaultFileName: AnsiString read FDefaultFileName write SetDefaultFileName; end; procedure Register; implementation uses edit_xml_config_form; procedure Register; begin {$I icxmlconfig_icon.lrs} RegisterComponents('IC Tools',[TICXMLConfig]); end; procedure TICXMLConfig.SetDefaultFileName(ADefaultFileName: AnsiString); begin if ADefaultFileName = '' then begin ADefaultFileName := FileName; end; FDefaultFileName := ADefaultFileName; end; { Получить значение как целое } function TICXMLConfig.GetValueAsInteger(APath: WideString; ADefault: Integer): Integer; var value: WideString; begin if FileName = '' then FileName := DefaultFileName; value := GetValue(APath, ''); if value = '' then Result := ADefault else Result := StrToInt(value); end; { Получить значение как вещественное } function TICXMLConfig.GetValueAsFloat(APath: WideString; ADefault: Double): Double; var value: WideString; begin if FileName = '' then FileName := DefaultFileName; value := GetValue(APath, ''); if value = '' then Result := ADefault else Result := StrToFloat(value); end; { Получить значение как логическое } function TICXMLConfig.GetValueAsBoolean(APath: WideString; ADefault: Boolean): Boolean; var value: WideString; begin if FileName = '' then FileName := DefaultFileName; value := GetValue(APath, ''); if value = '' then Result := ADefault else Result := LowerCase(value) = 'true'; end; { Получить значение как строку } function TICXMLConfig.GetValueAsString(APath: WideString; ADefault: AnsiString): AnsiString; begin if FileName = '' then FileName := DefaultFileName; Result := GetValue(APath, ADefault); end; { Запуск редактора конфигурационного файла XML } function TICXMLConfig.Edit(): Boolean; begin edit_xml_config_form.EditXmlConfigForm.EditConfig(self); Result := True; end; end.
{ ******************************************************************************* Copyright (c) 2004-2010 by Edyard Tolmachev IMadering project http://imadering.com ICQ: 118648 E-mail: imadering@mail.ru ******************************************************************************* } unit AddContactUnit; interface {$REGION 'Uses'} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VarsUnit, ComCtrls, JvSimpleXml; type TAddContactForm = class(TForm) AccountEdit: TEdit; NameEdit: TEdit; GroupComboBox: TComboBox; CancelButton: TButton; AddContactButton: TButton; AccountLabel: TLabel; NameLabel: TLabel; GroupLabel: TLabel; procedure FormCreate(Sender: TObject); procedure AddContactButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormDblClick(Sender: TObject); private { Private declarations } public { Public declarations } ContactType: string; procedure TranslateForm; procedure BuildGroupList(GProto, xId: string); end; {$ENDREGION} var AddContactForm: TAddContactForm; implementation {$R *.dfm} {$REGION 'MyUses'} uses MainUnit, IcqProtoUnit, UtilsUnit, RosterUnit, OverbyteIcsUrl; {$ENDREGION} {$REGION 'BuildGroupList'} procedure TAddContactForm.BuildGroupList(GProto, xId: string); var Z: Integer; XML_Node, Sub_Node, Tri_Node: TJvSimpleXmlElem; GId: string; begin // Составляем список групп из Ростера if V_Roster <> nil then begin with V_Roster do begin if Root <> nil then begin XML_Node := Root.Items.ItemNamed[GProto]; if XML_Node <> nil then begin // Открываем раздел групп Sub_Node := XML_Node.Items.ItemNamed[C_Group + C_SS]; if Sub_Node <> nil then begin if GProto = C_Icq then // Список для ICQ begin for Z := 0 to Sub_Node.Items.Count - 1 do begin Tri_Node := Sub_Node.Items.Item[Z]; if Tri_Node <> nil then begin GId := Tri_Node.Properties.Value(C_Id); if (GId <> '0000') and (GId <> C_NoCL) and (GId <> C_IgCL) then GroupComboBox.Items.Add(UrlDecode(Tri_Node.Properties.Value(C_Name)) + C_BN + C_QN + Tri_Node.Properties.Value(C_Id) + C_EN); end; end; end else if GProto = C_Jabber then // Список для Jabber begin end else if GProto = C_Mra then // Список для Mra begin end; end; end; end; end; end; // Выставляем по умолчанию первую группу в списке выбора групп if GroupComboBox.Items.Count > 0 then begin GroupComboBox.ItemIndex := 0; // Выставляем группу выбранную в КЛ if xId <> EmptyStr then begin for Z := 0 to GroupComboBox.Items.Count - 1 do begin if IsolateTextString(GroupComboBox.Items.Strings[Z], C_QN, C_EN) = xId then GroupComboBox.ItemIndex := Z; end; end; end; end; {$ENDREGION} {$REGION 'TranslateForm'} procedure TAddContactForm.TranslateForm; begin // Создаём шаблон для перевода // CreateLang(Self); // Применяем язык SetLang(Self); // Другое CancelButton.Caption := Lang_Vars[9].L_S; end; {$ENDREGION} {$REGION 'AddContactButtonClick'} procedure TAddContactForm.AddContactButtonClick(Sender: TObject); label X, Y; var NewId, GId, Nick: string; Get_Node: TJvSimpleXmlElem; begin // Добавляем контакты по протоколу ICQ if ContactType = C_Icq then begin // Проверяем в сети ли этот протокол if NotProtoOnline(C_Icq) then Exit; if AccountEdit.Text <> EmptyStr then begin // Нормализуем ICQ номер AccountEdit.Text := NormalizeScreenName(AccountEdit.Text); AccountEdit.Text := NormalizeIcqNumber(AccountEdit.Text); if Trim(NameEdit.Text) = EmptyStr then NameEdit.Text := AccountEdit.Text; // Ограничиваем длинну ника Nick := NameEdit.Text; if Length(Nick) > 20 then SetLength(Nick, 20); // Ищем такой контакт в Ростере Get_Node := RosterGetItem(C_Icq, C_Contact + C_SS, C_Login, AccountEdit.Text); if Get_Node <> nil then begin DAShow(Lang_Vars[19].L_S + C_BN + C_Icq, Lang_Vars[103].L_S, EmptyStr, 133, 0, 0); Exit; end else begin // Если фаза добавления контакта ещё активна, то ждём её окончания if ICQ_SSI_Phaze then begin DAShow(Lang_Vars[19].L_S + C_BN + C_Icq, Lang_Vars[104].L_S, EmptyStr, 134, 2, 0); Exit; end; // Если группа не выбрана if GroupComboBox.ItemIndex = -1 then begin DAShow(Lang_Vars[18].L_S, Lang_Vars[105].L_S, EmptyStr, 134, 2, 0); goto Y; end; // Генерируем идентификатор для этого контакта X: ; Randomize; NewId := IntToHex(Random($7FFF), 4); // Ищем нет ли уже такого идентификатора в списке контактов Get_Node := RosterGetItem(C_Icq, C_Contact + C_SS, C_Id, NewId); if Get_Node <> nil then goto X; // Получаем идентификатор выбранной группы GId := IsolateTextString(GroupComboBox.Text, C_QN, C_EN); // Открываем сессию и добавляем контакт if (NewId <> EmptyStr) and (GId <> EmptyStr) then begin ICQ_SSI_Phaze := True; ICQ_Add_Contact_Phaze := True; ICQ_Add_Group_Name := Trim(Parse(C_QN, GroupComboBox.Text, 1)); ICQ_AddContact(AccountEdit.Text, GId, NewId, Nick, False); end; end; end; end else if ContactType = C_Jabber then // Добавляем контакты по протоколу Jabber begin end else if ContactType = C_Mra then // Добавляем контакты по протоколу Mra begin end; // Выходим и закрываем модальное окно} Y: ; ModalResult := MrOk; end; {$ENDREGION} {$REGION 'FormCreate'} procedure TAddContactForm.FormCreate(Sender: TObject); begin // Переводим форму на другие языки TranslateForm; // Присваиваем иконку окну MainForm.AllImageList.GetIcon(143, Icon); // Помещаем кнопку формы в таскбар и делаем независимой SetWindowLong(Handle, GWL_HWNDPARENT, 0); SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW); end; {$ENDREGION} {$REGION 'Other'} procedure TAddContactForm.FormDblClick(Sender: TObject); begin // Устанавливаем перевод TranslateForm; end; procedure TAddContactForm.FormShow(Sender: TObject); begin // Ставим фокус в поле ввода учётной записи если она пустая if (AccountEdit.CanFocus) and (AccountEdit.Text = EmptyStr) then AccountEdit.SetFocus; // Подставляем название протокола в заголовок Caption := Caption + C_BN + ContactType; end; {$ENDREGION} end.
unit karatechamp_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,rom_engine,pal_engine, sound_engine,ay_8910,timer_engine,dac; function karatechamp_iniciar:boolean; implementation const karatechamp_rom:array[0..5] of tipo_roms=( (n:'b014.bin';l:$2000;p:0;crc:$0000d1a0),(n:'b015.bin';l:$2000;p:$2000;crc:$03fae67e), (n:'b016.bin';l:$2000;p:$4000;crc:$3b6e1d08),(n:'b017.bin';l:$2000;p:$6000;crc:$c1848d1a), (n:'b018.bin';l:$2000;p:$8000;crc:$b824abc7),(n:'b019.bin';l:$2000;p:$a000;crc:$3b487a46)); karatechamp_sound:array[0..6] of tipo_roms=( (n:'b026.bin';l:$2000;p:0;crc:$999ed2c7),(n:'b025.bin';l:$2000;p:$2000;crc:$33171e07), (n:'b024.bin';l:$2000;p:$4000;crc:$910b48b9),(n:'b023.bin';l:$2000;p:$6000;crc:$47f66aac), (n:'b022.bin';l:$2000;p:$8000;crc:$5928e749),(n:'b021.bin';l:$2000;p:$a000;crc:$ca17e3ba), (n:'b020.bin';l:$2000;p:$c000;crc:$ada4f2cd)); karatechamp_char:array[0..1] of tipo_roms=( (n:'b000.bin';l:$2000;p:0;crc:$a4fa98a1),(n:'b001.bin';l:$2000;p:$4000;crc:$fea09f7c)); karatechamp_sprt:array[0..11] of tipo_roms=( (n:'b013.bin';l:$2000;p:0;crc:$eaad4168),(n:'b004.bin';l:$2000;p:$2000;crc:$10a47e2d), (n:'b012.bin';l:$2000;p:$4000;crc:$b4842ea9),(n:'b003.bin';l:$2000;p:$6000;crc:$8cd166a5), (n:'b011.bin';l:$2000;p:$8000;crc:$4cbd3aa3),(n:'b002.bin';l:$2000;p:$a000;crc:$6be342a6), (n:'b007.bin';l:$2000;p:$c000;crc:$cb91d16b),(n:'b010.bin';l:$2000;p:$e000;crc:$489c9c04), (n:'b006.bin';l:$2000;p:$10000;crc:$7346db8a),(n:'b009.bin';l:$2000;p:$12000;crc:$b78714fc), (n:'b005.bin';l:$2000;p:$14000;crc:$b2557102),(n:'b008.bin';l:$2000;p:$16000;crc:$c85aba0e)); karatechamp_pal:array[0..2] of tipo_roms=( (n:'br27';l:$100;p:0;crc:$f683c54a),(n:'br26';l:$100;p:$100;crc:$3ddbb6c4), (n:'br25';l:$100;p:$200;crc:$ba4a5651)); //Dip karatechamp_dip:array [0..6] of def_dip=( (mask:$3;name:'Coin A';number:4;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$1;dip_name:'2C 1C'),(dip_val:$3;dip_name:'1C 1C'),(dip_val:$2;dip_name:'1C 2C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$4;dip_name:'2C 1C'),(dip_val:$c;dip_name:'1C 1C'),(dip_val:$8;dip_name:'1C 2C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'Difficulty';number:2;dip:((dip_val:$0;dip_name:'Hard'),(dip_val:$10;dip_name:'Normal'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Free Play';number:2;dip:((dip_val:$20;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Demo Sounds';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$80;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var sound_latch:byte; nmi_enable,nmi_enable_sound:boolean; procedure update_video_karatechamp; var x,y,atrib,color:byte; f,nchar:word; begin for f:=0 to $3ff do begin if gfx[0].buffer[f] then begin x:=31-(f div 32); y:=f mod 32; atrib:=memoria[$e400+f]; color:=atrib shr 3; nchar:=memoria[$e000+f]+((atrib and $7) shl 8); put_gfx(x*8,y*8,nchar,(color shl 2)+128,1,0); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,256,256,1,0,0,256,256,2); for f:=0 to $3f do begin atrib:=memoria[$ea02+(f*4)]; nchar:=memoria[$ea01+(f*4)]+((atrib and $10) shl 4); color:=(atrib and $f) shl 2; x:=memoria[$ea00+(f*4)]-9; y:=memoria[$ea03+(f*4)]-8; put_gfx_sprite(nchar,color,(atrib and $80)<>0,false,1+((atrib and $60) shr 5)); actualiza_gfx_sprite(x,y,2,1); end; actualiza_trozo_final(16,0,224,256,2); end; procedure eventos_karatechamp; begin if event.arcade then begin //SYS if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); //P1 if arcade_input.right[0] then marcade.in1:=marcade.in1 and $fe else marcade.in1:=marcade.in1 or $1; if arcade_input.left[0] then marcade.in1:=marcade.in1 and $fd else marcade.in1:=marcade.in1 or $2; if arcade_input.up[0] then marcade.in1:=marcade.in1 and $fb else marcade.in1:=marcade.in1 or $4; if arcade_input.down[0] then marcade.in1:=marcade.in1 and $f7 else marcade.in1:=marcade.in1 or $8; if arcade_input.right[1] then marcade.in1:=marcade.in1 and $ef else marcade.in1:=marcade.in1 or $10; if arcade_input.left[1] then marcade.in1:=marcade.in1 and $df else marcade.in1:=marcade.in1 or $20; if arcade_input.up[1] then marcade.in1:=marcade.in1 and $bf else marcade.in1:=marcade.in1 or $40; if arcade_input.down[1] then marcade.in1:=marcade.in1 and $7f else marcade.in1:=marcade.in1 or $80; end; end; procedure karatechamp_principal; var frame_m,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_s:=z80_1.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //Main z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //Sound z80_1.run(frame_s); frame_s:=frame_s+z80_1.tframes-z80_1.contador; if (f=241) then begin if nmi_enable then z80_0.change_nmi(ASSERT_LINE); update_video_karatechamp; end; end; eventos_karatechamp; video_sync; end; end; function karatechamp_getbyte(direccion:word):byte; begin karatechamp_getbyte:=memoria[direccion]; end; procedure karatechamp_putbyte(direccion:word;valor:byte); begin case direccion of 0..$bfff:; //ROM $c000..$dfff,$ea00..$ffff:memoria[direccion]:=valor; $e000..$e7ff:if memoria[direccion]<>valor then begin memoria[direccion]:=valor; gfx[0].buffer[direccion and $3ff]:=true; end; end; end; function karatechamp_inbyte(puerto:word):byte; begin case (puerto and $ff) of $80:karatechamp_inbyte:=marcade.dswa; $90:karatechamp_inbyte:=marcade.in1; $98:karatechamp_inbyte:=$ff; $a0:karatechamp_inbyte:=marcade.in0; $a8:; end; end; procedure karatechamp_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of $80:main_screen.flip_main_screen:=(valor and 1)<>0; $81:begin nmi_enable:=valor<>0; if not(nmi_enable) then z80_0.change_nmi(CLEAR_LINE); end; $a8:begin sound_latch:=valor; z80_1.change_irq(ASSERT_LINE); end; end; end; //sound function karatechamp_getbyte_snd(direccion:word):byte; begin karatechamp_getbyte_snd:=mem_snd[direccion]; end; procedure karatechamp_putbyte_snd(direccion:word;valor:byte); begin case direccion of 0..$dfff:; //ROM $e000..$e2ff:mem_snd[direccion]:=valor; end; end; function karatechamp_inbyte_snd(puerto:word):byte; begin if (puerto and $ff)=$6 then begin karatechamp_inbyte_snd:=sound_latch; z80_1.change_irq(CLEAR_LINE); end; end; procedure karatechamp_outbyte_snd(puerto:word;valor:byte); begin case (puerto and $ff) of 0:ay8910_0.write(valor); 1:ay8910_0.control(valor); 2:ay8910_1.write(valor); 3:ay8910_1.control(valor); 4:dac_0.data8_w(valor); 5:begin nmi_enable_sound:=(valor and $80)<>0; if not(nmi_enable_sound) then z80_1.change_nmi(CLEAR_LINE); end; end; end; procedure karatechamp_snd_irq; begin if nmi_enable_sound then z80_1.change_nmi(ASSERT_LINE); end; procedure karatechamp_sound_update; begin ay8910_0.Update; ay8910_1.Update; dac_0.update; end; //Main procedure karatechamp_reset; begin z80_0.reset; z80_1.reset; ay8910_0.reset; ay8910_1.reset; dac_0.reset; reset_audio; nmi_enable:=false; nmi_enable_sound:=false; sound_latch:=0; marcade.in0:=$ff; marcade.in1:=$ff; end; function karatechamp_iniciar:boolean; const ps_x:array[0..15] of dword=(0,1,2,3,4,5,6,7, $2000*8+0,$2000*8+1,$2000*8+2,$2000*8+3,$2000*8+4,$2000*8+5,$2000*8+6,$2000*8+7); ps_y:array[0..15] of dword=(0*8,1*8,2*8,3*8,4*8,5*8,6*8,7*8, 8*8,9*8,10*8,11*8,12*8,13*8,14*8, 15*8); var colores:tpaleta; f:word; memoria_temp:array[0..$17fff] of byte; begin llamadas_maquina.bucle_general:=karatechamp_principal; llamadas_maquina.reset:=karatechamp_reset; karatechamp_iniciar:=false; iniciar_audio(false); screen_init(1,256,256); screen_init(2,256,256,false,true); iniciar_video(224,256); //Main CPU z80_0:=cpu_z80.create(12000000 div 4,256); z80_0.change_ram_calls(karatechamp_getbyte,karatechamp_putbyte); z80_0.change_io_calls(karatechamp_inbyte,karatechamp_outbyte); if not(roms_load(@memoria,karatechamp_rom)) then exit; //Sound Chip z80_1:=cpu_z80.create(12000000 div 4,256); z80_1.change_ram_calls(karatechamp_getbyte_snd,karatechamp_putbyte_snd); z80_1.change_io_calls(karatechamp_inbyte_snd,karatechamp_outbyte_snd); z80_1.init_sound(karatechamp_sound_update); if not(roms_load(@mem_snd,karatechamp_sound)) then exit; //IRQ Sound CPU timers.init(z80_1.numero_cpu,3000000/125,karatechamp_snd_irq,nil,true); //Sound Chips ay8910_0:=ay8910_chip.create(12000000 div 12,AY8910,1); ay8910_1:=ay8910_chip.create(12000000 div 12,AY8910,1); dac_0:=dac_chip.create; //cargar chars if not(roms_load(@memoria_temp,karatechamp_char)) then exit; init_gfx(0,8,8,$800); gfx_set_desc_data(2,0,8*8,$4000*8,0); convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,true,false); //cargar sprites (3 bancos) if not(roms_load(@memoria_temp,karatechamp_sprt)) then exit; init_gfx(1,16,16,$200*3); gfx[1].trans[0]:=true; gfx_set_desc_data(2,0,16*8,$c000*8,0); convert_gfx(1,0,@memoria_temp[$8000],@ps_x,@ps_y,true,false); init_gfx(2,16,16,$200); gfx[2].trans[0]:=true; convert_gfx(2,0,@memoria_temp[$4000],@ps_x,@ps_y,true,false); init_gfx(3,16,16,$200); gfx[3].trans[0]:=true; convert_gfx(3,0,@memoria_temp[$0],@ps_x,@ps_y,true,false); //paleta de colores if not(roms_load(@memoria_temp,karatechamp_pal)) then exit; for f:=0 to 255 do begin colores[f].r:=pal4bit(memoria_temp[f]); colores[f].g:=pal4bit(memoria_temp[f+$100]); colores[f].b:=pal4bit(memoria_temp[f+$200]); end; set_pal(colores,$100); //DIP marcade.dswa:=$3f; marcade.dswa_val:=@karatechamp_dip; //Final karatechamp_reset; karatechamp_iniciar:=true; end; end.
unit AddressUnit; interface uses REST.Json.Types, System.Generics.Collections, System.Rtti, Classes, SysUtils, Generics.Defaults, JSONNullableAttributeUnit, NullableBasicTypesUnit, AddressNoteUnit, EnumsUnit, DirectionUnit, ManifestUnit, DirectionPathPointUnit, AddressGeocodingUnit, JSONDictionaryIntermediateObjectUnit; type /// <summary> /// Json schema for an Address class, which is used for Optimization and Route mantenance procedures /// </summary> /// <remarks> /// https://github.com/route4me/json-schemas/blob/master/Address.dtd /// </remarks> TAddress = class private [JSONName('route_destination_id')] [Nullable] FRouteDestinationId: NullableInteger; [JSONName('alias')] FAlias: String; [JSONName('member_id')] [Nullable] FMemberId: NullableInteger; [JSONName('address')] FAddressString: String; [JSONName('is_depot')] [Nullable] FIsDepot: NullableBoolean; [JSONName('lat')] FLatitude: double; [JSONName('lng')] FLongitude: double; [JSONName('route_id')] [Nullable] FRouteId: NullableString; [JSONName('time')] [Nullable] FTime: NullableInteger; [JSONName('custom_fields')] [NullableObject(TDictionaryStringIntermediateObject)] FCustomFields: NullableObject; [JSONName('curbside_lat')] [Nullable(True)] FCurbsideLatitude: NullableDouble; [JSONName('curbside_lng')] [Nullable(True)] FCurbsideLongitude: NullableDouble; [JSONName('time_window_start')] [Nullable] FTimeWindowStart: NullableInteger; [JSONName('time_window_end')] [Nullable] FTimeWindowEnd: NullableInteger; [JSONName('time_window_start_2')] [Nullable] FTimeWindowStart2: NullableInteger; [JSONName('time_window_end_2')] [Nullable] FTimeWindowEnd2: NullableInteger; [JSONName('sequence_no')] [Nullable] FSequenceNo: NullableInteger; [JSONName('original_route_id')] [Nullable] FOriginalRouteId: NullableString; [JSONName('optimization_problem_id')] [Nullable] FOptimizationProblemId: NullableString; [JSONName('timeframe_violation_state')] [Nullable] FTimeframeViolationState: NullableInteger; [JSONName('timeframe_violation_time')] [Nullable] FTimeframeViolationTime: NullableInteger; [JSONName('timeframe_violation_rate')] [Nullable] FTimeframeViolationRate: NullableDouble; [JSONName('priority')] [Nullable] FPriority: NullableInteger; [JSONName('address_stop_type')] [Nullable] FAddressStopType: NullableString; [JSONName('geofence_detected_visited_timestamp')] [Nullable] FGeofenceDetectedVisitedTimestamp: NullableInteger; [JSONName('geofence_detected_departed_timestamp')] [Nullable] FGeofenceDetectedDepartedTimestamp: NullableInteger; [JSONName('geofence_detected_service_time')] [Nullable] FGeofenceDetectedServiceTime: NullableInteger; [JSONName('geofence_detected_visited_lat')] [Nullable] FGeofenceDetectedVisitedLat: NullableDouble; [JSONName('geofence_detected_visited_lng')] [Nullable] FGeofenceDetectedVisitedLng: NullableDouble; [JSONName('geofence_detected_departed_lat')] [Nullable] FGeofenceDetectedDepartedLat: NullableDouble; [JSONName('geofence_detected_departed_lng')] [Nullable] FGeofenceDetectedDepartedLng: NullableDouble; [JSONName('route_name')] [Nullable] FRouteName: NullableString; [JSONName('geocoded')] [Nullable] FGeocoded: NullableBoolean; [JSONName('preferred_geocoding')] [Nullable] FPreferredGeocoding: NullableInteger; [JSONName('failed_geocoding')] [Nullable] FFailedGeocoding: NullableBoolean; [JSONName('geocodings')] [NullableArray(TAddressGeocoding)] FGeocodings: TAddressGeocodingArray; [JSONName('contact_id')] [Nullable] FContactId: NullableInteger; [JSONName('is_visited')] [Nullable] FIsVisited: NullableBoolean; [JSONName('is_departed')] [Nullable] FIsDeparted: NullableBoolean; [JSONName('visited_lat')] [Nullable] FVisitedLat: NullableDouble; [JSONName('visited_lng')] [Nullable] FVisitedLng: NullableDouble; [JSONName('departed_lat')] [Nullable] FDepartedLat: NullableDouble; [JSONName('departed_lng')] [Nullable] FDepartedLng: NullableDouble; [JSONName('timestamp_last_visited')] [Nullable] FTimestampLastVisited: NullableInteger; [JSONName('timestamp_last_departed')] [Nullable] FTimestampLastDeparted: NullableInteger; [JSONName('customer_po')] [Nullable] FCustomerPo: NullableString; [JSONName('invoice_no')] [Nullable] FInvoiceNo: NullableString; [JSONName('reference_no')] [Nullable] FReferenceNo: NullableString; [JSONName('account_no')] [Nullable] FAccountNo: NullableString; [JSONName('order_no')] [Nullable] FOrderNo: NullableString; [JSONName('tracking_number')] [Nullable] FTrackingNumber: NullableString; [JSONName('weight')] [Nullable] FWeight: NullableDouble; [JSONName('cost')] [Nullable] FCost: NullableDouble; [JSONName('revenue')] [Nullable] FRevenue: NullableDouble; [JSONName('cube')] [Nullable] FCube: NullableDouble; [JSONName('pieces')] [Nullable] FPieces: NullableInteger; [JSONName('email')] [Nullable] FEmail: NullableString; [JSONName('phone')] [Nullable] FPhone: NullableString; [JSONName('destination_note_count')] [Nullable] FDestinationNoteCount: NullableInteger; [JSONName('drive_time_to_next_destination')] [Nullable] FDriveTimeToNextDestination: NullableInteger; [JSONName('abnormal_traffic_time_to_next_destination')] [Nullable] FAbnormalTrafficTimeToNextDestination: NullableInteger; [JSONName('uncongested_time_to_next_destination')] [Nullable] FUncongestedTimeToNextDestination: NullableInteger; [JSONName('distance_to_next_destination')] [Nullable] FDistanceToNextDestination: NullableDouble; [JSONName('generated_time_window_start')] [Nullable] FGeneratedTimeWindowStart: NullableInteger; [JSONName('generated_time_window_end')] [Nullable] FGeneratedTimeWindowEnd: NullableInteger; [JSONName('path_to_next')] [NullableArray(TDirectionPathPoint)] FPathToNext: TDirectionPathPointArray; [JSONName('directions')] [NullableArray(TDirection)] FDirections: TDirectionArray; [JSONName('manifest')] [NullableObject(TManifest)] FManifest: NullableObject; [JSONName('notes')] [NullableArray(TAddressNote)] FNotes: TAddressNoteArray; [JSONMarshalled(False)] FOwnsNotes: boolean; function GetCustomFields: TDictionaryStringIntermediateObject; procedure SetCustomFields(const Value: TDictionaryStringIntermediateObject); function GetAddressStopType: TAddressStopType; procedure SetAddressStopType(const Value: TAddressStopType); function GetManifest: TManifest; procedure SetManifest(const Value: TManifest); public /// <remarks> /// Constructor with 0-arguments must be and be public. /// For JSON-deserialization. /// </remarks> constructor Create; overload; virtual; constructor Create(AddressString: String; Latitude, Longitude: double; Time: NullableInteger); overload; constructor Create(AddressString: String; Alias: String; Latitude, Longitude: double; Time: NullableInteger); overload; constructor Create(AddressString: String; Latitude, Longitude: double; Time: NullableInteger; TimeWindowStart, TimeWindowEnd: integer); overload; constructor Create(AddressString: String; Latitude, Longitude: double; Time: NullableInteger; TimeWindowStart, TimeWindowEnd, TimeWindowStart2, TimeWindowEnd2: integer); overload; destructor Destroy; override; property OwnsNotes: boolean read FOwnsNotes write FOwnsNotes; function Equals(Obj: TObject): Boolean; override; /// <summary> /// The route Address Line 1 /// </summary> property AddressString: String read FAddressString write FAddressString; /// <summary> /// Address Alias /// </summary> property Alias: String read FAlias write FAlias; /// <summary> /// Internal unique address identifier /// </summary> property RouteDestinationId: NullableInteger read FRouteDestinationId write FRouteDestinationId; /// <summary> /// Member ID /// </summary> property MemberId: NullableInteger read FMemberId write FMemberId; /// <summary> /// This address is a depot /// </summary> property IsDepot: NullableBoolean read FIsDepot write FIsDepot; /// <summary> /// The latitude of this address /// </summary> property Latitude: double read FLatitude write FLatitude; /// <summary> /// The longitude of this address /// </summary> property Longitude: double read FLongitude write FLongitude; /// <summary> /// The id of the route being viewed, modified, erased /// </summary> property RouteId: NullableString read FRouteId write FRouteId; /// <summary> /// Service time (seconds) /// </summary> property Time: NullableInteger read FTime write FTime; property CustomFields: TDictionaryStringIntermediateObject read GetCustomFields write SetCustomFields; procedure AddCustomField(Key: String; Value: String); /// <summary> /// Generate optimal routes and driving directions to this curbside latitude /// </summary> property CurbsideLatitude: NullableDouble read FCurbsideLatitude write FCurbsideLatitude; /// <summary> /// Generate optimal routes and driving directions to this curbside longitude /// </summary> property CurbsideLongitude: NullableDouble read FCurbsideLongitude write FCurbsideLongitude; /// <summary> /// Time Window Start in seconds, relative to the route start date (midnight), UTC time zone. It is relative to start datebecause start time changes would shift time windows /// </summary> property TimeWindowStart: NullableInteger read FTimeWindowStart write FTimeWindowStart; /// <summary> /// Time Window End in seconds, relative to the route start date (midnight), UTC time zone. It is relative to start datebecause start time changes would shift time windows /// </summary> property TimeWindowEnd: NullableInteger read FTimeWindowEnd write FTimeWindowEnd; /// <summary> /// See time_window_start /// </summary> property TimeWindowStart2: NullableInteger read FTimeWindowStart2 write FTimeWindowStart2; /// <summary> /// See time_window_end /// </summary> property TimeWindowEnd2: NullableInteger read FTimeWindowEnd2 write FTimeWindowEnd2; /// <summary> /// The sequence number for the address /// </summary> property SequenceNo: NullableInteger read FSequenceNo write FSequenceNo; /// <summary> /// The original customer-specific route id assigned at route creation time /// </summary> property OriginalRouteId: NullableString read FOriginalRouteId write FOriginalRouteId; /// <summary> /// the id of the optimization request that was used to initially instantiate this route /// </summary> property OptimizationProblemId: NullableString read FOptimizationProblemId write FOptimizationProblemId; /// <summary> /// State of the timeframe violation. In a response only /// </summary> property TimeframeViolationState: NullableInteger read FTimeframeViolationState write FTimeframeViolationState; /// <summary> /// Moment of the timeframe violation. In a response only /// </summary> property TimeframeViolationTime: NullableInteger read FTimeframeViolationTime write FTimeframeViolationTime; /// <summary> /// Rate of the timeframe violation. In a response only /// </summary> property TimeframeViolationRate: NullableDouble read FTimeframeViolationRate write FTimeframeViolationRate; /// <summary> /// 0 is the highest priority; n has higher priority than n + 1 /// </summary> property Priority: NullableInteger read FPriority write FPriority; /// <summary> /// The type of stop that this is (PICKUP, DELIVERY, BREAK, MEETUP) /// </summary> property AddressStopType: TAddressStopType read GetAddressStopType write SetAddressStopType; /// <summary> /// Timestamp of a geofence detected visited /// </summary> property GeofenceDetectedVisitedTimestamp: NullableInteger read FGeofenceDetectedVisitedTimestamp write FGeofenceDetectedVisitedTimestamp; /// <summary> /// Timestamp of a geofence detected departed /// </summary> property GeofenceDetectedDepartedTimestamp: NullableInteger read FGeofenceDetectedDepartedTimestamp write FGeofenceDetectedDepartedTimestamp; /// <summary> /// The service time of a detected geofence /// </summary> property GeofenceDetectedServiceTime: NullableInteger read FGeofenceDetectedServiceTime write FGeofenceDetectedServiceTime; /// <summary> /// Latitude of a visited detected geofence /// </summary> property GeofenceDetectedVisitedLat: NullableDouble read FGeofenceDetectedVisitedLat write FGeofenceDetectedVisitedLat; /// <summary> /// Longitude of a visited detected geofence /// </summary> property GeofenceDetectedVisitedLng: NullableDouble read FGeofenceDetectedVisitedLng write FGeofenceDetectedVisitedLng; /// <summary> /// Latitude of a departed detected geofence /// </summary> property GeofenceDetectedDepartedLat: NullableDouble read FGeofenceDetectedDepartedLat write FGeofenceDetectedDepartedLat; /// <summary> /// Longitude of a departed detected geofence /// </summary> property GeofenceDetectedDepartedLng: NullableDouble read FGeofenceDetectedDepartedLng write FGeofenceDetectedDepartedLng; /// <summary> /// Route Name /// </summary> property RouteName: NullableString read FRouteName write FRouteName; /// <summary> /// True means the 'address' field was successfully geocoded /// </summary> property Geocoded: NullableBoolean read FGeocoded write FGeocoded; /// <summary> /// Index of 'geocodings' array that the user has chosen /// </summary> property PreferredGeocoding: NullableInteger read FPreferredGeocoding write FPreferredGeocoding; /// <summary> /// True means there was a geocoding attempt which failed. False means success or no geocoding /// </summary> property FailedGeocoding: NullableBoolean read FFailedGeocoding write FFailedGeocoding; /// <summary> /// Geocodings ID /// </summary> property Geocodings: TAddressGeocodingArray read FGeocodings; procedure AddGeocoding(Geocoding: TAddressGeocoding); /// <summary> /// Address book contact id (0 means not connected to the address book) /// </summary> property ContactId: NullableInteger read FContactId write FContactId; /// <summary> /// The driver pressed the 'Visited' button /// </summary> property IsVisited: NullableBoolean read FIsVisited write FIsVisited; /// <summary> /// The driver marked the 'Departed' button /// </summary> property IsDeparted: NullableBoolean read FIsDeparted write FIsDeparted; /// <summary> /// Last known check in latitude /// </summary> property VisitedLat: NullableDouble read FVisitedLat write FVisitedLat; /// <summary> /// Last known check in longitude /// </summary> property VisitedLng: NullableDouble read FVisitedLng write FVisitedLng; /// <summary> /// Last known departed latitude /// </summary> property DepartedLat: NullableDouble read FDepartedLat write FDepartedLat; /// <summary> /// Last known departed longitude /// </summary> property DepartedLng: NullableDouble read FDepartedLng write FDepartedLng; /// <summary> /// Timestamp when the driver presses 'Visited' /// </summary> property TimestampLastVisited: NullableInteger read FTimestampLastVisited write FTimestampLastVisited; /// <summary> /// Timestamp when the driver marks the stop as 'Departed' /// </summary> property TimestampLastDeparted: NullableInteger read FTimestampLastDeparted write FTimestampLastDeparted; /// <summary> /// The customer purchase order for the address /// </summary> property CustomerPo: NullableString read FCustomerPo write FCustomerPo; /// <summary> /// The invoice number for the address /// </summary> property InvoiceNo: NullableString read FInvoiceNo write FInvoiceNo; /// <summary> /// The reference number for the address /// </summary> property ReferenceNo: NullableString read FReferenceNo write FReferenceNo; /// <summary> /// The account number for the address /// </summary> property AccountNo: NullableString read FAccountNo write FAccountNo; /// <summary> /// The order number for the address /// </summary> property OrderNo: NullableString read FOrderNo write FOrderNo; /// <summary> /// Systemwide unique code, which permits end-users (recipients) to track the status of their order /// </summary> property TrackingNumber: NullableString read FTrackingNumber write FTrackingNumber; /// <summary> /// Weight /// </summary> property Weight: NullableDouble read FWeight write FWeight; /// <summary> /// The cost of the order for the address /// </summary> property Cost: NullableDouble read FCost write FCost; /// <summary> /// The total revenue for the address /// </summary> property Revenue: NullableDouble read FRevenue write FRevenue; /// <summary> /// The cubic volume of the cargo being delivered or picked up at the address /// </summary> property Cube: NullableDouble read FCube write FCube; /// <summary> /// Pieces /// </summary> property Pieces: NullableInteger read FPieces write FPieces; /// <summary> /// A valid e-mail address assigned to this stop /// </summary> property Email: NullableString read FEmail write FEmail; /// <summary> /// Customer Phone /// </summary> property Phone: NullableString read FPhone write FPhone; /// <summary> /// How many notes have been added to this destination /// </summary> property DestinationNoteCount: NullableInteger read FDestinationNoteCount write FDestinationNoteCount; /// <summary> /// Time to next destination in seconds /// </summary> property DriveTimeToNextDestination: NullableInteger read FDriveTimeToNextDestination write FDriveTimeToNextDestination; /// <summary> /// Abnormal traffic time to next destination /// </summary> property AbnormalTrafficTimeToNextDestination: NullableInteger read FAbnormalTrafficTimeToNextDestination write FAbnormalTrafficTimeToNextDestination; /// <summary> /// Supposing that there was no traffic at all, this gives how many seconds it takes to get to the next stop /// </summary> property UncongestedTimeToNextDestination: NullableInteger read FUncongestedTimeToNextDestination write FUncongestedTimeToNextDestination; /// <summary> /// Distance to next destination in route unit (the default unit is in miles) /// </summary> property DistanceToNextDestination: NullableDouble read FDistanceToNextDestination write FDistanceToNextDestination; /// <summary> /// Generated Time Window Start in seconds /// </summary> property GeneratedTimeWindowStart: NullableInteger read FGeneratedTimeWindowStart write FGeneratedTimeWindowStart; /// <summary> /// Generated Time Window End in seconds /// </summary> property GeneratedTimeWindowEnd: NullableInteger read FGeneratedTimeWindowEnd write FGeneratedTimeWindowEnd; /// <summary> /// </summary> property PathToNext: TDirectionPathPointArray read FPathToNext; procedure AddPathToNext(DirectionPathPoint: TDirectionPathPoint); /// <summary> /// </summary> property Directions: TDirectionArray read FDirections; procedure AddDirection(Direction: TDirection); /// <summary> /// The manifest contains values derived from other values /// </summary> property Manifest: TManifest read GetManifest write SetManifest; /// <summary> /// Notes /// </summary> property Notes: TAddressNoteArray read FNotes; procedure AddNote(Note: TAddressNote); end; TAddressesArray = TArray<TAddress>; TAddressesList = TList<TAddress>; TOrderedAddress = class(TAddress) private [JSONName('order_id')] [Nullable] FOrderId: NullableInteger; public constructor Create(); override; property OrderId: NullableInteger read FOrderId write FOrderId; end; TOrderedAddressArray = TArray<TOrderedAddress>; function SortAddresses(Addresses: TAddressesArray): TAddressesArray; implementation uses Math; { TAddress } constructor TAddress.Create(AddressString: String; Latitude, Longitude: double; Time: NullableInteger); begin Create; FAddressString := AddressString; FLatitude := Latitude; FLongitude := Longitude; FTime := Time; end; procedure TAddress.AddCustomField(Key: String; Value: String); var Dic: TDictionaryStringIntermediateObject; begin if (FCustomFields.IsNull) then FCustomFields := TDictionaryStringIntermediateObject.Create(); Dic := FCustomFields.Value as TDictionaryStringIntermediateObject; Dic.Add(Key, Value); end; constructor TAddress.Create(AddressString, Alias: String; Latitude, Longitude: double; Time: NullableInteger); begin Create(AddressString, Latitude, Longitude, Time); FAlias := Alias; end; constructor TAddress.Create; begin FOwnsNotes := True; FAlias := EmptyStr; FCurbsideLatitude := NullableDouble.Null; FCurbsideLongitude := NullableDouble.Null; FMemberId := NullableInteger.Null; FRouteDestinationId := NullableInteger.Null; FRouteId := NullableString.Null; FIsDepot := NullableBoolean.Null; FTime := NullableInteger.Null; FTimeWindowStart := NullableInteger.Null; FTimeWindowEnd := NullableInteger.Null; FTimeWindowStart2 := NullableInteger.Null; FTimeWindowEnd2 := NullableInteger.Null; FSequenceNo := NullableInteger.Null; FOriginalRouteId := NullableString.Null; FOptimizationProblemId := NullableString.Null; FTimeframeViolationState := NullableInteger.Null; FTimeframeViolationTime := NullableInteger.Null; FTimeframeViolationRate := NullableDouble.Null; FPriority := NullableInteger.Null; FAddressStopType := NullableString.Null; FGeofenceDetectedVisitedTimestamp := NullableInteger.Null; FGeofenceDetectedDepartedTimestamp := NullableInteger.Null; FGeofenceDetectedServiceTime := NullableInteger.Null; FGeofenceDetectedVisitedLat := NullableDouble.Null; FGeofenceDetectedVisitedLng := NullableDouble.Null; FGeofenceDetectedDepartedLat := NullableDouble.Null; FGeofenceDetectedDepartedLng := NullableDouble.Null; FRouteName := NullableString.Null; FGeocoded := NullableBoolean.Null; FPreferredGeocoding := NullableInteger.Null; FFailedGeocoding := NullableBoolean.Null; FContactId := NullableInteger.Null; FIsVisited := NullableBoolean.Null; FIsDeparted := NullableBoolean.Null; FVisitedLat := NullableDouble.Null; FVisitedLng := NullableDouble.Null; FDepartedLat := NullableDouble.Null; FDepartedLng := NullableDouble.Null; FTimestampLastVisited := NullableInteger.Null; FTimestampLastDeparted := NullableInteger.Null; FCustomerPo := NullableString.Null; FInvoiceNo := NullableString.Null; FReferenceNo := NullableString.Null; FAccountNo := NullableString.Null; FOrderNo := NullableString.Null; FTrackingNumber := NullableString.Null; FWeight := NullableDouble.Null; FCost := NullableDouble.Null; FRevenue := NullableDouble.Null; FCube := NullableDouble.Null; FPieces := NullableInteger.Null; FEmail := NullableString.Null; FPhone := NullableString.Null; FDestinationNoteCount := NullableInteger.Null; FDriveTimeToNextDestination := NullableInteger.Null; FAbnormalTrafficTimeToNextDestination := NullableInteger.Null; FUncongestedTimeToNextDestination := NullableInteger.Null; FDistanceToNextDestination := NullableDouble.Null; FGeneratedTimeWindowStart := NullableInteger.Null; FGeneratedTimeWindowEnd := NullableInteger.Null; FManifest := NullableObject.Null; FCustomFields := NullableObject.Null; SetLength(FGeocodings, 0); SetLength(FNotes, 0); SetLength(FPathToNext, 0); SetLength(FDirections, 0); end; constructor TAddress.Create(AddressString: String; Latitude, Longitude: double; Time: NullableInteger; TimeWindowStart, TimeWindowEnd: integer); begin Create(AddressString, Latitude, Longitude, Time); FTimeWindowStart := TimeWindowStart; FTimeWindowEnd := TimeWindowEnd; end; procedure TAddress.AddNote(Note: TAddressNote); begin SetLength(FNotes, Length(FNotes) + 1); FNotes[High(FNotes)] := Note; end; procedure TAddress.AddPathToNext(DirectionPathPoint: TDirectionPathPoint); begin SetLength(FPathToNext, Length(FPathToNext) + 1); FPathToNext[High(FPathToNext)] := DirectionPathPoint; end; constructor TAddress.Create(AddressString: String; Latitude, Longitude: double; Time: NullableInteger; TimeWindowStart, TimeWindowEnd, TimeWindowStart2, TimeWindowEnd2: integer); begin Create(AddressString, Latitude, Longitude, Time, TimeWindowStart, TimeWindowEnd); FTimeWindowStart2 := TimeWindowStart2; FTimeWindowEnd2 := TimeWindowEnd2; end; destructor TAddress.Destroy; var i: integer; begin for i := Length(FPathToNext) - 1 downto 0 do FreeAndNil(FPathToNext[i]); for i := Length(FDirections) - 1 downto 0 do FreeAndNil(FDirections[i]); for i := Length(FGeocodings) - 1 downto 0 do FreeAndNil(FGeocodings[i]); if FOwnsNotes then for i := Length(FNotes) - 1 downto 0 do FreeAndNil(FNotes[i]); FManifest.Free; FCustomFields.Free; inherited; end; function TAddress.Equals(Obj: TObject): Boolean; var Other: TAddress; i: integer; SortedPathToNext1, SortedPathToNext2: TDirectionPathPointArray; SortedDirections1, SortedDirections2: TDirectionArray; SortedNotes1, SortedNotes2: TAddressNoteArray; SortedGeocodings1, SortedGeocodings2: TAddressGeocodingArray; begin Result := False; if not (Obj is TAddress) then Exit; Other := TAddress(Obj); Result := (FAddressString = Other.FAddressString) and (FAlias = Other.FAlias) and (FRouteDestinationId = Other.FRouteDestinationId) and (FMemberId = Other.FMemberId) and (FIsDepot = Other.FIsDepot) and (FLatitude = Other.FLatitude) and (FLongitude = Other.FLongitude) and (FRouteId = Other.FRouteId) and (FTime = Other.FTime) and (FCurbsideLatitude = Other.FCurbsideLatitude) and (FCurbsideLongitude = Other.FCurbsideLongitude) and (FTimeWindowStart = Other.FTimeWindowStart) and (FTimeWindowEnd = Other.FTimeWindowEnd) and (FTimeWindowStart2 = Other.FTimeWindowStart2) and (FTimeWindowEnd2 = Other.FTimeWindowEnd2) and (FSequenceNo = Other.FSequenceNo) and (FOriginalRouteId = Other.FOriginalRouteId) and (FOptimizationProblemId = Other.FOptimizationProblemId) and (FTimeframeViolationState = Other.FTimeframeViolationState) and (FTimeframeViolationTime = Other.FTimeframeViolationTime) and (FTimeframeViolationRate = Other.FTimeframeViolationRate) and (FPriority = Other.FPriority) and (FAddressStopType = Other.FAddressStopType) and (FGeofenceDetectedVisitedTimestamp = Other.FGeofenceDetectedVisitedTimestamp) and (FGeofenceDetectedDepartedTimestamp = Other.FGeofenceDetectedDepartedTimestamp) and (FGeofenceDetectedServiceTime = Other.FGeofenceDetectedServiceTime) and (FTimeframeViolationRate = Other.FTimeframeViolationRate) and (FGeofenceDetectedVisitedLat = Other.FGeofenceDetectedVisitedLat) and (FGeofenceDetectedVisitedLng = Other.FGeofenceDetectedVisitedLng) and (FGeofenceDetectedDepartedLat = Other.FGeofenceDetectedDepartedLat) and (FGeofenceDetectedDepartedLng = Other.FGeofenceDetectedDepartedLng) and (FRouteName = Other.FRouteName) and (FGeocoded = Other.FGeocoded) and (FPreferredGeocoding = Other.FPreferredGeocoding) and (FFailedGeocoding = Other.FFailedGeocoding) and (FContactId = Other.FContactId) and (FIsVisited = Other.FIsVisited) and (FIsDeparted = Other.FIsDeparted) and (FVisitedLat = Other.FVisitedLat) and (FVisitedLng = Other.FVisitedLng) and (FDepartedLat = Other.FDepartedLat) and (FDepartedLng = Other.FDepartedLng) and (FTimestampLastVisited = Other.FTimestampLastVisited) and (FTimestampLastDeparted = Other.FTimestampLastDeparted) and (FCustomerPo = Other.FCustomerPo) and (FInvoiceNo = Other.FInvoiceNo) and (FReferenceNo = Other.FReferenceNo) and (FAccountNo = Other.FAccountNo) and (FOrderNo = Other.FOrderNo) and (FTrackingNumber = Other.FTrackingNumber) and (FWeight = Other.FWeight) and (FCost = Other.FCost) and (FRevenue = Other.FRevenue) and (FCube = Other.FCube) and (FPieces = Other.FPieces) and (FEmail = Other.FEmail) and (FPhone = Other.FPhone) and (FDestinationNoteCount = Other.FDestinationNoteCount) and (FDriveTimeToNextDestination = Other.FDriveTimeToNextDestination) and (FAbnormalTrafficTimeToNextDestination = Other.FAbnormalTrafficTimeToNextDestination) and (FUncongestedTimeToNextDestination = Other.FUncongestedTimeToNextDestination) and (FDistanceToNextDestination = Other.FDistanceToNextDestination) and (FGeneratedTimeWindowStart = Other.FGeneratedTimeWindowStart) and (FGeneratedTimeWindowEnd = Other.FGeneratedTimeWindowEnd) and (FManifest = Other.FManifest) and (FCustomFields = Other.FCustomFields); if not Result then Exit; Result := False; if (Length(FPathToNext) <> Length(Other.FPathToNext)) or (Length(FDirections) <> Length(Other.FDirections)) or (Length(FGeocodings) <> Length(Other.FGeocodings)) or (Length(FNotes) <> Length(Other.FNotes)) then Exit; SortedDirections1 := DirectionUnit.SortDirections(Directions); SortedDirections2 := DirectionUnit.SortDirections(Other.Directions); for i := 0 to Length(SortedDirections1) - 1 do if (not SortedDirections1[i].Equals(SortedDirections2[i])) then Exit; SortedGeocodings1 := AddressGeocodingUnit.SortAddressGeocodings(Geocodings); SortedGeocodings2 := AddressGeocodingUnit.SortAddressGeocodings(Other.Geocodings); for i := 0 to Length(SortedGeocodings1) - 1 do if (not SortedGeocodings1[i].Equals(SortedGeocodings2[i])) then Exit; SortedNotes1 := AddressNoteUnit.SortAddressNotes(Notes); SortedNotes2 := AddressNoteUnit.SortAddressNotes(Other.Notes); for i := 0 to Length(SortedNotes1) - 1 do if (not SortedNotes1[i].Equals(SortedNotes2[i])) then Exit; SortedPathToNext1 := DirectionPathPointUnit.SortDirectionPathPoints(PathToNext); SortedPathToNext2 := DirectionPathPointUnit.SortDirectionPathPoints(Other.PathToNext); for i := 0 to Length(SortedPathToNext1) - 1 do if (not SortedPathToNext1[i].Equals(SortedPathToNext2[i])) then Exit; Result := True; end; function TAddress.GetAddressStopType: TAddressStopType; var AddressStopType: TAddressStopType; begin Result := TAddressStopType.astUnknown; if FAddressStopType.IsNotNull then for AddressStopType := Low(TAddressStopType) to High(TAddressStopType) do if (FAddressStopType = TAddressStopTypeDescription[AddressStopType]) then Exit(AddressStopType); end; function TAddress.GetCustomFields: TDictionaryStringIntermediateObject; begin if FCustomFields.IsNull then Result := nil else Result := FCustomFields.Value as TDictionaryStringIntermediateObject; end; function TAddress.GetManifest: TManifest; begin if (FManifest.IsNull) then Result := nil else Result := FManifest.Value as TManifest; end; procedure TAddress.SetAddressStopType(const Value: TAddressStopType); begin FAddressStopType := TAddressStopTypeDescription[Value]; end; procedure TAddress.SetCustomFields( const Value: TDictionaryStringIntermediateObject); begin FCustomFields := Value; end; procedure TAddress.SetManifest(const Value: TManifest); begin FManifest := Value; end; procedure TAddress.AddDirection(Direction: TDirection); begin SetLength(FDirections, Length(FDirections) + 1); FDirections[High(FDirections)] := Direction; end; procedure TAddress.AddGeocoding(Geocoding: TAddressGeocoding); begin SetLength(FGeocodings, Length(FGeocodings) + 1); FGeocodings[High(FGeocodings)] := Geocoding; end; function SortAddresses(Addresses: TAddressesArray): TAddressesArray; begin SetLength(Result, Length(Addresses)); if Length(Addresses) = 0 then Exit; TArray.Copy<TAddress>(Addresses, Result, Length(Addresses)); TArray.Sort<TAddress>(Result, TComparer<TAddress>.Construct( function (const Address1, Address2: TAddress): Integer begin Result := IfThen(Address1.SequenceNo.IsNotNull, Address1.SequenceNo.Value, -1) - IfThen(Address2.SequenceNo.IsNotNull, Address2.SequenceNo.Value, -1); if (result = 0) then Result := IfThen(Address1.IsDepot.IsNotNull and Address1.IsDepot.Value, 0, 1) - IfThen(Address2.IsDepot.IsNotNull and Address2.IsDepot.Value, 0, 1) end)); end; { TOrderedAddress } constructor TOrderedAddress.Create; begin Inherited Create; FOrderId := NullableInteger.Null; end; end.
unit SubscriptionsService; interface uses JunoApi4Delphi.Interfaces, Data.DB, System.JSON; type TSubscriptionsService = class(TInterfacedObject, iSubscriptions) private FBilling : iBilling<iSubscriptions>; FSplit : iSplit<iSubscriptions>; FParent : iJunoApi4DelphiConig; FAuth : iAuthorizationService; FJSON : TJSONObject; public constructor Create(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService); destructor Destroy; override; class function New(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService) : iSubscriptions; function CreateSubscription : iSubscriptions; function DueDay(Value : Integer) : iSubscriptions; function PlanId(Value : String) : iSubscriptions; function ChargeDescription(Value : String): iSubscriptions; function CreditCardDetails(Value : String) : iSubscriptions; function Billing : iBilling<iSubscriptions>; function Split : iSplit<iSubscriptions>; function &End(Value : TDataSet) : iSubscriptions; overload; function &End : String; overload; function GetSubscriptions(Value : TDataSet) : iSubscriptions; overload; function GetSubscriptions : String; overload; function GetSubscription(Value : String; dtValue : TDataSet) : iSubscriptions; overload; function GetSubscription(Value : String) : String; overload; function DeactiveSubscription(Value : String) : String; function ActiveSubscription(Value : String) : String; function CancelationSubscription(Value : String) : String; end; implementation uses Billing, Split, REST.Response.Adapter, RESTRequest4D, REST.Types, System.SysUtils; CONST SUBSCRIPTIONS_ENDPONT = '/subscriptions'; { TSubscriptionsService } function TSubscriptionsService.ActiveSubscription(Value: String): String; begin Result := TRequest.New .BaseURL(FParent.ResourceEndpoint + SUBSCRIPTIONS_ENDPONT + '/' + Value + '/activation') .Token(FAuth.Token) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .Post.Content; end; function TSubscriptionsService.Billing: iBilling<iSubscriptions>; begin Result := FBilling; end; function TSubscriptionsService.CancelationSubscription(Value: String): String; begin Result := TRequest.New .BaseURL(FParent.ResourceEndpoint + SUBSCRIPTIONS_ENDPONT + '/' + Value + '/cancelation') .Token(FAuth.Token) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .Post.Content; end; function TSubscriptionsService.ChargeDescription(Value: String): iSubscriptions; begin Result := Self; FJSON.AddPair('chargeDescription', Value); end; function TSubscriptionsService.&End: String; var lJSONBilling : TJSONObject; ljson:TJSONObject; begin lJSONBilling := TJSONObject.Create; ljson := TJSONObject.Create; lJSONBilling.AddPair('email', FBilling.Email); lJSONBilling.AddPair('name', FBilling.Name); lJSONBilling.AddPair('document', FBilling.Document); ljson.AddPair('street', FBilling.Street); ljson.AddPair('number', FBilling.Number); ljson.AddPair('complement', FBilling.Complement); ljson.AddPair('neighborhood', FBilling.Neighborhood); ljson.AddPair('city', FBilling.City); ljson.AddPair('state', FBilling.State); ljson.AddPair('postCode', FBilling.PostCode); lJSONBilling.AddPair('address', ljson); FJSON.AddPair('billing', lJSONBilling); Result := TRequest.New .BaseURL(FParent.ResourceEndpoint + SUBSCRIPTIONS_ENDPONT) .Accept('application/json') .Token(FAuth.Token) .AddBody('application/json',ctAPPLICATION_JSON) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .AddParam('body', FJSON.ToString, pkREQUESTBODY) .Post.Content; end; function TSubscriptionsService.GetSubscription(Value: String): String; begin Result := TRequest.New .BaseURL(FParent.ResourceEndpoint + SUBSCRIPTIONS_ENDPONT + '/' + Value) .Token(FAuth.Token) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .Get.Content; end; function TSubscriptionsService.GetSubscription(Value: String; dtValue: TDataSet): iSubscriptions; var lJSONObj : TJSONObject; lConv : TCustomJSONDataSetAdapter; lJSON : String; begin Result := Self; lJSON := TRequest.New .BaseURL(FParent.ResourceEndpoint + SUBSCRIPTIONS_ENDPONT + '/' + Value) .Token(FAuth.Token) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .Get.Content; lJSONObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(lJSON), 0) as TJSONObject; lConv := TCustomJSONDataSetAdapter.Create(nil); try lConv.DataSet := dtValue; lConv.UpdateDataSet(lJSONObj); finally lConv.Free; end; end; function TSubscriptionsService.GetSubscriptions: String; begin Result := TRequest.New .BaseURL(FParent.ResourceEndpoint + SUBSCRIPTIONS_ENDPONT) .Token(FAuth.Token) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .Get.Content; end; function TSubscriptionsService.GetSubscriptions(Value: TDataSet): iSubscriptions; var lJSONObj : TJSONObject; lJSONArray : TJSONArray; jv : TJSONValue; lConv : TCustomJSONDataSetAdapter; lJSON : String; begin Result := Self; lJSON := TRequest.New .BaseURL(FParent.ResourceEndpoint + SUBSCRIPTIONS_ENDPONT) .Token(FAuth.Token) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .Get.Content; lJSONObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(lJSON), 0) as TJSONObject; jv := lJSONObj.Get('_embedded').JsonValue; lJSONObj := jv as TJSONObject; lJSONArray := lJSONObj.Get('subscriptions').JsonValue as TJSONArray; lConv := TCustomJSONDataSetAdapter.Create(nil); try lConv.DataSet := Value; lConv.UpdateDataSet(lJSONArray); finally lConv.Free; end; end; function TSubscriptionsService.&End(Value: TDataSet): iSubscriptions; var lJSONObj,lJSONBilling,ljsono : TJSONObject; lConv : TCustomJSONDataSetAdapter; ljson : String; begin Result := Self; lJSONBilling := TJSONObject.Create; ljsono := TJSONObject.Create; lJSONBilling.AddPair('email', FBilling.Email); lJSONBilling.AddPair('name', FBilling.Name); lJSONBilling.AddPair('document', FBilling.Document); ljsono.AddPair('street', FBilling.Street); ljsono.AddPair('number', FBilling.Number); ljsono.AddPair('complement', FBilling.Complement); ljsono.AddPair('neighborhood', FBilling.Neighborhood); ljsono.AddPair('city', FBilling.City); ljsono.AddPair('state', FBilling.State); ljsono.AddPair('postCode', FBilling.PostCode); lJSONBilling.AddPair('address', ljsono); FJSON.AddPair('billing', lJSONBilling); lJSON := TRequest.New .BaseURL(FParent.ResourceEndpoint + SUBSCRIPTIONS_ENDPONT) .Accept('application/json') .Token(FAuth.Token) .AddBody('application/json',ctAPPLICATION_JSON) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .AddParam('body', FJSON.ToString, pkREQUESTBODY) .Post.Content; lJSONObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(lJSON), 0) as TJSONObject; lConv := TCustomJSONDataSetAdapter.Create(nil); try lConv.DataSet := Value; lConv.UpdateDataSet(lJSONObj); finally lConv.Free; end; end; constructor TSubscriptionsService.Create(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService); begin FBilling := TBilling<iSubscriptions>.New(Self); FSplit := TSplit<iSubscriptions>.New(Self); FParent := Parent; FAuth := AuthService; FJSON := TJSONObject.Create; end; function TSubscriptionsService.CreateSubscription: iSubscriptions; begin Result := Self; end; function TSubscriptionsService.CreditCardDetails(Value: String): iSubscriptions; var ljson : TJSONObject; begin Result := Self; ljson := TJSONObject.Create; lJson.AddPair('creditCardHash', Value); FJson.AddPair('creditCardDetails',ljson); end; function TSubscriptionsService.DeactiveSubscription(Value: String): String; begin Result := TRequest.New .BaseURL(FParent.ResourceEndpoint + SUBSCRIPTIONS_ENDPONT + '/' + Value + '/deactivation') .Token(FAuth.Token) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .Post.Content; end; destructor TSubscriptionsService.Destroy; begin inherited; end; function TSubscriptionsService.DueDay(Value: Integer): iSubscriptions; begin Result := Self; FJSON.AddPair('dueDay', TJSONNumber.Create(Value)); end; class function TSubscriptionsService.New(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService) : iSubscriptions; begin Result := Self.Create(Parent, AuthService); end; function TSubscriptionsService.PlanId(Value: String): iSubscriptions; begin Result := Self; FJSON.AddPair('planId', Value); end; function TSubscriptionsService.Split: iSplit<iSubscriptions>; begin Result := FSplit; end; end.
unit PDMainForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OutputEngine, RMEngineInt, Engine3D, Dresser, ClassLibrary, VisualClasses, Notifications; const GridSizeX = 100; GridSizeZ = 100; type TForm1 = class(TForm, IHook, IModelLoader) procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private fInitialized : boolean; fActive : boolean; f3DEngine : I3DEngine; fDDOutputEngine : IDDrawOutputEngine; fDresser : IMeshDresser; fClassRenderer : IVisualClassesRenderer; fClassLibrary : TClassLibrary; fClassContainer : TClassContainer; fAnimated : I3DAnimated; fCamera : I3DCamera; procedure InitNotifications; procedure InitClasses; procedure InitAmbientEffects; procedure InitMaterials; procedure CreateScene; procedure OnIdle(Sender: TObject; var Done: Boolean); function InsertObject( x, y, z : T3DValue; Parent : I3DObject; ClassId : cardinal ) : I3DMesh; procedure Notify( Event : TEventClass; const Info ); private procedure LoadPartition( x, y, z : integer; Parent : I3DObject ); procedure UnLoadPartition( x, y, z : integer; Parent : I3DObject ); end; var Form1: TForm1; implementation uses DDEngine, RMEngine, RMDresser, AmbientEffectsInt, AmbientEffects, D3DRMDef, Events; const CLASSID_GUY = 100; {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); begin fInitialized := false; fActive := false; InitNotifications; fDDOutputEngine := TDDOutputEngine.Create( Handle, DMMODE_WINDOWED ); f3DEngine := TD3DRMEngine.Create( Width, Height ); InitClasses; InitMaterials; Application.OnIdle := OnIdle; end; procedure TForm1.FormActivate(Sender: TObject); var VideoModeId : TVideoModeId; begin fActive := Application.Active; if fActive then begin if not fInitialized then begin if SUCCEEDED( f3DEngine.Initialize( fDDOutputEngine as IOutputDevice )) then begin fInitialized := true; fInitialized := fDDOutputEngine.FindVideoMode( 640, 480, 16, VideoModeId ) and SUCCEEDED(fDDOutputEngine.setVideoMode( VideoModeId )); CreateScene; end; end; end; end; type TDrawArea = class( TInterfacedObject, IDrawArea ) public x, y, width, height : DWORD; function getX : DWORD; function getY : DWORD; function getWidth : DWORD; function getHeight : DWORD; end; // TDrawArea function TDrawArea.getX : DWORD; begin result := x; end; function TDrawArea.getY : DWORD; begin result := y; end; function TDrawArea.getWidth : DWORD; begin result := width; end; function TDrawArea.getHeight : DWORD; begin result := height; end; function CreateDrawArea( x, y, width, height : DWORD ) : IDrawArea; var DA : TDrawArea; begin DA := TDrawArea.Create; DA.x := x; DA.y := y; DA.width := width; DA.height := height; result := DA; end; procedure TForm1.InitNotifications; begin InitNotificationEngine; RegisterEventClass( evAnimationFinishes, 0 ); RegisterEventClass( evCameraMove, 0 ); RegisterEventClass( evCameraCreated, 0 ); RegisterEventClass( evCameraRemoved, 0 ); end; procedure TForm1.InitClasses; var i : integer; begin fClassContainer := TClassContainer.Create; fClassContainer.AddSearchPath( '\work\pd client\release\classes' ); fClassContainer.RegisterClasses; fClassLibrary := TClassLibrary.Create; fDresser := TRetainedModeDresser.Create( fClassLibrary, f3DEngine as ID3DRMEngine ); fClassRenderer := fDresser as IVisualClassesRenderer; for i := 0 to pred(fClassContainer.Count) do fClassRenderer.RenderVisualClass( fClassContainer.Classes[i] ); end; procedure TForm1.InitAmbientEffects; var FogParams : TFogParams; AmbientEffect : IAmbientEffect; begin AmbientEffect := TFogAmbientEffect.Create( AMBIENT_FOG, f3DEngine as ID3DRMEngine ); with FogParams do begin PByteArray(@Color)[0] := 100; PByteArray(@Color)[1] := 100; PByteArray(@Color)[2] := 100; PByteArray(@Color)[3] := 0; FogMode := D3DRMFOG_LINEAR; FogStart := 10; FogEnd := 200; FogDensity := 0; end; AmbientEffect.SetParams( FogParams ); f3DEngine.RegisterAmbientEffect( AmbientEffect ); end; procedure TForm1.InitMaterials; var MaterialClass : IMaterialClass; begin MaterialClass := f3DEngine.getMaterialLibrary.CreateMaterialClass; MaterialClass.SetMaterialId( pchar('pepe') ); MaterialClass.CreateMapFromFile( 0, pchar('c:\work\media\tex3.ppm') ); end; procedure TForm1.CreateScene; var XCamera : I3DCamera; Viewport1 : I3DViewport; Viewport2 : I3DViewport; Light : I3DLight; Mesh : I3DMesh; SubMesh : I3DMesh; Animated : I3DAnimated; Animation : IAnimation; Pos : T3DVector; Material : IMaterial; begin f3DEngine.AddEventHook( evAnimationFinishes, self ); // LM Support!!! f3DEngine.setLMGridInfo( GridSizeX, 10, GridSizeZ ); f3DEngine.EnableLMSupport( self ); f3DEngine.CreateCamera( 0, nil, fCamera ); f3DEngine.CreateViewport( CreateDrawArea( 0, 0, 200, 200 ), fCamera, Viewport1 ); fCamera.setVisualRange( 1, 50000 ); f3DEngine.CreateLight( LIGHT_DIRECTIONAL, nil, Light ); Light.setPosition( 0, 0, 500 ); Light.SetOrientation(0, 0, -1, 0, 1, 0); Light.setRGBColor( 1, 1, 1 ); f3DEngine.CreateLight( LIGHT_AMBIENT, nil, Light ); Light.setRGBColor( 0.6, 0.6, 0.6 ); { Material := f3DEngine.getMaterialLibrary.CreateMaterial( 'pepe' ); Mesh := InsertObject( 0, 0, 150, CLASSID_GUY ) as I3DMesh; Mesh.SetOrientation(0, 0, 1, 0, 1, 0); f3DEngine.CreateCamera( 0, Mesh, XCamera ); XCamera.SetPosition( 0, 0, 300 ); XCamera.SetOrientation(0, 0, -1, 0, 1, 0); XCamera.setVisualRange(1, 600 ); f3DEngine.CreateViewport( CreateDrawArea( 0, 200, 200, 200 ), XCamera, Viewport2 ); //Mesh.SetMaterial( Material ); SubMesh := Mesh.getNamedSubObject( pchar('x3ds_Chest') ); SubMesh.SetMaterial( Material ); Animated := SubMesh as I3DAnimated; Animation := Animated.CreateAnimation( 20, 12 ); Animation.SetLooped( false ); SubMesh.GetPosition( Pos.x, Pos.y, Pos.z ); Animation.AddKeyAtFrame( 1, KEYTYPE_POSITION, Pos ); Pos.x := -10; Pos.y := 0; Pos.z := 0; Animation.AddKeyAtFrame( 10, KEYTYPE_POSITION, Pos ); SubMesh.GetPosition( Pos.x, Pos.y, Pos.z ); Animation.AddKeyAtFrame( 19, KEYTYPE_POSITION, Pos ); Animated.Animate( Animation.GetAnimationId ); fAnimated := Mesh as I3DAnimated; } end; procedure TForm1.OnIdle(Sender: TObject; var Done: Boolean); begin try if (fInitialized and fActive) then begin f3DEngine.Move( 1 ); f3DEngine.Render; Done := false; end; except end; end; function TForm1.InsertObject( x, y, z : T3DValue; Parent : I3DObject; ClassId : cardinal ) : I3DMesh; var Obj : I3DObject; Mesh : I3DMesh; begin if SUCCEEDED(f3DEngine.CreateObject( OBJTYPE_MESH, Parent, 0, Obj )) then begin Mesh := Obj as I3DMesh; fDresser.DressMesh( Mesh, ClassId ); Mesh.SetPosition( x, y, z ); result := Mesh; end; end; procedure TForm1.Notify( Event : TEventClass; const Info ); begin fAnimated.Animate( 100 + random(6) ); end; procedure TForm1.LoadPartition( x, y, z : integer; Parent : I3DObject ); var Pos : T3DVector; begin Pos.x := x*GridSizeX; Pos.y := 5; Pos.z := z*GridSizeZ; InsertObject( Pos.x, Pos.y, Pos.z, Parent, CLASSID_GUY ); end; procedure TForm1.UnLoadPartition( x, y, z : integer; Parent : I3DObject ); begin f3DEngine.RemoveObject( Parent ); end; procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var Dir, Up : T3DVector; Pos : T3DVector; begin case Key of VK_UP : begin fCamera.getOrientation( Dir.x, Dir.y, Dir.z, Up.x, Up.y, Up.z ); fCamera.getRelativePosition( nil, Pos.x, Pos.y, Pos.z ); fCamera.SetRelativePosition( nil, Pos.x + Dir.x*20, Pos.y + Dir.y*20, Pos.z + Dir.z*20 ); end; VK_DOWN : begin fCamera.getOrientation( Dir.x, Dir.y, Dir.z, Up.x, Up.y, Up.z ); fCamera.getRelativePosition( nil, Pos.x, Pos.y, Pos.z ); fCamera.SetRelativePosition( nil, Pos.x - Dir.x*20, Pos.y - Dir.y*20, Pos.z - Dir.z*20 ); end; VK_LEFT : fCamera.SetAngVelocity( 0, 1, 0, -0.1 ); VK_RIGHT : fCamera.SetAngVelocity( 0, 1, 0, 0.1 ); end; end; procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_UP, VK_DOWN : fCamera.SetVelocity( 0 ); VK_LEFT, VK_RIGHT : fCamera.SetAngVelocity( 0, 1, 0, 0 ); end; end; end.
unit App; { Based on TextureWrap.c from Book: OpenGL(R) ES 2.0 Programming Guide Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner ISBN-10: 0321502795 ISBN-13: 9780321502797 Publisher: Addison-Wesley Professional URLs: http://safari.informit.com/9780321563835 http://www.opengles-book.com } {$INCLUDE 'Sample.inc'} interface uses System.Classes, Neslib.Ooogles, Neslib.FastMath, Sample.App; type TTextureWrapApp = class(TApplication) private FProgram: TGLProgram; FAttrPosition: TGLVertexAttrib; FAttrTexCoord: TGLVertexAttrib; FUniSampler: TGLUniform; FUniOffset: TGLUniform; FTexture: TGLTexture; public procedure Initialize; override; procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override; procedure Shutdown; override; procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override; end; implementation uses {$INCLUDE 'OpenGL.inc'} System.UITypes, Sample.Texture; { TTextureWrapApp } procedure TTextureWrapApp.Initialize; var VertexShader, FragmentShader: TGLShader; begin { Compile vertex and fragment shaders } VertexShader.New(TGLShaderType.Vertex, 'uniform float u_offset;'#10+ 'attribute vec4 a_position;'#10+ 'attribute vec2 a_texCoord;'#10+ 'varying vec2 v_texCoord;'#10+ 'void main()'#10+ '{'#10+ ' gl_Position = a_position;'#10+ ' gl_Position.x += u_offset;'#10+ ' v_texCoord = a_texCoord;'#10+ '}'); VertexShader.Compile; FragmentShader.New(TGLShaderType.Fragment, 'precision mediump float;'#10+ 'varying vec2 v_texCoord;'#10+ 'uniform sampler2D s_texture;'#10+ 'void main()'#10+ '{'#10+ ' gl_FragColor = texture2D(s_texture, v_texCoord);'#10+ '}'); FragmentShader.Compile; { Link shaders into program } FProgram.New(VertexShader, FragmentShader); FProgram.Link; { We don't need the shaders anymore. Note that the shaders won't actually be deleted until the program is deleted. } VertexShader.Delete; FragmentShader.Delete; { Initialize vertex attributes } FAttrPosition.Init(FProgram, 'a_position'); FAttrTexCoord.Init(FProgram, 'a_texCoord'); { Initialize uniforms } FUniSampler.Init(FProgram, 's_texture'); FUniOffset.Init(FProgram, 'u_offset'); { Load the texture } FTexture := CreateMipmappedTexture2D; { Set clear color to black } gl.ClearColor(0, 0, 0, 0); end; procedure TTextureWrapApp.KeyDown(const AKey: Integer; const AShift: TShiftState); begin { Terminate app when Esc key is pressed } if (AKey = vkEscape) then Terminate; end; procedure TTextureWrapApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double); type TVertex = record Pos: TVector4; TexCoord: TVector2; end; const VERTICES: array [0..3] of TVertex = ( (Pos: (X: -0.3; Y: 0.3; Z: 0.0; W: 1.0); TexCoord: (X: -1.0; Y: -1.0)), (Pos: (X: -0.3; Y: -0.3; Z: 0.0; W: 1.0); TexCoord: (X: -1.0; Y: 2.0)), (Pos: (X: 0.3; Y: -0.3; Z: 0.0; W: 1.0); TexCoord: (X: 2.0; Y: 2.0)), (Pos: (X: 0.3; Y: 0.3; Z: 0.0; W: 1.0); TexCoord: (X: 2.0; Y: -1.0))); INDICES: array [0..5] of UInt16 = ( 0, 1, 2, 0, 2, 3); begin { Clear the color buffer } gl.Clear([TGLClear.Color]); { Use the program } FProgram.Use; { Set the data for the vertex attributes } FAttrPosition.SetData(TGLDataType.Float, 4, @VERTICES[0].Pos, SizeOf(TVertex)); FAttrPosition.Enable; FAttrTexCoord.SetData(TGLDataType.Float, 2, @VERTICES[0].TexCoord, SizeOf(TVertex)); FAttrTexCoord.Enable; { Bind the texture } FTexture.BindToTextureUnit(0); { Set the sampler texture unit to 0 } FUniSampler.SetValue(0); { Draw quad with repeat wrap mode } FTexture.WrapS(TGLWrapMode.NormalRepeat); FTexture.WrapT(TGLWrapMode.NormalRepeat); FUniOffset.SetValue(-0.7); gl.DrawElements(TGLPrimitiveType.Triangles, INDICES); { Draw quad with clamp to edge wrap mode } FTexture.WrapS(TGLWrapMode.ClampToEdge); FTexture.WrapT(TGLWrapMode.ClampToEdge); FUniOffset.SetValue(0.0); gl.DrawElements(TGLPrimitiveType.Triangles, INDICES); { Draw quad with mirrored repeat } FTexture.WrapS(TGLWrapMode.MirroredRepeat); FTexture.WrapT(TGLWrapMode.MirroredRepeat); FUniOffset.SetValue(0.7); gl.DrawElements(TGLPrimitiveType.Triangles, INDICES); end; procedure TTextureWrapApp.Shutdown; begin { Release resources } FTexture.Delete; FProgram.Delete; end; end.
unit CustomFormFactory; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "DUnitTuning" // Модуль: "w:/common/components/rtl/Garant/DUnitTuning/CustomFormFactory.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi TFW::DUnitTuning::VCM_TFW::CustomFormFactory // // Базовая фабрика форм для тестов. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\DUnitTuning\tfwDefine.inc} interface {$If defined(nsTest) AND not defined(NoScripts) AND not defined(NotTunedDUnit)} uses Forms ; type TCustomFormFactory = class {* Базовая фабрика для создания форм. } protected // protected methods class function GetFormName(const aName: AnsiString): AnsiString; {* Получает название класса формы из зарегистрированного слова. } public // public methods class function MakeFormByClassName(const aName: AnsiString): TCustomForm; virtual; abstract; class procedure Load(const aForm: TCustomForm; const aFileName: AnsiString; const aStr: AnsiString = 'Load'); virtual; abstract; {* Загрузить из файла. } end;//TCustomFormFactory RFactoryFormClass = class of TCustomFormFactory; {$IfEnd} //nsTest AND not NoScripts AND not NotTunedDUnit implementation {$If defined(nsTest) AND not defined(NoScripts) AND not defined(NotTunedDUnit)} // start class TCustomFormFactory class function TCustomFormFactory.GetFormName(const aName: AnsiString): AnsiString; //#UC START# *4E2D254A0364_4E2E96F40343_var* const csClassPref = 'TT'; //#UC END# *4E2D254A0364_4E2E96F40343_var* begin //#UC START# *4E2D254A0364_4E2E96F40343_impl* Result := aName; if Pos(csClassPref, aName) = 0 then Result := 'T' + Result; //#UC END# *4E2D254A0364_4E2E96F40343_impl* end;//TCustomFormFactory.GetFormName {$IfEnd} //nsTest AND not NoScripts AND not NotTunedDUnit end.
{*******************************************************} { } { Delphi FireMonkey Notification Service } { } { Implementation Notification Center for iOS } { } { Copyright(c) 2012-2013 Embarcadero Technologies, Inc. } { } {*******************************************************} // Reference on programm guide in Apple developer center: // https://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction/Introduction.html unit FMX.Notification.iOS; interface procedure RegisterNotificationService; procedure UnregisterNotificationService; implementation uses FMX.Notification, FMX.Platform, System.SysUtils, System.Generics.Collections, Macapi.ObjectiveC, iOSapi.Foundation, iOSapi.CocoaTypes, iOSapi.UIKit; type { TNotificationCenterCocoa } TNotificationCenterCocoa = class (TInterfacedObject, IFMXNotificationCenter) strict private function CreateNativeNotification(const ANotification: TNotification): UILocalNotification; function FindNativeNotification(const AID: string): UILocalNotification; public { IFMXNotificationCenter } procedure ScheduleNotification(const ANotification: TNotification); procedure PresentNotification(const ANotification: TNotification); procedure CancelNotification(const AName: string); overload; procedure CancelNotification(const ANotification: TNotification); overload; procedure CancelAllNotifications; procedure SetIconBadgeNumber(const ACount: Integer); procedure ResetIconBadgeNumber; end; var NotificationCenter: TNotificationCenterCocoa; procedure RegisterNotificationService; begin NotificationCenter := TNotificationCenterCocoa.Create; TPlatformServices.Current.AddPlatformService(IFMXNotificationCenter, NotificationCenter); end; procedure UnregisterNotificationService; begin TPlatformServices.Current.RemovePlatformService(IFMXNotificationCenter); NotificationCenter := nil; end; {$REGION 'Objective C - Delphi Helpers'} function GetTimeZone: Integer; begin Result := TNSTimeZone.Wrap(TNSTimeZone.OCClass.localTimeZone).secondsFromGMT div SecsPerHour; end; function DateTimeToNSDate(const ADateTime: TDateTime): NSDate; var IntervalInterval: NSTimeInterval; begin IntervalInterval := (ADateTime - EncodeDate(2001, 1, 1)) * SecsPerDay; Result := TNSDate.Wrap(TNSDate.OCClass.dateWithTimeIntervalSinceReferenceDate(IntervalInterval)); end; function NSDateToDateTime(const ADateTime: NSDate): TDateTime; begin Result := (ADateTime.TimeIntervalSince1970 + GetTimeZone) / SecsPerDay + EncodeDate(1970, 1, 1); end; function GetGMTDateTime(const ADateTime: TDateTime): TDateTime; begin if GetTimeZone > 0 then Result := ADateTime - EncodeTime(GetTimeZone, 0, 0, 0) else Result := ADateTime + EncodeTime(Abs(GetTimeZone), 0, 0, 0); end; function SharedApplication: UIApplication; begin Result := TUIApplication.Wrap(TUIApplication.OCClass.sharedApplication); end; {$ENDREGION} {$REGION 'TNotificationCenterCocoa'} procedure TNotificationCenterCocoa.CancelAllNotifications; begin SharedApplication.cancelAllLocalNotifications; end; function TNotificationCenterCocoa.FindNativeNotification(const AID: string): UILocalNotification; var Notifications: NSArray; NativeNotification: UILocalNotification; Found: Boolean; I: NSUInteger; UserInfo: NSDictionary; begin Notifications := SharedApplication.scheduledLocalNotifications; Found := False; I := 0; while (I < Notifications.count) and not Found do begin NativeNotification := TUILocalNotification.Wrap(Notifications.objectAtIndex(I)); UserInfo := NativeNotification.userInfo; if (UserInfo <> nil) and (UTF8ToString(TNSString.Wrap(UserInfo.valueForKey(NSSTR('id'))).UTF8String) = AID) then Found := True else Inc(I); end; if Found then Result := TUILocalNotification.Wrap(Notifications.objectAtIndex(I)) else Result := nil; end; procedure TNotificationCenterCocoa.CancelNotification(const AName: string); var NativeNotification: UILocalNotification; begin NativeNotification := FindNativeNotification(AName); if NativeNotification <> nil then SharedApplication.cancelLocalNotification(NativeNotification); end; procedure TNotificationCenterCocoa.CancelNotification(const ANotification: TNotification); var NativeNotification: UILocalNotification; begin if not Assigned(ANotification) then Exit; NativeNotification := FindNativeNotification(ANotification.Name); if NativeNotification <> nil then SharedApplication.cancelLocalNotification(NativeNotification); end; function TNotificationCenterCocoa.CreateNativeNotification(const ANotification: TNotification): UILocalNotification; var NativeNotification: UILocalNotification; UserInfo: NSDictionary; GMTDateTime: TDateTime; begin NativeNotification := TUILocalNotification.Create; if not ANotification.Name.IsEmpty then begin // Set unique identificator UserInfo := TNSDictionary.Wrap(TNSDictionary.OCClass.dictionaryWithObject( (NSSTR(ANotification.Name) as ILocalObject).GetObjectID, (NSSTR('id') as ILocalObject).GetObjectID)); NativeNotification.setUserInfo(UserInfo); end; // Get GMT time and set notification fired date GMTDateTime := GetGMTDateTime(ANotification.FireDate); NativeNotification.setTimeZone(TNSTimeZone.Wrap(TNSTimeZone.OCClass.defaultTimeZone)); NativeNotification.setFireDate(DateTimeToNSDate(GMTDateTime)); NativeNotification.setApplicationIconBadgeNumber(ANotification.ApplicationIconBadgeNumber); NativeNotification.setAlertBody(NSSTR(ANotification.AlertBody)); NativeNotification.setAlertAction(NSSTR(ANotification.AlertAction)); NativeNotification.setHasAction(ANotification.HasAction); if ANotification.EnableSound then NativeNotification.setSoundName(UILocalNotificationDefaultSoundName) else NativeNotification.setSoundName(nil); Result := NativeNotification; end; procedure TNotificationCenterCocoa.PresentNotification(const ANotification: TNotification); var NativeNatification: UILocalNotification; begin NativeNatification := FindNativeNotification(ANotification.Name); if NativeNatification = nil then NativeNatification := CreateNativeNotification(ANotification); SharedApplication.presentLocalNotificationNow(NativeNatification); end; procedure TNotificationCenterCocoa.ScheduleNotification(const ANotification: TNotification); var NativeNatification: UILocalNotification; begin NativeNatification := FindNativeNotification(ANotification.Name); if NativeNatification = nil then NativeNatification := CreateNativeNotification(ANotification); SharedApplication.scheduleLocalNotification(NativeNatification); end; procedure TNotificationCenterCocoa.SetIconBadgeNumber(const ACount: Integer); begin SharedApplication.setApplicationIconBadgeNumber(ACount); end; procedure TNotificationCenterCocoa.ResetIconBadgeNumber; begin SharedApplication.setApplicationIconBadgeNumber(0); end; {$ENDREGION} end.
{ controlsexports.pas Exports the functionality from the Controls LCL unit This file is part of the LCL Exports library. LICENSE: The same modifyed LGPL as the Free Pascal Runtime Library and the Lazarus Component Library Copyright (C) 2008 Felipe Monteiro de Carvalho } unit controlsexports; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls; { TControl } { Events } function TControl_GetOnClick(Self: TControl): TNotifyEvent; cdecl; procedure TControl_SetOnClick(Self: TControl; AValue: TNotifyEvent); cdecl; { Properties } function TControl_GetCaption(Self: TControl): PChar; cdecl; procedure TControl_SetCaption(Self: TControl; AValue: PChar); cdecl; function TControl_GetLeft(Self: TControl): Integer; cdecl; procedure TControl_SetLeft(Self: TControl; AValue: Integer); cdecl; function TControl_GetHeight(Self: TControl): Integer; cdecl; procedure TControl_SetHeight(Self: TControl; AValue: Integer); cdecl; function TControl_GetHint(Self: TControl): PChar; cdecl; procedure TControl_SetHint(Self: TControl; AValue: PChar); cdecl; function TControl_GetTop(Self: TControl): Integer; cdecl; procedure TControl_SetTop(Self: TControl; AValue: Integer); cdecl; function TControl_GetWidth(Self: TControl): Integer; cdecl; procedure TControl_SetWidth(Self: TControl; AValue: Integer); cdecl; { TWinControl } function TWinControl_GetParent(Self: TWinControl): TWinControl; cdecl; procedure TWinControl_SetParent(Self: TWinControl; AValue: TWinControl); cdecl; implementation { TControl } function TControl_GetOnClick(Self: TControl): TNotifyEvent; cdecl; begin Result := Self.OnClick; end; procedure TControl_SetOnClick(Self: TControl; AValue: TNotifyEvent); cdecl; begin Self.OnClick := AValue; end; function TControl_GetCaption(Self: TControl): PChar; cdecl; begin Result := PChar(Self.Caption); end; procedure TControl_SetCaption(Self: TControl; AValue: PChar); cdecl; begin Self.Caption := string(AValue); end; function TControl_GetLeft(Self: TControl): Integer; cdecl; begin Result := Self.Left; end; procedure TControl_SetLeft(Self: TControl; AValue: Integer); cdecl; begin Self.Left := AValue; end; function TControl_GetHeight(Self: TControl): Integer; cdecl; begin Result := Self.Height; end; procedure TControl_SetHeight(Self: TControl; AValue: Integer); cdecl; begin Self.Height := AValue; end; function TControl_GetHint(Self: TControl): PChar; cdecl; begin Result := PChar(Self.Hint); end; procedure TControl_SetHint(Self: TControl; AValue: PChar); cdecl; begin Self.Hint := string(AValue); end; function TControl_GetTop(Self: TControl): Integer; cdecl; begin Result := Self.Top; end; procedure TControl_SetTop(Self: TControl; AValue: Integer); cdecl; begin Self.Top := AValue; end; function TControl_GetWidth(Self: TControl): Integer; cdecl; begin Result := Self.Width; end; procedure TControl_SetWidth(Self: TControl; AValue: Integer); cdecl; begin Self.Width := AValue; end; { TWinControl } function TWinControl_GetParent(Self: TWinControl): TWinControl; cdecl; begin Result := Self.Parent; end; procedure TWinControl_SetParent(Self: TWinControl; AValue: TWinControl); cdecl; begin Self.Parent := AValue; end; end.
unit PI.Config; interface uses // PushIt PI.Types; type TPushItConfig = class(TObject) private class var FCurrent: TPushItConfig; class destructor DestroyClass; class function GetCurrent: TPushItConfig; static; class function GetFileName: string; private FAPIKeyMRU: TAPIKeyMRU; FServiceAccountFileName: string; FToken: string; public class property Current: TPushItConfig read GetCurrent; public procedure Save; procedure UpdateAPIKeyMRU(const AMRU: TArray<string>); property APIKeyMRU: TAPIKeyMRU read FAPIKeyMRU write FAPIKeyMRU; property ServiceAccountFileName: string read FServiceAccountFileName write FServiceAccountFileName; property Token: string read FToken write FToken; end; implementation uses // RTL System.IOUtils, System.SysUtils, // REST REST.Json; { TPushItConfig } class destructor TPushItConfig.DestroyClass; begin FCurrent.Free; end; class function TPushItConfig.GetCurrent: TPushItConfig; begin if FCurrent = nil then begin if TFile.Exists(GetFileName) then FCurrent := TJson.JsonToObject<TPushItConfig>(TFile.ReadAllText(GetFileName)) else FCurrent := TPushItConfig.Create; end; Result := FCurrent; end; class function TPushItConfig.GetFileName: string; begin Result := TPath.Combine(TPath.GetDocumentsPath, 'PushIt\Config.json'); ForceDirectories(TPath.GetDirectoryName(Result)); end; procedure TPushItConfig.Save; begin TFile.WriteAllText(GetFileName, TJson.ObjectToJsonString(Self)); end; procedure TPushItConfig.UpdateAPIKeyMRU(const AMRU: TArray<string>); begin Current.APIKeyMRU := AMRU; Current.Save; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.1 12/7/2002 06:43:48 PM JPMugaas These should now compile except for Socks server. IPVersion has to be a property someplace for that. Rev 1.0 11/13/2002 08:04:00 AM JPMugaas } unit IdTunnelSlave; interface {$i IdCompilerDefines.inc} uses SysUtils, Classes, SyncObjs, IdTunnelCommon, IdTCPServer, IdTCPClient, IdGlobal, IdStack, IdResourceStrings, IdThread, IdComponent, IdTCPConnection; type TSlaveThread = class; TIdTunnelSlave = class; TTunnelEvent = procedure(Thread: TSlaveThread) of object; /////////////////////////////////////////////////////////////////////////////// // Slave Tunnel classes // // Client data structure TClientData = class public Id: Integer; TimeOfConnection: TDateTime; DisconnectedOnRequest: Boolean; SelfDisconnected: Boolean; ClientAuthorised: Boolean; Locker: TCriticalSection; Port: Word; IpAddr: TIdInAddr; constructor Create; destructor Destroy; override; end; // Slave thread - tunnel thread to communicate with Master TSlaveThread = class(TIdThread) private FLock: TCriticalSection; FExecuted: Boolean; FConnection: TIdTCPClient; protected procedure SetExecuted(Value: Boolean); function GetExecuted: Boolean; procedure AfterRun; override; procedure BeforeRun; override; public SlaveParent: TIdTunnelSlave; Receiver: TReceiver; property Executed: Boolean read GetExecuted write SetExecuted; property Connection: TIdTCPClient read fConnection; constructor Create(Slave: TIdTunnelSlave); reintroduce; destructor Destroy; override; procedure Execute; override; procedure Run; override; end; // TTunnelEvent = procedure(Thread: TSlaveThread) of object; TIdTunnelSlave = class(TIdTCPServer) private fiMasterPort: Integer; // Port on which Master Tunnel accepts connections fsMasterHost: String; // Address of the Master Tunnel SClient: TIdTCPClient; // Client which talks to the Master Tunnel // fOnExecute, fOnConnect, fOnDisconnect: TIdServerThreadEvent; fOnStatus: TIdStatusEvent; fOnBeforeTunnelConnect: TSendTrnEventC; fOnTransformRead: TTunnelEventC; fOnInterpretMsg: TSendMsgEventC; fOnTransformSend: TSendTrnEventC; fOnTunnelDisconnect: TTunnelEvent; Sender: TSender; // Communication class OnlyOneThread: TCriticalSection; // Some locking code SendThroughTunnelLock: TCriticalSection; // Some locking code GetClientThreadLock: TCriticalSection; // Some locking code // LockClientNumber: TCriticalSection; StatisticsLocker: TCriticalSection; ManualDisconnected: Boolean; // We trigered the disconnection StopTransmiting: Boolean; fbActive: Boolean; fbSocketize: Boolean; SlaveThread: TSlaveThread; // Thread which receives data from the Master fLogger: TLogger; // Statistics counters flConnectedClients, // Number of connected clients fNumberOfConnectionsValue, fNumberOfPacketsValue, fCompressionRatioValue, fCompressedBytes, fBytesRead, fBytesWrite: Integer; SlaveThreadTerminated: Boolean; procedure SendMsg(var Header: TIdHeader; s: String); procedure ClientOperation(Operation: Integer; UserId: Integer; s: String); procedure DisconectAllUsers; //procedure DoStatus(Sender: TComponent; const sMsg: String); function GetNumClients: Integer; procedure TerminateTunnelThread; function GetClientThread(UserID: Integer): TIdPeerThread; procedure OnTunnelThreadTerminate(Sender: TObject); protected fbAcceptConnections: Boolean; // status if we accept new connections // it is used with tunnels with some athentication // procedure between slave and master tunnel procedure DoConnect(Thread: TIdPeerThread); override; procedure DoDisconnect(Thread: TIdPeerThread); override; function DoExecute(Thread: TIdPeerThread): boolean; override; procedure DoBeforeTunnelConnect(var Header: TIdHeader; var CustomMsg: String); virtual; procedure DoTransformRead(Receiver: TReceiver); virtual; procedure DoInterpretMsg(var CustomMsg: String); virtual; procedure DoTransformSend(var Header: TIdHeader; var CustomMsg: String); virtual; procedure DoStatus(Sender: TComponent; const sMsg: String); virtual; procedure DoTunnelDisconnect(Thread: TSlaveThread); virtual; procedure LogEvent(Msg: String); procedure SetActive(pbValue: Boolean); override; public procedure SetStatistics(Module: Integer; Value: Integer); procedure GetStatistics(Module: Integer; var Value: Integer); constructor Create(AOwner: TComponent); override; destructor Destroy; override; // property Active: Boolean read FbActive write SetActive; property Logger: TLogger read fLogger write fLogger; property NumClients: Integer read GetNumClients; published property MasterHost: string read fsMasterHost write fsMasterHost; property MasterPort: Integer read fiMasterPort write fiMasterPort; property Socks4: Boolean read fbSocketize write fbSocketize default False; // property OnConnect: TIdServerThreadEvent read FOnConnect write FOnConnect; property OnDisconnect: TIdServerThreadEvent read FOnDisconnect write FOnDisconnect; // property OnExecute: TIdServerThreadEvent read FOnExecute write FOnExecute; property OnBeforeTunnelConnect: TSendTrnEventC read fOnBeforeTunnelConnect write fOnBeforeTunnelConnect; property OnTransformRead: TTunnelEventC read fOnTransformRead write fOnTransformRead; property OnInterpretMsg: TSendMsgEventC read fOnInterpretMsg write fOnInterpretMsg; property OnTransformSend: TSendTrnEventC read fOnTransformSend write fOnTransformSend; property OnStatus: TIdStatusEvent read FOnStatus write FOnStatus; property OnTunnelDisconnect: TTunnelEvent read FOnTunnelDisconnect write FOnTunnelDisconnect; end; // // END Slave Tunnel classes /////////////////////////////////////////////////////////////////////////////// implementation uses IdCoreGlobal, IdException, IdSocks, IdThreadSafe; Var GUniqueID: TIdThreadSafeInteger; function GetNextID: Integer; begin if Assigned(GUniqueID) then begin Result := GUniqueID.Increment; end else result := -1; end; /////////////////////////////////////////////////////////////////////////////// // Slave Tunnel classes // constructor TIdTunnelSlave.Create(AOwner: TComponent); begin inherited; fbActive := False; flConnectedClients := 0; fNumberOfConnectionsValue := 0; fNumberOfPacketsValue := 0; fCompressionRatioValue := 0; fCompressedBytes := 0; fBytesRead := 0; fBytesWrite := 0; fbAcceptConnections := True; SlaveThreadTerminated := False; OnlyOneThread := TCriticalSection.Create; SendThroughTunnelLock := TCriticalSection.Create; GetClientThreadLock := TCriticalSection.Create; // LockClientNumber := TCriticalSection.Create; StatisticsLocker := TCriticalSection.Create; Sender := TSender.Create; SClient := TIdTCPClient.Create(nil); // POZOR MOŽNA NAPAKA // SClient.OnStatus := self.DoStatus; ORIGINAL SClient.OnStatus := self.OnStatus; ManualDisconnected := False; StopTransmiting := False; end; destructor TIdTunnelSlave.Destroy; begin fbAcceptConnections := False; StopTransmiting := True; ManualDisconnected := True; Active := False; // DisconectAllUsers; try if SClient.Connected then begin // DisconnectedByServer := False; SClient.Disconnect; end; except ; end; // if Assigned(SlaveThread) then // if not SlaveThread.Executed then // SlaveThread.TerminateAndWaitFor; if not SlaveThreadTerminated then TerminateTunnelThread; FreeAndNil(SClient); FreeAndNil(Sender); // FreeAndNil(LockClientNumber); FreeAndNil(OnlyOneThread); FreeAndNil(SendThroughTunnelLock); FreeAndNil(GetClientThreadLock); FreeAndNil(StatisticsLocker); Logger := nil; inherited Destroy; end; procedure TIdTunnelSlave.LogEvent(Msg: String); begin if Assigned(fLogger) then fLogger.LogEvent(Msg); end; procedure TIdTunnelSlave.DoStatus(Sender: TComponent; const sMsg: String); begin if Assigned(OnStatus) then begin OnStatus(self, hsStatusText, sMsg); end; end; procedure TIdTunnelSlave.SetActive(pbValue: Boolean); var ErrorConnecting: Boolean; begin // Active = False gets called again by inherited destructor if OnlyOneThread = nil then begin exit; end; OnlyOneThread.Enter; try if fbActive = pbValue then begin exit; end; // if not ((csLoading in ComponentState) or (csDesigning in ComponentState)) then begin if pbValue then begin // DisconnectedByServer := False; ManualDisconnected := False; StopTransmiting := False; ErrorConnecting := False; SClient.Host := fsMasterHost; SClient.Port := fiMasterPort; try SClient.Connect; except fbActive := False; raise EIdTunnelConnectToMasterFailed.Create(RSTunnelConnectToMasterFailed); //Exit; end; if not ErrorConnecting then begin SlaveThread := TSlaveThread.Create(self); SlaveThreadTerminated := False; SlaveThread.Start; // Maybe we wait here till authentication of Slave happens // here can happen the error if the port is already occupied // we must handle this try inherited SetActive(True); fbActive := True; fbAcceptConnections := True; except StopTransmiting := False; DisconectAllUsers; SClient.Disconnect; TerminateTunnelThread; fbActive := False; end; end; end else begin fbAcceptConnections := False; StopTransmiting := True; ManualDisconnected := True; // inherited Active := False; // Cancel accepting new clients inherited SetActive(False); DisconectAllUsers; // Disconnect existing ones SClient.Disconnect; TerminateTunnelThread; fbActive := pbValue; end; // end; //fbActive := pbValue; finally OnlyOneThread.Leave; end; end; function TIdTunnelSlave.GetNumClients: Integer; var ClientsNo: Integer; begin GetStatistics(NumberOfClientsType, ClientsNo); Result := ClientsNo; end; procedure TIdTunnelSlave.SetStatistics(Module: Integer; Value: Integer); var packets: Real; ratio: Real; begin StatisticsLocker.Enter; try case Module of NumberOfClientsType: begin if TIdStatisticsOperation(Value) = soIncrease then begin Inc(flConnectedClients); Inc(fNumberOfConnectionsValue); end else begin Dec(flConnectedClients); end; end; NumberOfConnectionsType: begin Inc(fNumberOfConnectionsValue); end; NumberOfPacketsType: begin Inc(fNumberOfPacketsValue); end; CompressionRatioType: begin ratio := fCompressionRatioValue; packets := fNumberOfPacketsValue; ratio := (ratio/100.0 * (packets - 1.0) + Value/100.0) / packets; fCompressionRatioValue := Trunc(ratio * 100); end; CompressedBytesType: begin fCompressedBytes := fCompressedBytes + Value; end; BytesReadType: begin fBytesRead := fBytesRead + Value; end; BytesWriteType: begin fBytesWrite := fBytesWrite + Value; end; end; finally StatisticsLocker.Leave; end; end; procedure TIdTunnelSlave.GetStatistics(Module: Integer; var Value: Integer); begin StatisticsLocker.Enter; try case Module of NumberOfClientsType: begin Value := flConnectedClients; end; NumberOfConnectionsType: begin Value := fNumberOfConnectionsValue; end; NumberOfPacketsType: begin Value := fNumberOfPacketsValue; end; CompressionRatioType: begin if fCompressedBytes > 0 then begin Value := Trunc((fBytesRead * 1.0) / (fCompressedBytes * 1.0) * 100.0) end else begin Value := 0; end; end; CompressedBytesType: begin Value := fCompressedBytes; end; BytesReadType: begin Value := fBytesRead; end; BytesWriteType: begin Value := fBytesWrite; end; end; finally StatisticsLocker.Leave; end; end; //////////////////////////////////////////////////////////////// // // CLIENT SERVICES // //////////////////////////////////////////////////////////////// procedure TIdTunnelSlave.DoConnect(Thread: TIdPeerThread); const MAXLINE=255; var SID: Integer; s: String; req: TIdSocksRequest; res: TIdSocksResponse; numread: Integer; Header: TIdHeader; begin if not fbAcceptConnections then begin Thread.Connection.Disconnect; // don't allow to enter in OnExecute {Do not Localize} raise EIdTunnelDontAllowConnections.Create (RSTunnelDontAllowConnections); end; SetStatistics(NumberOfClientsType, Integer(soIncrease)); Thread.Data := TClientData.Create; // Socket version begin if fbSocketize then begin try Thread.Connection.IOHandler.ReadBuffer(req, 8); except try Thread.Connection.Disconnect; except ; end; Thread.Terminate; Exit; end; numread := 0; repeat begin s := Thread.Connection.ReadString(1); req.UserName[numread+1] := s[1]; Inc(numread); end until ((numread >= MAXLINE) or (s[1]=#0)); SetLength(req.UserName, numread); s := GStack.TInAddrToString(req.IpAddr); res.Version := 0; res.OpCode := 90; res.Port := req.Port; res.IpAddr := req.IpAddr; SetString(s, PChar(@res), SizeOf(res)); Thread.Connection.Write(s); end; with TClientData(Thread.Data) do begin // Id := Thread.Handle; SID := Id; TimeOfConnection := Now; DisconnectedOnRequest := False; if fbSocketize then begin Port := GStack.WSNToHs(req.Port); IpAddr := req.IpAddr; end else begin Port := self.DefaultPort; IpAddr.S_addr := 0; end; Header.Port := Port; Header.IpAddr := IpAddr; end; Header.MsgType := tmConnect; Header.UserId := SID; SendMsg(Header, RSTunnelConnectMsg); end; procedure TIdTunnelSlave.DoDisconnect(Thread: TIdPeerThread); var Header: TIdHeader; begin try with TClientData(Thread.Data) do begin if DisconnectedOnRequest = False then begin Header.MsgType := tmDisconnect; Header.UserId := Id; SendMsg(Header, RSTunnelDisconnectMsg); end; end; SetStatistics(NumberOfClientsType, Integer(soDecrease)); except ; end; end; // Thread to communicate with the user // reads the requests and transmits them through the tunnel function TIdTunnelSlave.DoExecute(Thread: TIdPeerThread): boolean; var user: TClientData; s: String; Header: TIdHeader; begin result := true; if Thread.Connection.IOHandler.Readable(IdTimeoutInfinite) then begin s := Thread.Connection.CurrentReadBuffer; try user := TClientData(Thread.Data); Header.MsgType := tmData; Header.UserId := user.Id; SendMsg(Header, s); except Thread.Connection.Disconnect; raise; end; end; end; procedure TIdTunnelSlave.SendMsg(var Header: TIdHeader; s: String); var tmpString: String; begin SendThroughTunnelLock.Enter; try try if not StopTransmiting then begin if Length(s) > 0 then begin try // Custom data transformation before send tmpString := s; try DoTransformSend(Header, tmpString); except on E: Exception do begin raise; end; end; if Header.MsgType = 0 then begin // error ocured in transformation raise EIdTunnelTransformErrorBeforeSend.Create(RSTunnelTransformErrorBS); end; try Sender.PrepareMsg(Header, PChar(@tmpString[1]), Length(tmpString)); except raise; end; try SClient.Write(Sender.Msg); except StopTransmiting := True; raise; end; except ; raise; end; end end; except SClient.Disconnect; end; finally SendThroughTunnelLock.Leave; end; end; procedure TIdTunnelSlave.DoBeforeTunnelConnect(var Header: TIdHeader; var CustomMsg: String); begin if Assigned(fOnBeforeTunnelConnect) then fOnBeforeTunnelConnect(Header, CustomMsg); end; procedure TIdTunnelSlave.DoTransformRead(Receiver: TReceiver); begin if Assigned(fOnTransformRead) then fOnTransformRead(Receiver); end; procedure TIdTunnelSlave.DoInterpretMsg(var CustomMsg: String); begin if Assigned(fOnInterpretMsg) then fOnInterpretMsg(CustomMsg); end; procedure TIdTunnelSlave.DoTransformSend(var Header: TIdHeader; var CustomMsg: String); begin if Assigned(fOnTransformSend) then fOnTransformSend(Header, CustomMsg); end; procedure TIdTunnelSlave.DoTunnelDisconnect(Thread: TSlaveThread); begin try StopTransmiting := True; if not ManualDisconnected then begin if Active then begin Active := False; end; end; except ; end; If Assigned(OnTunnelDisconnect) then OnTunnelDisconnect(Thread); end; procedure TIdTunnelSlave.OnTunnelThreadTerminate(Sender:TObject); begin // Just set the flag SlaveThreadTerminated := True; end; function TIdTunnelSlave.GetClientThread(UserID: Integer): TIdPeerThread; var user: TClientData; Thread: TIdPeerThread; i: integer; begin // GetClientThreadLock.Enter; Result := nil; with ThreadMgr.ActiveThreads.LockList do try try for i := 0 to Count-1 do begin try if Assigned(Items[i]) then begin Thread := TIdPeerThread(Items[i]); if Assigned(Thread.Data) then begin user := TClientData(Thread.Data); if user.Id = UserID then begin Result := Thread; break; end; end; end; except Result := nil; end; end; except Result := nil; end; finally ThreadMgr.ActiveThreads.UnlockList; // GetClientThreadLock.Leave; end; end; procedure TIdTunnelSlave.TerminateTunnelThread; begin OnlyOneThread.Enter; try if Assigned(SlaveThread) then begin if not IsCurrentThread(SlaveThread) then begin SlaveThread.TerminateAndWaitFor; SlaveThread.Free; SlaveThread := nil; end else begin SlaveThread.FreeOnTerminate := True; end; end; finally OnlyOneThread.Leave; end; end; procedure TIdTunnelSlave.ClientOperation(Operation: Integer; UserId: Integer; s: String); var Thread: TIdPeerThread; user: TClientData; begin if StopTransmiting then begin Exit; end; Thread := GetClientThread(UserID); if Assigned(Thread) then begin try case Operation of 1: begin try if Thread.Connection.Connected then begin try Thread.Connection.Write(s); except end; end; except try Thread.Connection.Disconnect; except end; end; end; 2: begin user := TClientData(Thread.Data); user.DisconnectedOnRequest := True; Thread.Connection.Disconnect; end; end; except end; end; end; procedure TIdTunnelSlave.DisconectAllUsers; begin TerminateAllThreads; end; // // END Slave Tunnel classes /////////////////////////////////////////////////////////////////////////////// constructor TClientData.Create; begin inherited Create; id := GetNextID; Locker := TCriticalSection.Create; SelfDisconnected := False; end; destructor TClientData.Destroy; begin Locker.Free; inherited Destroy; end; constructor TSlaveThread.Create(Slave: TIdTunnelSlave); begin SlaveParent := Slave; // FreeOnTerminate := True; FreeOnTerminate := False; FExecuted := False; FConnection := Slave.SClient; OnTerminate := Slave.OnTunnelThreadTerminate; // InitializeCriticalSection(FLock); FLock := TCriticalSection.Create; Receiver := TReceiver.Create; inherited Create(True); StopMode := smTerminate; end; destructor TSlaveThread.Destroy; begin // Executed := True; Connection.Disconnect; Receiver.Free; // DeleteCriticalSection(FLock); FLock.Destroy; inherited Destroy; end; procedure TSlaveThread.SetExecuted(Value: Boolean); begin // Lock; FLock.Enter; try FExecuted := Value; finally // Unlock; FLock.Leave; end; end; function TSlaveThread.GetExecuted: Boolean; begin // Lock; FLock.Enter; try Result := FExecuted; finally // Unlock; FLock.Leave; end; end; procedure TSlaveThread.Execute; begin inherited; Executed := True; end; procedure TSlaveThread.Run; var Header: TIdHeader; s: String; CustomMsg: String; begin try if Connection.IOHandler.Readable(IdTimeoutInfinite) then begin // if Connection.Binding.Readable(IdTimeoutDefault) then begin Receiver.Data := Connection.CurrentReadBuffer; // increase the packets counter SlaveParent.SetStatistics(NumberOfPacketsType, 0); while (Receiver.TypeDetected) and (not Terminated) do begin if Receiver.NewMessage then begin if Receiver.CRCFailed then begin raise EIdTunnelCRCFailed.Create(RSTunnelCRCFailed); end; try // Custom data transformation SlaveParent.DoTransformRead(Receiver); except raise EIdTunnelTransformError.Create(RSTunnelTransformError); end; // Action case Receiver.Header.MsgType of 0: // transformation of data failed, disconnect the tunnel begin SlaveParent.ManualDisconnected := False; raise EIdTunnelMessageTypeRecognitionError.Create(RSTunnelMessageTypeError); end; // Failure END 1: // Data begin try SetString(s, Receiver.Msg, Receiver.MsgLen); SlaveParent.ClientOperation(1, Receiver.Header.UserId, s); except raise EIdTunnelMessageHandlingFailed.Create(RSTunnelMessageHandlingError); end; end; // Data END 2: // Disconnect begin try SlaveParent.ClientOperation(2, Receiver.Header.UserId, ''); {Do not Localize} except raise EIdTunnelMessageHandlingFailed.Create(RSTunnelMessageHandlingError); end; end; 99: // Session begin // Custom data interpretation CustomMsg := ''; {Do not Localize} SetString(CustomMsg, Receiver.Msg, Receiver.MsgLen); try try SlaveParent.DoInterpretMsg(CustomMsg); except raise EIdTunnelInterpretationOfMessageFailed.Create(RSTunnelMessageInterpretError); end; if Length(CustomMsg) > 0 then begin Header.MsgType := 99; Header.UserId := 0; SlaveParent.SendMsg(Header, CustomMsg); end; except SlaveParent.ManualDisconnected := False; raise EIdTunnelCustomMessageInterpretationFailure.Create(RSTunnelMessageCustomInterpretError); end; end; end; // case // Shift of data Receiver.ShiftData; end else break; // break the loop end; // end while end; // if readable except on E: EIdSocketError do begin case E.LastError of 10054: Connection.Disconnect; else begin Terminate; end; end; end; on EIdClosedSocket do ; else raise; end; if not Connection.Connected then Terminate; end; procedure TSlaveThread.AfterRun; begin SlaveParent.DoTunnelDisconnect(self); end; procedure TSlaveThread.BeforeRun; var Header: TIdHeader; tmpString: String; begin tmpString := ''; {Do not Localize} try SlaveParent.DoBeforeTunnelConnect(Header, tmpString); except ; end; if Length(tmpString) > 0 then begin Header.MsgType := 99; Header.UserId := 0; SlaveParent.SendMsg(Header, tmpString); end; end; initialization GUniqueID := TIdThreadSafeInteger.Create; finalization FreeAndNil(GUniqueID); end.
unit l3ListenersManager; // Модуль: "w:\common\components\rtl\Garant\L3\l3ListenersManager.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tl3ListenersManager" MUID: (4F636139008F) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses , l3ProtoObject , l3WndProcListenersList , l3CBTListenersList , l3GetMessageListenersList , Windows , l3WndProcRetListenersList , l3MouseListenersList , l3MouseWheelListenersList , l3Interfaces ; type Tl3ListenersManager = class(Tl3ProtoObject) private f_WndProcListeners: Tl3WndProcListenersList; f_CBTListeners: Tl3CBTListenersList; f_GetMessageListeners: Tl3GetMessageListenersList; f_WndProcHook: HHOOK; f_CBTHook: HHOOK; f_GetMessageHook: HHOOK; f_WndProcRetListeners: Tl3WndProcRetListenersList; f_WndProcRetHook: HHOOK; f_MouseHook: HHOOK; f_MouseListeners: Tl3MouseListenersList; f_MouseWheelListeners: Tl3MouseWheelListenersList; protected procedure UpdateHooks; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; public class procedure AddCBTListener(const aListener: Il3CBTListener); class procedure AddWndProcListener(const aListener: Il3WndProcListener); class procedure AddGetMessageListener(const aListener: Il3GetMessageListener); class procedure RemoveCBTListener(const aListener: Il3CBTListener); class procedure RemoveWndProcListener(const aListener: Il3WndProcListener); class procedure RemoveGetMessageListener(const aListener: Il3GetMessageListener); class procedure AddWndProcRetListener(const aListener: Il3WndProcRetListener); class procedure RemoveWndProcRetListener(const aListener: Il3WndProcRetListener); class procedure AddMouseListener(const aListener: Il3MouseListener); class procedure RemoveMouseListener(const aListener: Il3MouseListener); class procedure AddMouseWheelListener(const aListener: Il3MouseWheelListener); class procedure RemoveMouseWheelListener(const aListener: Il3MouseWheelListener); class procedure Add(const aListener: Il3Listener); class procedure Remove(const aListener: Il3Listener); class function Instance: Tl3ListenersManager; {* Метод получения экземпляра синглетона Tl3ListenersManager } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } public property WndProcListeners: Tl3WndProcListenersList read f_WndProcListeners; property CBTListeners: Tl3CBTListenersList read f_CBTListeners; property GetMessageListeners: Tl3GetMessageListenersList read f_GetMessageListeners; property WndProcHook: HHOOK read f_WndProcHook; property CBTHook: HHOOK read f_CBTHook; property GetMessageHook: HHOOK read f_GetMessageHook; property WndProcRetListeners: Tl3WndProcRetListenersList read f_WndProcRetListeners; property WndProcRetHook: HHOOK read f_WndProcRetHook; property MouseHook: HHOOK read f_MouseHook; property MouseListeners: Tl3MouseListenersList read f_MouseListeners; property MouseWheelListeners: Tl3MouseWheelListenersList read f_MouseWheelListeners; end;//Tl3ListenersManager implementation uses l3ImplUses , SysUtils , l3ListenersHooks , l3Base //#UC START# *4F636139008Fimpl_uses* //#UC END# *4F636139008Fimpl_uses* ; var g_Tl3ListenersManager: Tl3ListenersManager = nil; {* Экземпляр синглетона Tl3ListenersManager } procedure Tl3ListenersManagerFree; {* Метод освобождения экземпляра синглетона Tl3ListenersManager } begin l3Free(g_Tl3ListenersManager); end;//Tl3ListenersManagerFree class procedure Tl3ListenersManager.AddCBTListener(const aListener: Il3CBTListener); //#UC START# *4F636B3003E5_4F636139008F_var* //#UC END# *4F636B3003E5_4F636139008F_var* begin //#UC START# *4F636B3003E5_4F636139008F_impl* with Instance do if CBTListeners.IndexOf(aListener) < 0 then begin CBTListeners.Add(aListener); UpdateHooks; end; //#UC END# *4F636B3003E5_4F636139008F_impl* end;//Tl3ListenersManager.AddCBTListener class procedure Tl3ListenersManager.AddWndProcListener(const aListener: Il3WndProcListener); //#UC START# *4F6370E0022B_4F636139008F_var* //#UC END# *4F6370E0022B_4F636139008F_var* begin //#UC START# *4F6370E0022B_4F636139008F_impl* with Instance do if WndProcListeners.IndexOf(aListener) < 0 then begin WndProcListeners.Add(aListener); UpdateHooks; end; //#UC END# *4F6370E0022B_4F636139008F_impl* end;//Tl3ListenersManager.AddWndProcListener class procedure Tl3ListenersManager.AddGetMessageListener(const aListener: Il3GetMessageListener); //#UC START# *4F63711700CB_4F636139008F_var* //#UC END# *4F63711700CB_4F636139008F_var* begin //#UC START# *4F63711700CB_4F636139008F_impl* with Instance do if GetMessageListeners.IndexOf(aListener) < 0 then begin GetMessageListeners.Add(aListener); UpdateHooks; end; //#UC END# *4F63711700CB_4F636139008F_impl* end;//Tl3ListenersManager.AddGetMessageListener class procedure Tl3ListenersManager.RemoveCBTListener(const aListener: Il3CBTListener); //#UC START# *4F6372FC0118_4F636139008F_var* //#UC END# *4F6372FC0118_4F636139008F_var* begin //#UC START# *4F6372FC0118_4F636139008F_impl* if Exists then with Instance do begin CBTListeners.Remove(aListener); UpdateHooks; end; //#UC END# *4F6372FC0118_4F636139008F_impl* end;//Tl3ListenersManager.RemoveCBTListener class procedure Tl3ListenersManager.RemoveWndProcListener(const aListener: Il3WndProcListener); //#UC START# *4F63733101FE_4F636139008F_var* //#UC END# *4F63733101FE_4F636139008F_var* begin //#UC START# *4F63733101FE_4F636139008F_impl* if Exists then with Instance do begin WndProcListeners.Remove(aListener); UpdateHooks; end; //#UC END# *4F63733101FE_4F636139008F_impl* end;//Tl3ListenersManager.RemoveWndProcListener class procedure Tl3ListenersManager.RemoveGetMessageListener(const aListener: Il3GetMessageListener); //#UC START# *4F6373800326_4F636139008F_var* //#UC END# *4F6373800326_4F636139008F_var* begin //#UC START# *4F6373800326_4F636139008F_impl* if Exists then with Instance do begin GetMessageListeners.Remove(aListener); UpdateHooks; end; //#UC END# *4F6373800326_4F636139008F_impl* end;//Tl3ListenersManager.RemoveGetMessageListener procedure Tl3ListenersManager.UpdateHooks; //#UC START# *4F670A190240_4F636139008F_var* procedure DoCBT; begin if (f_CBTListeners.Count > 0) and (f_CBThook = 0) then f_CBTHook := SetWindowsHookEx(WH_CBT, @CBTHookFunc, 0, GetCurrentThreadId) else if (f_CBTListeners.Count = 0) and (f_CBThook <> 0) then begin UnhookWindowsHookEx(f_CBTHook); f_CBTHook := 0; end; end; //DoCBT; procedure DoGetMessage; begin if ((f_GetMessageListeners.Count > 0) or (f_MouseWheelListeners.Count > 0)) and (f_GetMessageHook = 0) then f_GetMessageHook := SetWindowsHookEx(WH_GETMESSAGE, @GetMessageHookFunc, 0, GetCurrentThreadId) else if (f_GetMessageListeners.Count = 0) and (f_MouseWheelListeners.Count = 0) and (f_GetMessageHook <> 0) then begin UnhookWindowsHookEx(f_GetMessageHook); f_GetMessageHook := 0; end; end; //DoGetMessage; procedure DoWndProc; begin if ((f_WndProcListeners.Count > 0) {or (f_MouseWheelListeners.Count > 0)}) and (f_WndProcHook = 0) then f_WndProcHook := SetWindowsHookEx(WH_CALLWNDPROC, @CallWndProcHookFunc, 0, GetCurrentThreadID) else if (f_WndProcListeners.Count = 0) and {(f_MouseWheelListeners.Count = 0) and} (f_WndProcHook <> 0) then begin UnhookWindowsHookEx(f_WndProcHook); f_WndProcHook := 0; end; end; //DoWndProc; procedure DoWndProcRet; begin if (f_WndProcRetListeners.Count > 0) and (f_WndProcRetHook = 0) then f_WndProcRetHook := SetWindowsHookEx(WH_CALLWNDPROCRET, @CallWndProcRetHookFunc, 0, GetCurrentThreadID) else if (f_WndProcRetListeners.Count = 0) and (f_WndProcRetHook <> 0) then begin UnhookWindowsHookEx(f_WndProcRetHook); f_WndProcRetHook := 0; end; end; //DoWndProcRet; procedure DoMouse; begin if (f_MouseListeners.Count > 0) and (f_MouseHook = 0) then f_MouseHook := SetWindowsHookEx(WH_MOUSE, @MouseHookFunc, 0, GetCurrentThreadID) else if (f_MouseListeners.Count = 0) and (f_MouseHook <> 0) then begin UnhookWindowsHookEx(f_MouseHook); f_MouseHook := 0; end; end; //DoMouse; //#UC END# *4F670A190240_4F636139008F_var* begin //#UC START# *4F670A190240_4F636139008F_impl* DoCBT; DoGetMessage; DoWndProc; DoWndProcRet; DoMouse; //#UC END# *4F670A190240_4F636139008F_impl* end;//Tl3ListenersManager.UpdateHooks class procedure Tl3ListenersManager.AddWndProcRetListener(const aListener: Il3WndProcRetListener); //#UC START# *4F7322B90325_4F636139008F_var* //#UC END# *4F7322B90325_4F636139008F_var* begin //#UC START# *4F7322B90325_4F636139008F_impl* with Instance do if WndProcRetListeners.IndexOf(aListener) < 0 then begin WndProcRetListeners.Add(aListener); UpdateHooks; end; //#UC END# *4F7322B90325_4F636139008F_impl* end;//Tl3ListenersManager.AddWndProcRetListener class procedure Tl3ListenersManager.RemoveWndProcRetListener(const aListener: Il3WndProcRetListener); //#UC START# *4F7322EA002B_4F636139008F_var* //#UC END# *4F7322EA002B_4F636139008F_var* begin //#UC START# *4F7322EA002B_4F636139008F_impl* if Exists then with Instance do begin WndProcRetListeners.Remove(aListener); UpdateHooks; end; //#UC END# *4F7322EA002B_4F636139008F_impl* end;//Tl3ListenersManager.RemoveWndProcRetListener class procedure Tl3ListenersManager.AddMouseListener(const aListener: Il3MouseListener); //#UC START# *4F74226B03A5_4F636139008F_var* //#UC END# *4F74226B03A5_4F636139008F_var* begin //#UC START# *4F74226B03A5_4F636139008F_impl* with Instance do if MouseListeners.IndexOf(aListener) < 0 then begin MouseListeners.Add(aListener); UpdateHooks; end; //#UC END# *4F74226B03A5_4F636139008F_impl* end;//Tl3ListenersManager.AddMouseListener class procedure Tl3ListenersManager.RemoveMouseListener(const aListener: Il3MouseListener); //#UC START# *4F74229F007B_4F636139008F_var* //#UC END# *4F74229F007B_4F636139008F_var* begin //#UC START# *4F74229F007B_4F636139008F_impl* if Exists then with Instance do begin MouseListeners.Remove(aListener); UpdateHooks; end; //#UC END# *4F74229F007B_4F636139008F_impl* end;//Tl3ListenersManager.RemoveMouseListener class procedure Tl3ListenersManager.AddMouseWheelListener(const aListener: Il3MouseWheelListener); //#UC START# *4F79BC3000BD_4F636139008F_var* //#UC END# *4F79BC3000BD_4F636139008F_var* begin //#UC START# *4F79BC3000BD_4F636139008F_impl* with Instance do if MouseWheelListeners.IndexOf(aListener) < 0 then begin MouseWheelListeners.Add(aListener); UpdateHooks; end; //#UC END# *4F79BC3000BD_4F636139008F_impl* end;//Tl3ListenersManager.AddMouseWheelListener class procedure Tl3ListenersManager.RemoveMouseWheelListener(const aListener: Il3MouseWheelListener); //#UC START# *4F79BC860012_4F636139008F_var* //#UC END# *4F79BC860012_4F636139008F_var* begin //#UC START# *4F79BC860012_4F636139008F_impl* if Exists then with Instance do begin MouseWheelListeners.Remove(aListener); UpdateHooks; end; //#UC END# *4F79BC860012_4F636139008F_impl* end;//Tl3ListenersManager.RemoveMouseWheelListener class procedure Tl3ListenersManager.Add(const aListener: Il3Listener); //#UC START# *4F79BCB203AE_4F636139008F_var* var l_CBTListener: Il3CBTListener; l_WndProcListener: Il3WndProcListener; l_GetMessageListener: Il3GetMessageListener; l_WndProcRetListener: Il3WndProcRetListener; l_MouseListener: Il3MouseListener; l_MouseWheelListener: Il3MouseWheelListener; //#UC END# *4F79BCB203AE_4F636139008F_var* begin //#UC START# *4F79BCB203AE_4F636139008F_impl* if Supports(aListener, Il3CBTListener, l_CBTListener) then AddCBTListener(l_CBTListener); if Supports(aListener, Il3WndProcListener, l_WndProcListener) then AddWndProcListener(l_WndProcListener); if Supports(aListener, Il3GetMessageListener, l_GetMessageListener) then AddGetMessageListener(l_GetMessageListener); if Supports(aListener, Il3WndProcRetListener, l_WndProcRetListener) then AddWndProcRetListener(l_WndProcRetListener); if Supports(aListener, Il3MouseListener, l_MouseListener) then AddMouseListener(l_MouseListener); if Supports(aListener, Il3MouseWheelListener, l_MouseWheelListener) then AddMouseWheelListener(l_MouseWheelListener); //#UC END# *4F79BCB203AE_4F636139008F_impl* end;//Tl3ListenersManager.Add class procedure Tl3ListenersManager.Remove(const aListener: Il3Listener); //#UC START# *4F79BD74036A_4F636139008F_var* var l_CBTListener: Il3CBTListener; l_WndProcListener: Il3WndProcListener; l_GetMessageListener: Il3GetMessageListener; l_WndProcRetListener: Il3WndProcRetListener; l_MouseListener: Il3MouseListener; l_MouseWheelListener: Il3MouseWheelListener; //#UC END# *4F79BD74036A_4F636139008F_var* begin //#UC START# *4F79BD74036A_4F636139008F_impl* if Supports(aListener, Il3CBTListener, l_CBTListener) then RemoveCBTListener(l_CBTListener); if Supports(aListener, Il3WndProcListener, l_WndProcListener) then RemoveWndProcListener(l_WndProcListener); if Supports(aListener, Il3GetMessageListener, l_GetMessageListener) then RemoveGetMessageListener(l_GetMessageListener); if Supports(aListener, Il3WndProcRetListener, l_WndProcRetListener) then RemoveWndProcRetListener(l_WndProcRetListener); if Supports(aListener, Il3MouseListener, l_MouseListener) then RemoveMouseListener(l_MouseListener); if Supports(aListener, Il3MouseWheelListener, l_MouseWheelListener) then RemoveMouseWheelListener(l_MouseWheelListener); //#UC END# *4F79BD74036A_4F636139008F_impl* end;//Tl3ListenersManager.Remove class function Tl3ListenersManager.Instance: Tl3ListenersManager; {* Метод получения экземпляра синглетона Tl3ListenersManager } begin if (g_Tl3ListenersManager = nil) then begin l3System.AddExitProc(Tl3ListenersManagerFree); g_Tl3ListenersManager := Create; end; Result := g_Tl3ListenersManager; end;//Tl3ListenersManager.Instance class function Tl3ListenersManager.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_Tl3ListenersManager <> nil; end;//Tl3ListenersManager.Exists procedure Tl3ListenersManager.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4F636139008F_var* procedure AssertUnhook(aHooks: array of HHOOK); var I: Integer; begin for I := Low(aHooks) to High(aHooks) do if (aHooks[I] <> 0) then begin UnhookWindowsHookEx(aHooks[I]); Assert(False); end; end; //#UC END# *479731C50290_4F636139008F_var* begin //#UC START# *479731C50290_4F636139008F_impl* f_WndProcListeners.Clear; f_WndProcRetListeners.Clear; f_CBTListeners.Clear; f_GetMessageListeners.Clear; f_MouseListeners.Clear; f_MouseWheelListeners.Clear; UpdateHooks; FreeAndNil(f_WndProcListeners); FreeAndNil(f_WndProcRetListeners); FreeAndNil(f_CBTListeners); FreeAndNil(f_GetMessageListeners); FreeAndNil(f_MouseListeners); FreeAndNil(f_MouseWheelListeners); AssertUnhook([f_WndProcHook, f_WndProcRetHook, f_CBTHook, f_GetMessageHook, f_MouseHook]); inherited; //#UC END# *479731C50290_4F636139008F_impl* end;//Tl3ListenersManager.Cleanup procedure Tl3ListenersManager.InitFields; //#UC START# *47A042E100E2_4F636139008F_var* //#UC END# *47A042E100E2_4F636139008F_var* begin //#UC START# *47A042E100E2_4F636139008F_impl* inherited; f_WndProcListeners := Tl3WndProcListenersList.Create; f_MouseWheelListeners := Tl3MouseWheelListenersList.Create; f_MouseListeners := Tl3MouseListenersList.Create; f_WndProcRetListeners := Tl3WndProcRetListenersList.Create; f_GetMessageListeners := Tl3GetMessageListenersList.Create; f_CBTListeners := Tl3CBTListenersList.Create; //#UC END# *47A042E100E2_4F636139008F_impl* end;//Tl3ListenersManager.InitFields end.