text
stringlengths
14
6.51M
(* Copyright (c) 2011, Stefan Glienke All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of this library nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) unit DSharp.PresentationModel.VCLWindowManager; interface uses Classes, Controls, Dialogs, DSharp.ComponentModel.Composition, DSharp.PresentationModel.WindowManager, Forms, Messages; type [PartCreationPolicy(cpShared)] TWindowManager = class(TInterfacedObject, IWindowManager) private FRunning: Boolean; function WindowHook(var Message: TMessage): Boolean; protected function CreateWindow(Model: TObject; IsDialog: Boolean): TForm; function EnsureWindow(Model: TObject; View: TControl): TForm; public constructor Create; destructor Destroy; override; function InputBox(const ACaption, APrompt, ADefault: string; AShowPasswordChar: Boolean = False): string; function MessageDlg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: LongInt = 0): Integer; function ShowDialog(Model: IInterface): Integer; overload; function ShowDialog(Model: TObject): Integer; overload; procedure ShowWindow(Model: IInterface); overload; procedure ShowWindow(Model: TObject); overload; end; implementation uses DSharp.Bindings, DSharp.PresentationModel.ChildForm, DSharp.PresentationModel.Screen, DSharp.PresentationModel.VCLConventionManager, DSharp.PresentationModel.ViewLocator, DSharp.PresentationModel.ViewModelBinder, DSharp.PresentationModel.WindowConductor, SysUtils, Windows; { TWindowManager } constructor TWindowManager.Create; begin // Following line should be here - // but if this line is missing in project file the runtime themes cannot be set // Application.Initialize; Application.MainFormOnTaskbar := True; Application.HookMainWindow(WindowHook); end; function TWindowManager.CreateWindow(Model: TObject; IsDialog: Boolean): TForm; var LView: TControl; LViewClass: TClass; LWindow: TForm; begin LViewClass := ViewLocator.FindViewType(Model.ClassType); if not FRunning and LViewClass.InheritsFrom(TForm) then begin Application.CreateForm(TComponentClass(LViewClass), LWindow); LView := LWindow; end else begin LView := ViewLocator.GetOrCreateViewType(Model.ClassType) as TControl; LWindow := EnsureWindow(Model, LView); end; TWindowConductor.Create(Model, LWindow); ViewModelBinder.Bind(Model, LView); if Supports(Model, IHaveDisplayName) then begin FindBindingGroup(LView).AddBinding( Model, 'DisplayName', LWindow, 'Caption', bmOneWay); end; Result := LWindow; end; destructor TWindowManager.Destroy; begin Application.UnhookMainWindow(WindowHook); end; function TWindowManager.EnsureWindow(Model: TObject; View: TControl): TForm; var LForm: TChildForm; begin if View is TForm then begin Result := View as TForm; end else begin if not FRunning then begin Application.CreateForm(TChildForm, LForm); LForm.BorderIcons := [biSystemMenu..biMaximize]; end else begin LForm := TChildForm.Create(nil); LForm.BorderIcons := [biSystemMenu]; LForm.Position := poOwnerFormCenter; end; LForm.Content := View; Result := LForm; end; end; function TWindowManager.InputBox(const ACaption, APrompt, ADefault: string; AShowPasswordChar: Boolean): string; begin if AShowPasswordChar then PostMessage(Application.Handle, WM_USER + EM_SETPASSWORDCHAR, 0, 0); Result := Dialogs.InputBox(ACaption, APrompt, ADefault); end; function TWindowManager.MessageDlg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Integer): Integer; begin {$IF COMPILERVERSION < 23} Result := Dialogs.MessageDlg(Msg, Dialogs.TMsgDlgType(DlgType), Dialogs.TMsgDlgButtons(Buttons), HelpCtx); {$ELSE} Result := Dialogs.MessageDlg(Msg, DlgType, Buttons, HelpCtx); {$IFEND} end; function TWindowManager.ShowDialog(Model: IInterface): Integer; begin Result := ShowDialog(Model as TObject); end; function TWindowManager.ShowDialog(Model: TObject): Integer; var LWindow: TForm; begin LWindow := CreateWindow(Model, True); try Result := LWindow.ShowModal(); finally LWindow.Free(); end; end; procedure TWindowManager.ShowWindow(Model: IInterface); begin ShowWindow(Model as TObject); end; procedure TWindowManager.ShowWindow(Model: TObject); var LWindow: TForm; begin LWindow := CreateWindow(Model, False); if not FRunning then begin LWindow.Caption := Application.Title; LWindow.Position := poScreenCenter; FRunning := True; Application.Run(); end else begin LWindow.BorderIcons := [biSystemMenu]; LWindow.Position := poOwnerFormCenter; LWindow.Show(); end; end; function TWindowManager.WindowHook(var Message: TMessage): Boolean; var LInputForm, LEdit: HWND; begin case Message.Msg of WM_USER + EM_SETPASSWORDCHAR: begin LInputForm := Screen.Forms[0].Handle; if LInputForm <> 0 then begin LEdit := FindWindowEx(LInputForm, 0, 'TEdit', nil); SendMessage(LEdit, EM_SETPASSWORDCHAR, Ord('*'), 0); end; Result := True; end else Result := False; end; end; initialization TWindowManager.ClassName; end.
unit Alcinoe.iOSApi.MessageUI; interface uses iOSapi.Foundation, iOSapi.CocoaTypes, iOSapi.UIKit, Macapi.ObjectiveC; {$M+} type //typedef enum MessageComposeResult MessageComposeResult; // available in iPhone 4.0 MFMessageComposeResult = NSInteger; const {*************************************************************************} //@abstract Composition result sent to the delegate upon user completion. //@discussion This result will inform the client of the user's message composition action. If the // user cancels the composition, <tt>MessageComposeResultCancelled</tt> will be sent to the delegate. // Typically <tt>MessageComposeResultSent</tt> will be sent, but <tt>MessageComposeResultFailed</tt> will // be sent in the case of failure. </p>Send may only be interpreted as a successful queueing of // the message for later sending. The actual send will occur when the device is able to send. //@constant MessageComposeResultCancelled User canceled the composition. //@constant MessageComposeResultSent User successfully sent/queued the message. //@constant MessageComposeResultFailed User's attempt to save or send was unsuccessful. //@enum MessageComposeResult MessageComposeResultCancelled = 0; MessageComposeResultSent = 1; MessageComposeResultFailed = 2; type {*************************************************} MFMessageComposeViewControllerDelegate = interface; {*****************************************************************} //@interface MFMessageComposeViewController : UINavigationController //@class MFMessageComposeViewController //@abstract The MFMessageComposeViewController class provides an interface for editing and sending a message. //@discussion The MFMessageComposeViewController class manages all user interaction. The client needs to set // the recipient or recipients. The client may also set the body of the message. After setup, the // client needs to only display the view. // </p>The provided delegate will be informed of the user's composition completion and how they chose // to complete the operation. // <p>Prior to use, clients should verify the user has set up the device for sending messages via // <tt>+[MFMessageComposeViewController canSendText]</tt>. MFMessageComposeViewControllerClass = interface(UINavigationControllerClass) ['{BF34F7BC-9C09-4D86-9EB0-6D563E0ADFD3}'] //@method canSendText //@abstract Returns <tt>YES</tt> if the user has set up the device for sending text only messages. //@discussion If the return value is YES, the client can set the recipients and body of the message. // If the return value is NO, the client may notify the user of the failure, or the // client may open an SMS URL via <tt>-[UIApplication openURL:]</tt>. //+ (BOOL)canSendText __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_0); {classe} function canSendText: Boolean; cdecl; //@method canSendSubject //@abstract Returns <tt>YES</tt> if the user has set up the device for including subjects in messages.</tt>. //+ (BOOL)canSendSubject __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0); //@method canSendAttachments //@abstract Returns <tt>YES</tt> if the user has set up the device for including attachments in messages.</tt>. //+ (BOOL)canSendAttachments __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0); //@method isSupportedAttachmentUTI: //@abstract Returns <tt>YES</tt>if the attachment at the specified URL could be accepted by the current composition. //@discussion If the return value is YES, the UTI is acceptable for attachment to a message, a return value of NO // indicates that the given UTI is unsupported. //+ (BOOL)isSupportedAttachmentUTI:(NSString *)uti __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0); end; MFMessageComposeViewController = interface(UINavigationController) ['{8C21FEF5-8AAA-4C51-BE7D-154BB6E11387}'] //@property messageComposeDelegate //@abstract This property is the delegate for the MFMessageComposeViewController method callbacks. //@property(nonatomic,assign,nullable) id<MFMessageComposeViewControllerDelegate> messageComposeDelegate /*__OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_0)*/; function messageComposeDelegate: MFMessageComposeViewControllerDelegate; cdecl; procedure setMessageComposeDelegate(messageComposeDelegate: MFMessageComposeViewControllerDelegate); cdecl; //@method disableUserAttachments; //@abstract Calling this method will disable the camera/attachment button in the view controller. After the controller has been presented, // this call will have no effect. The camera / attachment button is visible by default. //- (void)disableUserAttachments __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0); //@property recipients //@abstract This property sets the initial value of the To field for the message to the specified addresses. //@discussion This property will set the initial value of the To field for the message from an NSArray of // NSString instances specifying the message addresses of recipients. This should be called prior // to display. // </p>After the view has been presented to the user, this property will no longer change the value. //@property(nonatomic,copy,nullable) NSArray<NSString *> *recipients /*__OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_0)*/; function recipients: NSArray; cdecl; procedure setRecipients(recipients: NSArray); cdecl; //@property body //@abstract This property sets the initial value of the body of the message to the specified content. //@discussion This property will set the initial value of the body of the message. This should be called prior // to display. // </p>After the view has been presented to the user, this property will no longer change the value. //@property(nonatomic,copy,nullable) NSString *body /*__OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_0)*/; function body: NSString; cdecl; procedure setBody(body: NSString); cdecl; //@property subject //@abstract This property sets the initial value of the subject of the message to the specified content. //@discussion This property will set the initial value of the subject of the message. This should be called prior //to display. //</p>After the view has been presented to the user, this property will no longer change the value. //@property(nonatomic,copy,nullable) NSString *subject /*__OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0)*/; function subject: NSString; cdecl; procedure setSubject(subject: NSString); cdecl; //@property attachments //@abstract This property returns an NSArray of NSDictionaries describing the properties of the current attachments. //@discussion This property returns an NSArray of NSDictionaries describing the properties of the current attachments. // See MFMessageComposeViewControllerAttachmentURL, MFMessageComposeViewControllerAttachmentAlternateFilename. //@property(nonatomic,copy,readonly,nullable) NSArray<NSDictionary *> *attachments /*__OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0)*/; //@method addAttachmentURL:withAlternateFilename: //@abstract Returns <tt>YES</tt>if the attachment at the specified URL was added to the composition successfully. //@discussion If the return value is YES, the attachment was added to the composition. If the return value is NO, // the attachment was not added to the composition. All attachment URLs must be file urls. The file // URL must not be NIL. The alternate filename will be display to the user in leiu of the attachments URL. // The alternate filename may be NIL. //- (BOOL)addAttachmentURL:(NSURL *)attachmentURL withAlternateFilename:(nullable NSString *)alternateFilename __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0); //@method addAttachmentData:typeIdentifier:filename: //@abstract Returns <tt>YES</tt>if the attachment was added to the composition successfully. //@discussion If the return value is YES, the attachment was added to the composition. If the return value is NO, //the attachment was not added to the composition. The data and typeIdentifer must be non-nil. typeIdentifier should be a valid Uniform Type Identifier. //- (BOOL)addAttachmentData:(NSData *)attachmentData typeIdentifier:(NSString *)uti filename:(NSString *)filename __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_7_0); end; TMFMessageComposeViewController = class(TOCGenericImport<MFMessageComposeViewControllerClass, MFMessageComposeViewController>) end; {***************************************************} //@protocol MFMessageComposeViewControllerDelegate //@abstract Protocol for delegate callbacks to MFMessageComposeViewControllerDelegate instances. //@discussion This protocol will be implemented by delegates of MFMessageComposeViewController instances. // It will be called at various times while the user is composing, sending, or canceling // message composition. //@protocol MFMessageComposeViewControllerDelegate <NSObject> MFMessageComposeViewControllerDelegate = interface(IObjectiveC) ['{1C9616CB-1EA8-4AC8-A1AA-38A12DB5C26A}'] //@required //@method messageComposeViewController:didFinishWithResult: //@abstract Delegate callback which is called upon user's completion of message composition. //@discussion This delegate callback will be called when the user completes the message composition. // How the user chose to complete this task will be given as one of the parameters to the // callback. Upon this call, the client should remove the view associated with the controller, // typically by dismissing modally. //@param controller The MFMessageComposeViewController instance which is returning the result. //@param result MessageComposeResult indicating how the user chose to complete the composition process. //- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result; procedure messageComposeViewController(controller: MFMessageComposeViewController; didFinishWithResult: MFMessageComposeResult); cdecl; end; {***********************************************************************************************} TMFMessageComposeViewControllerDelegate = class(TOCLocal, MFMessageComposeViewControllerDelegate) private fMFMessageComposeViewController: MFMessageComposeViewController; public constructor Create(aMFMessageComposeViewController: MFMessageComposeViewController); procedure messageComposeViewController(controller: MFMessageComposeViewController; didFinishWithResult: MFMessageComposeResult); cdecl; end; type //typedef enum MFMailComposeResult MFMailComposeResult; // available in iPhone 3.0 MFMailComposeResult = NSInteger; const {*************************************************************************} //@abstract Composition result sent to the delegate upon user completion. //@discussion This result will inform of the user's choice in regards to email composition. If the user // cancels the composition, <tt>MFMailComposeResultCancelled</tt> will be sent to the delegate. // Typically <tt>MFMailComposeResultSent</tt> or <tt>MFMailComposeResultSaved</tt> will // be sent, but <tt>MFMailComposeResultFailed</tt> will be sent in the case of failure. // </p>Send may only be interpreted as a successful queueing of the message for later sending. // The actual send will occur when the device is able to send. //@constant MFMailComposeResultCancelled User canceled the composition. //@constant MFMailComposeResultSaved User successfully saved the message. //@constant MFMailComposeResultSent User successfully sent/queued the message. //@constant MFMailComposeResultFailed User's attempt to save or send was unsuccessful. //@enum MFMailComposeResult MFMailComposeResultCancelled = 0; MFMailComposeResultSaved = 1; MFMailComposeResultSent = 2; MFMailComposeResultFailed = 3; type {**********************************************} MFMailComposeViewControllerDelegate = interface; {****************************************} //@class MFMailComposeViewController //@abstract The MFMailComposeViewController class provides an interface for editing and sending email. //@discussion The MFMailComposeViewController class manages all user interaction. The client needs to set the recipient or // recipients. The client may also set the subject and the body of the message. Attachments may be added, if // so desired. After setup, the client needs to only display the view.</p>The provided delegate will be informed // of the user's composition completion and how they chose to complete the operation.<p>Prior to use, clients // should verify the user has set up the device for sending email via <tt>+[MFMailComposeViewController canSendMail]</tt>. //@interface MFMailComposeViewController : UINavigationController MFMailComposeViewControllerClass = interface(UINavigationControllerClass) ['{B6292F63-0DE9-4FE7-BEF7-871D5FE75362}'] //@method canSendMail //@abstract Returns <tt>YES</tt> if the user has set up the device for sending email. //@discussion The client may continue to set the recipients and content if the return value was <tt>YES</tt>. If <tt>NO</tt> // was the result, the client has a couple options. It may choose to simply notify the user of the inability to // send mail, or it may issue a "mailto" URL via <tt>-[UIApplication openURL:]</tt>. //+ (BOOL)canSendMail __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); function canSendMail: Boolean; cdecl; end; MFMailComposeViewController = interface(UINavigationController) ['{5AD35A29-4418-48D3-AB8A-2F114B4B0EDC}'] //@property mailComposeDelegate //@abstract This property is the delegate for the MFMailComposeViewControllerDelegate method callbacks. //@property (nonatomic, assign, nullable) id<MFMailComposeViewControllerDelegate> mailComposeDelegate /*__OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); function mailComposeDelegate: MFMailComposeViewControllerDelegate; cdecl; procedure setMailComposeDelegate( mailComposeDelegate: MFMailComposeViewControllerDelegate ); cdecl; //@method setSubject: //@abstract This method sets the Subject header for the email message. //@discussion This method will set the Subject header for the email message. This should be called prior to display. // Newlines are removed from the parameter. // </p>After the view has been presented to the user, this method will no longer change the value. //@param subject A NSString specifying the message's Subject header. //- (void)setSubject:(NSString *)subject __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); procedure setSubject( subject: NSString ); cdecl; //@method setToRecipients: //@abstract This method sets the To header for the email message to the specified email addresses. //@discussion This method will set the To header for the email message. This should be called prior to display. // </p>Recipient addresses should be specified as per RFC5322. // </p>After the view has been presented to the user, this method will no longer change the value. //@param toRecipients A NSArray of NSString instances specifying the email addresses of recipients. //- (void)setToRecipients:(nullable NSArray<NSString *> *)toRecipients __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); procedure setToRecipients( toRecipients: NSArray ); cdecl; //@method setCcRecipients: //@abstract This method sets the CC header for the email message to the specified email addresses. //@discussion This method will set the CC header for the email message. This should be called prior to display. // </p>Recipient addresses should be specified as per RFC5322. // </p>After the view has been presented to the user, this method will no longer change the value. //@param ccRecipients A NSArray of NSString instances specifying the email addresses of recipients. //- (void)setCcRecipients:(nullable NSArray<NSString *> *)ccRecipients __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); procedure setCcRecipients( ccRecipients: NSArray ); cdecl; //@method setBccRecipients: //@abstract This method sets the BCC header for the email message to the specified email addresses. //@discussion This method will set the BCC header for the email message. This should be called prior to display. // </p>Recipient addresses should be specified as per RFC5322. // </p>After the view has been presented to the user, this method will no longer change the value. //@param bccRecipients A NSArray of NSString instances specifying the email addresses of recipients. //- (void)setBccRecipients:(nullable NSArray<NSString *> *)bccRecipients __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); procedure setBccRecipients( bccRecipients: NSArray ); cdecl; //@method setMessageBody:isHTML: //@abstract This method sets the body of the email message to the specified content. //@discussion This method will set the body of the email message. This should be called prior to display. // The user's signature, if specified, will be added after the body content. //@param body A NSString containing the body contents of the email message. //@param isHTML A boolean value indicating if the body argument is to be interpreted as HTML content. //- (void)setMessageBody:(NSString *)body isHTML:(BOOL)isHTML __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); procedure setMessageBody( body: NSString; isHTML: Boolean ); cdecl; //@method addAttachmentData:mimeType:fileName: //@abstract This method adds the specified attachment to the email message. //@discussion This method adds the specified attachment to the email message. This should be called prior to display. // Attachments will be appended to the end of the message. //@param attachment NSData containing the contents of the attachment. Must not be <tt>nil</tt>. //@param mimeType NSString specifying the MIME type for the attachment, as specified by the IANA // (http://www.iana.org/assignments/media-types/). Must not be <tt>nil</tt>. //@param filename NSString specifying the intended filename for the attachment. This is displayed below // the attachment's icon if the attachment is not decoded when displayed. Must not be <tt>nil</tt>. //- (void)addAttachmentData:(NSData *)attachment mimeType:(NSString *)mimeType fileName:(NSString *)filename __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); procedure addAttachmentData( attachment: NSData; mimeType: NSString; fileName: NSString ); cdecl; end; TMFMailComposeViewController = class(TOCGenericImport<MFMailComposeViewControllerClass, MFMailComposeViewController>) end; {********************************************************} //@protocol MFMailComposeViewControllerDelegate <NSObject> //@protocol MFMailComposeViewControllerDelegate //@abstract Protocol for delegate callbacks to MFMailComposeViewController instances. //@discussion This protocol must be implemented for delegates of MFMailComposeViewController instances. It will // be called at various times while the user is composing, sending, saving, or canceling email composition. MFMailComposeViewControllerDelegate = interface(IObjectiveC) ['{068352EB-9182-4581-86F5-EAFCE7304E32}'] //@method mailComposeController:didFinishWithResult:error: //@abstract Delegate callback which is called upon user's completion of email composition. //@discussion This delegate callback will be called when the user completes the email composition. How the user chose // to complete this task will be given as one of the parameters to the callback. Upon this call, the client // should remove the view associated with the controller, typically by dismissing modally. //@param controller The MFMailComposeViewController instance which is returning the result. //@param result MFMailComposeResult indicating how the user chose to complete the composition process. //@param error NSError indicating the failure reason if failure did occur. This will be <tt>nil</tt> if // result did not indicate failure. //- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(nullable NSError *)error __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); procedure mailComposeController(controller: MFMailComposeViewController; didFinishWithResult: MFMailComposeResult; error: NSError); cdecl; end; {*****************************************************************************************} TMFMailComposeViewControllerDelegate = class(TOCLocal, MFMailComposeViewControllerDelegate) private fMFMailComposeViewController: MFMailComposeViewController; public constructor Create(aMFMailComposeViewController: MFMailComposeViewController); procedure mailComposeController(controller: MFMailComposeViewController; didFinishWithResult: MFMailComposeResult; error: NSError); cdecl; end; const libMessageUI = '/System/Library/Frameworks/MessageUI.framework/MessageUI'; implementation uses FMX.Helpers.iOS; {**************************************************************************************************************************} constructor TMFMessageComposeViewControllerDelegate.Create(aMFMessageComposeViewController: MFMessageComposeViewController); begin inherited Create; fMFMessageComposeViewController := aMFMessageComposeViewController; end; {**********************************************************************************************************************************************************************} procedure TMFMessageComposeViewControllerDelegate.messageComposeViewController(controller: MFMessageComposeViewController; didFinishWithResult: MFMessageComposeResult); var LWindow: UIWindow; begin LWindow := SharedApplication.keyWindow; if Assigned(LWindow) and Assigned(LWindow.rootViewController) then LWindow.rootViewController.dismissModalViewControllerAnimated(True{animated}); fMFMessageComposeViewController.release; fMFMessageComposeViewController := nil; end; {*****************************************************************************************************************} constructor TMFMailComposeViewControllerDelegate.Create(aMFMailComposeViewController: MFMailComposeViewController); begin inherited Create; fMFMailComposeViewController := aMFMailComposeViewController; end; {**********************************************************************************************************************************************************************} procedure TMFMailComposeViewControllerDelegate.mailComposeController(controller: MFMailComposeViewController; didFinishWithResult: MFMailComposeResult; error: NSError); var LWindow: UIWindow; begin LWindow := SharedApplication.keyWindow; if Assigned(LWindow) and Assigned(LWindow.rootViewController) then LWindow.rootViewController.dismissModalViewControllerAnimated(True{animated}); fMFMailComposeViewController.release; fMFMailComposeViewController := nil; end; {*************************************************************} procedure LibMessageUIFakeLoader; cdecl; external libMessageUI; end.
unit Vs.Pedido.Venda.Salvar.Eventos; interface uses // Vs Vs.Pedido.Venda.Entidade; type IPedidoVendaSalvoEvento = interface ['{633625B9-937F-422C-A55A-236C1E5C0136}'] function Quem: string; function Quando: TDateTime; function oQue: TPedidoVenda; end; function EventoPedidoVendaSalvo(APedidoVenda: TPedidoVenda): IPedidoVendaSalvoEvento; implementation uses System.SysUtils; type TPedidoVendaSalvoEvento = class(TInterfacedObject, IPedidoVendaSalvoEvento) strict private FQuem: string; FQuando: TDateTime; FoQue: TPedidoVenda; constructor Create(APedidoVenda: TPedidoVenda); public destructor Destroy; override; class function Instancia(APedidoVenda: TPedidoVenda): IPedidoVendaSalvoEvento; function Quem: string; function Quando: TDateTime; function oQue: TPedidoVenda; end; function EventoPedidoVendaSalvo(APedidoVenda: TPedidoVenda): IPedidoVendaSalvoEvento; begin Result := TPedidoVendaSalvoEvento.Instancia(APedidoVenda); end; { TPedidoVendaSalvoEvento } constructor TPedidoVendaSalvoEvento.Create(APedidoVenda: TPedidoVenda); begin inherited Create; FQuem := 'USUARIO_LOGADO'; FQuando := now; FoQue := APedidoVenda; end; destructor TPedidoVendaSalvoEvento.Destroy; begin inherited; end; class function TPedidoVendaSalvoEvento.Instancia( APedidoVenda: TPedidoVenda): IPedidoVendaSalvoEvento; begin Result := Self.Create(APedidoVenda); end; function TPedidoVendaSalvoEvento.oQue: TPedidoVenda; begin Result := FoQue; end; function TPedidoVendaSalvoEvento.Quando: TDateTime; begin Result := FQuando; end; function TPedidoVendaSalvoEvento.Quem: string; begin Result := FQuem; end; end.
unit crt32; {$APPTYPE CONSOLE} {# freeware} {# version 1.0.0127} {# Date 18.01.1997} {# Author Frank Zimmer} {# description Copyright © 1997, Frank Zimmer, 100703.1602@compuserve.com Version: 1.0.0119 Date: 18.01.1997 an Implementation of Turbo Pascal CRT-Unit for Win32 Console Subsystem testet with Windows NT 4.0 At Startup you get the Focus to the Console!!!! ( with * are not in the original Crt-Unit): Procedure and Function: ClrScr ClrEol WhereX WhereY GotoXY InsLine DelLine HighVideo LowVideo NormVideo TextBackground TextColor Delay // use no processtime KeyPressed ReadKey // use no processtime Sound // with Windows NT your could use the Variables SoundFrequenz, SoundDuration NoSound *TextAttribut // Set TextBackground and TextColor at the same time, usefull for Lastmode *FlushInputBuffer // Flush the Keyboard and all other Events *ConsoleEnd // output of 'Press any key' and wait for key input when not pipe *Pipe // True when the output is redirected to a pipe or a file Variables: WindMin // the min. WindowRect WindMax // the max. WindowRect *ViewMax // the max. ConsoleBuffer start at (1,1); TextAttr // Actual Attributes only by changing with this Routines LastMode // Last Attributes only by changing with this Routines *SoundFrequenz // with Windows NT your could use these Variables *SoundDuration // how long bells the speaker -1 until ??, default = -1 *HConsoleInput // the Input-handle; *HConsoleOutput // the Output-handle; *HConsoleError // the Error-handle; This Source is freeware, have fun :-) History 18.01.97 the first implementation 23.01.97 Sound, delay, Codepage inserted and setfocus to the console 24.01.97 Redirected status } interface uses windows,messages; {$ifdef win32} const Black = 0; Blue = 1; Green = 2; Cyan = 3; Red = 4; Magenta = 5; Brown = 6; LightGray = 7; DarkGray = 8; LightBlue = 9; LightGreen = 10; LightCyan = 11; LightRed = 12; LightMagenta = 13; Yellow = 14; White = 15; EVERYKEY = #255; NOKEY = #0; Function WhereX: integer; Function WhereY: integer; procedure ClrEol; procedure ClrScr; procedure InsLine; Procedure DelLine; Procedure GotoXY(const x,y:integer); procedure HighVideo; procedure LowVideo; procedure NormVideo; procedure TextBackground(const Color:word); procedure TextColor(const Color:word); procedure TextAttribut(const Color,Background:word); procedure Delay(const ms:integer); function KeyPressed:boolean; procedure WaitKey(c: Char); function ReadKey:Char; Procedure Sound; Procedure NoSound; procedure ConsoleEnd; procedure FlushInputBuffer; Function Pipe:boolean; var HConsoleInput:tHandle; HConsoleOutput:thandle; HConsoleError:Thandle; WindMin:tcoord; WindMax:tcoord; ViewMax:tcoord; TextAttr : Word; LastMode : Word; SoundFrequenz :Integer; SoundDuration : Integer; {$endif win32} implementation {$ifdef win32} uses sysutils; var StartAttr:word; OldCP:integer; CrtPipe : Boolean; German : boolean; procedure ClrEol; var tC :tCoord; Len,Nw: dword; Cbi : TConsoleScreenBufferInfo; begin GetConsoleScreenBufferInfo(HConsoleOutput,cbi); len := cbi.dwsize.x-cbi.dwcursorposition.x; tc.x := cbi.dwcursorposition.x; tc.y := cbi.dwcursorposition.y; FillConsoleOutputAttribute(HConsoleOutput,textattr,len,tc,nw); FillConsoleOutputCharacter(HConsoleOutput,#32,len,tc,nw); end; procedure ClrScr; var tc :tcoord; nw: dword; cbi : TConsoleScreenBufferInfo; begin getConsoleScreenBufferInfo(HConsoleOutput,cbi); tc.x := 0; tc.y := 0; FillConsoleOutputAttribute(HConsoleOutput,textattr,cbi.dwsize.x*cbi.dwsize.y,tc,nw); FillConsoleOutputCharacter(HConsoleOutput,#32,cbi.dwsize.x*cbi.dwsize.y,tc,nw); setConsoleCursorPosition(hconsoleoutput,tc); end; Function WhereX: integer; var cbi : TConsoleScreenBufferInfo; begin getConsoleScreenBufferInfo(HConsoleOutput,cbi); result := tcoord(cbi.dwCursorPosition).x+1 end; Function WhereY: integer; var cbi : TConsoleScreenBufferInfo; begin getConsoleScreenBufferInfo(HConsoleOutput,cbi); result := tcoord(cbi.dwCursorPosition).y+1 end; Procedure GotoXY(const x,y:integer); var coord :tcoord; begin coord.x := x-1; coord.y := y-1; setConsoleCursorPosition(hconsoleoutput,coord); end; procedure InsLine; var cbi : TConsoleScreenBufferInfo; ssr:tsmallrect; coord :tcoord; ci :tcharinfo; nw:dword; begin getConsoleScreenBufferInfo(HConsoleOutput,cbi); coord := cbi.dwCursorPosition; ssr.left := 0; ssr.top := coord.y; ssr.right := cbi.srwindow.right; ssr.bottom := cbi.srwindow.bottom; ci.asciichar := #32; ci.attributes := cbi.wattributes; coord.x := 0; coord.y := coord.y+1; ScrollConsoleScreenBuffer(HconsoleOutput,ssr,nil,coord,ci); coord.y := coord.y-1; FillConsoleOutputAttribute(HConsoleOutput,textattr,cbi.dwsize.x*cbi.dwsize.y,coord,nw); end; procedure DelLine; var cbi : TConsoleScreenBufferInfo; ssr:tsmallrect; coord :tcoord; ci :tcharinfo; nw:dword; begin getConsoleScreenBufferInfo(HConsoleOutput,cbi); coord := cbi.dwCursorPosition; ssr.left := 0; ssr.top := coord.y+1; ssr.right := cbi.srwindow.right; ssr.bottom := cbi.srwindow.bottom; ci.asciichar := #32; ci.attributes := cbi.wattributes; coord.x := 0; coord.y := coord.y; ScrollConsoleScreenBuffer(HconsoleOutput,ssr,nil,coord,ci); FillConsoleOutputAttribute(HConsoleOutput,textattr,cbi.dwsize.x*cbi.dwsize.y,coord,nw); end; procedure TextBackground(const Color:word); begin LastMode := TextAttr; textattr := (color shl 4) or (textattr and $f); SetConsoleTextAttribute(hconsoleoutput,textattr); end; procedure TextColor(const Color:word); begin LastMode := TextAttr; textattr := (color and $f) or (textattr and $f0); SetConsoleTextAttribute(hconsoleoutput,textattr); end; procedure TextAttribut(const Color,Background:word); begin LastMode := TextAttr; textattr := (color and $f) or (Background shl 4); SetConsoleTextAttribute(hconsoleoutput,textattr); end; procedure HighVideo; begin LastMode := TextAttr; textattr := textattr or $8; SetConsoleTextAttribute(hconsoleoutput,textattr); end; procedure LowVideo; begin LastMode := TextAttr; textattr := textattr and $f7; SetConsoleTextAttribute(hconsoleoutput,textattr); end; procedure NormVideo; begin LastMode := TextAttr; textattr := startAttr; SetConsoleTextAttribute(hconsoleoutput,textattr); end; procedure FlushInputBuffer; begin FlushConsoleInputBuffer(hconsoleinput) end; function KeyPressed:boolean; var NumberOfEvents:dword; begin GetNumberOfConsoleInputEvents(hconsoleinput,NumberOfEvents); result := NumberOfEvents = 0; FlushInputBuffer; end; function ReadKey: Char; var NumRead: dword; InputRec: TInputRecord; begin Result:= #0; { while not ReadConsoleInput(HConsoleInput, InputRec, 1, NumRead) or (InputRec.EventType = KEY_EVENT) do ; Result := InputRec.Event.KeyEvent.AsciiChar; } while Result=#0 do ReadLn(result); end; procedure WaitKey(c: Char); var a:char; begin a:=#0; if c = everykey then begin while not keypressed do ; end else if c in [#10,#13] then begin while a<>c do read(a); end else while a<>c do readln; end; procedure Delay(const ms:integer); var s,e:integer; begin s:= GetTickCount; e:= s+ms; while (GetTickCount<e) do ; end; Procedure Sound; begin windows.beep(SoundFrequenz,soundduration); end; Procedure NoSound; begin windows.beep(soundfrequenz,0); end; procedure ConsoleEnd; begin if isconsole and not crtpipe then begin if wherex > 1 then writeln; textcolor(green); setfocus(GetCurrentProcess); if german then write('Bitte eine Taste drücken!') else write('Press any key!'); normvideo; FlushInputBuffer; ReadKey; FlushInputBuffer; end; end; function Pipe:boolean; begin result := crtpipe; end; procedure init; var cbi : TConsoleScreenBufferInfo; tc : tcoord; begin SetActiveWindow(0); HConsoleInput := GetStdHandle(STD_InPUT_HANDLE); HConsoleOutput := GetStdHandle(STD_OUTPUT_HANDLE); HConsoleError := GetStdHandle(STD_Error_HANDLE); if getConsoleScreenBufferInfo(HConsoleOutput,cbi) then begin TextAttr := cbi.wAttributes; StartAttr := cbi.wAttributes; lastmode := cbi.wAttributes; tc.x := cbi.srwindow.left+1; tc.y := cbi.srwindow.top+1; windmin := tc; ViewMax := cbi.dwsize; tc.x := cbi.srwindow.right+1; tc.y := cbi.srwindow.bottom+1; windmax := tc; crtpipe := false; end else crtpipe := true; SoundFrequenz := 1000; SoundDuration := -1; oldCp := GetConsoleoutputCP; SetConsoleoutputCP(1252); german := $07 = (LoWord(GetUserDefaultLangID) and $3ff); end; initialization init; finalization SetConsoleoutputCP(oldcp); {$endif win32} end. 
unit ksCommon; interface uses FMX.Controls, FMX.Graphics, System.UITypes, FMX.Types, Types, System.UIConsts, ksTypes; {$I ksComponents.inc} function GetScreenScale: single; procedure ProcessMessages; procedure ReplaceOpaqueColor(ABmp: TBitmap; Color : TAlphaColor); function GetColorOrDefault(AColor, ADefaultIfNull: TAlphaColor): TAlphaColor; procedure SimulateClick(AControl: TControl; x, y: single); function IsBlankBitmap(ABmp: TBitmap; const ABlankColor: TAlphaColor = claNull): Boolean; function GetTextSizeHtml(AText: string; AFont: TFont; const AWidth: single = 0): TPointF; function CalculateTextWidth(AText: string; AFont: TFont; AWordWrap: Boolean; const AMaxWidth: single = 0; const APadding: single = 0): single; function CalculateTextHeight(AText: string; AFont: TFont; AWordWrap: Boolean; ATrimming: TTextTrimming; const AWidth: single = 0; const APadding: single = 0): single; procedure RenderText(ACanvas: TCanvas; x, y, AWidth, AHeight: single; AText: string; AFont: TFont; ATextColor: TAlphaColor; AWordWrap: Boolean; AHorzAlign: TTextAlign; AVertAlign: TTextAlign; ATrimming: TTextTrimming; const APadding: single = 0); overload; procedure RenderText(ACanvas: TCanvas; ARect: TRectF; AText: string; AFont: TFont; ATextColor: TAlphaColor; AWordWrap: Boolean; AHorzAlign: TTextAlign; AVertAlign: TTextAlign; ATrimming: TTextTrimming; const APadding: single = 0); overload; procedure RenderHhmlText(ACanvas: TCanvas; x, y, AWidth, AHeight: single; AText: string; AFont: TFont; ATextColor: TAlphaColor; AWordWrap: Boolean; AHorzAlign: TTextAlign; AVertAlign: TTextAlign; ATrimming: TTextTrimming); procedure GenerateBadge(ACanvas: TCanvas; ATopLeft: TPointF; AValue: integer; AColor, ABackgroundColor, ATextColor: TAlphaColor); implementation uses FMX.Platform, FMX.Forms, SysUtils, FMX.TextLayout, Math, FMX.Utils {$IFDEF IOS} , IOSApi.Foundation {$ENDIF} {$IFDEF USE_TMS_HTML_ENGINE} , FMX.TMSHTMLEngine {$ENDIF} ; var AScreenScale: single; ATextLayout: TTextLayout; function GetScreenScale: single; var Service: IFMXScreenService; begin if AScreenScale > 0 then begin Result := AScreenScale; Exit; end; Service := IFMXScreenService(TPlatformServices.Current.GetPlatformService(IFMXScreenService)); Result := Service.GetScreenScale; {$IFDEF IOS} if Result < 2 then Result := 2; {$ENDIF} AScreenScale := Result; end; procedure ProcessMessages; {$IFDEF IOS} var TimeoutDate: NSDate; begin TimeoutDate := TNSDate.Wrap(TNSDate.OCClass.dateWithTimeIntervalSinceNow(0.0)); TNSRunLoop.Wrap(TNSRunLoop.OCClass.currentRunLoop).runMode(NSDefaultRunLoopMode, TimeoutDate); end; {$ELSE} begin // FMX can occasionally raise an exception. try Application.ProcessMessages; except // end; end; {$ENDIF} function GetColorOrDefault(AColor, ADefaultIfNull: TAlphaColor): TAlphaColor; begin Result := AColor; if Result = claNull then Result := ADefaultIfNull; end; function IsBlankBitmap(ABmp: TBitmap; const ABlankColor: TAlphaColor = claNull): Boolean; var ABlank: TBitmap; begin ABlank := TBitmap.Create(ABmp.Width, ABmp.Height); try ABlank.Clear(ABlankColor); Result := ABmp.EqualsBitmap(ABlank); finally FreeAndNil(ABlank); end; end; procedure RenderText(ACanvas: TCanvas; x, y, AWidth, AHeight: single; AText: string; AFont: TFont; ATextColor: TAlphaColor; AWordWrap: Boolean; AHorzAlign: TTextAlign; AVertAlign: TTextAlign; ATrimming: TTextTrimming; const APadding: single = 0); overload; begin if AText = '' then Exit; ATextLayout.BeginUpdate; ATextLayout.Text := AText; ATextLayout.WordWrap := AWordWrap; ATextLayout.Font.Assign(AFont); ATextLayout.Color := ATextColor; ATextLayout.HorizontalAlign := AHorzAlign; ATextLayout.VerticalAlign := AVertAlign; ATextLayout.Padding.Rect := RectF(APadding, APadding, APadding, APadding); ATextLayout.Trimming := ATrimming; if AWordWrap then ATextLayout.Trimming := TTextTrimming.None; ATextLayout.TopLeft := PointF(x, y); ATextLayout.MaxSize := PointF(AWidth, AHeight); ATextLayout.EndUpdate; ATextLayout.RenderLayout(ACanvas); end; procedure RenderText(ACanvas: TCanvas; ARect: TRectF; AText: string; AFont: TFont; ATextColor: TAlphaColor; AWordWrap: Boolean; AHorzAlign: TTextAlign; AVertAlign: TTextAlign; ATrimming: TTextTrimming; const APadding: single = 0); overload; begin RenderText(ACanvas, ARect.Left, ARect.Top, ARect.Width, ARect.Height, AText, AFont, ATextColor, AWordWrap, AHorzAlign, AVertAlign, ATrimming, APadding); end; function GetTextSizeHtml(AText: string; AFont: TFont; const AWidth: single = 0): TPointF; {$IFDEF USE_TMS_HTML_ENGINE} var AnchorVal, StripVal, FocusAnchor: string; XSize, YSize: single; HyperLinks, MouseLink: integer; HoverRect: TRectF; ABmp: TBitmap; {$ENDIF} begin Result := PointF(0, 0); {$IFDEF USE_TMS_HTML_ENGINE} XSize := AWidth; if XSize <= 0 then XSize := MaxSingle; ABmp := TBitmap.Create(10, 10); try ABmp.BitmapScale := GetScreenScale; ABmp.Canvas.Assign(AFont); {$IFDEF USE_TMS_HTML_ENGINE} HTMLDrawEx(ABmp.Canvas, AText, RectF(0, 0, XSize, MaxSingle), 0, 0, 0, 0, 0, False, False, False, False, False, False, False, 1, claNull, claNull, claNull, claNull, AnchorVal, StripVal, FocusAnchor, XSize, YSize, HyperLinks, MouseLink, HoverRect, 1, nil, 1); Result := PointF(XSize, YSize); {$ELSE} Result := PointF(0, 0); {$ENDIF} finally FreeAndNil(ABmp); end; {$ENDIF} end; function CalculateTextWidth(AText: string; AFont: TFont; AWordWrap: Boolean; const AMaxWidth: single = 0; const APadding: single = 0): single; var APoint: TPointF; begin ATextLayout.BeginUpdate; // Setting the layout MaxSize if AMaxWidth > 0 then APoint.X := AMaxWidth else APoint.x := MaxSingle; APoint.y := 100; ATextLayout.MaxSize := APoint; ATextLayout.Text := AText; ATextLayout.WordWrap := AWordWrap; ATextLayout.Padding.Rect := RectF(APadding, APadding, APadding, APadding); ATextLayout.Font.Assign(AFont); ATextLayout.HorizontalAlign := TTextAlign.Leading; ATextLayout.VerticalAlign := TTextAlign.Leading; ATextLayout.EndUpdate; //ATextLayout.RenderLayout(ATextLayout.LayoutCanvas); Result := ATextLayout.Width; end; function CalculateTextHeight(AText: string; AFont: TFont; AWordWrap: Boolean; ATrimming: TTextTrimming; const AWidth: single = 0; const APadding: single = 0): single; var APoint: TPointF; begin Result := 0; if AText = '' then Exit; ATextLayout.BeginUpdate; // Setting the layout MaxSize APoint.x := MaxSingle; if AWidth > 0 then APoint.x := AWidth; APoint.y := MaxSingle; ATextLayout.Font.Assign(AFont); ATextLayout.Trimming := ATrimming; ATextLayout.MaxSize := APoint; ATextLayout.Text := AText; ATextLayout.WordWrap := AWordWrap; ATextLayout.Padding.Rect := RectF(APadding, APadding, APadding, APadding); ATextLayout.HorizontalAlign := TTextAlign.Leading; ATextLayout.VerticalAlign := TTextAlign.Leading; ATextLayout.EndUpdate; Result := ATextLayout.Height; end; procedure RenderHhmlText(ACanvas: TCanvas; x, y, AWidth, AHeight: single; AText: string; AFont: TFont; ATextColor: TAlphaColor; AWordWrap: Boolean; AHorzAlign: TTextAlign; AVertAlign: TTextAlign; ATrimming: TTextTrimming); {$IFDEF USE_TMS_HTML_ENGINE} var AnchorVal, StripVal, FocusAnchor: string; XSize, YSize: single; HyperLinks, MouseLink: integer; HoverRect: TRectF; {$ENDIF} begin {$IFDEF USE_TMS_HTML_ENGINE} ACanvas.Fill.Color := ATextColor; ACanvas.Font.Assign(AFont); HTMLDrawEx(ACanvas, AText, RectF(x, y, x + AWidth, y + AHeight), 0, 0, 0, 0, 0, False, False, True, False, False, False, AWordWrap, 1, claNull, claNull, claNull, claNull, AnchorVal, StripVal, FocusAnchor, XSize, YSize, HyperLinks, MouseLink, HoverRect, 1, nil, 1); {$ELSE} AFont.Size := 10; RenderText(ACanvas, x, y, AWidth, AHeight, 'Requires TMS FMX', AFont, ATextColor, AWordWrap, AHorzAlign, AVertAlign, ATrimming); {$ENDIF} end; { procedure DrawAccessory(ACanvas: TCanvas; ARect: TRectF; AAccessory: TksAccessoryType; AStroke, AFill: TAlphaColor); var AState: TCanvasSaveState; begin AState := ACanvas.SaveState; try ACanvas.IntersectClipRect(ARect); ACanvas.Fill.Color := AFill; ACanvas.Fill.Kind := TBrushKind.Solid; ACanvas.FillRect(ARect, 0, 0, AllCorners, 1); AccessoryImages.GetAccessoryImage(AAccessory).DrawToCanvas(ACanvas, ARect, False); ACanvas.Stroke.Color := AStroke; ACanvas.DrawRect(ARect, 0, 0, AllCorners, 1); finally ACanvas.RestoreState(AState); end; end; } procedure ReplaceOpaqueColor(ABmp: TBitmap; Color : TAlphaColor); var x,y: Integer; AMap: TBitmapData; PixelColor: TAlphaColor; PixelWhiteColor: TAlphaColor; C: PAlphaColorRec; begin if (Assigned(ABmp)) then begin if ABmp.Map(TMapAccess.ReadWrite, AMap) then try AlphaColorToPixel(Color , @PixelColor, AMap.PixelFormat); AlphaColorToPixel(claWhite, @PixelWhiteColor, AMap.PixelFormat); for y := 0 to ABmp.Height - 1 do begin for x := 0 to ABmp.Width - 1 do begin C := @PAlphaColorArray(AMap.Data)[y * (AMap.Pitch div 4) + x]; if (C^.Color<>claWhite) and (C^.A>0) then C^.Color := PremultiplyAlpha(MakeColor(PixelColor, C^.A / $FF)); end; end; finally ABmp.Unmap(AMap); end; end; end; procedure SimulateClick(AControl: TControl; x, y: single); var AForm : TCommonCustomForm; AFormPoint: TPointF; begin AForm := nil; if (AControl.Root is TCustomForm) then AForm := (AControl.Root as TCustomForm); if AForm <> nil then begin AFormPoint := AControl.LocalToAbsolute(PointF(X,Y)); AForm.MouseDown(TMouseButton.mbLeft, [], AFormPoint.X, AFormPoint.Y); AForm.MouseUp(TMouseButton.mbLeft, [], AFormPoint.X, AFormPoint.Y); end; end; procedure GenerateBadge(ACanvas: TCanvas; ATopLeft: TPointF; AValue: integer; AColor, ABackgroundColor, ATextColor: TAlphaColor); procedure DrawEllipse(ACanvas: TCanvas; ARect: TRectF; AColor: TAlphaColor); begin ACanvas.Fill.Color := AColor; ACanvas.FillEllipse(ARect, 1); ACanvas.Stroke.Color := AColor; ACanvas.StrokeThickness := 1; ACanvas.DrawEllipse(ARect, 1); end; var ABmp: TBitmap; AOutlineRect: TRectF; ARect: TRectF; r, r2: TRectF; s: single; begin s := GetScreenScale; ABmp := TBitmap.Create(Round(32*s), Round(32*s)); try ARect := RectF(ATopLeft.X, ATopLeft.Y, ATopLeft.X + 16, ATopLeft.Y + 16); AOutlineRect := ARect; InflateRect(AOutlineRect, GetScreenScale, GetScreenScale); ABmp.Clear(claNull); ABmp.Canvas.BeginScene; r := RectF(2, 2, 30*s, 30*s); r2 := RectF(0, 0, 32*s, 32*s); DrawEllipse(ABmp.Canvas, r2, ABackgroundColor); DrawEllipse(ABmp.Canvas, r, AColor); ABmp.Canvas.EndScene; ACanvas.DrawBitmap(ABmp, RectF(0, 0, ABmp.Width, ABmp.Height), ARect, 1, False); ACanvas.Fill.Color := ATextColor; ACanvas.Font.Size := 9; ACanvas.FillText(ARect, IntToStr(AValue), False, 1, [], TTextAlign.Center); finally FreeAndNil(ABmp); end; end; initialization AScreenScale := 0; ATextLayout := TTextLayoutManager.DefaultTextLayout.Create; finalization FreeAndNil(ATextLayout); end.
unit Project87.Types.SystemGenerator; interface uses Project87.Hero, Project87.Types.StarMap; type TSystemGenerator = class private class var FInstance: TSystemGenerator; private class var FEnemies: TEnemies; private FGenerator: Cardinal; constructor Create; function GenerateAsteroids(AStarSystem: TStarSystem): Single; procedure GenerateEnemies(AStarSystem: TStarSystem; SystemSize: Single); public function PRandom: Integer; overload; function PRandom(AMax: Integer): Integer; overload; function PRandom(AMin, AMax: Integer): Integer; overload; function SRandom: Single; class function GetLastEnemies: TEnemies; class function GetRemainingResources: TResources; class procedure GenerateSystem(AHero: THeroShip; AParameter: TStarSystem); end; implementation uses SysUtils, Generics.Collections, Strope.Math, QApplication.Application, Project87.BigEnemy, Project87.BaseEnemy, Project87.SmallEnemy, Project87.BaseUnit, Project87.Types.GameObject, Project87.Asteroid, Project87.Fluid; {$REGION ' Generator const '} const STABLE_NOISE_COMPONENT = 1; NOISE_MULTIPLIER = 22695477; {$ENDREGION} {$REGION ' TSystemGenerator '} constructor TSystemGenerator.Create; begin FGenerator := 1; end; function TSystemGenerator.PRandom: Integer; begin FGenerator := (NOISE_MULTIPLIER * FGenerator + STABLE_NOISE_COMPONENT) mod $ffffffff; Result := Abs(FGenerator); end; function TSystemGenerator.PRandom(AMax: Integer): Integer; begin Result := PRandom mod AMax; end; function TSystemGenerator.PRandom(AMin, AMax: Integer): Integer; begin Result := PRandom mod AMax + AMin; end; function TSystemGenerator.SRandom: Single; begin Result := PRandom(1000) / 1000; end; function TSystemGenerator.GenerateAsteroids(AStarSystem: TStarSystem): Single; var I, J, L, Count: Integer; Asteroid: TList<TAsteroid>; SystemRadius: Single; SizeFactor: Single; Resources: TResources; begin SizeFactor := 1; Count := -1; case AStarSystem.Size of ssSmall: begin SizeFactor := 0.6; Count := 90; end; ssMedium: begin SizeFactor := 1; Count := 180; end; ssBig: begin SizeFactor := 1.3; Count := 250; end; end; Asteroid := TList<TAsteroid>.Create(); SystemRadius := 3300 * SizeFactor; if (AStarSystem.Seed mod 10 = 0) then TAsteroid.CreateAsteroid( GetRotatedVector(PRandom(3600) / 10, SystemRadius - SRandom * SRandom * SystemRadius), PRandom(360), 120, TFluidType(I mod (FLUID_TYPE_COUNT)), 3); case AStarSystem.Configuration of scDischarged: begin for I := 0 to Count do Asteroid.Add(TAsteroid.CreateAsteroid( GetRotatedVector(PRandom(3600) / 10, SystemRadius - SRandom * SRandom * SystemRadius), PRandom(360), 20 + PRandom(120), TFluidType(I mod (FLUID_TYPE_COUNT)), PRandom(3))); end; scCompact: begin L := Round(4.3 * SizeFactor); for I := 1 to L do for J := 0 to I * 8 do Asteroid.Add(TAsteroid.CreateAsteroid( GetRotatedVector(J * (360 / (I * 8)) + SRandom * (360 / I * 8), SystemRadius / L * (I - 0.4) + SRandom * 180 * SizeFactor), PRandom(360), 20 + PRandom(120), TFluidType((I + J) mod (FLUID_TYPE_COUNT)), PRandom(3))); TObjectManager.GetInstance.SolveCollisions(10); end; scPlanet: //like a planetar system begin for I := 0 to count div 4 do Asteroid.Add(TAsteroid.CreateAsteroid( GetRotatedVector(PRandom(3600) / 10, PRandom(1000) / 1000 * SystemRadius * 0.8), PRandom(360), 20 + PRandom(80), TFluidType(I mod (FLUID_TYPE_COUNT)), PRandom(3))); TObjectManager.GetInstance.SolveCollisions(10); for I := 0 to count div 2 do Asteroid.Add(TAsteroid.CreateAsteroid( GetRotatedVector(PRandom(3600) / 10, SystemRadius - SRandom * SystemRadius * 0.05), PRandom(360), 20 + PRandom(100), TFluidType(I mod (FLUID_TYPE_COUNT)), PRandom(3))); for I := 0 to trunc(4.8 * SizeFactor) do Asteroid.Add(TAsteroid.CreateAsteroid( GetRotatedVector(PRandom(3600) / 10, PRandom(1000) / 1000 * SystemRadius * 0.35), PRandom(360), 80 + PRandom(150) * SizeFactor, TFluidType(I mod (FLUID_TYPE_COUNT)), PRandom(3))); end; end; //Resource division for J := 0 to FLUID_TYPE_COUNT - 1 do Resources[J] := AStarSystem.Resources[J]; for J := 0 to FLUID_TYPE_COUNT - 1 do for I := 0 to Asteroid.Count - 1 do if Asteroid[i].FluidType = TFluidType(J) then begin if Resources[J] >= Asteroid[i].MaxFluids then begin Asteroid[i].Fluids := PRandom(Asteroid[i].MaxFluids div 2) * (PRandom(2) + 1); Resources[J] := Resources[J] - Asteroid[i].Fluids; end else begin Asteroid[i].Fluids := Resources[J]; Resources[J] := Resources[J] - Asteroid[i].Fluids; end; if Resources[J] = 0 then Break; end; Asteroid.Free; Result := SystemRadius; end; procedure TSystemGenerator.GenerateEnemies(AStarSystem: TStarSystem; SystemSize: Single); var FFraction: TLifeFraction; SwarmCount, I, J: Word; Count: Single; SwarmPosition: TVectorF; SwarmType: Byte; begin for I := 0 to LIFEFRACTION_COUNT - 1 do FEnemies[I] := 0; for FFraction in AStarSystem.Fractions do begin case AStarSystem.Size of ssSmall: SwarmCount := 1; ssMedium: SwarmCount := 2; ssBig: SwarmCount := 4; end; Count:= AStarSystem.Enemies[Integer(FFraction)]; for I := 0 to SwarmCount do begin SwarmType := PRandom(3); SwarmPosition := GetRotatedVector(PRandom(360), PRandom(Trunc(SystemSize * 0.9))); case SwarmType of 0: for J := 1 to trunc(Count * 10) do begin FEnemies[Integer(FFraction)] := FEnemies[Integer(FFraction)] + 1; TSmallEnemy.CreateUnit(SwarmPosition + Vec2F(Random(300) - 150, Random(300) - 150), Random(360), FFraction); end; 1: for J := 1 to trunc(Count * 10) do begin FEnemies[Integer(FFraction)] := FEnemies[Integer(FFraction)] + 1; if J < 2 then TBigEnemy.CreateUnit(SwarmPosition + Vec2F(Random(300) - 150, Random(300) - 150), Random(360), FFraction) else TBaseEnemy.CreateUnit(SwarmPosition + Vec2F(Random(300) - 150, Random(300) - 150), Random(360), FFraction); end; 2: for J := 1 to trunc(Count * 10) do begin FEnemies[Integer(FFraction)] := FEnemies[Integer(FFraction)] + 1; if J < 3 then TBigEnemy.CreateUnit(SwarmPosition + Vec2F(Random(300) - 150, Random(300) - 150), Random(360), FFraction) else if J < 6 then TBaseEnemy.CreateUnit(SwarmPosition + Vec2F(Random(300) - 150, Random(300) - 150), Random(360), FFraction) else TSmallEnemy.CreateUnit(SwarmPosition + Vec2F(Random(300) - 150, Random(300) - 150), Random(360), FFraction); end; end; end; end; end; class function TSystemGenerator.GetLastEnemies: TEnemies; var I: Byte; Enemy: TList<TPhysicalObject>; Current: TPhysicalObject; Enemies: TEnemies; begin for I := 0 to LIFEFRACTION_COUNT - 1 do Enemies[I] := 0; Enemy := TObjectManager.GetInstance.GetObjects(TBaseEnemy); for Current in Enemy do Enemies[Integer(TBaseEnemy(Current).LifeFraction)] := Enemies[Integer(TBaseEnemy(Current).LifeFraction)] + 1; TheApplication.Window.Caption := IntToStr(trunc(Enemies[0])) + ' ' + IntToStr(trunc(Enemies[1])) + ' ' + IntToStr(trunc(Enemies[2])); Enemy.Free; for I := 0 to LIFEFRACTION_COUNT - 1 do if (FEnemies[I] > 0) then Enemies[I] := Enemies[I] / FEnemies[I]; Result := Enemies; end; class function TSystemGenerator.GetRemainingResources: TResources; var I: Byte; Asteroid: TList<TPhysicalObject>; Current: TPhysicalObject; Resources: TResources; begin for I := 0 to FLUID_TYPE_COUNT - 1 do Resources[I] := 0; Asteroid := TObjectManager.GetInstance.GetObjects(TAsteroid); I := 0; for Current in Asteroid do Resources[Integer(TAsteroid(Current).FluidType)] := Resources[Integer(TAsteroid(Current).FluidType)] + TAsteroid(Current).Fluids; Asteroid.Free; Result := Resources; end; class procedure TSystemGenerator.GenerateSystem(AHero: THeroShip; AParameter: TStarSystem); var I: Byte; SystemSize, Angle: Single; begin if (FInstance = nil) then FInstance := Create(); if AParameter <> nil then with FInstance do begin FGenerator := AParameter.Seed; SystemSize := GenerateAsteroids(AParameter); Angle := PRandom(360); AHero.FlyInSystem(GetRotatedVector(Angle, -SystemSize * 1.1), Angle); FGenerator := AParameter.Seed; GenerateEnemies(AParameter, SystemSize); { for FFraction in AParameter.Fractions do begin for I := 0 to 8 do TBigEnemy.CreateUnit(Vec2F(Random(5000) - 2500, Random(5000) - 2500), Random(360), FFraction); for I := 0 to 30 do TBaseEnemy.CreateUnit(Vec2F(Random(5000) - 2500, Random(5000) - 2500), Random(360), FFraction); for I := 0 to 20 do TSmallEnemy.CreateUnit(Vec2F(Random(5000) - 2500, Random(5000) - 2500), Random(360), FFraction); end; } end; end; {$ENDREGION} end.
unit lib.coc.basic; interface type TBasic = class(TObject) private FName: string; FBestTrophies: Integer; FVersusTrophies: integer; FWarStars: integer; FRole: string; FDonationsReceived: integer; FAttacksWin: integer; FTag: string; FBuilderHallLevel: integer; FBesVersusTrophies: integer; FTownHallLevel: integer; FExpLevel: integer; FTrophies: integer; FDonations: integer; FDefenseWin: integer; FVersusBattleWinCount: integer; procedure SetAttacksWin(const Value: integer); procedure SetBestTrophies(const Value: Integer); procedure SetBesVersusTrophies(const Value: integer); procedure SetBuilderHallLevel(const Value: integer); procedure SetDefenseWin(const Value: integer); procedure SetDonations(const Value: integer); procedure SetDonationsReceived(const Value: integer); procedure SetExpLevel(const Value: integer); procedure SetName(const Value: string); procedure SetRole(const Value: string); procedure SetTag(const Value: string); procedure SetTownHallLevel(const Value: integer); procedure SetTrophies(const Value: integer); procedure SetVersusTrophies(const Value: integer); procedure SetWarStars(const Value: integer); procedure SetVersusBattleWinCount(const Value: integer); published property Tag : string read FTag write SetTag; property Name : string read FName write SetName; property TownHallLevel : integer read FTownHallLevel write SetTownHallLevel; property ExpLevel : integer read FExpLevel write SetExpLevel; property Trophies : integer read FTrophies write SetTrophies; property BestTrophies : Integer read FBestTrophies write SetBestTrophies; property WarStars : integer read FWarStars write SetWarStars; property AttacksWin : integer read FAttacksWin write SetAttacksWin; property DefenseWin : integer read FDefenseWin write SetDefenseWin; property BuilderHallLevel :integer read FBuilderHallLevel write SetBuilderHallLevel; property VersusTrophies : integer read FVersusTrophies write SetVersusTrophies; property BesVersusTrophies : integer read FBesVersusTrophies write SetBesVersusTrophies; property Role : string read FRole write SetRole; property Donations: integer read FDonations write SetDonations; property DonationsReceived: integer read FDonationsReceived write SetDonationsReceived; property VersusBattleWinCount : integer read FVersusBattleWinCount write SetVersusBattleWinCount; procedure LoadValues(const AObject : TObject); end; implementation uses typInfo; { TBasic } procedure TBasic.LoadValues(const AObject : TObject); var PropIndex: Integer; PropCount: Integer; PropList: PPropList; PropInfo: PPropInfo; const TypeKinds: TTypeKinds = [tkEnumeration, tkString, tkLString, tkWString, tkUString, tkInteger]; begin PropCount := GetPropList(AObject.ClassInfo, TypeKinds, nil); GetMem(PropList, PropCount * SizeOf(PPropInfo)); try GetPropList(AObject.ClassInfo, TypeKinds, PropList); for PropIndex := 0 to PropCount - 1 do begin PropInfo := PropList^[PropIndex]; if Assigned(PropInfo^.SetProc) then case PropInfo^.PropType^.Kind of tkString, tkLString, tkUString, tkWString: SetStrProp(AObject, PropInfo, ''); tkEnumeration: if GetTypeData(PropInfo^.PropType^)^.BaseType^ = TypeInfo(Boolean) then SetOrdProp(AObject, PropInfo, 0); end; end; finally FreeMem(PropList); end; end; procedure TBasic.SetAttacksWin(const Value: integer); begin FAttacksWin := Value; end; procedure TBasic.SetBestTrophies(const Value: Integer); begin FBestTrophies := Value; end; procedure TBasic.SetBesVersusTrophies(const Value: integer); begin FBesVersusTrophies := Value; end; procedure TBasic.SetBuilderHallLevel(const Value: integer); begin FBuilderHallLevel := Value; end; procedure TBasic.SetDefenseWin(const Value: integer); begin FDefenseWin := Value; end; procedure TBasic.SetDonations(const Value: integer); begin FDonations := Value; end; procedure TBasic.SetDonationsReceived(const Value: integer); begin FDonationsReceived := Value; end; procedure TBasic.SetExpLevel(const Value: integer); begin FExpLevel := Value; end; procedure TBasic.SetName(const Value: string); begin FName := Value; end; procedure TBasic.SetRole(const Value: string); begin FRole := Value; end; procedure TBasic.SetTag(const Value: string); begin FTag := Value; end; procedure TBasic.SetTownHallLevel(const Value: integer); begin FTownHallLevel := Value; end; procedure TBasic.SetTrophies(const Value: integer); begin FTrophies := Value; end; procedure TBasic.SetVersusBattleWinCount(const Value: integer); begin FVersusBattleWinCount := Value; end; procedure TBasic.SetVersusTrophies(const Value: integer); begin FVersusTrophies := Value; end; procedure TBasic.SetWarStars(const Value: integer); begin FWarStars := Value; end; end.
unit LossTest; interface uses dbTest, dbMovementTest, ObjectTest; type TLossTest = class (TdbMovementTestNew) published procedure ProcedureLoad; override; procedure Test; override; end; TLoss = class(TMovementTest) private protected function InsertDefault: integer; override; public function InsertUpdateMovementLoss(Id: Integer; InvNumber: String; OperDate: TDateTime; UnitID, ArticleLossId: Integer): integer; constructor Create; override; end; implementation uses UtilConst, UnitsTest, dbObjectTest, SysUtils, Db, TestFramework, GoodsTest, ArticleLossTest; { TLoss } constructor TLoss.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_Movement_Loss'; spSelect := 'gpSelect_Movement_Loss'; spGet := 'gpGet_Movement_Loss'; end; function TLoss.InsertDefault: integer; var Id: Integer; InvNumber: String; OperDate: TDateTime; UnitID, ArticleLossId: Integer; begin Id:=0; InvNumber:='1'; OperDate:= Date; UnitId := TUnit.Create.GetDefault; ArticleLossId := TArticleLoss.Create.GetDefault; result := InsertUpdateMovementLoss(Id, InvNumber, OperDate, UnitId, ArticleLossId); end; function TLoss.InsertUpdateMovementLoss(Id: Integer; InvNumber: String; OperDate: TDateTime; UnitId, ArticleLossId: Integer):Integer; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inInvNumber', ftString, ptInput, InvNumber); FParams.AddParam('inOperDate', ftDateTime, ptInput, OperDate); FParams.AddParam('inUnitId', ftInteger, ptInput, UnitId); FParams.AddParam('inArticleLossId', ftInteger, ptInput, ArticleLossId); result := InsertUpdate(FParams); end; { TLossTest } procedure TLossTest.ProcedureLoad; begin ScriptDirectory := LocalProcedurePath + 'Movement\Loss\'; inherited; end; procedure TLossTest.Test; var MovementLoss: TLoss; Id: Integer; begin MovementLoss := TLoss.Create; // создание документа Id := MovementLoss.InsertDefault; try // редактирование finally // удаление DeleteMovement(Id); end; end; { TLossItem } initialization // TestFramework.RegisterTest('Документы', TLossTest.Suite); end.
// Color Library // (Also see PaletteLibrary for Palette-related routines) // // Earl F. Glynn, April 1998. Updated September 1998. UNIT ColorLibrary; INTERFACE USES Windows, // TRGBTRiple Graphics; // TBitmap, TPixelFormat CONST // 16 of the 20 System Palette Colors are defined in Graphics.PAS. // The additional 4 colors that NEVER dither, even in 256-color mode, // are as follows: (See Microsoft Systems Journal, Sept. 91, // page 119, for Windows 3.0 Default Palette. Interestingly, // some of the "standard" colors weren't always the same!) clMoneyGreen = TColor($C0DCC0); // Color "8" RGB: 192 220 192 clSkyBlue = TColor($F0CAA6); // Color "9" RGB: 166 202 240 clCream = TColor($F0FBFF); // Color "246" RGB: 255 251 240 clMediumGray = TColor($A4A0A0); // Color "247" RGB: 160 160 164 NonDitherColors: ARRAY[0..19] OF TColor = (clBlack, clMaroon, clGreen, clOlive, clNavy, clPurple, clTeal, clSilver, clMoneyGreen, clSkyblue, clCream, clMediumGray, clGray, clRed, clGreen, clYellow, clBlue, clFuchsia, clAqua, clWhite); // Windows 3.0 Default Palette is used with 8-bit bitmasks. These 20 values // are from the "Microsoft Systems Journal," Sept. 1991, p. 119. Use these // values when looking at the histogram for an 8-bit image. // // Only the first 8 colors display/print the same in 256 color, 16-bit // and 24-bit color modes. MaskBlack = 0; {RGB = 0 0 0} MaskDarkRed = 1; {128 0 0} MaskDarkGreen = 2; { 0 128 0} MaskPeaGreen = 3; {128 128 0} MaskDarkBlue = 4; { 0 0 128} MaskLavender = 5; {128 0 128} MaskSlate = 6; { 0 128 128} MaskLightGray = 7; {192 192 192} TYPE TColorSpace = (csRGB, csHSV, csHLS, csCMYK); TColorPlane = (cpRGB, {really a composite of csRed, csGreen, csBlue} cpRed, cpGreen, cpBlue, cpHueHSV, cpSaturationHSV, cpValue, // HSV cpHueHLS, cpLightness, cpSaturationHLS, // HLS cpCyan, cpMagenta, cpYellow, cpBlack, // CMYK cpIntensity, cpY); // Y in YIQ coordinates // Miscellaneous FUNCTION GetColorPlaneString(CONST ColorPlane: TColorPlane): STRING; FUNCTION ExtractImagePlane (CONST ColorPlane: TColorPlane; CONST ColorOutput: BOOLEAN; CONST Invert: BOOLEAN; CONST OriginalBitmap: TBitmap): TBitmap; // Color Conversions // HLS FUNCTION HLSToRGBTriple (CONST H,L,S: INTEGER): TRGBTriple; PROCEDURE RGBTripleToHLS (CONST RGBTriple: TRGBTriple; VAR H,L,S: INTEGER); // HSV FUNCTION HSVToRGBTriple (CONST H,S,V: INTEGER): TRGBTriple; PROCEDURE RGBTripleToHSV (CONST RGBTriple: TRGBTriple; VAR H,S,V: INTEGER); // CMY FUNCTION CMYToRGBTriple (CONST C,M,Y: INTEGER): TRGBTriple; PROCEDURE RGBTripleToCMY(CONST RGB: TRGBTriple; // r, g and b IN [0..255] VAR C,M,Y: INTEGER); // c, m and y IN [0..255] // CMYK FUNCTION CMYKToRGBTriple (CONST C,M,Y,K: INTEGER): TRGBTriple; PROCEDURE RGBTripleToCMYK(CONST RGB: TRGBTriple; VAR C,M,Y,K: INTEGER); IMPLEMENTATION USES Dialogs, // ShowMessage Math, // MaxIntValue, MaxValue IEEE754, // NAN (not a number) ImageProcessingPrimitives, // pRGBTripleArray RealColorLibrary, // HLStoRGB SysUtils; // Exception TYPE EColorError = CLASS(Exception); // == Miscellaneous ================================================= FUNCTION GetColorPlaneString(CONST ColorPlane: TColorPlane): STRING; BEGIN CASE ColorPlane OF cpRGB: RESULT := 'RGB Composite'; cpRed: RESULT := 'Red'; cpGreen: RESULT := 'Green'; cpBlue: RESULT := 'Blue'; cpHueHSV: RESULT := 'Hue (HSV)'; cpSaturationHSV: RESULT := 'Saturation (HSV)'; cpValue: RESULT := 'Value (HSV)'; cpHueHLS: RESULT := 'Hue (HLS)'; cpLightness: RESULT := 'Lightness'; cpSaturationHLS: RESULT := 'Saturation (HLS)'; cpIntensity: RESULT := 'Intensity'; END END {GetColorPlaneString}; FUNCTION ExtractImagePlane (CONST ColorPlane: TColorPlane; CONST ColorOutput: BOOLEAN; CONST Invert: BOOLEAN; CONST OriginalBitmap: TBitmap): TBitmap; VAR C,M,Y,K : INTEGER; H,S,V : INTEGER; // color coordinates i : INTEGER; Intensity : INTEGER; j : INTEGER; L : INTEGER; Triple : TRGBTriple; RowOriginal : pRGBTripleArray; RowProcessed: pRGBTripleArray; BEGIN IF OriginalBitmap.PixelFormat <> pf24bit THEN RAISE EColorError.Create('GetImageSpace: ' + 'Bitmap must be 24-bit color.'); RESULT := TBitmap.Create; RESULT.Width := OriginalBitmap.Width; RESULT.Height := OriginalBitmap.Height; RESULT.PixelFormat := OriginalBitmap.PixelFormat; // Step through each row of image. FOR j := OriginalBitmap.Height-1 DOWNTO 0 DO BEGIN RowOriginal := OriginalBitmap.Scanline[j]; RowProcessed := RESULT.Scanline[j]; FOR i := OriginalBitmap.Width-1 DOWNTO 0 DO BEGIN CASE ColorPlane OF // =============================================================== cpRGB: IF ColorOutput THEN RowProcessed[i] := RowOriginal[i] ELSE BEGIN Intensity := RGBTripleToIntensity(RowOriginal[i]); RowProcessed[i] := RGBtoRGBTriple(Intensity, Intensity, Intensity) END; cpRed: IF ColorOutput THEN RowProcessed[i] := RGBtoRGBTriple(RowOriginal[i].rgbtRed, 0, 0) ELSE BEGIN Intensity := RowOriginal[i].rgbtRed; RowProcessed[i] := RGBtoRGBTriple(Intensity, Intensity, Intensity) END; cpGreen: IF ColorOutput THEN RowProcessed[i] := RGBtoRGBTriple(0, RowOriginal[i].rgbtGreen, 0) ELSE BEGIN Intensity := RowOriginal[i].rgbtGreen; RowProcessed[i] := RGBtoRGBTriple(Intensity, Intensity, Intensity) END; cpBlue: IF ColorOutput THEN RowProcessed[i] := RGBtoRGBTriple(0, 0, RowOriginal[i].rgbtBlue) ELSE BEGIN Intensity := RowOriginal[i].rgbtBlue; RowProcessed[i] := RGBtoRGBTriple(Intensity, Intensity, Intensity) END; // =============================================================== cpHueHSV: BEGIN RGBTripleToHSV(RowOriginal[i], H,S,V); // "Shades" of Hue with full saturation and value. RowProcessed[i] := HSVtoRGBTriple(H, 255, 255); IF NOT ColorOutput THEN BEGIN Intensity := RGBTripleToIntensity(RowProcessed[i]); RowProcessed[i] := RGBtoRGBTriple(Intensity, Intensity, Intensity) END END; cpSaturationHSV: BEGIN RGBTripletoHSV(RowOriginal[i], H,S,V); // "Shades" of Saturation RowProcessed[i] := RGBtoRGBTriple(S,S,S) END; cpValue: BEGIN RGBTripleToHSV(RowOriginal[i], H,S,V); // "Shades" of Value RowProcessed[i] := RGBtoRGBTriple(V,V,V) END; // =============================================================== cpHueHLS: BEGIN RGBTripleToHLS(RowOriginal[i], H,L,S); // "Shades" of Hue with half lightness and full saturation. RowProcessed[i] := HLStoRGBTriple(H, 128,255); IF NOT ColorOutput THEN BEGIN Intensity := RGBTripleToIntensity(RowProcessed[i]); RowProcessed[i] := RGBtoRGBTriple(Intensity, Intensity, Intensity) END END; cpLightness: BEGIN RGBTripleToHLS(RowOriginal[i], H,L,S); // "Shades" of Lightness RowProcessed[i] := RGBtoRGBTriple(L,L,L) END; cpSaturationHLS: BEGIN RGBTripleToHLS(RowOriginal[i], H,L,S); // Shades of Saturation RowProcessed[i] := RGBtoRGBTriple(S,S,S) END; // =============================================================== cpCyan: BEGIN RGBTripleToCMYK(RowOriginal[i], C,M,Y,K); // Shades of Cyan RowProcessed[i] := RGBtoRGBTriple(C,C,C) END; cpMagenta: BEGIN RGBTripleToCMYK(RowOriginal[i], C,M,Y,K); // Shades of Magenta RowProcessed[i] := RGBtoRGBTriple(M,M,M) END; cpYellow: BEGIN RGBTripleToCMYK(RowOriginal[i], C,M,Y,K); // Shades of Yellow RowProcessed[i] := RGBtoRGBTriple(Y,Y,Y) END; cpBlack: BEGIN RGBTripleToCMYK(RowOriginal[i], C,M,Y,K); // Shades of "Black" RowProcessed[i] := RGBtoRGBTriple(K,K,K) END; // =============================================================== cpIntensity: BEGIN Intensity := RGBTripleToIntensity(RowOriginal[i]); // Shades of Intensity RowProcessed[i] := RGBtoRGBTriple(Intensity, Intensity, Intensity) END END; {Case} IF Invert THEN RowProcessed[i] := RGBTripleInvert( RowProcessed[i] ) END; END END {ExtractImagePlane}; // == HLS / RGB ======================================================= // // Based on C Code in "Computer Graphics -- Principles and Practice," // Foley et al, 1996, p. 596. FUNCTION HLStoRGBTriple (CONST H,L,S: INTEGER): TRGBTriple; VAR R,G,B: TReal; BEGIN HLStoRGB(H, L/255, S/255, R,G,B); RESULT := ColorToRGBTriple( RGB(ROUND(255*R), ROUND(255*G), ROUND(255*B)) ) END {HLStoRGBTriple}; // RGB to HLS // H = 0 to 360 (corresponding to 0..360 degrees around hexcone) // L = 0 (shade of gray) to 255 (pure color) // S = 0 (black) to 255 {white) // // R, G, B each in [0, 255] PROCEDURE RGBTripleToHLS (CONST RGBTriple: TRGBTriple; VAR H,L,S: INTEGER); VAR Hue : TReal; Lightness : TReal; Saturation: TReal; BEGIN WITH RGBTriple DO RGBToHLS(rgbtRed/255, rgbtGreen/255, rgbtBlue/255, Hue, Lightness, Saturation); IF IsNan(Hue) THEN H := 0 ELSE H := ROUND(Hue); // 0..360 L := ROUND(255*Lightness); // 0..255 S := ROUND(255*Saturation); // 0..255 END {RGBTripleToHLS}; // Floating point fractions, 0..1, replaced with integer values, 0..255. // Use integer conversion ONLY for one-way, or a single final conversions. // Use floating-point for converting reversibly (see HSVtoRGB above). // // H = 0 to 360 (corresponding to 0..360 degrees around hexcone) // 0 (undefined) for S = 0 // S = 0 (shade of gray) to 255 (pure color) // V = 0 (black) to 255 (white) FUNCTION HSVtoRGBTriple (CONST H,S,V: INTEGER): TRGBTriple; CONST divisor: INTEGER = 255*60; VAR f : INTEGER; hTemp: INTEGER; p,q,t: INTEGER; VS : INTEGER; BEGIN IF S = 0 THEN RESULT := RGBtoRGBTriple(V, V, V) // achromatic: shades of gray ELSE BEGIN // chromatic color IF H = 360 THEN hTemp := 0 ELSE hTemp := H; f := hTemp MOD 60; // f is IN [0, 59] hTemp := hTemp DIV 60; // h is now IN [0,6) VS := V*S; p := V - VS DIV 255; // p = v * (1 - s) q := V - (VS*f) DIV divisor; // q = v * (1 - s*f) t := V - (VS*(60 - f)) DIV divisor; // t = v * (1 - s * (1 - f)) CASE hTemp OF 0: RESULT := RGBtoRGBTriple(V, t, p); 1: RESULT := RGBtoRGBTriple(q, V, p); 2: RESULT := RGBtoRGBTriple(p, V, t); 3: RESULT := RGBtoRGBTriple(p, q, V); 4: RESULT := RGBtoRGBTriple(t, p, V); 5: RESULT := RGBtoRGBTriple(V, p, q); ELSE RESULT := RGBtoRGBTriple(0,0,0) // should never happen; // avoid compiler warning END END END {HSVtoRGBTriple}; // RGB, each 0 to 255, to HSV. // H = 0 to 360 (corresponding to 0..360 degrees around hexcone) // S = 0 (shade of gray) to 255 (pure color) // V = 0 (black) to 255 {white) // Based on C Code in "Computer Graphics -- Principles and Practice," // Foley et al, 1996, p. 592. Floating point fractions, 0..1, replaced with // integer values, 0..255. PROCEDURE RGBTripleToHSV (CONST RGBTriple: TRGBTriple; {r, g and b IN [0..255]} VAR H,S,V: INTEGER); {h IN 0..359; s,v IN 0..255} VAR Delta: INTEGER; Min : INTEGER; BEGIN WITH RGBTriple DO BEGIN Min := MinIntValue( [rgbtRed, rgbtGreen, rgbtBlue] ); V := MaxIntValue( [rgbtRed, rgbtGreen, rgbtBlue] ) END; Delta := V - Min; // Calculate saturation: saturation is 0 if r, g and b are all 0 IF V = 0 THEN S := 0 ELSE S := MulDiv(Delta, 255, V); IF S = 0 THEN H := 0 // Achromatic: When s = 0, h is undefined but assigned the value 0 ELSE BEGIN // Chromatic WITH RGBTriple DO BEGIN IF rgbtRed = V THEN // degrees -- between yellow and magenta H := MulDiv(rgbtGreen - rgbtBlue, 60, Delta) ELSE IF rgbtGreen = V THEN // between cyan and yellow H := 120 + MulDiv(rgbtBlue-rgbtRed, 60, Delta) ELSE IF rgbtBlue = V THEN // between magenta and cyan H := 240 + MulDiv(rgbtRed-rgbtGreen, 60, Delta); END; IF H < 0 THEN H := H + 360; END END {RGBTripleToHSV}; // == CMY / RGB ======================================================= // // Based on C Code in "Computer Graphics -- Principles and Practice," // Foley et al, 1996, p. 588 // R, G, B, C, M, Y each IN [0..255] FUNCTION CMYtoRGBTriple (CONST C,M,Y: INTEGER): TRGBTriple; BEGIN WITH RESULT DO BEGIN rgbtRed := 255 - C; rgbtGreen := 255 - M; rgbtBlue := 255 - Y END END {CMYtoRGBTriple}; // R, G, B, C, M, Y each IN [0..255] PROCEDURE RGBTripleToCMY(CONST RGB: TRGBTriple; VAR C,M,Y: INTEGER); BEGIN WITH RGB DO BEGIN C := 255 - rgbtRed; M := 255 - rgbtGreen; Y := 255 - rgbtBlue END END {RGBtoCMY}; // == CMYK / RGB ====================================================== // // Based on C Code in "Computer Graphics -- Principles and Practice," // Foley et al, 1996, p. 589 // R, G, B, C, M, Y,K each IN [0..255] FUNCTION CMYKtoRGBTriple (CONST C,M,Y,K: INTEGER): TRGBTriple; BEGIN WITH RESULT DO BEGIN rgbtRed := 255 - (C + K); rgbtGreen := 255 - (M + K); rgbtBlue := 255 - (Y + K) END END {CMYtoRGBTriple}; // R, G, B, C, M, Y each IN [0..255] PROCEDURE RGBTripleToCMYK(CONST RGB: TRGBTriple; VAR C,M,Y,K: INTEGER); BEGIN RGBTripleToCMY(RGB, C,M,Y); K := MinIntValue([C, M, Y]); C := C - K; M := M - K; Y := Y - K END {RGBtoCMYK}; END.
program e1p6; uses crt; const MAX_ELEMENTOS = 9; type arInt = ^tArInt; tArInt = record num:integer; men:arInt; may:arInt; end; archivo = file of integer; //////////////////////////////////////////////////////////////////////// procedure verificarExisteArchivo(var arch:archivo; var error:boolean); begin {$i-} reset(arch); {$i+} if (ioresult <> 0) then error:=true; end; procedure cargarArchivo(var arch:archivo); var contador:integer; num:integer; begin contador:=0; writeln('INGRESE ELEMENTOS:'); while (contador < MAX_ELEMENTOS) do begin readln(num); write(arch, num); contador:=contador+1; end; end; procedure insertarNodo(var arbol:arInt; nodo:arInt); begin if (arbol = nil) then arbol:=nodo else if (arbol^.num > nodo^.num) then insertarNodo(arbol^.men, nodo) else if (arbol^.num < nodo^.num) then insertarNodo(arbol^.may, nodo); end; procedure crearNodo(var nodo:arInt; num:integer); begin new(nodo); nodo^.num:=num; nodo^.men:=nil; nodo^.may:=nil; end; procedure cargarArbol(var arch:archivo; var arbol:arInt); var nodo:arInt; num:integer; begin nodo:=nil; reset(arch); while not eof(arch) do begin read(arch, num); crearNodo(nodo, num); insertarNodo(arbol, nodo); end; end; procedure imprimirAscendentemente(arbol:arInt); begin if (arbol <> nil) then begin imprimirAscendentemente(arbol^.men); write(arbol^.num,' '); imprimirAscendentemente(arbol^.may); end; end; procedure imprimirDescendentemente(arbol:arInt); begin if (arbol <> nil) then begin imprimirDescendentemente(arbol^.may); write(arbol^.num,' '); imprimirDescendentemente(arbol^.men); end; end; procedure imprimirPreOrden(arbol:arInt); begin if (arbol <> nil) then begin write(arbol^.num,' '); imprimirPreOrden(arbol^.men); imprimirPreOrden(arbol^.may); end; end; procedure buscarMenor(arbol:arInt; var menor:integer); begin if (arbol <> nil) then if (arbol^.num >= menor) then buscarMenor(arbol^.men, menor) else if (arbol^.num < menor) then menor:=arbol^.num; end; procedure calcularMayorRama(arbol:arInt; var longitud:integer; longActual:integer); begin if (arbol <> nil) then begin calcularMayorRama(arbol^.men, longitud, longActual+1); if (longitud < longActual) then longitud:=longActual; calcularMayorRama(arbol^.may, longitud, longActual+1); end; end; function retornaCantidad(arbol:arInt):integer; begin if (arbol = nil) then retornaCantidad:=0 else retornaCantidad:=retornaCantidad(arbol^.men) + 1 + retornaCantidad(arbol^.may); end; procedure eliminarArbol(var arbol:arInt); begin if (arbol <> nil) then begin eliminarArbol(arbol^.men); dispose(arbol); eliminarArbol(arbol^.may); end; end; //////////////////////////////////////////////////////////////////////// var arch:archivo; arbol:arInt; error:boolean; menor, longitud, longActual:integer; begin error:=false; arbol:=nil; assign(arch,'enteros.dat'); verificarExisteArchivo(arch, error); if (error) then begin rewrite(arch); cargarArchivo(arch); end; cargarArbol(arch, arbol); writeln('ARBOL ASCENDIENTEMENTE:'); imprimirAscendentemente(arbol); writeln; writeln('ARBOL DESCENDIENTEMENTE:'); imprimirDescendentemente(arbol); writeln; writeln('ARBOL PRE-ORDEN:'); imprimirPreOrden(arbol); menor:=arbol^.num; buscarMenor(arbol, menor); writeln; writeln('EL MENOR ES:',menor); longActual:=0; longitud:=0; calcularMayorRama(arbol, longitud, longActual); writeln('LA MAYOR LONGITUD ES: ',longitud); writeln('LA CANTIDAD DE NODOS DEL ARBOL ES:', retornaCantidad(arbol)); eliminarArbol(arbol); close(arch); end.
{* ***************************************************************************** PROYECTO FACTURACION ELECTRONICA Copyright (C) 2010-2014 - Bambu Code SA de CV - Ing. Luis Carrasco Esta clase representa un Comprobante Fiscal Digital en su Version 2.0 asi como los metodos para generarla. Este archivo pertenece al proyecto de codigo abierto de Bambu Code: http://bambucode.com/codigoabierto La licencia de este codigo fuente se encuentra en: http://github.com/bambucode/tfacturaelectronica/blob/master/LICENCIA Cambios para CFDI v3.2 Por Ing. Pablo Torres TecSisNet.net Cd. Juarez Chihuahua el 11-24-2013 ***************************************************************************** *} unit ComprobanteFiscal; interface uses FacturaTipos, SysUtils, // Unidades especificas de manejo de XML: {$IF Compilerversion >= 20} Xml.xmldom, Xml.XMLIntf, Xml.Win.MsXmlDom, Xml.XMLDoc, {$ELSE} XmlDom, XMLIntf, Xml.win.MsXmlDom, XMLDoc, {$ENDIF} DocComprobanteFiscal, FeCFDv22,FeCFDv32, FeCFDv2, feCFD; type // Excepciones que pueden ser generadas EFEFolioFueraDeRango = class(Exception); EFEXMLVacio = class(Exception); {$REGION 'Documentation'} /// <summary> /// Excepcion lanzada cuando se intenta generar una factura sin ningun concepto /// </summary> {$ENDREGION} EFESinConceptosException = class(Exception); /// <summary>Representa la estructura de comprobante fiscal digital (ver2.2) y sus elementos /// definidos de acuerdo al XSD del SAT. Esta pensado para ser extendido en las versiones /// posteriores que el SAT publique (ver3.0, ver4.0, etc.). /// Se encarga de validar y formatear todos los datos de la factura que le sean proporcionados /// </summary> TFEComprobanteFiscal = class(TDocumentoComprobanteFiscal) {$IFDEF VERSION_DE_PRUEBA} public {$ELSE} private {$ENDIF} // Variables internas fDocumentoXML: TXMLDocument; // Referencia a un comprobante "comun" que puede ser v2.0 o v2.2 o v3.2 fXmlComprobante: IFEXMLComprobante; // Propiedades exclusivas del comprobante digital: fCadenaOriginalCalculada: TStringCadenaOriginal; fSelloDigitalCalculado: String; fCertificado: TFECertificado; fCertificadoTexto: WideString; fBloqueFolios: TFEBloqueFolios; fTimbre : TFETimbre; fVersion : TFEVersionComprobante; fComprobanteLleno: Boolean; // Opciones de configuracion _CADENA_PAGO_UNA_EXHIBICION: String; _CADENA_PAGO_PARCIALIDADES: String; fDesglosarTotalesImpuestos: Boolean; bIncluirCertificadoEnXML: Boolean; fAutoAsignarFechaGeneracion: Boolean; FValidarCertificadoYLlavePrivada: Boolean; FVerificarRFCDelCertificado: Boolean; fRecalcularImporte : Boolean; {$REGION 'Documentation'} /// <summary> /// Este metodo es llamado cuando estamos generando el XML del /// comprobante y se encarga de asignar el XML del timbre del nodo /// "Complemento". /// </summary> {$ENDREGION} procedure AgregarTimbreFiscalAlXML; procedure LlenarComprobante; procedure setCertificado(Certificado: TFECertificado); function getCadenaOriginal(): TStringCadenaOriginal; function getSelloDigital(): String; procedure setBloqueFolios(Bloque: TFEBloqueFolios); procedure ValidarQueFolioEsteEnRango; procedure AsignarCondicionesDePago; procedure AsignarEmisor; procedure AsignarReceptor; procedure AsignarContenidoCertificado; procedure AsignarConceptos; procedure AsignarImpuestosRetenidos; procedure AsignarImpuestosTrasladados; procedure AsignarDatosFolios; procedure AsignarFolio; procedure AsignarFormaDePago; procedure AsignarSubtotal; procedure AsignarTotal; procedure AsignarDescuentos; procedure AsignarMetodoDePago; procedure AsignarTipoComprobante; procedure AsignarExpedidoEn; procedure AsignarTotalesImpuestos; procedure AsignarFechaGeneracion; procedure AsignarLugarExpedicion; procedure AsignarNumeroDeCuenta; procedure AgregarAtributoOpcionalSiNoEstaVacio(const nodoXML: IXMLNode; const aPropiedad: string; const aValorAsignar : String); procedure AgregarComplementos; {$REGION 'Documentation'} /// <summary> /// Agrega un Domicilio Fiscal de acuerdo a las leyes de validacion de /// CFDI 3.2 /// </summary> {$ENDREGION} procedure AgregarDireccionFiscalv32(const aNodoContribuyente: IXMLNode; const aDireccionContribuyente: TFEDireccion); procedure AsignarImpuestosLocales; function ConvertirCadenaMetodoPagoaNumero(const aCadenaMetodoPago: String): String; {$REGION 'Documentation'} /// <summary> /// Este metodo es llamado cuando leemos un XML (a través del metodo /// setXML) para leer las propiedades del TimbreFiscalDigital /// </summary> {$ENDREGION} procedure LeerPropiedadesDeTimbre; procedure EstablecerVersionDelComprobante; function GetCadenaOriginalTimbre: TStringCadenaOriginal; function GetTimbre: TFETimbre; procedure LeerImpuestosLocales; procedure LeerVersionDeComprobanteLeido(const aDocumentoXML: WideString); function ObtenerFechaHoraDeGeneracionActual: TDateTime; procedure ValidarCamposEmisor; procedure ValidarCamposReceptor; procedure ValidarCertificado; protected fFueTimbrado: Boolean; procedure GenerarComprobante; function getXML: WideString; virtual; procedure setXML(const Valor: WideString); virtual; {$IFDEF VERSION_DE_PRUEBA} public _USAR_HORA_REAL : Boolean; {$ELSE} protected {$ENDIF} public const VERSION_ACTUAL = '3.2'; // Version del CFD que implementa este código {$REGION 'Documentation'} /// <summary> /// Se encarga de crear un nuevo CFD, por default crea el CFD con la /// versión mas reciente o que debe ser de acuerdo a la vigencia /// </summary> /// <param name="aVersionComprobante"> /// Version del comprobante a crear /// </param> {$ENDREGION} constructor Create(const aVersionComprobante: TFEVersionComprobante = fev32; aRecalcularImporte: Boolean = True); destructor Destroy(); override; procedure Cancelar(); deprecated; // Propiedades especificas al comprobante electronico property BloqueFolios: TFEBloqueFolios read fBloqueFolios write setBloqueFolios; property XML: WideString read getXML write setXML; property CadenaOriginal: TStringCadenaOriginal read getCadenaOriginal; property SelloDigital: String read getSelloDigital; property CertificadoTexto : WideString read fCertificadoTexto write fCertificadoTexto; property Certificado: TFECertificado read fCertificado write setCertificado; property DesglosarTotalesImpuestos: Boolean read fDesglosarTotalesImpuestos write fDesglosarTotalesImpuestos; property IncluirCertificadoEnXml: Boolean read bIncluirCertificadoEnXML write bIncluirCertificadoEnXML default true; property AutoAsignarFechaGeneracion : Boolean read fAutoAsignarFechaGeneracion write fAutoAsignarFechaGeneracion default true; property CadenaOriginalTimbre: TStringCadenaOriginal read GetCadenaOriginalTimbre; property Timbre: TFETimbre read GetTimbre; property ValidarCertificadoYLlavePrivada: Boolean read FValidarCertificadoYLlavePrivada write FValidarCertificadoYLlavePrivada default true; property VerificarRFCDelCertificado: Boolean read FVerificarRFCDelCertificado write FVerificarRFCDelCertificado; property Version : TFEVersionComprobante read fVersion; {$REGION 'Documentation'} /// <summary> /// Evento llamado cuando hemos recibido el timbre de parte del PAC para /// asignarle el mismo al CFD de forma interna así como al XML. /// </summary> {$ENDREGION} procedure AsignarTimbreFiscal(const aTimbre: TFETimbre); virtual; procedure BorrarConceptos; override; /// <summary>Guarda una copia del XML en el archivo indicado</summary> /// <param name="ArchivoFacturaXML">Ruta completa con nombre de archivo en el que se /// almacenara el XML del comprobante</param> procedure GuardarEnArchivo(sArchivoDestino: String); end; const // A partir del 6 de Mayo de 2016, usamos el numero de catalogo del SAT _CADENA_METODO_PAGO_NO_DISPONIBLE = '98'; // Antes cadena "No identificado". implementation uses FacturaReglamentacion, ClaseOpenSSL, StrUtils, SelloDigital, Classes, CadenaOriginal, ClaseCertificadoSellos, CadenaOriginalTimbre, {$IFDEF DEBUG} Dialogs, {$ENDIF} FETimbreFiscalDigital, FEImpuestosLocales, {$IFDEF CODESITE} CodeSiteLogging, {$ENDIF} DateUtils; // Al crear el objeto, comenzamos a "llenar" el XML interno constructor TFEComprobanteFiscal.Create(const aVersionComprobante: TFEVersionComprobante = fev32; aRecalcularImporte: Boolean = True); begin inherited Create(aRecalcularImporte); _CADENA_PAGO_UNA_EXHIBICION := 'Pago en una sola exhibición'; _CADENA_PAGO_PARCIALIDADES := 'En parcialidades'; {$IFDEF VERSION_DE_PRUEBA} _USAR_HORA_REAL := False; {$ENDIF} // Almacenamos si queremos recalcular el Importe fRecalcularImporte := aRecalcularImporte; // Ahora La decisión de que tipo de comprobante y su versión deberá de ser del programa y no de la clase fVersion:=aVersionComprobante; // Establecemos como default que SI queremos incluir el certificado en el XML // ya que presenta la ventaja de poder validar el comprobante con solo el archivo // XML. fAutoAsignarFechaGeneracion := True; bIncluirCertificadoEnXML := True; fDesglosarTotalesImpuestos := True; fCadenaOriginalCalculada := ''; fSelloDigitalCalculado := ''; fFueTimbrado := False; FValidarCertificadoYLlavePrivada := True; // Creamos el objeto XML fDocumentoXML := TXMLDocument.Create(nil); fDocumentoXML.Active := True; // Obtenemos el elemento "Comprobante" para llenar sus datos... case fVersion of fev20: fXmlComprobante := GetComprobante(fDocumentoXML); fev22: fXmlComprobante := GetComprobanteV22(fDocumentoXML); fev32: fXmlComprobante := GetComprobanteV32(fDocumentoXML); end; // De acuerdo a los articulos 29 y 29-A del CFF EstablecerVersionDelComprobante; end; destructor TFEComprobanteFiscal.Destroy(); begin // Al ser una interface el objeto TXMLDocument se libera automaticamente por Delphi al dejar de ser usado // aunque para asegurarnos hacemos lo siguiente: //fXmlComprobante := nil; inherited; end; procedure TFEComprobanteFiscal.AgregarAtributoOpcionalSiNoEstaVacio(const nodoXML: IXMLNode; const aPropiedad: string; const aValorAsignar : String); begin // Checamos si el atributo opcional NO esta vacio if Trim(aValorAsignar) <> '' then begin nodoXML.Attributes[aPropiedad] := aValorAsignar; end; end; procedure TFEComprobanteFiscal.AgregarComplementos; begin AsignarImpuestosLocales; end; procedure TFEComprobanteFiscal.AgregarDireccionFiscalv32(const aNodoContribuyente: IXMLNode; const aDireccionContribuyente: TFEDireccion); begin aNodoContribuyente.Attributes['calle'] := TFEReglamentacion.ComoCadena(aDireccionContribuyente.Calle); //AgregarAtributoOpcionalSiNoEstaVacio(aNodoContribuyente, 'Calle', aDireccionContribuyente.Calle); AgregarAtributoOpcionalSiNoEstaVacio(aNodoContribuyente, 'noExterior', aDireccionContribuyente.NoExterior); AgregarAtributoOpcionalSiNoEstaVacio(aNodoContribuyente, 'noInterior', aDireccionContribuyente.NoInterior); AgregarAtributoOpcionalSiNoEstaVacio(aNodoContribuyente, 'colonia', TFEReglamentacion.ComoCadena(aDireccionContribuyente.Colonia)); AgregarAtributoOpcionalSiNoEstaVacio(aNodoContribuyente, 'localidad', TFEReglamentacion.ComoCadena(aDireccionContribuyente.Localidad)); AgregarAtributoOpcionalSiNoEstaVacio(aNodoContribuyente, 'referencia', TFEReglamentacion.ComoCadena(aDireccionContribuyente.Referencia)); AgregarAtributoOpcionalSiNoEstaVacio(aNodoContribuyente, 'municipio', TFEReglamentacion.ComoCadena(aDireccionContribuyente.Municipio)); AgregarAtributoOpcionalSiNoEstaVacio(aNodoContribuyente, 'estado', TFEReglamentacion.ComoCadena(aDireccionContribuyente.Estado)); // Requerido aNodoContribuyente.Attributes['pais'] := TFEReglamentacion.ComoCadena(aDireccionContribuyente.Pais); AgregarAtributoOpcionalSiNoEstaVacio(aNodoContribuyente, 'codigoPostal', TFEReglamentacion.ComoCadena(aDireccionContribuyente.CodigoPostal)); end; procedure TFEComprobanteFiscal.AgregarTimbreFiscalAlXML; var xmlTimbrado: WideString; const _CARACTER_RETORNO_DE_CARRO = #13#10; begin Assert(fTimbre.XML <> '', 'El timbre interno fue nulo'); // Debido a que el nodo XML trae retornos de carro al final, los removemos para no tener diferencias // en el XML (por si fue leido) xmlTimbrado := StringReplace(fTimbre.XML, _CARACTER_RETORNO_DE_CARRO, '', [rfReplaceAll, rfIgnoreCase]); // Creamos un nuevo nodo complemento y le asignamos el XML del Timbre // Ref: http://stackoverflow.com/questions/16743380/string-to-xmlnode-delphi-or-how-to-add-an-xml-fragment-to-txmldocument IFEXmlComprobanteV32(fXmlComprobante).Complemento.ChildNodes.Add(LoadXMLData(xmlTimbrado).DocumentElement); fFueTimbrado := True; end; procedure TFEComprobanteFiscal.AsignarCondicionesDePago; begin if Trim(inherited CondicionesDePago) <> '' then fXmlComprobante.CondicionesDePago := TFEReglamentacion.ComoCadena(inherited CondicionesDePago); end; procedure TFEComprobanteFiscal.AsignarDescuentos; begin // Si el descuento es cero NO lo asignamos en v3.2 ya que se agregaria incorrectamente a la cadena original if fVersion = fev32 then if (inherited DescuentoMonto) = 0 then exit; fXmlComprobante.Descuento := TFEReglamentacion.ComoMoneda(inherited DescuentoMonto); if Trim(inherited DescuentoMotivo) <> '' then fXmlComprobante.MotivoDescuento := TFEReglamentacion.ComoCadena(inherited DescuentoMotivo); end; function TFEComprobanteFiscal.getCadenaOriginal(): TStringCadenaOriginal; var CadenaOriginal: TCadenaOriginal; begin if FacturaGenerada = True then begin Result:=fCadenaOriginalCalculada; end else begin // Si aun no ha sido generada la factura la "llenamos" LlenarComprobante; try CadenaOriginal:=TCadenaOriginal.Create(fXmlComprobante, fVersion); fCadenaOriginalCalculada:=CadenaOriginal.Calcular; Result:=fCadenaOriginalCalculada; finally FreeAndNil(CadenaOriginal); end; end; end; function TFEComprobanteFiscal.GetCadenaOriginalTimbre: TStringCadenaOriginal; var generadorCadenaOriginalTimbre: TCadenaOriginalDeTimbre; begin if fVersion <> fev32 then raise EComprobanteNoSoportaPropiedadException.Create('Esta version del CFD no soporta obtener la CadenaOriginal del Timbre'); if fFueTimbrado then begin Assert(fTimbre.XML <> '', 'El contenido del timbre fue vacio'); try generadorCadenaOriginalTimbre := TCadenaOriginalDeTimbre.Create(fTimbre.XML, ''); // Calculamos la cadena y la regresamos Result := generadorCadenaOriginalTimbre.Generar; finally generadorCadenaOriginalTimbre.Free; end; end else Result := ''; end; // 1. Datos de quien la expide (Emisor) (Art. 29-A, Fraccion I) procedure TFEComprobanteFiscal.AsignarEmisor; procedure AsignarRegimenesFiscales; var I: Integer; NombreRegimenFiscal : String; begin // Agregamos cada regimen fiscal del emisor al comprobante for I := 0 to Length(inherited Emisor.Regimenes) - 1 do begin NombreRegimenFiscal:=(inherited Emisor.Regimenes)[I]; case fVersion of fev22: begin with IFEXMLComprobanteV22(fXmlComprobante).Emisor.RegimenFiscal.Add do Regimen:=NombreRegimenFiscal; end; fev32: begin with IFEXMLComprobanteV32(fXmlComprobante).Emisor.RegimenFiscal.Add do Regimen:=NombreRegimenFiscal; end; end; end; end; begin // Realizamos las validaciones correspondientes ValidarCamposEmisor; // Segun la version del CFD asignamos el "Emisor" correspondiente case fVersion of fev20: begin with IFEXmlComprobanteV2(fXmlComprobante).Emisor do begin RFC :=(inherited Emisor).RFC; Nombre := TFEReglamentacion.ComoCadena((inherited Emisor).Nombre); with DomicilioFiscal do // Alias de UbicacionFiscal begin Calle := TFEReglamentacion.ComoCadena((inherited Emisor).Direccion.Calle); if Trim((inherited Emisor).Direccion.NoExterior) <> '' then NoExterior := (inherited Emisor).Direccion.NoExterior; // Opcional if Trim((inherited Emisor).Direccion.NoInterior) <> '' then NoInterior := (inherited Emisor).Direccion.NoInterior; // Opcional if Trim((inherited Emisor).Direccion.Colonia) <> '' then Colonia := TFEReglamentacion.ComoCadena((inherited Emisor).Direccion.Colonia); // Opcional if Trim((inherited Emisor).Direccion.Localidad) <> '' then Localidad := TFEReglamentacion.ComoCadena((inherited Emisor).Direccion.Localidad); // Opcional if Trim((inherited Emisor).Direccion.Referencia) <> '' then Referencia := TFEReglamentacion.ComoCadena((inherited Emisor).Direccion.Referencia); // Opcional Municipio := TFEReglamentacion.ComoCadena((inherited Emisor).Direccion.Municipio); Estado := TFEReglamentacion.ComoCadena((inherited Emisor).Direccion.Estado); Pais := TFEReglamentacion.ComoCadena((inherited Emisor).Direccion.Pais); CodigoPostal := (inherited Emisor).Direccion.CodigoPostal; end; end; end; fev22: begin with IFEXmlComprobanteV22(fXmlComprobante).Emisor do begin RFC :=(inherited Emisor).RFC; Nombre := TFEReglamentacion.ComoCadena((inherited Emisor).Nombre); with DomicilioFiscal do // Alias de UbicacionFiscal begin Calle := TFEReglamentacion.ComoCadena((inherited Emisor).Direccion.Calle); if Trim((inherited Emisor).Direccion.NoExterior) <> '' then NoExterior := (inherited Emisor).Direccion.NoExterior; // Opcional if Trim((inherited Emisor).Direccion.NoInterior) <> '' then NoInterior := (inherited Emisor).Direccion.NoInterior; // Opcional if Trim((inherited Emisor).Direccion.Colonia) <> '' then Colonia := TFEReglamentacion.ComoCadena((inherited Emisor).Direccion.Colonia); // Opcional if Trim((inherited Emisor).Direccion.Localidad) <> '' then Localidad := TFEReglamentacion.ComoCadena((inherited Emisor).Direccion.Localidad); // Opcional if Trim((inherited Emisor).Direccion.Referencia) <> '' then Referencia := TFEReglamentacion.ComoCadena((inherited Emisor).Direccion.Referencia); // Opcional Municipio := TFEReglamentacion.ComoCadena((inherited Emisor).Direccion.Municipio); Estado := TFEReglamentacion.ComoCadena((inherited Emisor).Direccion.Estado); Pais := TFEReglamentacion.ComoCadena((inherited Emisor).Direccion.Pais); CodigoPostal := (inherited Emisor).Direccion.CodigoPostal; end; // Agregamos el nuevo campo requerido Regimen Fiscal (implementado en 2.2) Assert(Length(inherited Emisor.Regimenes) > 0, 'Se debe especificar al menos un régimen del cliente'); AsignarRegimenesFiscales; end; end; fev32: begin with IFEXmlComprobanteV32(fXmlComprobante).Emisor do begin RFC :=(inherited Emisor).RFC; Nombre := TFEReglamentacion.ComoCadena((inherited Emisor).Nombre); // Agregamos el domicilio fiscal del Emisor solo si tiene Calle if (inherited Emisor).Direccion.Calle <> '' then AgregarDireccionFiscalv32(DomicilioFiscal, (inherited Emisor).Direccion); // Agregamos el nuevo campo requerido Regimen Fiscal (implementado en 2.2) AsignarRegimenesFiscales; end; end; end; end; // 2. Lugar y fecha de expedicion (29-A, Fraccion III) - En caso de ser sucursal procedure TFEComprobanteFiscal.AsignarExpedidoEn; begin // Checamos si tiene direccion de expedicion... if (inherited ExpedidoEn.Calle <> '') then begin case fVersion of fev20: begin with IFEXmlComprobanteV2(fXmlComprobante).Emisor.ExpedidoEn do begin Calle := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Calle); if Trim((inherited ExpedidoEn).NoExterior) <> '' then NoExterior := (inherited ExpedidoEn).NoExterior; // Opcional if Trim((inherited ExpedidoEn).NoInterior) <> '' then NoInterior := (inherited ExpedidoEn).NoInterior; // Opcional if Trim((inherited ExpedidoEn).Colonia) <> '' then Colonia := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Colonia); // Opcional if Trim((inherited ExpedidoEn).Localidad) <> '' then Localidad := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Localidad); // Opcional if Trim((inherited ExpedidoEn).Referencia) <> '' then Referencia := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Referencia); // Opcional Municipio := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Municipio); Estado := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Estado); Pais := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Pais); CodigoPostal := (inherited ExpedidoEn).CodigoPostal; end; end; fev22: begin with IFEXmlComprobanteV22(fXmlComprobante).Emisor.ExpedidoEn do begin Calle := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Calle); if Trim((inherited ExpedidoEn).NoExterior) <> '' then NoExterior := (inherited ExpedidoEn).NoExterior; // Opcional if Trim((inherited ExpedidoEn).NoInterior) <> '' then NoInterior := (inherited ExpedidoEn).NoInterior; // Opcional if Trim((inherited ExpedidoEn).Colonia) <> '' then Colonia := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Colonia); // Opcional if Trim((inherited ExpedidoEn).Localidad) <> '' then Localidad := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Localidad); // Opcional if Trim((inherited ExpedidoEn).Referencia) <> '' then Referencia := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Referencia); // Opcional Municipio := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Municipio); Estado := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Estado); Pais := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Pais); CodigoPostal := (inherited ExpedidoEn).CodigoPostal; end; end; fev32: begin with IFEXmlComprobanteV32(fXmlComprobante).Emisor.ExpedidoEn do begin Calle := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Calle); if Trim((inherited ExpedidoEn).NoExterior) <> '' then NoExterior := (inherited ExpedidoEn).NoExterior; // Opcional if Trim((inherited ExpedidoEn).NoInterior) <> '' then NoInterior := (inherited ExpedidoEn).NoInterior; // Opcional if Trim((inherited ExpedidoEn).Colonia) <> '' then Colonia := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Colonia); // Opcional if Trim((inherited ExpedidoEn).Localidad) <> '' then Localidad := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Localidad); // Opcional if Trim((inherited ExpedidoEn).Referencia) <> '' then Referencia := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Referencia); // Opcional Municipio := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Municipio); Estado := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Estado); Pais := TFEReglamentacion.ComoCadena((inherited ExpedidoEn).Pais); CodigoPostal := (inherited ExpedidoEn).CodigoPostal; end; end; end; end; end; // 3. Clave del RFC de la persona a favor de quien se expida la factura (29-A, Fraccion IV) procedure TFEComprobanteFiscal.AsignarReceptor; begin ValidarCamposReceptor; with fXmlComprobante.Receptor do begin RFC := Trim((inherited Receptor).RFC); Nombre := TFEReglamentacion.ComoCadena((inherited Receptor).Nombre); // Agregamos el domicilio fiscal del Receptor if (inherited Receptor).Direccion.Calle <> '' then AgregarDireccionFiscalv32(Domicilio, (inherited Receptor).Direccion); end; end; procedure TFEComprobanteFiscal.AsignarContenidoCertificado; begin ValidarCertificado; if Trim(fCertificadoTexto) <> '' then fXmlComprobante.Certificado := TFEReglamentacion.ComoCadena(fCertificadoTexto); end; procedure TFEComprobanteFiscal.AsignarConceptos; var I: Integer; Concepto: TFEConcepto; begin if Length(inherited Conceptos) = 0 then raise EFESinConceptosException.Create('No es posible generar una factura ya que no tuvo ningun concepto.'); // Obtenemos los conceptos agregados al documento previamente for I := 0 to Length(inherited Conceptos) - 1 do begin Concepto:=(inherited Conceptos)[I]; // Agregamos el concepto al XML with fXmlComprobante.Conceptos.Add do begin Cantidad := TFEReglamentacion.ComoCantidad(Concepto.Cantidad); if Trim(Concepto.Unidad) <> '' then Unidad := Concepto.Unidad; // Requerido a partir de la v2.2 if Trim(Concepto.NoIdentificacion) <> '' then NoIdentificacion := TFEReglamentacion.ComoCadena(Concepto.NoIdentificacion); // Opcional Descripcion := TFEReglamentacion.ComoCadena(Concepto.Descripcion); // Se guardan 4 decimales para que pase la prueba del validador de ValidaCFD ValorUnitario := TFEReglamentacion.ComoMoneda(Concepto.ValorUnitario, 4); // Si esta habilitada la bandera permite recalcular el importe u obtenerlo directamente de la variable if fRecalcularImporte then Importe := TFEReglamentacion.ComoMoneda(Concepto.ValorUnitario * Concepto.Cantidad) else Importe := TFEReglamentacion.ComoMoneda(Concepto.Importe); // Le fue asignada informacion aduanera?? if (Concepto.DatosAduana.NumeroDocumento <> '') then with InformacionAduanera.Add do begin Numero := Concepto.DatosAduana.NumeroDocumento; Fecha := TFEReglamentacion.ComoFechaAduanera(Concepto.DatosAduana.FechaExpedicion); Aduana := TFEReglamentacion.ComoCadena(Concepto.DatosAduana.Aduana); end; if Trim(Concepto.CuentaPredial) <> '' then CuentaPredial.Numero := TFEReglamentacion.ComoCadena(Concepto.CuentaPredial); // Opcional end; end; end; procedure TFEComprobanteFiscal.AsignarImpuestosRetenidos; var NuevoImpuesto: TFEImpuestoRetenido; I: Integer; begin for I := 0 to Length(inherited ImpuestosRetenidos) - 1 do begin NuevoImpuesto:=(inherited ImpuestosRetenidos)[I]; with fXmlComprobante.Impuestos.Retenciones.Add do begin Impuesto := TFEReglamentacion.ComoCadena(NuevoImpuesto.Nombre); Importe := TFEReglamentacion.ComoMoneda(NuevoImpuesto.Importe); end; end; end; procedure TFEComprobanteFiscal.AsignarImpuestosTrasladados; var NuevoImpuesto: TFEImpuestoTrasladado; I: Integer; begin for I := 0 to Length(inherited ImpuestosTrasladados) - 1 do begin NuevoImpuesto:=(inherited ImpuestosTrasladados)[I]; with fXmlComprobante.Impuestos.Traslados.Add do begin Impuesto := TFEReglamentacion.ComoCadena(NuevoImpuesto.Nombre); Tasa := TFEReglamentacion.ComoTasaImpuesto(NuevoImpuesto.Tasa); Importe := TFEReglamentacion.ComoMoneda(NuevoImpuesto.Importe); end; end; end; procedure TFEComprobanteFiscal.AsignarImpuestosLocales; var NuevoImpuesto: TFEImpuestoLocal; I: Integer; nodoImpuestosLocales: IFEXMLImpuestosLocales; documentoImpuestosLocales : TXMLDocument; nodoImpuestoTrasladado: IFEXMLImpuestosLocales_TrasladosLocales; schemaLocationAnterior: string; const _SCHEMA_IMPUESTOS_NS = 'http://www.sat.gob.mx/implocal'; _SCHEMA_IMPUESTOS_LOCALES = _SCHEMA_IMPUESTOS_NS + ' http://www.sat.gob.mx/sitio_internet/cfd/implocal/implocal.xsd'; const _DECIMALES_ACEPTADOS_EN_IMPUESTO_LOCAL = 2; begin if Length(inherited ImpuestosLocales) > 0 then begin try // Agregamos al Schema que estamos usando impuestos locales schemaLocationAnterior := fXmlComprobante.Attributes['xsi:schemaLocation']; fXmlComprobante.SetAttribute('xsi:schemaLocation', schemaLocationAnterior + ' ' + _SCHEMA_IMPUESTOS_LOCALES); fXmlComprobante.SetAttribute('xmlns:implocal', _SCHEMA_IMPUESTOS_NS); documentoImpuestosLocales := TXMLDocument.Create(nil); documentoImpuestosLocales.Active := True; // Creamos el nodo de totales de impuestos locales nodoImpuestosLocales := NuevoNodoImpuestosLocales(documentoImpuestosLocales); nodoImpuestosLocales.Version := '1.0'; nodoImpuestosLocales.TotaldeRetenciones := TFEReglamentacion.ComoMoneda(inherited TotalImpuestosLocalesRetenidos, _DECIMALES_ACEPTADOS_EN_IMPUESTO_LOCAL); nodoImpuestosLocales.TotaldeTraslados := TFEReglamentacion.ComoMoneda(inherited TotalImpuestosLocalesTrasladados, _DECIMALES_ACEPTADOS_EN_IMPUESTO_LOCAL); // Agregamos el detalle de los impuestos "hijo" for I := 0 to Length(inherited ImpuestosLocales) - 1 do begin nuevoImpuesto:=(inherited ImpuestosLocales)[I]; // Agregamos el nodo de impuesto segun el tipo de impuesto... case nuevoImpuesto.Tipo of tiRetenido : begin with nodoImpuestosLocales.RetencionesLocales.Add do begin ImpLocRetenido := TFEReglamentacion.ComoCadena(nuevoImpuesto.Nombre); TasadeRetencion := TFEReglamentacion.ComoTasaImpuesto(nuevoImpuesto.Tasa, _DECIMALES_ACEPTADOS_EN_IMPUESTO_LOCAL); Importe := TFEReglamentacion.ComoMoneda(nuevoImpuesto.Importe, _DECIMALES_ACEPTADOS_EN_IMPUESTO_LOCAL); end; end; tiTrasladado : begin with nodoImpuestosLocales.TrasladosLocales.Add do begin ImpLocTrasladado := TFEReglamentacion.ComoCadena(nuevoImpuesto.Nombre); TasadeTraslado := TFEReglamentacion.ComoTasaImpuesto(nuevoImpuesto.Tasa, _DECIMALES_ACEPTADOS_EN_IMPUESTO_LOCAL); Importe := TFEReglamentacion.ComoMoneda(nuevoImpuesto.Importe, _DECIMALES_ACEPTADOS_EN_IMPUESTO_LOCAL); end; end; end; end; finally // No liberamos el TXMLDocument por que impleneta a un TInterfacedObject y Delphi lo libera solo //documentoImpuestosLocales.Free; end; // Agregamos como complemento el nodo de los impuestos locales IFEXmlComprobanteV32(fXmlComprobante).Complemento.ChildNodes.Add(nodoImpuestosLocales); end; end; procedure TFEComprobanteFiscal.AsignarTimbreFiscal(const aTimbre: TFETimbre); begin Assert(fVersion In [fev32], 'No es posible asignar un timbre a un CFD que no es v3.2'); //Assert(FacturaGenerada, 'Se debio haber tenido generada la factura antes de asignarle el timbre'); Assert(Not fFueTimbrado, 'No es posible asignar un timbre a una factura timbrada previamente'); Assert(aTimbre.XML <> '', 'El contenido del timbre fue nulo'); // Asignamos el timbre a la estructura interna del mismo fTimbre := aTimbre; end; procedure TFEComprobanteFiscal.setCertificado(Certificado: TFECertificado); begin fCertificado := Certificado; end; // Asignamos la serie, el no y año de aprobacion al XML... procedure TFEComprobanteFiscal.AsignarDatosFolios; var soportaFolios : IFESoportaBloqueFolios; begin case fVersion of fev20, fev22: begin if Trim(fBloqueFolios.Serie) <> '' then fXmlComprobante.Serie := fBloqueFolios.Serie; end; fev32: begin if Trim(inherited Serie) <> '' then fXmlComprobante.Serie := inherited Serie; end; end; // Los folios asignados solo se soportan en CFD 2.0, 2.2 if fVersion In [fev20, fev22] then begin if Supports(fXmlComprobante, IFESoportaBloqueFolios, soportaFolios) then begin if fBloqueFolios.NumeroAprobacion > 0 then soportaFolios.NoAprobacion := fBloqueFolios.NumeroAprobacion; if fBloqueFolios.AnoAprobacion > 0 then soportaFolios.AnoAprobacion := fBloqueFolios.AnoAprobacion; end; end; end; // 8. Numero de folio, el cual debe de ser asignado de manera automatica por el sistema procedure TFEComprobanteFiscal.AsignarFolio; begin fXmlComprobante.Folio := IntToStr(inherited Folio); end; // 9. Cumplir con las reglas de control de pagos (Art 29, fraccion V) procedure TFEComprobanteFiscal.AsignarFormaDePago; var sForma: String; begin case (inherited FormaDePago) of fpUnaSolaExhibicion: sForma := _CADENA_PAGO_UNA_EXHIBICION; fpParcialidades: sForma := _CADENA_PAGO_PARCIALIDADES; end; fXmlComprobante.FormaDePago := sForma; end; procedure TFEComprobanteFiscal.AsignarSubtotal; begin fXmlComprobante.SubTotal := TFEReglamentacion.ComoMoneda(inherited Subtotal); end; procedure TFEComprobanteFiscal.AsignarTotal; begin fXmlComprobante.Total := TFEReglamentacion.ComoMoneda(inherited Total); end; procedure TFEComprobanteFiscal.AsignarMetodoDePago; var cadenaMetodoDePago, metodoDePagoFinal, metodoDePago: String; numeroCatalogoMetodoPago, I: Integer; fechaEntradaVigorConceptosMetodosDePago: TDate; listadoFormasPago: TStrings; const _MISMA_FECHA = 0; _FECHA_POSTERIOR = 1; _SEPARADOR_METODOS_PAGO = ','; _NUEVA_LINEA = #13#10; begin // Asignamos el metodo de pago if (Trim(inherited MetodoDePago) <> '') then begin cadenaMetodoDePago := (inherited MetodoDePago); // Checamos si tenemos que convertir el método de pago a número de catálogo // solo lo hacemos si la factura fue generada posteriormente a la entrada en vigor // del cambio a la regla (2.7.1.32) del 15 de Julio de 2016 fechaEntradaVigorConceptosMetodosDePago := EncodeDate(_ANO_CAMBIO_METODO_PAGO, _MES_CAMBIO_METODO_PAGO, _DIA_CAMBIO_METODO_PAGO); if CompareDate(inherited FechaGeneracion, fechaEntradaVigorConceptosMetodosDePago) In [_MISMA_FECHA, _FECHA_POSTERIOR] then begin try listadoFormasPago := TStringList.Create; // Usamos la funcionalidad interna de TStrings que separa las cadenas automaticamente cuando encuentra un NewLine listadoFormasPago.Text := StringReplace(cadenaMetodoDePago, _SEPARADOR_METODOS_PAGO, _NUEVA_LINEA, [rfReplaceAll]); metodoDePagoFinal := ''; for I := 0 to listadoFormasPago.Count - 1 do begin metodoDePago := listadoFormasPago[I]; metodoDePagoFinal := metodoDePagoFinal + ConvertirCadenaMetodoPagoaNumero(metodoDePago); // Agregamos la coma separadora excepto en el ultimo ciclo if I < listadoFormasPago.Count - 1 then metodoDePagoFinal := metodoDePagoFinal + _SEPARADOR_METODOS_PAGO; end; finally listadoFormasPago.Free; end; // Checamos si se esta especificando metodos de pago separados por coma end else begin {$IFDEF CODESITE} CodeSite.Send('La factura se generó previo a la entrada en vigor de ' + 'numero de catálogo de métodos de pago, usando método de pago tal cual', cadenaMetodoDePago); {$ENDIF} metodoDePagoFinal := cadenaMetodoDePago; end; fXmlComprobante.MetodoDePago := TFEReglamentacion.ComoCadena(metodoDePagoFinal) end else fXmlComprobante.MetodoDePago := _CADENA_METODO_PAGO_NO_DISPONIBLE; end; procedure TFEComprobanteFiscal.AsignarTipoComprobante; var sTipo: String; begin case (inherited Tipo) of tcIngreso: sTipo := 'ingreso'; tcEgreso: sTipo := 'egreso'; tcTraslado: sTipo := 'traslado'; end; // TODO: Que cambios deben hacerse cuando es un egreso o traslado??? fXmlComprobante.TipoDeComprobante := sTipo; end; procedure TFEComprobanteFiscal.AsignarTotalesImpuestos; begin // Agregamos al XML los totales de los diferentes tipos de impuestos usados // si asi se desea... with fXmlComprobante.Impuestos do begin if (inherited TotalImpuestosRetenidos > 0) then TotalImpuestosRetenidos := TFEReglamentacion.ComoMoneda(inherited TotalImpuestosRetenidos); // Opcional if (inherited TotalImpuestosTrasladados > 0) then TotalImpuestosTrasladados := TFEReglamentacion.ComoMoneda(inherited TotalImpuestosTrasladados); // Opcional end; end; procedure TFEComprobanteFiscal.AsignarFechaGeneracion; var d,m,a: Word; begin // Especificamos la fecha exacta en la que se esta generando el comprobante {$IFDEF VERSION_DE_PRUEBA} // Si estamos en las pruebas de unidad, dejamos que la prueba // defina la fecha/hora en que se "genero" el comprobante // para que sea el mismo que se uso al haber sido generado con el MicroE if (_USAR_HORA_REAL = True) then FechaGeneracion:=ObtenerFechaHoraDeGeneracionActual; {$ELSE} // Si ya fue generada la factura (por ejemplo cuando se lee) if (fAutoAsignarFechaGeneracion = True) then FechaGeneracion := ObtenerFechaHoraDeGeneracionActual; {$ENDIF} // Verificamos que la fecha sea valida DecodeDate(FechaGeneracion, a, m, d); If (a <= 2004) then Raise Exception.Create('La fecha de generacion del comprobante no fue asignada correctamente. No es posible generar factura'); // Almacenamos las propiedades del XML antes de generar la cadena original fXmlComprobante.Fecha := TFEReglamentacion.ComoFechaHora(FechaGeneracion); end; procedure TFEComprobanteFiscal.AsignarLugarExpedicion; begin case fVersion of fev22: IFEXMLComprobanteV22(fXmlComprobante).LugarExpedicion := (inherited LugarDeExpedicion); fev32: IFEXMLComprobanteV32(fXmlComprobante).LugarExpedicion := (inherited LugarDeExpedicion); end; end; procedure TFEComprobanteFiscal.AsignarNumeroDeCuenta; begin // En CFD 2.2 agregamos el Num Cta Pago (al menos los 4 ultimos digitos) el cual // es un nodo opcional case fVersion of fev22: begin if Trim(inherited NumeroDeCuenta) <> '' then IFEXMLComprobanteV22(fXmlComprobante).NumCtaPago:=inherited NumeroDeCuenta; end; fev32: begin if Trim(inherited NumeroDeCuenta) <> '' then IFEXMLComprobanteV32(fXmlComprobante).NumCtaPago:=inherited NumeroDeCuenta; end; end; end; procedure TFEComprobanteFiscal.BorrarConceptos; begin inherited; // Borramos los conceptos previos del XML if Assigned(fXmlComprobante) then fXmlComprobante.Conceptos.Clear; // Indicamos que es necesario de nuevo llenar el XML fComprobanteLleno := False; end; procedure TFEComprobanteFiscal.LeerPropiedadesDeTimbre; var complementoTimbre: IFEXMLtimbreFiscalDigital; documentoXMLTimbre: TXmlDocument; nodoTimbreFiscal: IXMLNode; const _NOMBRE_NODO_TIMBRE = 'TimbreFiscalDigital'; _NAMESPACE_NODO_TIMBRE = 'http://www.sat.gob.mx/TimbreFiscalDigital'; begin Assert(fVersion = fev32, 'Solo es posible asignar el timbre de un CFD v3.2'); if IFEXMLComprobanteV32(fXmlComprobante).Complemento.HasChildNodes then begin // Creamos el documento XML solamente del timbre documentoXMLTimbre := TXMLDocument.Create(nil); nodoTimbreFiscal := IFEXMLComprobanteV32(fXmlComprobante).Complemento.ChildNodes.FindNode(_NOMBRE_NODO_TIMBRE, _NAMESPACE_NODO_TIMBRE); if nodoTimbreFiscal <> nil then begin documentoXMLTimbre.XML.Text := nodoTimbreFiscal.XML; documentoXMLTimbre.Active := True; try // Convertimos el XML del nodo a la interfase del Timbre v3.2 complementoTimbre := GetTimbreFiscalDigital(documentoXMLTimbre); // Asignamos las propiedades del XMl del timbre a las internas fTimbre.Version := complementoTimbre.Version; fTimbre.UUID := complementoTimbre.UUID; fTimbre.FechaTimbrado := TFEReglamentacion.DeFechaHoraISO8601(complementoTimbre.FechaTimbrado); fTimbre.SelloCFD := complementoTimbre.SelloCFD; fTimbre.NoCertificadoSAT := complementoTimbre.NoCertificadoSAT; fTimbre.SelloSAT := complementoTimbre.SelloSAT; fTimbre.XML := documentoXMLTimbre.XML.Text; fFueTimbrado := True; except On E:Exception do raise; end; end; end else fFueTimbrado := False; end; procedure TFEComprobanteFiscal.LeerImpuestosLocales; var complementoImpuestosLocales: IFEXMLImpuestosLocales; documentoXML: TXmlDocument; nodoImpuestosLocales : IXMLNode; I: Integer; impuestoLocal : TFEImpuestoLocal; const _NOMBRE_NODO_IMPUESTOS_LOCALES = 'ImpuestosLocales'; _NAMESPACE_NODO_IMPUESTOS_LOCALES = 'http://www.sat.gob.mx/implocal'; begin nodoImpuestosLocales := fXmlComprobante.Complemento.ChildNodes.FindNode(_NOMBRE_NODO_IMPUESTOS_LOCALES, _NAMESPACE_NODO_IMPUESTOS_LOCALES); if Assigned(nodoImpuestosLocales) then begin // Creamos el documento XML para poder leer el XML de impuestos locales con su correspondiente interfase documentoXML := TXMLDocument.Create(nil); documentoXML.XML.Text := nodoImpuestosLocales.XML; documentoXML.Active := True; complementoImpuestosLocales := NuevoNodoImpuestosLocales(documentoXML); for I := 0 to complementoImpuestosLocales.RetencionesLocales.Count - 1 do begin impuestoLocal.Nombre := complementoImpuestosLocales.RetencionesLocales[I].ImpLocRetenido; impuestoLocal.Tasa := TFEReglamentacion.DeTasaImpuesto(complementoImpuestosLocales.RetencionesLocales[I].TasadeRetencion); impuestoLocal.Importe := TFEReglamentacion.DeMoneda(complementoImpuestosLocales.RetencionesLocales[I].Importe); impuestoLocal.Tipo := tiRetenido; inherited AgregarImpuestoLocal(impuestoLocal); end; for I := 0 to complementoImpuestosLocales.TrasladosLocales.Count - 1 do begin impuestoLocal.Nombre := complementoImpuestosLocales.TrasladosLocales[I].ImpLocTrasladado; impuestoLocal.Tasa := TFEReglamentacion.DeTasaImpuesto(complementoImpuestosLocales.TrasladosLocales[I].TasadeTraslado); impuestoLocal.Importe := TFEReglamentacion.DeMoneda(complementoImpuestosLocales.TrasladosLocales[I].Importe); impuestoLocal.Tipo := tiTrasladado; inherited AgregarImpuestoLocal(impuestoLocal); end; end; end; // Funcion encargada de llenar el comprobante fiscal EN EL ORDEN que se especifica en el XSD // ya que si no es asi, el XML se va llenando en el orden en que se establecen las propiedades de la clase // haciendo que el comprobante no pase las validaciones del SAT. procedure TFEComprobanteFiscal.LlenarComprobante; begin if (fComprobanteLleno = False) then begin // Atributos de comprobante AsignarDatosFolios; AsignarFechaGeneracion; AsignarFolio; AsignarFormaDePago; AsignarSubtotal; AsignarDescuentos; AsignarTotal; AsignarTipoComprobante; AsignarContenidoCertificado; AsignarCondicionesDePago; AsignarMetodoDePago; // Nuevas propiedades de CFD 2.2: y 3.2 if (fVersion = fev22) or (fVersion = fev32) then begin AsignarLugarExpedicion; AsignarNumeroDeCuenta; end; // Por implementar: AsignarTipoDeCambioYMoneda; // Por implementar: AsignarMontoFolioFiscalOriginal; AsignarEmisor; AsignarExpedidoEn; // Atributo Receptor AsignarReceptor; // Atributo conceptos AsignarConceptos; // Atributo Impuestos AsignarImpuestosRetenidos; AsignarImpuestosTrasladados; AgregarComplementos; if (fDesglosarTotalesImpuestos = True) then AsignarTotalesImpuestos; fComprobanteLleno:=True; end; end; procedure TFEComprobanteFiscal.Cancelar; begin raise Exception.Create('Funcion depreciada. Se dejará de usar en versiones futuras'); end; function TFEComprobanteFiscal.ConvertirCadenaMetodoPagoaNumero(const aCadenaMetodoPago: String): String; var cadenaMetodoDePago: String; numeroCatalogoMetodoPago: Integer; begin cadenaMetodoDePago := Trim(aCadenaMetodoPago); // ¿El usuario especifico un numero de catalogo? Lo "pasamos" directo if TryStrToInt(cadenaMetodoDePago, numeroCatalogoMetodoPago) then begin {$IFDEF CODESITE} CodeSite.Send('Usando código de método de pago definido por usuario', numeroCatalogoMetodoPago); {$ENDIF} Result := IntToStr(numeroCatalogoMetodoPago); // Si el método de pago es menor a 10, asignamos un 0 al principio, ya que el SAT maneja "01", en lugar de solo "1" if numeroCatalogoMetodoPago < 10 then Result := '0' + Result; end else begin {$IFDEF CODESITE} CodeSite.Send('Intentando obtener número de método de pago: ' + cadenaMetodoDePago); {$ENDIF} // Si fue una cadena, tratamos de convertirla al catálogo oficial Result := TFEReglamentacion.ConvertirCadenaMetodoDePagoANumeroCatalogo(cadenaMetodoDePago); {$IFDEF CODESITE} CodeSite.Send('Numero de método de pago', Result); {$ENDIF} // Si regreso cadena vacia es que no encontró una equivalencia de la cadena al numero de catalogo en el SAT if (Result = '') then raise EFECadenaMetodoDePagoNoEnCatalogoException.Create('La cadena "' + inherited MetodoDePago + '" no está en el catálogo de métodos de pago del SAT. Favor de verificar'); end; end; procedure TFEComprobanteFiscal.EstablecerVersionDelComprobante; begin Assert(fXmlComprobante <> nil, 'El comprobante No debio haber sido NULO'); fXmlComprobante.SetAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); case fVersion of fev22: begin fXmlComprobante.SetAttribute('xsi:schemaLocation', 'http://www.sat.gob.mx/cfd/2 http://www.sat.gob.mx/sitio_internet/cfd/2/cfdv22.xsd'); fXmlComprobante.Version := '2.2'; end; fev32: begin fXmlComprobante.SetAttribute('xsi:schemaLocation', 'http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd'); fXmlComprobante.Version := '3.2'; end; end; fDocumentoXML.Version := '1.0'; fDocumentoXML.Encoding := 'UTF-8'; end; procedure TFEComprobanteFiscal.GenerarComprobante; begin // Al mandar solicitar el sello se genera la cadena original y por lo tanto se llena el comprobante fXmlComprobante.Sello:=Self.SelloDigital; // Complementos - Timbre Fiscal if fVersion In [fev32] then begin // Si tenemos timbre y no lo hemos agregado al XML lo agregamos if ((fFueTimbrado = False) And (fTimbre.XML <> '')) then AgregarTimbreFiscalAlXML; end; end; procedure TFEComprobanteFiscal.ValidarQueFolioEsteEnRango; begin // Validamos que el folio este dentro del rango definido si ya se nos fue proporcionado // el bloque de folios y el numero de folio if not FacturaGenerada then if ((fBloqueFolios.FolioInicial > -1) And (inherited Folio > -1)) then begin if Not((inherited Folio >= fBloqueFolios.FolioInicial) And (inherited Folio <= fBloqueFolios.FolioFinal)) then raise EFEFolioFueraDeRango.Create('El folio se encuentra fuera del rango autorizado'); end; end; procedure TFEComprobanteFiscal.setBloqueFolios(Bloque: TFEBloqueFolios); begin // Asignamos el bloque a la variable interna y validamos que este dentro del rango... fBloqueFolios := Bloque; // Establecemos la serie inherited Serie := fBloqueFolios.Serie; // Si esta asignado el folio if Folio > 0 then ValidarQueFolioEsteEnRango(); end; // El metodo que genera el CFD al final... procedure TFEComprobanteFiscal.GuardarEnArchivo(sArchivoDestino: String); begin GenerarComprobante; fDocumentoXML.SaveToFile(sArchivoDestino); // TODO: Implementar las diversas fallas que pueden ocurrir end; // Calculamos el sello digital para la cadena original de la factura function TFEComprobanteFiscal.getSelloDigital(): String; var TipoDigestion: TTipoDigestionOpenSSL; SelloDigital: TSelloDigital; // Es importante que en cualquier variable que almacenemos la cadena original // sea del tipo TStringCadenaOriginal para no perder la codificacion UTF8 CadenaOriginal: TStringCadenaOriginal; begin // Si la factura ya fue generada regresamos el sello previamente calculado if (FacturaGenerada = True) then Result:=fSelloDigitalCalculado else begin fSelloDigitalCalculado:=''; ValidarCertificado; // Si tiene activada la opcion de "VerificarRFCDelCertificado" checamos que el // RFC del emisor del CFD corresponda al RFC para el que fue generado el Emisor if fVerificarRFCDelCertificado then if UpperCase(fCertificado.RFCAlQuePertenece) <> UpperCase(inherited Emisor.RFC) then begin raise EFECertificadoNoCorrespondeAEmisor.Create('Al parecer el certificado no corresponde al emisor, ' + 'el RFC del certificado es ' + fCertificado.RFCAlQuePertenece + ' y el del ' + 'emisor es ' + (inherited Emisor.RFC)); end; // Obtenemos la cadena Original del CFD primero CadenaOriginal := Self.CadenaOriginal; {$IFDEF VERSION_DE_PRUEBA} Assert(FechaGeneracion > EncodeDate(2009, 1, 1), 'La fecha de generacion debe ser en el 2010 o superior!! fue' + DateTimeToStr(FechaGeneracion)); {$ENDIF} // Segun la leglislacion vigente si la factura se hace // antes del 1 de Enero del 2011, usamos MD5 if (FechaGeneracion < EncodeDate(2011, 1, 1)) then TipoDigestion := tdMD5 else // Si es 2011 usamos el algoritmo SHA-1 TipoDigestion := tdSHA1; try // Creamos la clase SelloDigital que nos ayudara a "sellar" la factura en XML SelloDigital := TSelloDigital.Create(CadenaOriginal, fCertificado, TipoDigestion); try // Finalmente regresamos la factura en XML con todas sus propiedades llenas fSelloDigitalCalculado := SelloDigital.SelloCalculado; result := fSelloDigitalCalculado; FacturaGenerada:=True; finally // Liberamos la clase de sello usada previamente FreeAndNil(SelloDigital); end; except // TODO: Manejar los diferentes tipos de excepciones... on E:Exception do begin {$IFDEF DEBUG} ShowMessage(E.Message); {$ENDIF} FacturaGenerada := False; raise; end; end; end; end; function TFEComprobanteFiscal.GetTimbre: TFETimbre; begin if fVersion In [fev32] then Result := fTimbre else raise EComprobanteNoSoportaPropiedadException.Create('La version de este CFD no soporta timbrado'); end; // Permite establecer el XML del comprobante (por si se esta leyendo de la BD, etc) // y almacena todo en la estructura interna de datos y XML procedure TFEComprobanteFiscal.setXML(const Valor: WideString); var I: Integer; ValorEmisor, ValorReceptor: TFEContribuyente; feConcepto: TFEConcepto; feRegimen: String; iXmlDoc: IXMLDocument; tieneNodoDomicilio : Boolean; ValorExpedidoEn: TFEExpedidoEn; ImpuestoTrasladado: TFEImpuestoTrasladado; ImpuestoRetenido: TFEImpuestoRetenido; sMotivoDescuento: String; comprobanteConBloqueFolios:IFESoportaBloqueFolios; complementoTimbre: IFEXMLtimbreFiscalDigital; function TieneAtributo(NodoPadre: IXMLNode; NombreAtributo: String) : Boolean; begin // Checamos que el XML que estamos leyendo tenga dicho atributo ya que si esta vacio // y lo tratamos de "leer" se agregara al XML leido con valores nulos if Assigned(NodoPadre) then Result:=NodoPadre.HasAttribute(NombreAtributo) else Result:=False; end; function TieneHijo(const aNodoPadre: IXMLNode; const aNombreHijo: String) : Boolean; begin if Assigned(aNodoPadre) then Result := aNodoPadre.ChildNodes.FindNode(aNombreHijo) <> nil else Result := False; end; begin if (Trim(Valor) = '') then begin Raise EFEXMLVacio.Create('El valor proveido al XML esta vacio. Imposible crear comprobante.'); Exit; end; try // Leemos el contenido XML en el Documento XML interno {$IF Compilerversion >= 20} // Usamos esta nueva funcion ya que UTF8Decode esta depreciada en Delphi XE2 y superiores iXmlDoc:=LoadXMLData(Valor); //UTF8ToString {$ELSE} iXmlDoc:=LoadXMLData(UTF8Decode(Valor)); {$IFEND} // Creamos el documento "dueño" del comprobante fDocumentoXML:=TXmlDocument.Create(nil); // Pasamos el XML para poder usarlo en la clase fDocumentoXML.XML:=iXmlDoc.XML; // Leemos la interface XML adecuada segun la version del XML, si la version no está soportada // lanzaremos una excepcion LeerVersionDeComprobanteLeido(Valor); fDocumentoXML.Encoding := 'UTF-8'; Assert(fXmlComprobante <> nil, 'No se obtuvo una instancia del comprobante ya que fue nula'); Assert(fXmlComprobante.Version <> '', 'El comprobante no fue leido correctamente.'); // Checamos que versión es if fXmlComprobante.Version = '2.0' then fVersion:=fev20; if fXmlComprobante.Version = '2.2' then fVersion:=fev22; if fXmlComprobante.Version = '3.2' then fVersion:=fev32; // Ahora, actualizamos todas las variables internas (de la clase) con los valores del XML with fXmlComprobante do begin inherited Folio:=StrToInt(Folio); // Datos del certificado fCertificado.NumeroSerie:=NoCertificado; fCertificadoTexto := Certificado; if fVersion In [fev20, fev22] then begin if Supports(fXmlComprobante, IFESoportaBloqueFolios, comprobanteConBloqueFolios) then begin fBloqueFolios.NumeroAprobacion := comprobanteConBloqueFolios.NoAprobacion; fBloqueFolios.AnoAprobacion := comprobanteConBloqueFolios.AnoAprobacion; end; end; if TieneAtributo(fXmlComprobante, 'serie') then begin fBloqueFolios.Serie := Serie; inherited Serie := Serie; end; fBloqueFolios.FolioInicial := inherited Folio; fBloqueFolios.FolioFinal := inherited Folio; // CFD 2.2 /CFD 3.2 if (fVersion = fev22) then begin inherited LugarDeExpedicion:=IFEXMLComprobanteV22(fXmlComprobante).LugarExpedicion; if TieneAtributo(fXmlComprobante, 'NumCtaPago') then inherited NumeroDeCuenta:=IFEXMLComprobanteV22(fXmlComprobante).NumCtaPago; end Else if (fVersion = fev32) then begin inherited LugarDeExpedicion:=IFEXMLComprobanteV32(fXmlComprobante).LugarExpedicion; if TieneAtributo(fXmlComprobante, 'NumCtaPago') then inherited NumeroDeCuenta:=IFEXMLComprobanteV32(fXmlComprobante).NumCtaPago; end; FechaGeneracion:=TFEReglamentacion.ComoDateTime(fXmlComprobante.Fecha); if TieneAtributo(fXmlComprobante, 'condicionesDePago') then inherited CondicionesDePago:=CondicionesDePago; if TieneAtributo(fXmlComprobante, 'metodoDePago') then inherited MetodoDePago:=MetodoDePago; // Leemos los datos del emisor case fVersion of fev20: begin if TieneAtributo(IFEXmlComprobanteV2(fXmlComprobante).Emisor, 'nombre') then ValorEmisor.Nombre:=IFEXmlComprobanteV2(fXmlComprobante).Emisor.Nombre; if TieneAtributo(IFEXmlComprobanteV2(fXmlComprobante).Emisor, 'rfc') then ValorEmisor.RFC:=IFEXmlComprobanteV2(fXmlComprobante).Emisor.RFC; with IFEXmlComprobanteV2(fXmlComprobante).Emisor do begin if TieneAtributo(DomicilioFiscal, 'calle') then ValorEmisor.Direccion.Calle := DomicilioFiscal.Calle; if TieneAtributo(DomicilioFiscal, 'noExterior') then ValorEmisor.Direccion.NoExterior := DomicilioFiscal.NoExterior; if TieneAtributo(DomicilioFiscal, 'noInterior') then ValorEmisor.Direccion.NoInterior := DomicilioFiscal.NoInterior; if TieneAtributo(DomicilioFiscal, 'codigoPostal') then ValorEmisor.Direccion.CodigoPostal := DomicilioFiscal.CodigoPostal; if TieneAtributo(DomicilioFiscal, 'colonia') then ValorEmisor.Direccion.Colonia := DomicilioFiscal.Colonia; if TieneAtributo(DomicilioFiscal, 'localidad') then ValorEmisor.Direccion.Localidad := DomicilioFiscal.Localidad; if TieneAtributo(DomicilioFiscal, 'municipio') then ValorEmisor.Direccion.Municipio := DomicilioFiscal.Municipio; if TieneAtributo(DomicilioFiscal, 'estado') then ValorEmisor.Direccion.Estado := DomicilioFiscal.Estado; if TieneAtributo(DomicilioFiscal, 'pais') then ValorEmisor.Direccion.Pais := DomicilioFiscal.Pais; end; end; fev22: begin if TieneAtributo(IFEXmlComprobanteV22(fXmlComprobante).Emisor, 'nombre') then ValorEmisor.Nombre:=IFEXmlComprobanteV22(fXmlComprobante).Emisor.Nombre; if TieneAtributo(IFEXmlComprobanteV22(fXmlComprobante).Emisor, 'rfc') then ValorEmisor.RFC:=IFEXmlComprobanteV22(fXmlComprobante).Emisor.RFC; with IFEXmlComprobanteV22(fXmlComprobante).Emisor do begin if TieneAtributo(DomicilioFiscal, 'calle') then ValorEmisor.Direccion.Calle := DomicilioFiscal.Calle; if TieneAtributo(DomicilioFiscal, 'noExterior') then ValorEmisor.Direccion.NoExterior := DomicilioFiscal.NoExterior; if TieneAtributo(DomicilioFiscal, 'noInterior') then ValorEmisor.Direccion.NoInterior := DomicilioFiscal.NoInterior; if TieneAtributo(DomicilioFiscal, 'codigoPostal') then ValorEmisor.Direccion.CodigoPostal := DomicilioFiscal.CodigoPostal; if TieneAtributo(DomicilioFiscal, 'colonia') then ValorEmisor.Direccion.Colonia := DomicilioFiscal.Colonia; if TieneAtributo(DomicilioFiscal, 'localidad') then ValorEmisor.Direccion.Localidad := DomicilioFiscal.Localidad; if TieneAtributo(DomicilioFiscal, 'municipio') then ValorEmisor.Direccion.Municipio := DomicilioFiscal.Municipio; if TieneAtributo(DomicilioFiscal, 'estado') then ValorEmisor.Direccion.Estado := DomicilioFiscal.Estado; if TieneAtributo(DomicilioFiscal, 'pais') then ValorEmisor.Direccion.Pais := DomicilioFiscal.Pais; end; end; fev32: begin if TieneAtributo(IFEXmlComprobanteV32(fXmlComprobante).Emisor, 'nombre') then ValorEmisor.Nombre:=IFEXmlComprobanteV32(fXmlComprobante).Emisor.Nombre; if TieneAtributo(IFEXmlComprobanteV32(fXmlComprobante).Emisor, 'rfc') then ValorEmisor.RFC:=IFEXmlComprobanteV32(fXmlComprobante).Emisor.RFC; // Checamos si tuvo Domicilio Fiscal el Emisor if TieneHijo(IFEXmlComprobanteV32(fXmlComprobante).Emisor, 'DomicilioFiscal') then begin with IFEXmlComprobanteV32(fXmlComprobante).Emisor do begin if TieneAtributo(DomicilioFiscal, 'calle') then ValorEmisor.Direccion.Calle := DomicilioFiscal.Calle; if TieneAtributo(DomicilioFiscal, 'noExterior') then ValorEmisor.Direccion.NoExterior := DomicilioFiscal.NoExterior; if TieneAtributo(DomicilioFiscal, 'noInterior') then ValorEmisor.Direccion.NoInterior := DomicilioFiscal.NoInterior; if TieneAtributo(DomicilioFiscal, 'codigoPostal') then ValorEmisor.Direccion.CodigoPostal := DomicilioFiscal.CodigoPostal; if TieneAtributo(DomicilioFiscal, 'colonia') then ValorEmisor.Direccion.Colonia := DomicilioFiscal.Colonia; if TieneAtributo(DomicilioFiscal, 'localidad') then ValorEmisor.Direccion.Localidad := DomicilioFiscal.Localidad; if TieneAtributo(DomicilioFiscal, 'municipio') then ValorEmisor.Direccion.Municipio := DomicilioFiscal.Municipio; if TieneAtributo(DomicilioFiscal, 'estado') then ValorEmisor.Direccion.Estado := DomicilioFiscal.Estado; if TieneAtributo(DomicilioFiscal, 'pais') then ValorEmisor.Direccion.Pais := DomicilioFiscal.Pais; end; end; end; end; // Copiamos los régimenes fiscales del emisor if (fVersion = fev22) then begin SetLength(ValorEmisor.Regimenes, IFEXMLComprobanteV22(fXmlComprobante).Emisor.RegimenFiscal.Count); for I := 0 to IFEXMLComprobanteV22(fXmlComprobante).Emisor.RegimenFiscal.Count - 1 do begin feRegimen := IFEXMLComprobanteV22(fXmlComprobante).Emisor.RegimenFiscal[I].Regimen; ValorEmisor.Regimenes[I] := feRegimen; end; end else if (fVersion = fev32) then begin SetLength(ValorEmisor.Regimenes, IFEXMLComprobanteV32(fXmlComprobante).Emisor.RegimenFiscal.Count); for I := 0 to IFEXMLComprobanteV32(fXmlComprobante).Emisor.RegimenFiscal.Count - 1 do begin feRegimen := IFEXMLComprobanteV32(fXmlComprobante).Emisor.RegimenFiscal[I].Regimen; ValorEmisor.Regimenes[I] := feRegimen; end; end; inherited Emisor:=ValorEmisor; ValorReceptor.RFC:=Receptor.Rfc; // Leemos los datos del receptor solo si no es publico en general o extranjero if ((Uppercase(ValorReceptor.RFC) <> _RFC_VENTA_PUBLICO_EN_GENERAL) And (Uppercase(ValorReceptor.RFC) <> _RFC_VENTA_EXTRANJEROS)) then begin if TieneAtributo(Receptor, 'nombre') then ValorReceptor.Nombre:=Receptor.Nombre; tieneNodoDomicilio := (fVersion In [fev20, fev22]); if fVersion = fev32 then tieneNodoDomicilio := TieneHijo(IFEXmlComprobanteV32(fXmlComprobante).Receptor, 'Domicilio'); if tieneNodoDomicilio then begin with Receptor do begin if TieneAtributo(Domicilio, 'calle') then ValorReceptor.Direccion.Calle := Domicilio.Calle; if TieneAtributo(Domicilio, 'noExterior') then ValorReceptor.Direccion.NoExterior := Domicilio.NoExterior; if TieneAtributo(Domicilio, 'noInterior') then ValorReceptor.Direccion.NoInterior := Domicilio.NoInterior; if TieneAtributo(Domicilio, 'codigoPostal') then ValorReceptor.Direccion.CodigoPostal := Domicilio.CodigoPostal; if TieneAtributo(Domicilio, 'colonia') then ValorReceptor.Direccion.Colonia := Domicilio.Colonia; if TieneAtributo(Domicilio, 'localidad') then ValorReceptor.Direccion.Localidad := Domicilio.Localidad; if TieneAtributo(Domicilio, 'municipio') then ValorReceptor.Direccion.Municipio := Domicilio.Municipio; if TieneAtributo(Domicilio, 'estado') then ValorReceptor.Direccion.Estado := Domicilio.Estado; if TieneAtributo(Domicilio, 'pais') then ValorReceptor.Direccion.Pais := Domicilio.Pais; end; end; end; inherited Receptor:=ValorReceptor; // Tiene lugar de expedicion case fVersion of fev20: begin if TieneAtributo(IFEXmlComprobanteV2(fXmlComprobante).Emisor, 'ExpedidoEn') then begin with IFEXmlComprobanteV2(fXmlComprobante).Emisor.ExpedidoEn do begin if TieneAtributo(IFEXmlComprobanteV2(fXmlComprobante).Emisor.ExpedidoEn, 'calle') then ValorExpedidoEn.Calle := Calle; if TieneAtributo(IFEXmlComprobanteV2(fXmlComprobante).Emisor.ExpedidoEn, 'NoExterior') then ValorExpedidoEn.NoExterior := NoExterior; if TieneAtributo(IFEXmlComprobanteV2(fXmlComprobante).Emisor.ExpedidoEn, 'codigoPostal') then ValorExpedidoEn.CodigoPostal := CodigoPostal; if TieneAtributo(IFEXmlComprobanteV2(fXmlComprobante).Emisor.ExpedidoEn, 'localidad') then ValorExpedidoEn.Localidad := Localidad; if TieneAtributo(IFEXmlComprobanteV2(fXmlComprobante).Emisor.ExpedidoEn, 'municipio') then ValorExpedidoEn.Municipio := Municipio; if TieneAtributo(IFEXmlComprobanteV2(fXmlComprobante).Emisor.ExpedidoEn, 'colonia') then ValorExpedidoEn.Colonia := Colonia; if TieneAtributo(IFEXmlComprobanteV2(fXmlComprobante).Emisor.ExpedidoEn, 'estado') then ValorExpedidoEn.Estado := Estado; if TieneAtributo(IFEXmlComprobanteV2(fXmlComprobante).Emisor.ExpedidoEn, 'pais') then ValorExpedidoEn.Pais := Pais; end; end; end; fev22: begin if TieneAtributo(IFEXmlComprobanteV22(fXmlComprobante).Emisor, 'ExpedidoEn') then begin with IFEXmlComprobanteV22(fXmlComprobante).Emisor.ExpedidoEn do begin if TieneAtributo(IFEXmlComprobanteV22(fXmlComprobante).Emisor.ExpedidoEn, 'calle') then ValorExpedidoEn.Calle := Calle; if TieneAtributo(IFEXmlComprobanteV22(fXmlComprobante).Emisor.ExpedidoEn, 'NoExterior') then ValorExpedidoEn.NoExterior := NoExterior; if TieneAtributo(IFEXmlComprobanteV22(fXmlComprobante).Emisor.ExpedidoEn, 'codigoPostal') then ValorExpedidoEn.CodigoPostal := CodigoPostal; if TieneAtributo(IFEXmlComprobanteV22(fXmlComprobante).Emisor.ExpedidoEn, 'localidad') then ValorExpedidoEn.Localidad := Localidad; if TieneAtributo(IFEXmlComprobanteV22(fXmlComprobante).Emisor.ExpedidoEn, 'municipio') then ValorExpedidoEn.Municipio := Municipio; if TieneAtributo(IFEXmlComprobanteV22(fXmlComprobante).Emisor.ExpedidoEn, 'colonia') then ValorExpedidoEn.Colonia := Colonia; if TieneAtributo(IFEXmlComprobanteV22(fXmlComprobante).Emisor.ExpedidoEn, 'estado') then ValorExpedidoEn.Estado := Estado; if TieneAtributo(IFEXmlComprobanteV22(fXmlComprobante).Emisor.ExpedidoEn, 'pais') then ValorExpedidoEn.Pais := Pais; end; end; end; fev32: begin if TieneAtributo(IFEXmlComprobanteV32(fXmlComprobante).Emisor, 'ExpedidoEn') then begin with IFEXmlComprobanteV32(fXmlComprobante).Emisor.ExpedidoEn do begin if TieneAtributo(IFEXmlComprobanteV32(fXmlComprobante).Emisor.ExpedidoEn, 'calle') then ValorExpedidoEn.Calle := Calle; if TieneAtributo(IFEXmlComprobanteV32(fXmlComprobante).Emisor.ExpedidoEn, 'NoExterior') then ValorExpedidoEn.NoExterior := NoExterior; if TieneAtributo(IFEXmlComprobanteV32(fXmlComprobante).Emisor.ExpedidoEn, 'codigoPostal') then ValorExpedidoEn.CodigoPostal := CodigoPostal; if TieneAtributo(IFEXmlComprobanteV32(fXmlComprobante).Emisor.ExpedidoEn, 'localidad') then ValorExpedidoEn.Localidad := Localidad; if TieneAtributo(IFEXmlComprobanteV32(fXmlComprobante).Emisor.ExpedidoEn, 'municipio') then ValorExpedidoEn.Municipio := Municipio; if TieneAtributo(IFEXmlComprobanteV32(fXmlComprobante).Emisor.ExpedidoEn, 'colonia') then ValorExpedidoEn.Colonia := Colonia; if TieneAtributo(IFEXmlComprobanteV32(fXmlComprobante).Emisor.ExpedidoEn, 'estado') then ValorExpedidoEn.Estado := Estado; if TieneAtributo(IFEXmlComprobanteV32(fXmlComprobante).Emisor.ExpedidoEn, 'pais') then ValorExpedidoEn.Pais := Pais; end; end; end; end; inherited ExpedidoEn:=ValorExpedidoEn; for I := 0 to Conceptos.Count - 1 do begin feConcepto.Cantidad:=TFEReglamentacion.DeCantidad(Conceptos[I].Cantidad); if TieneAtributo(Conceptos[I], 'unidad') then feConcepto.Unidad:=Conceptos[I].Unidad; feConcepto.Descripcion:=Conceptos[I].Descripcion; feConcepto.ValorUnitario:=TFEReglamentacion.DeMoneda(Conceptos[I].ValorUnitario); if TieneAtributo(Conceptos[I], 'noIdentificacion') then feConcepto.NoIdentificacion:=Conceptos[I].NoIdentificacion; feConcepto.ValorUnitarioFinal := TFEReglamentacion.DeMoneda(Conceptos[I].ValorUnitario); feConcepto.Importe := TFEReglamentacion.DeMoneda(Conceptos[I].Importe); inherited AgregarConcepto(feConcepto); end; // Agregamos las reteneciones if Assigned(ChildNodes.FindNode('Impuestos')) then if Assigned(ChildNodes.FindNode('Impuestos').ChildNodes.FindNode('Retenciones')) then for I := 0 to fXmlComprobante.Impuestos.Retenciones.Count - 1 do begin ImpuestoRetenido.Nombre := fXmlComprobante.Impuestos.Retenciones.Retencion[I].Impuesto; ImpuestoRetenido.Importe := TFEReglamentacion.DeMoneda(fXmlComprobante.Impuestos.Retenciones.Retencion[I].Importe); inherited AgregarImpuestoRetenido(ImpuestoRetenido); end; // Agregamos los traslados if Assigned(ChildNodes.FindNode('Impuestos')) then begin if Assigned(ChildNodes.FindNode('Impuestos').ChildNodes.FindNode('Traslados')) then for I := 0 to Impuestos.Traslados.Count - 1 do begin with Impuestos.Traslados do begin ImpuestoTrasladado.Nombre := Traslado[I].Impuesto; ImpuestoTrasladado.Tasa:= TFEReglamentacion.DeTasaImpuesto(Traslado[I].Tasa); ImpuestoTrasladado.Importe := TFEReglamentacion.DeMoneda(Traslado[I].Importe); inherited AgregarImpuestoTrasladado(ImpuestoTrasladado); end; end; //AsignarImpuestosTrasladados; end; if TieneAtributo(Impuestos, 'totalImpuestosTraslados') then Self.DesglosarTotalesImpuestos := True else Self.DesglosarTotalesImpuestos := False; // Que forma de pago tuvo?? if AnsiPos('UNA', Uppercase(FormaDePago)) > 0 then inherited FormaDePago := fpUnaSolaExhibicion else inherited FormaDePago := fpParcialidades; // Tipo de comprobante if TipoDeComprobante = 'ingreso' then inherited Tipo := tcIngreso; if TipoDeComprobante = 'egreso' then inherited Tipo := tcEgreso; if TipoDeComprobante = 'traslado' then inherited Tipo := tcTraslado; // Asignamos el descuento if TieneAtributo(fXmlComprobante, 'descuento') then begin if TieneAtributo(fXmlComprobante, 'motivoDescuento') then sMotivoDescuento:=MotivoDescuento else sMotivoDescuento:=''; Self.AsignarDescuento(TFEReglamentacion.DeMoneda(Descuento), sMotivoDescuento); end; // Asignamos el subtotal de la factura inherited SubTotal := TFEReglamentacion.DeMoneda(Subtotal); // Asignamos el total de la factura inherited Total := TFEReglamentacion.DeMoneda(Total); // Leemos los complementos if TieneHijo(fXmlComprobante, 'Complemento') then begin LeerImpuestosLocales; // Leemos el timbre del CFDI if fVersion In [fev32] then begin LeerPropiedadesDeTimbre; end; end; // Indicamos que el comprobante XML ya fue "llenado" fComprobanteLleno := True; // Asignamos el sello que trae el XML fSelloDigitalCalculado := Sello; // Ahora hacemos que se calcule la cadena original de nuevo fCadenaOriginalCalculada := getCadenaOriginal; // Indicamos que la factura ya fue generada FacturaGenerada := True; end; except On E:Exception do Raise Exception.Create(E.Message); end; end; // Regresa el XML final del comprobante ya lleno function TFEComprobanteFiscal.getXML: WideString; begin GenerarComprobante; // Checamos si ya fue generada previamente la factura if FacturaGenerada = True then Result:=fDocumentoXML.XML.Text else Raise Exception.Create('No se puede obtener el XML cuando aún no se ha generado el archivo CFD'); end; procedure TFEComprobanteFiscal.LeerVersionDeComprobanteLeido(const aDocumentoXML: WideString); var cadenaVersion : String; const _LONGITUD_CADENA_VERSION = 3; _CADENA_COMIENZO_VERSION = '.xsd" version="'; begin // Obtenemos la cadena de la version exclusivamente cadenaVersion := Copy(aDocumentoXML, AnsiPos(_CADENA_COMIENZO_VERSION, aDocumentoXML) + Length(_CADENA_COMIENZO_VERSION), _LONGITUD_CADENA_VERSION); if (cadenaVersion = '2.0') then fXmlComprobante := GetComprobante(fDocumentoXML); if (cadenaVersion = '2.2') then fXmlComprobante := GetComprobanteV22(fDocumentoXML); if (cadenaVersion = '3.2') then fXmlComprobante := GetComprobanteV32(fDocumentoXML); // Si llegamos aqui y la instancia fue nula es que no tuvimos una version compatible if fXmlComprobante = nil then raise EFEVersionComprobanteNoSoportadaException.Create('No es posible leer un CFD/I con version "' + cadenaVersion + '" ya que esta versión del programa no es capaz de leerla'); end; function TFEComprobanteFiscal.ObtenerFechaHoraDeGeneracionActual: TDateTime; const _SEGUNDOS_A_RESTAR = -30; begin // Debido a que la fecha de generación NO puede ser mayor que la hora de la Cd. de México, // en ocasiones aunque la hora "este correcta" al mandarla al PAC se genera un error 401 // en que la fecha/hora están fuera de rango. Para evitar este tipo de fallas, restamos 30 segundos // a la fecha de generación para evitar esta falla cuando la diferencia entre la PC y el PAC es mínima Result := DateUtils.IncSecond(Now, _SEGUNDOS_A_RESTAR); end; procedure TFEComprobanteFiscal.ValidarCamposEmisor; begin case fVersion of fev22, fev32: begin if Trim((inherited Emisor).RFC) = '' then raise EFEAtributoRequeridoNoPresenteException.Create('El Atributo RFC de Emisor está vacio'); if Length(inherited Emisor.Regimenes) = 0 then raise EFEAtributoRequeridoNoPresenteException.Create('Se debe especificar al menos 1 régimen fiscal'); if Trim((inherited Emisor).Direccion.Pais) = '' then raise EFEAtributoRequeridoNoPresenteException.Create('Se debe especificar el pais del emisor'); end; end; end; procedure TFEComprobanteFiscal.ValidarCamposReceptor; begin case fVersion of fev22, fev32: begin if Trim((inherited Receptor).RFC) = '' then raise EFEAtributoRequeridoNoPresenteException.Create('El Atributo RFC de Receptor está vacio'); if Trim((inherited Receptor).Direccion.Pais) = '' then raise EFEAtributoRequeridoNoPresenteException.Create('Se debe especificar el pais del Receptor'); end; end; end; procedure TFEComprobanteFiscal.ValidarCertificado; var certificadoSellos: TCertificadoSellos; llavePrivadaOriginal: TFELlavePrivada; begin // Ya que tenemos los datos del certificado, lo procesamos para obtener los datos // necesarios try certificadoSellos := TCertificadoSellos.Create(fCertificado.Ruta); llavePrivadaOriginal := fCertificado.LlavePrivada; if Not certificadoSellos.FueLeido then raise EFECertificadoNoFueLeidoException.Create('No fue posible leer el certificado: ' + certificadoSellos.RazonNoLeido + ' (' + fCertificado.Ruta + ')'); // Checamos que el certificado este dentro de la vigencia if Not certificadoSellos.Vigente then raise EFECertificadoNoVigente.Create('El certificado no tiene vigencia actual'); // Solo realizamos las validaciones del certificado y llave privada si así se especificó if fValidarCertificadoYLlavePrivada then begin // Checamos que el certificado no sea el de la FIEL if Not (certificadoSellos.Tipo = tcSellos) then raise EFECertificadoNoEsDeSellosException.Create('El certificado leido no es de sellos' ); // Checamos que la Llave Privada sea pareja del Certificado if Not certificadoSellos.esParejaDe(Certificado.LlavePrivada) then raise EFELlavePrivadaNoCorrespondeACertificadoException.Create('La llave privada no corresponde al certificado'); end; // Sobre escribimos el certificado interno con las propiedades obtenidas con la clase // TCertificadoSellos... fCertificado := certificadoSellos.paraFacturar; fCertificado.LlavePrivada := llavePrivadaOriginal; // Ya procesado llenamos su propiedad en el XML Assert(Assigned(fXmlComprobante), 'El Nodo comprobante no est asignado!'); fXmlComprobante.NoCertificado := fCertificado.NumeroSerie; // Incluir el certificado en el XML? if bIncluirCertificadoEnXML = True then fCertificadoTexto:=certificadoSellos.ComoBase64; finally if Assigned(certificadoSellos) then FreeAndNil(certificadoSellos); end; end; end.
unit UMDITextView; (* Multi Document Style Window *) (* ◆aiai/zdSWk *) interface uses Windows, Messages, Classes, Controls, ExtCtrls, HogeTextView; type //ウィンドウの状態 {// MTV_MIN・・・最小化} // MTV_NOR・・・いわゆるウィンドウ、タイトルバーやシステムメニュー、最大化・最小化ボタンを持つ // MTV_MAX・・・親ウィンドウのクライント領域いっぱいに配置される TMTVState = ({MTV_MIN,} MTV_NOR, MTV_MAX); TMDITextView = class(THogeTextView) // MDI子ウィンドウになるTHogeTextview private FNorRect: TRect; FMTVState: TMTVState; FCloseWindow: TNotifyEvent; FMaximizeWindow: TNotifyEvent; FDbClickTBar: TNotifyEvent; FActive: TNotifyEvent; //FHide: TNotifyEvent; procedure DoCloseWindow; procedure DoMaximizeWindow; procedure DoDbClickTBar; procedure DoActive; //procedure DoHide; procedure CMEnter(var Message: TCMEnter); message CM_ENTER; procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure SetWndState(AState: TMTVState); //function GetWndState: TMTVState; protected procedure WndProc(var Message: TMessage); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property WndState: TMTVState read FMTVState write SetWndState; property NorRect: TRect read FNorRect write FNorRect; property OnCloseWindow: TNotifyEvent read FCloseWindow write FCloseWindow; property OnMaximizeWindow: TNotifyEvent read FMaximizeWindow write FMaximizeWindow; property OnDbClickTBar: TNotifyEvent read FDbClickTBar write FDbClickTBar; property OnActive: TNotifyEvent read FActive write FActive; //property OnHide: TNotifyEvent read FHide write FHide; end; implementation const WS_MDIDEFAULTWINDOW = (WS_OVERLAPPED or WS_CAPTION or WS_SYSMENU or WS_THICKFRAME {or WS_MINIMIZEBOX} or WS_MAXIMIZEBOX); { TMDITextView } constructor TMDITextView.Create(AOwner: TComponent); begin inherited Create(AOwner); FNorRect := Bounds(10, 10, 300, 300); FMTVState := MTV_MAX; end; destructor TMDITextView.Destroy; begin inherited Destroy; end; procedure TMDITextView.WndProc(var Message: TMessage); begin if Message.Msg = WM_SYSCOMMAND then begin Case Message.WParam of SC_CLOSE: begin DoCloseWindow; exit; end; SC_MAXIMIZE: begin DoMaximizeWindow; exit; end; SC_MAXIMIZE + 2: begin DoDbClickTBar; exit; end; //SC_MINIMIZE: begin // Hide; // DoHide; // exit; //end; //SC_RESTORE, SC_RESTORE + 2: begin // WndState := MTV_NOR; // exit; //end; end; //Case end; inherited WndProc(Message); end; procedure TMDITextView.CMEnter(var Message: TCMEnter); begin inherited; Perform(WM_NCACTIVATE, 1, 0); DoActive; BringToFront; end; procedure TMDITextView.CMExit(var Message: TCMExit); begin inherited; Perform(WM_NCACTIVATE, 0, 0); end; procedure TMDITextView.SetWndState(AState: TMTVState); var WS: Longint; begin if FMTVState = AState then exit; //Show; {if AState = MTV_MIN then begin FMTVState := AState; WS := GetWindowLong(Handle, GWL_STYLE); WS := WS or WS_MINIMIZE; SetWindowLong(Handle, GWL_STYLE, WS); SetWindowPos(Handle, 0, 0, 0, 0, 0, 0 or SWP_FRAMECHANGED or SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOOWNERZORDER or SWP_NOSIZE or SWP_NOZORDER); end else} if AState = MTV_NOR then begin FMTVState := AState; WS := GetWindowLong(Handle, GWL_STYLE); WS := WS or WS_MDIDEFAULTWINDOW; SetWindowLong(Handle, GWL_STYLE, WS); Align := alNone; SetWindowPos(Handle, 0, 0, 0, 0, 0, 0 or SWP_FRAMECHANGED or SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOOWNERZORDER or SWP_NOSIZE or SWP_NOZORDER); BoundsRect := FNorRect; end else if AState = MTV_MAX then begin FMTVState := AState; FNorRect := BoundsRect; WS := GetWindowLong(Handle, GWL_STYLE); WS := WS and not WS_MDIDEFAULTWINDOW; SetWindowLong(Handle, GWL_STYLE, WS); Align := alClient; SetWindowPos(Handle, 0, 0, 0, 0, 0, 0 or SWP_FRAMECHANGED or SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOOWNERZORDER or SWP_NOSIZE or SWP_NOZORDER); end; end; procedure TMDITextView.DoCloseWindow; begin if Assigned(FCloseWindow) then FCloseWindow(Self); end; procedure TMDITextView.DoMaximizeWindow; begin if Assigned(FMaximizeWindow) then FMaximizeWindow(Self); end; procedure TMDITextView.DoDbClickTBar; begin if Assigned(FDbClickTBar) then FDbClickTBar(Self); end; procedure TMDITextView.DoActive; begin if Assigned(FActive) then FActive(self); end; //procedure TMDITextView.DoHide; //begin // if Assigned(FHide) then // FHide(self); //end; end.
unit u.utility; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Objects , u.typeinfo ; procedure ByteArrayToFIle(const ByteArray: TRecArray; const FileName: string); function FIleToByteArray(const FileName: string): TRecArray; procedure CreateUDG; procedure DrawMap(Const aLivello: oRecLivello; Var rWMain: TRectangle); implementation uses FMX.Graphics, u.Constant.Loc, u.graph; procedure ByteArrayToFIle(const ByteArray: TRecArray; const FileName: string); var Count : integer; F: FIle of Byte; pTemp: Pointer; begin AssignFile( F, FileName ); Rewrite(F); try Count := Length( ByteArray ); pTemp := @ByteArray[0]; BlockWrite(F, pTemp^, Count ); finally CloseFile( F ); end; end; function FIleToByteArray(const FileName: string): TRecArray; var Count: integer; F: FIle of Byte; pTemp: Pointer; begin AssignFile( F, FileName ); Reset(F); try Count := FileSize( F ); pTemp := @Result[0]; BlockRead(f,pTemp^,count); finally CloseFile( F ); end; end; procedure CreateUDG; var bitdata1: TBitmapData; i, x, y: Integer; sTemp: String; function IntToBin(Value: Byte): String; var i: Integer; pStr: PChar; begin SetLength( Result,8); pStr := PChar(Pointer(Result)); for i := 7 downto 0 do begin pStr[i] := Char(Ord('0') + ((Value shr (7 - i)) and 1)); end; end; begin for i := 0 to CS_SPRITE do begin oSprite[i] := TBitmap.Create; oSprite[i].Width := 8; oSprite[i].Height := 8; if (oSprite[i].Map(TMapAccess.ReadWrite, bitdata1)) then try for y := 0 to 7 do begin sTemp := IntToBin(aUDG[i][y]); for x := 0 to CS_BYTE do begin if sTemp[x+1] = '1' then bitdata1.SetPixel(x, y, TAlphaColorRec.Black); end; end; finally oSprite[i].Unmap(bitdata1); end; // MakePNG(oSprite[i], 'sprite\'+i.ToString+'.png'); // oSprite[i].SaveToFile('sprite\'+i.ToString+'.bmp'); end; end; procedure DrawMap(const aLivello: oRecLivello; Var rWMain: TRectangle); var i: Integer; j: Integer; z: Integer; s: String; begin for i := 0 to CS_MAPPA_H do begin for j := 0 to CS_MAPPA_W do if aLivello.Mappa[i][j] ='2' then begin DrawSprite(rWMain, oSprite[2], i, j, TAlphaColorRec.Blueviolet, TAlphaColorRec.Yellow); oMappa[I, J] := 2; end else if aLivello.Mappa[i][j] ='3' then begin DrawSprite(rWMain, oSprite[6], i, j, TAlphaColorRec.Blueviolet, TAlphaColorRec.Black); oMappa[I, J] := 2; end else if aLivello.Mappa[i][j] ='4' then begin DrawSprite(rWMain, oSprite[7], i, j, TAlphaColorRec.Blueviolet, TAlphaColorRec.Black); oMappa[I, J] := 2; end else if aLivello.Mappa[i][j] ='5' then begin DrawSprite(rWMain, oSprite[8], i, j, TAlphaColorRec.Blueviolet, TAlphaColorRec.Black); oMappa[I, J] := 2; end else if aLivello.Mappa[i][j] ='6' then begin DrawSprite(rWMain, oSprite[9], i, j, TAlphaColorRec.Blueviolet, TAlphaColorRec.Black); oMappa[I, J] := 2; end else if aLivello.Mappa[i][j] ='7' then begin DrawSprite(rWMain, oSprite[10], i, j, TAlphaColorRec.Blueviolet, TAlphaColorRec.Black); oMappa[I, J] := 2; end else if aLivello.Mappa[i][j] ='8' then begin DrawSprite(rWMain, oSprite[11], i, j, TAlphaColorRec.Blueviolet, TAlphaColorRec.Black); oMappa[I, J] := 2; end else if aLivello.Mappa[i][j] ='0' then begin DrawSprite(rWMain, oSprite[12], i, j, TAlphaColorRec.Chartreuse, TAlphaColorRec.Black); oMappa[I, J] := 0; end else if aLivello.Mappa[i][j] ='A' then begin DrawSprite(rWMain, oSprite[13], i, j, TAlphaColorRec.Blueviolet, TAlphaColorRec.Black); oMappa[I, J] := 2; end else if aLivello.Mappa[i][j] ='9' then begin DrawSprite(rWMain, oSprite[5], i, j, TAlphaColorRec.red, TAlphaColorRec.Black); oMappa[I, J] := 9; end; end; end; end.
unit SG_Date; interface uses Controls; function delphiDateToSqlDate(date:TDate):String; function addYears(date:TDate;years:integer):TDate; implementation uses Sysutils; function delphiDateToSqlDate(date:TDate):String; begin Result:=QuotedStr(FormatDateTime('yyyymmdd',date)); end; function addYears(date:TDate;years:integer):TDate; begin Result:=IncMonth(Date,12*years); end; end.
{Hint: save all files to location: D:\dev\dev\lazarus\Unzipper\AppLAMWUnzipDemo\jni } {Demo project for using the unzip function} {by Johan Hofman / 2019-07-20} unit unit1; {$mode delphi} interface uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, AndroidWidget, Laz_And_Controls, Zipper; type { TAndroidModule1 } TAndroidModule1 = class(jForm) jButton1: jButton; jTextView1: jTextView; jTextView2: jTextView; procedure AndroidModule1JNIPrompt(Sender: TObject); procedure jButton1Click(Sender: TObject); Function StartUnzipFile:boolean; procedure DoCreateOutZipStream(Sender: TObject; var AStream: TStream; AItem: TFullZipFileEntry); procedure DoDoneOutZipStream(Sender: TObject; var AStream: TStream; AItem: TFullZipFileEntry); private {private declarations} public {public declarations} end; var AndroidModule1: TAndroidModule1; implementation {$R *.lfm} { TAndroidModule1 } procedure TAndroidModule1.DoCreateOutZipStream(Sender: TObject; var AStream: TStream; AItem: TFullZipFileEntry); begin AStream:= TMemorystream.Create; end; procedure TAndroidModule1.DoDoneOutZipStream(Sender: TObject; var AStream: TStream; AItem: TFullZipFileEntry); begin AStream.Position:=0; TMemoryStream(astream).SaveToFile(Self.GetEnvironmentDirectoryPath(dirdownloads)+'/'+aitem.DiskFileName); Astream.Free; end; Function TAndroidModule1.StartUnzipfile:boolean; var zipfile: TUnZipper; flist: TStringlist; installpath: string; begin try installpath:= Self.GetEnvironmentDirectoryPath(dirDownloads)+'/'; zipfile:= TUnZipper.Create; zipfile.FileName:= installpath+'Demo.zip'; flist:= TStringlist.create; flist.add('Demo.txt'); // Normally the zipfile can be extracted via zipfile.UnzipAllFiles but this will result in an application crash // The workaround is to use a memorystream for the extraction: ZipFile.OnCreateStream := DoCreateOutZipStream; ZipFile.OnDoneStream:= DoDoneOutZipStream; ZipFile.UnZipFiles(flist); ZipFile.Free; flist.Free; Showmessage('Success! Unpacking done !!'); Result:=true; except on e:exception do showmessage('Error occured during unzip process: '+e.message); end; end; procedure TAndroidModule1.jButton1Click(Sender: TObject); begin if IsRuntimePermissionGranted('android.permission.WRITE_EXTERNAL_STORAGE') then begin Self.CopyFromAssetsToEnvironmentDir('Demo.zip',Self.GetEnvironmentDirectoryPath(dirDownloads)); StartUnzipFile; end else Showmessage('Sorry.. "WRITE_EXTERNAL_STORAGE" DENIED ...'); end; procedure TAndroidModule1.AndroidModule1JNIPrompt(Sender: TObject); begin if IsRuntimePermissionGranted('android.permission.WRITE_EXTERNAL_STORAGE') = False then Self.RequestRuntimePermission('android.permission.WRITE_EXTERNAL_STORAGE',1001); end; end.
// ************************************************************************ // This file implements library imports for the caller. // ------- // WARNING // ------- // This file was generated by PWIG. Do not edit. // File generated on 4.1.2017 17:40:15 unit testlib_caller; {$IFDEF FPC}{$MODE DELPHI}{$ENDIF} // Library properties: // Name: TestLib // Version: 1.0 // GUID: F3C093C0-035B-4C33-BB28-C1FDE270D3B5 // Description: Test library interface uses {$IFDEF FPC} DynLibs, {$ELSE} {$IFDEF MSWINDOWS} Windows, {$ENDIF} {$ENDIF} testlib_intf; type // Forward declarations: TProjectGroup = class; TProject = class; // Name: ProjectGroup // GUID: 7C12BB43-A6AB-4A52-8B1D-EDD5D94B344B // Description: ProjectGroup Object TProjectGroupIProjectGroupEventsOnErrorEvent = procedure(const ErrorCode: TErrorCode; const ErrorText: string) of object; TProjectGroupIProjectGroupEventsOnProgressEvent = procedure(const EventCode: TProgressEvent; const ProgressValue: LongInt; const EventText: string) of object; TProjectGroup = class(TObject) private FOnError: TProjectGroupIProjectGroupEventsOnErrorEvent; FOnProgress: TProjectGroupIProjectGroupEventsOnProgressEvent; FItemHandle: IProjectGroup; // Property getters and setters: public constructor Create(AInterfaceHandle: IProjectGroup = 0); destructor Destroy; override; // Methods: function AddProject: IProject; procedure RunPeriodic; procedure Finalize; // Properties: // Events: property OnError: TProjectGroupIProjectGroupEventsOnErrorEvent read FOnError write FOnError; property OnProgress: TProjectGroupIProjectGroupEventsOnProgressEvent read FOnProgress write FOnProgress; // Default interface handle: property Handle: IProjectGroup read FItemHandle; end; // Name: Project // GUID: D96EA22B-D750-4C05-9F32-8C5C8E9F846D // Description: Project Object TProject = class(TObject) private FItemHandle: IProject; // Property getters and setters: function GetConnectionFRC: LongInt; function GetConnectionString: string; public constructor Create(AInterfaceHandle: IProject = 0); destructor Destroy; override; // Methods: procedure Connect; procedure Disconnect; function LoadFromFile(const Path: string): TBool; function SaveToFile(const Path: string): TBool; // Properties: property ConnectionFRC: LongInt read GetConnectionFRC; property ConnectionString: string read GetConnectionString; // Default interface handle: property Handle: IProject read FItemHandle; end; function TestLibLibLoad(const FileName: string): Boolean; procedure TestLibLibUnload; var LibLoadErrorMsg: string; implementation uses Math, SysUtils; const LibModule: HMODULE = 0; // Name: ProjectGroup // GUID: 7C12BB43-A6AB-4A52-8B1D-EDD5D94B344B // Description: ProjectGroup Object // Constructor: FuncProjectGroupCreate: TProjectGroupCreate = nil; // Destructor: FuncProjectGroupDestroy: TProjectGroupDestroy = nil; // Methods: FuncProjectGroupIProjectGroupAddProject: TIProjectGroupAddProject = nil; FuncProjectGroupIProjectGroupRunPeriodic: TIProjectGroupRunPeriodic = nil; FuncProjectGroupIProjectGroupFinalize: TIProjectGroupFinalize = nil; // Properties: // Event handler setters: FuncSetProjectGroupIProjectGroupEventsOnError: TSetProjectGroupIProjectGroupEventsOnError = nil; FuncSetProjectGroupIProjectGroupEventsOnProgress: TSetProjectGroupIProjectGroupEventsOnProgress = nil; // Name: Project // GUID: D96EA22B-D750-4C05-9F32-8C5C8E9F846D // Description: Project Object // Constructor: FuncProjectCreate: TProjectCreate = nil; // Destructor: FuncProjectDestroy: TProjectDestroy = nil; // Methods: FuncProjectIProjectConnect: TIProjectConnect = nil; FuncProjectIProjectDisconnect: TIProjectDisconnect = nil; FuncProjectIProjectLoadFromFile: TIProjectLoadFromFile = nil; FuncProjectIProjectSaveToFile: TIProjectSaveToFile = nil; // Properties: FuncProjectGetIProjectConnectionFRC: TGetIProjectConnectionFRC = nil; FuncProjectGetIProjectConnectionString: TGetIProjectConnectionString = nil; procedure LibError(const AMessage: string); begin raise Exception.Create(AMessage); end; procedure LibCallError(const AFuncName: string); begin LibError(Format('Error while calling library function %s!', [AFuncName])); end; procedure LibLoadError(const AFuncName: string); begin LibError(Format('Requested function %s does not exist in the library!', [AFuncName])); end; function TestLibLibLoad(const FileName: string): Boolean; type T_FuncLibID = function: PAnsichar; cdecl; var _FuncLibID: T_FuncLibID; begin Result := False; try if LibModule = 0 then begin LibModule := LoadLibrary({$IFnDEF FPC}PChar{$ENDIF}(FileName)); {$IFDEF FPC} LibLoadErrorMsg := GetLoadErrorStr; {$ENDIF} end; if LibModule <> 0 then begin // Call library identification code first _FuncLibID := GetProcAddress(LibModule, 'GetLibGUID'); if not Assigned(_FuncLibID) then LibLoadError('GetLibGUID'); if _FuncLibID <> cLibGUID then LibError('Incompatible library interface!'); // Name: ProjectGroup // GUID: 7C12BB43-A6AB-4A52-8B1D-EDD5D94B344B // Description: ProjectGroup Object // Constructor: FuncProjectGroupCreate := GetProcAddress(LibModule, 'ProjectGroupCreate'); if not Assigned(FuncProjectGroupCreate) then LibLoadError('ProjectGroupCreate'); // Destructor: FuncProjectGroupDestroy := GetProcAddress(LibModule, 'ProjectGroupDestroy'); if not Assigned(FuncProjectGroupDestroy) then LibLoadError('ProjectGroupDestroy'); // Methods: FuncProjectGroupIProjectGroupAddProject := GetProcAddress(LibModule, 'ProjectGroupIProjectGroupAddProject'); if not Assigned(FuncProjectGroupIProjectGroupAddProject) then LibLoadError('ProjectGroupIProjectGroupAddProject'); FuncProjectGroupIProjectGroupRunPeriodic := GetProcAddress(LibModule, 'ProjectGroupIProjectGroupRunPeriodic'); if not Assigned(FuncProjectGroupIProjectGroupRunPeriodic) then LibLoadError('ProjectGroupIProjectGroupRunPeriodic'); FuncProjectGroupIProjectGroupFinalize := GetProcAddress(LibModule, 'ProjectGroupIProjectGroupFinalize'); if not Assigned(FuncProjectGroupIProjectGroupFinalize) then LibLoadError('ProjectGroupIProjectGroupFinalize'); // Properties: // Event handler setters: FuncSetProjectGroupIProjectGroupEventsOnError := GetProcAddress(LibModule, 'SetProjectGroupIProjectGroupEventsOnError'); if not Assigned(FuncSetProjectGroupIProjectGroupEventsOnError) then LibLoadError('SetProjectGroupIProjectGroupEventsOnError'); FuncSetProjectGroupIProjectGroupEventsOnProgress := GetProcAddress(LibModule, 'SetProjectGroupIProjectGroupEventsOnProgress'); if not Assigned(FuncSetProjectGroupIProjectGroupEventsOnProgress) then LibLoadError('SetProjectGroupIProjectGroupEventsOnProgress'); // Name: Project // GUID: D96EA22B-D750-4C05-9F32-8C5C8E9F846D // Description: Project Object // Constructor: FuncProjectCreate := GetProcAddress(LibModule, 'ProjectCreate'); if not Assigned(FuncProjectCreate) then LibLoadError('ProjectCreate'); // Destructor: FuncProjectDestroy := GetProcAddress(LibModule, 'ProjectDestroy'); if not Assigned(FuncProjectDestroy) then LibLoadError('ProjectDestroy'); // Methods: FuncProjectIProjectConnect := GetProcAddress(LibModule, 'ProjectIProjectConnect'); if not Assigned(FuncProjectIProjectConnect) then LibLoadError('ProjectIProjectConnect'); FuncProjectIProjectDisconnect := GetProcAddress(LibModule, 'ProjectIProjectDisconnect'); if not Assigned(FuncProjectIProjectDisconnect) then LibLoadError('ProjectIProjectDisconnect'); FuncProjectIProjectLoadFromFile := GetProcAddress(LibModule, 'ProjectIProjectLoadFromFile'); if not Assigned(FuncProjectIProjectLoadFromFile) then LibLoadError('ProjectIProjectLoadFromFile'); FuncProjectIProjectSaveToFile := GetProcAddress(LibModule, 'ProjectIProjectSaveToFile'); if not Assigned(FuncProjectIProjectSaveToFile) then LibLoadError('ProjectIProjectSaveToFile'); // Properties: FuncProjectGetIProjectConnectionFRC := GetProcAddress(LibModule, 'ProjectGetIProjectConnectionFRC'); if not Assigned(FuncProjectGetIProjectConnectionFRC) then LibLoadError('ProjectGetIProjectConnectionFRC'); FuncProjectGetIProjectConnectionString := GetProcAddress(LibModule, 'ProjectGetIProjectConnectionString'); if not Assigned(FuncProjectGetIProjectConnectionString) then LibLoadError('ProjectGetIProjectConnectionString'); Result := True; end; except end; end; procedure TestLibLibUnload; begin if LibModule <> 0 then FreeLibrary(LibModule); LibModule := 0; // Name: ProjectGroup // GUID: 7C12BB43-A6AB-4A52-8B1D-EDD5D94B344B // Description: ProjectGroup Object // Constructor: FuncProjectGroupCreate := nil; // Destructor: FuncProjectGroupDestroy := nil; // Methods: FuncProjectGroupIProjectGroupAddProject := nil; FuncProjectGroupIProjectGroupRunPeriodic := nil; FuncProjectGroupIProjectGroupFinalize := nil; // Properties: // Event handler setters: FuncSetProjectGroupIProjectGroupEventsOnError := nil; FuncSetProjectGroupIProjectGroupEventsOnProgress := nil; // Name: Project // GUID: D96EA22B-D750-4C05-9F32-8C5C8E9F846D // Description: Project Object // Constructor: FuncProjectCreate := nil; // Destructor: FuncProjectDestroy := nil; // Methods: FuncProjectIProjectConnect := nil; FuncProjectIProjectDisconnect := nil; FuncProjectIProjectLoadFromFile := nil; FuncProjectIProjectSaveToFile := nil; // Properties: FuncProjectGetIProjectConnectionFRC := nil; FuncProjectGetIProjectConnectionString := nil; end; // Name: ProjectGroup // GUID: 7C12BB43-A6AB-4A52-8B1D-EDD5D94B344B // Description: ProjectGroup Object // Event handler callbacks: function ProjectGroupIProjectGroupEventsOnError(const ItemHandle: IProjectGroupEvents; const ErrorCode: TErrorCode; const ErrorText: PAnsiChar): Boolean; cdecl; begin Result := False; try if TObject(ItemHandle) is TProjectGroup then begin if Assigned(TProjectGroup(ItemHandle).OnError) then begin TProjectGroup(ItemHandle).OnError(ErrorCode, LibUtf8String2String(ErrorText)); end; Result := True; end; except end; end; function ProjectGroupIProjectGroupEventsOnProgress(const ItemHandle: IProjectGroupEvents; const EventCode: TProgressEvent; const ProgressValue: LongInt; const EventText: PAnsiChar): Boolean; cdecl; begin Result := False; try if TObject(ItemHandle) is TProjectGroup then begin if Assigned(TProjectGroup(ItemHandle).OnProgress) then begin TProjectGroup(ItemHandle).OnProgress(EventCode, ProgressValue, LibUtf8String2String(EventText)); end; Result := True; end; except end; end; // Constructor: constructor TProjectGroup.Create(AInterfaceHandle: IProjectGroup); begin try FItemHandle := AInterfaceHandle; if (FItemHandle = 0) and Assigned(FuncProjectGroupCreate) then FuncProjectGroupCreate(FItemHandle); FOnError := nil; if Assigned(FuncSetProjectGroupIProjectGroupEventsOnError) then begin if not ( FuncSetProjectGroupIProjectGroupEventsOnError(FItemHandle, IProjectGroupEvents(Self), ProjectGroupIProjectGroupEventsOnError) ) then LibError('FuncSetProjectGroupIProjectGroupEventsOnError'); end; FOnProgress := nil; if Assigned(FuncSetProjectGroupIProjectGroupEventsOnProgress) then begin if not ( FuncSetProjectGroupIProjectGroupEventsOnProgress(FItemHandle, IProjectGroupEvents(Self), ProjectGroupIProjectGroupEventsOnProgress) ) then LibError('FuncSetProjectGroupIProjectGroupEventsOnProgress'); end; except on E : Exception do LibCallError(E.Message); end; end; // Destructor: destructor TProjectGroup.Destroy; begin try if Assigned(FuncProjectGroupDestroy) then FuncProjectGroupDestroy(FItemHandle); inherited; except on E : Exception do LibCallError(E.Message); end; end; // Methods: function TProjectGroup.AddProject: IProject; begin try if Assigned(FuncProjectGroupIProjectGroupAddProject) then begin if not ( FuncProjectGroupIProjectGroupAddProject(FItemHandle, Result) ) then LibError('FuncProjectGroupIProjectGroupAddProject'); end; except on E : Exception do LibCallError(E.Message); end; end; procedure TProjectGroup.RunPeriodic; begin try if Assigned(FuncProjectGroupIProjectGroupRunPeriodic) then begin if not ( FuncProjectGroupIProjectGroupRunPeriodic(FItemHandle) ) then LibError('FuncProjectGroupIProjectGroupRunPeriodic'); end; except on E : Exception do LibCallError(E.Message); end; end; procedure TProjectGroup.Finalize; begin try if Assigned(FuncProjectGroupIProjectGroupFinalize) then begin if not ( FuncProjectGroupIProjectGroupFinalize(FItemHandle) ) then LibError('FuncProjectGroupIProjectGroupFinalize'); end; except on E : Exception do LibCallError(E.Message); end; end; // Properties: // Name: Project // GUID: D96EA22B-D750-4C05-9F32-8C5C8E9F846D // Description: Project Object // Constructor: constructor TProject.Create(AInterfaceHandle: IProject); begin try FItemHandle := AInterfaceHandle; if (FItemHandle = 0) and Assigned(FuncProjectCreate) then FuncProjectCreate(FItemHandle); except on E : Exception do LibCallError(E.Message); end; end; // Destructor: destructor TProject.Destroy; begin try if Assigned(FuncProjectDestroy) then FuncProjectDestroy(FItemHandle); inherited; except on E : Exception do LibCallError(E.Message); end; end; // Methods: procedure TProject.Connect; begin try if Assigned(FuncProjectIProjectConnect) then begin if not ( FuncProjectIProjectConnect(FItemHandle) ) then LibError('FuncProjectIProjectConnect'); end; except on E : Exception do LibCallError(E.Message); end; end; procedure TProject.Disconnect; begin try if Assigned(FuncProjectIProjectDisconnect) then begin if not ( FuncProjectIProjectDisconnect(FItemHandle) ) then LibError('FuncProjectIProjectDisconnect'); end; except on E : Exception do LibCallError(E.Message); end; end; function TProject.LoadFromFile(const Path: string): TBool; begin try if Assigned(FuncProjectIProjectLoadFromFile) then begin if not ( FuncProjectIProjectLoadFromFile(FItemHandle, PAnsiChar(String2LibUtf8String(Path)), Result) ) then LibError('FuncProjectIProjectLoadFromFile'); end; except on E : Exception do LibCallError(E.Message); end; end; function TProject.SaveToFile(const Path: string): TBool; begin try if Assigned(FuncProjectIProjectSaveToFile) then begin if not ( FuncProjectIProjectSaveToFile(FItemHandle, PAnsiChar(String2LibUtf8String(Path)), Result) ) then LibError('FuncProjectIProjectSaveToFile'); end; except on E : Exception do LibCallError(E.Message); end; end; // Properties: function TProject.GetConnectionFRC: LongInt; begin try if Assigned(FuncProjectGetIProjectConnectionFRC) then begin if not ( FuncProjectGetIProjectConnectionFRC(FItemHandle, Result) ) then LibError('FuncProjectGetIProjectConnectionFRC'); end; except on E : Exception do LibCallError(E.Message); end; end; function TProject.GetConnectionString: string; var AnsiString__Value: AnsiString; Length__Value: LongInt; begin try if Assigned(FuncProjectGetIProjectConnectionString) then begin Length__Value := 0; if not ( FuncProjectGetIProjectConnectionString(FItemHandle, nil, Length__Value) ) then LibError('FuncProjectGetIProjectConnectionString'); SetLength(AnsiString__Value, Max(Length__Value, 1)); if not ( FuncProjectGetIProjectConnectionString(FItemHandle, PAnsiChar(AnsiString__Value), Length__Value) ) then LibError('FuncProjectGetIProjectConnectionString'); end; if Length__Value > 0 then Result := LibUtf8String2String(AnsiString__Value) else Result := ''; except on E : Exception do LibCallError(E.Message); end; end; end.
unit uDataComputer; interface uses Vcl.Dialogs, SynCommons, mORMot, mORMotSQLite3, SynSQLite3, SynSQLite3Static, System.Classes, System.Variants, System.SysUtils, System.Types, System.IOUtils, System.Diagnostics, System.Math, uCommon, uFileWriter; type TSQLSource = class(TSQLRow) protected fRowCount: Cardinal; fMaxValueCount: Word; fMaxValueCount2: Word; fRowSpacing: Cardinal; fValueCountGroup: RawUTF8; published property RowCount: Cardinal read fRowCount write fRowCount; property MaxValueCount: Word read fMaxValueCount write fMaxValueCount; property MaxValueCount2: Word read fMaxValueCount2 write fMaxValueCount2; property RowSpacing: Cardinal read fRowSpacing write fRowSpacing; property ValueCountGroup: RawUTF8 read fValueCountGroup write fValueCountGroup; end; TSQLCompare = class(TSQLRow); TSQLCompareData = class(TSQLData) protected fFileIndex: Integer; fSourceNumber: Cardinal; fCompareNumber: Cardinal; published property FileIndex: Integer read fFileIndex write fFileIndex; property SourceNumber: Cardinal read fSourceNumber write fSourceNumber; property CompareNumber: Cardinal read fCompareNumber write fCompareNumber; end; TSQLSourceGroup = class(TSQLRecord) protected fValue: RawUTF8; fMaxNumber: Cardinal; fMinNumber: Cardinal; fMaxRowSpacing: Cardinal; fDifferenceValue: Cardinal; published property Value: RawUTF8 read fValue write fValue; property MaxNumber: Cardinal read fMaxNumber write fMaxNumber; property MinNumber: Cardinal read fMinNumber write fMinNumber; property MaxRowSpacing: Cardinal read fMaxRowSpacing write fMaxRowSpacing; property DifferenceValue: Cardinal read fDifferenceValue write fDifferenceValue; end; TDataComputer = class(TThread) private fStopwatch: TStopwatch; fRest: TSQLRestServerDB; fDataMode: Byte; fMaxSourceNumber: Cardinal; fFileIndex: Integer; fIntervalValues: TWordDynArray; fSourceFileDirectory: string; fCompareFileDirectory: string; fCompareFileName: string; fExportDirectory: string; fSameValues: TArray<TRect>; fMinSameValueCount: Word; fSeparateMode: Boolean; fMergeMode: Boolean; fMode: Byte; fModeStr: string; procedure SetExportDirectory(Value: string); procedure BuildRest; procedure LoadRow(Row: TSQLRow; FileName: string); procedure LoadSourceFile; procedure Compare; procedure BuildSourceMaxValueCount; procedure BuildGroup; procedure BuildRowSpacing; procedure ExportFile; procedure ExportFile2; procedure ExportFile3; procedure ExportData; overload; public constructor Create; destructor Destroy; override; procedure Execute; override; published property Stopwatch: TStopwatch read fStopwatch; property DataMode: Byte read fDataMode; property IntervalValues: TWordDynArray read fIntervalValues write fIntervalValues; property SourceFileDirectory: string read fSourceFileDirectory write fSourceFileDirectory; property CompareFileDirectory: string read fCompareFileDirectory write fCompareFileDirectory; property ExportDirectory: string read fExportDirectory write SetExportDirectory; property SameValues: TArray<TRect> read fSameValues write fSameValues; property MinSameValueCount: Word read fMinSameValueCount write fMinSameValueCount; property SeparateMode: Boolean read fSeparateMode write fSeparateMode; property MergeMode: Boolean read fMergeMode write fMergeMode; end; var fDataComputer: TDataComputer; fRestSettings: TSQLRestServerDB; fKeyValue: TSQLKeyValue; implementation procedure TDataComputer.SetExportDirectory(Value: string); begin fExportDirectory := Value.Trim; if not fExportDirectory.IsEmpty and not fExportDirectory.Substring(fExportDirectory.Length - 1).Equals('\') then fExportDirectory := fExportDirectory + '\'; end; procedure TDataComputer.BuildRest; begin fRest := TSQLRestServerDB.CreateWithOwnModel( [TSQLSource, TSQLCompare, TSQLCompareData, TSQLSourceGroup] ); fRest.CreateMissingTables; end; procedure TDataComputer.LoadRow(Row: TSQLRow; FileName: string); function Extract(s: string): string; var i, iLeft: Integer; begin Result := s; for i := 1 to Length(s) do begin if s[i] = '(' then iLeft := i else if s[i] = '列' then begin Result := s.Substring(0, iLeft - 1); Break; end; end; end; function SpecialMode(s: string): Boolean; var HasLeft, HasLie: Boolean; c: Char; begin Result := False; HasLeft := False; HasLie := False; for c in s do begin case c of '(': begin HasLeft := True; end; '列': begin HasLie := True; end; ')': begin Result := HasLeft and not HasLie; if Result then Exit; end; end; end; end; var i, j, Digit: Integer; s: string; SetDataMode: Boolean; begin SetDataMode := Row.ClassType = TSQLSource; with TStringList.Create do begin try LoadFromFile(FileName); fRest.TransactionBegin(Row.RecordClass); try //fRest.Delete(Row.RecordClass, ''); for i := Count - 1 downto 0 do begin if not TryStrToInt(Names[i].Trim, Digit) then Continue; Row.Number := Digit; s := Extract(ValueFromIndex[i]); //自动识别数据模式 if SetDataMode then begin if SpecialMode(s) then fDataMode := 2; SetDataMode := False; end; Row.AssignValue(s, fIntervalValues, fDataMode); fRest.Add(Row, True); end; fRest.Commit(1, True); except on e: Exception do begin fRest.RollBack; raise; end; end; finally Free; end; end; end; procedure TDataComputer.LoadSourceFile; var Source: TSQLSource; FileName: string; begin if Terminated then Exit; TSQLSource.AutoFree(Source); for FileName in TDirectory.GetFiles(fSourceFileDirectory, '*.txt') do begin if Terminated then Exit; LoadRow(Source, FileName); end; fMaxSourceNumber := StrToInt64(fRest.OneFieldValue(TSQLSource, 'Max(Number)', '')); end; procedure TDataComputer.Compare; var Source: TSQLSource; Compare: TSQLCompare; CompareData, CompareData2: TSQLCompareData; v: Word; IsValid: Boolean; i: Integer; l: TStringList; v2, v3, v4: TWordDynArray; begin if Terminated then Exit; TSQLSource.AutoFree(Source, fRest, '', []); TSQLCompare.AutoFree(Compare, fRest, 'ORDER BY Number DESC', []); TSQLCompareData.AutoFree(CompareData); TSQLCompareData.AutoFree(CompareData2); CompareData.AssignValue('', fIntervalValues, fDataMode); CompareData.FileIndex := fFileIndex; fRest.TransactionBegin(TSQLCompareData); try while Source.FillOne do begin CompareData.SourceNumber := Source.Number; Compare.FillRewind; while Compare.FillOne do begin CompareData.ClearValue; for v in Compare.Values do if Source.ValueExist(v) then CompareData.AddValue(v); CompareData.CalcValueCount; CompareData.CompareNumber := Compare.Number; v2 := Source.Values; v3 := Compare.Values; v4 := CompareData.Values; IsValid := False; case fMode of 1: begin for i := Low(fSameValues) to High(fSameValues) do begin IsValid := (CompareData.ValueCount >= fSameValues[i].Left) and (CompareData.ValueCount <= fSameValues[i].Top) and (CompareData.ValueCount2 >= fSameValues[i].Right) and (CompareData.ValueCount2 <= fSameValues[i].Bottom); if IsValid then Break; end; end; else begin for i := Low(fSameValues) to High(fSameValues) do begin IsValid := (CompareData.ValueCount >= fSameValues[i].Left) and (CompareData.ValueCount2 >= fSameValues[i].Top); if IsValid then Break; end; if not IsValid and (fMinSameValueCount > 0) then IsValid := CompareData.ValueCount2 >= fMinSameValueCount; end; end; if IsValid then begin CompareData2.FillPrepare(fRest, 'SourceNumber = ? AND CompareNumber = ? AND ValueCount = ? AND ValueCount2 = ?', [Source.Number, Compare.Number, CompareData.ValueCount, CompareData.ValueCount2]); if CompareData2.FillOne then begin CompareData2.FileIndex := fFileIndex; fRest.Update(CompareData2); end else begin fRest.Add(CompareData, True); end; end; end; end; fRest.Commit(1, True); except fRest.RollBack; raise; end; end; procedure TDataComputer.BuildSourceMaxValueCount; var Source: TSQLSource; CompareData: TSQLCompareData; s: string; begin TSQLSource.AutoFree(Source, fRest, '', []); TSQLCompareData.AutoFree(CompareData); while Source.FillOne do begin Source.MaxValueCount := 0; Source.MaxValueCount2 := 0; s := 'SourceNumber = ? ORDER BY ValueCount DESC, ValueCount2 DESC, CompareNumber'; if fFileIndex > -1 then s := Format('FileIndex = %d AND ', [fFileIndex]) + s; CompareData.FillPrepare(fRest, s, [Source.Number]); if CompareData.FillOne then begin Source.MaxValueCount := CompareData.ValueCount; Source.MaxValueCount2 := CompareData.ValueCount2; end; Source.RowCount := CompareData.FillTable.RowCount; Source.ValueCountGroup := ''; if fMode = 0 then begin Source.ValueCountGroup := Source.MaxValueCount.ToString; if Length(fIntervalValues) > 1 then Source.ValueCountGroup := Source.ValueCountGroup + '+' + Source.MaxValueCount2.ToString; end; fRest.Update(Source); end; if fMode = 1 then begin Source.FillPrepare(fRest, 'ORDER BY MaxValueCount DESC, MaxValueCount2 DESC LIMIT 1', []); if Source.FillOne then begin Source.ValueCountGroup := Source.MaxValueCount.ToString; if Length(fIntervalValues) > 1 then Source.ValueCountGroup := Source.ValueCountGroup + '+' + Source.MaxValueCount2.ToString; fRest.Execute(Format('UPDATE Source SET ValueCountGroup = ''%s''', [Source.ValueCountGroup])) end; end; end; procedure TDataComputer.BuildGroup; var Group: TSQLSourceGroup; l: TSQLTableJSON; begin if Terminated then Exit; fRest.Delete(TSQLSourceGroup, ''); TSQLSourceGroup.AutoFree(Group); l := fRest.MultiFieldValues(TSQLSource, 'ValueCountGroup, Max(Number), Min(Number)', 'RowCount > 0 GROUP BY ValueCountGroup ORDER BY MaxValueCount DESC, MaxValueCount2 DESC', []); try fRest.TransactionBegin(TSQLSourceGroup); try while l.Step do begin Group.Value := l.FieldAsRawUTF8(0); Group.MaxNumber := l.FieldAsInteger(1); Group.MinNumber := l.FieldAsInteger(2); fRest.Add(Group, True); end; fRest.Commit(1, True); except fRest.RollBack; raise; end; finally l.Free; end; end; procedure TDataComputer.BuildRowSpacing; var Group: TSQLSourceGroup; Source, Source2: TSQLSource; begin if Terminated then Exit; TSQLSourceGroup.AutoFree(Group, fRest, '', []); TSQLSource.AutoFree(Source); TSQLSource.AutoFree(Source2); fRest.TransactionBegin(TSQLSource); try while Group.FillOne do begin Group.MaxRowSpacing := 0; Source.FillPrepare(fRest, 'ValueCountGroup = ? AND RowCount > 0 ORDER BY Number DESC', [Group.Value]); while Source.FillOne do begin Source2.Number := 1; if Source.FillCurrentRow <= Source.FillTable.RowCount then Source.FillRow(Source.FillCurrentRow, Source2); Source.RowSpacing := Source.Number - Source2.Number; if Source.RowSpacing > Group.MaxRowSpacing then Group.MaxRowSpacing := Source.RowSpacing; fRest.Update(Source); end; fRest.Update(Group); end; Group.FillPrepare(fRest, '', []); while Group.FillOne do begin Group.DifferenceValue := fMaxSourceNumber + 1 - Group.MaxNumber - Group.MaxRowSpacing; fRest.Update(Group); end; fRest.Commit(1, True); except fRest.RollBack; raise; end; end; procedure TDataComputer.ExportFile; var fr: TFileWriter; Group: TSQLSourceGroup; Source: TSQLSource; CompareData, CompareData2: TSQLCompareData; s, s2, FileName, FileName2, sNumber, sCompareData, sCompareNumber: string; begin if Terminated then Exit; FileName := fCompareFileName.Replace('.txt', ':' + fModeStr + '导出结果 1 .txt'); FileName := fExportDirectory + ExtractFileName(FileName); fr := TFileWriter.Create(FileName); try TSQLSourceGroup.AutoFree(Group); TSQLSource.AutoFree(Source); TSQLCompareData.AutoFree(CompareData); TSQLCompareData.AutoFree(CompareData2); Group.FillPrepare(fRest, '', []); while Group.FillOne and not Terminated do begin if Group.FillCurrentRow > 2 then begin fr.WriteLn(''); fr.WriteLn(''); fr.WriteLn(''); end; s := '[ 全部行的首行( 第 %d 行 )( 加上 + )1 ] = [ 第 %d 行 ]( 减去 - )[ 该组首行( 第 %d 行 )] =( 行间差 :%d )'; s := Format(s, [fMaxSourceNumber, fMaxSourceNumber + 1, Group.MaxNumber, fMaxSourceNumber + 1 - Group.MaxNumber]); fr.WriteLn(''); fr.WriteLn(''); fr.WriteLn(s); Source.FillPrepare(fRest, 'ValueCountGroup = ? AND RowCount > 0 ORDER BY Number DESC', [Group.Value]); if Group.FillCurrentRow = 2 then FileName2 := FileName.Replace('.txt', Format('(注:总共 %d = 行 ).txt', [Source.FillTable.RowCount])); while Source.FillOne and not Terminated do begin sNumber := Source.Number.ToString; if sNumber.Length < 2 then sNumber := '0' + sNumber; sCompareNumber := ''; sCompareData := ''; s := 'SourceNumber = ? ORDER BY ValueCount DESC, ValueCount2 DESC, CompareNumber'; if fFileIndex > -1 then s := Format('FileIndex = %d AND ', [fFileIndex]) + s; CompareData.FillPrepare(fRest, s, [Source.Number]); while CompareData.FillOne and not Terminated do begin CompareData2.ValueCount := 0; CompareData2.ValueCount2 := 0; if CompareData.FillCurrentRow <= CompareData.FillTable.RowCount then CompareData.FillRow(CompareData.FillCurrentRow, CompareData2); if not sCompareNumber.IsEmpty then sCompareNumber := sCompareNumber + '、'; sCompareNumber := sCompareNumber + CompareData.CompareNumber.ToString; s := CompareData.ValueCount.ToString; if Length(fIntervalValues) > 1 then s := Format('%d + %d', [CompareData.ValueCount, CompareData.ValueCount2]); s2 := CompareData2.ValueCount.ToString; if Length(fIntervalValues) > 1 then s2 := Format('%d + %d', [CompareData2.ValueCount, CompareData2.ValueCount2]); if not s.Equals(s2) then begin if sCompareData <> '' then sCompareData := sCompareData + ' ;'; sCompareData := sCompareData + Format('%s = %s', [sCompareNumber, s]); sCompareNumber := ''; end; end; s := '%s=%s ( 行间差 :%d ) ( %s )'; s := Format(s, [sNumber, Source.ToString(fDataMode), Source.RowSpacing, sCompareData]); if Source.FillCurrentRow = 2 then fr.WriteLn(''); fr.WriteLn(s); end; s := '[ 该组行的末行( 第 %d 行 )( 减去 - )1 ] =( 行间差 :%d )'; s := Format(s, [Group.MinNumber, Group.MinNumber - 1]); fr.WriteLn(''); fr.WriteLn(s); end; fr.WriteFinish; finally fr.Free; end; if (fMode = 1) and TFile.Exists(FileName) then RenameFile(FileName, FileName2); end; procedure TDataComputer.ExportFile2; var fr: TFileWriter; Group: TSQLSourceGroup; Source: TSQLSource; CompareData, CompareData2: TSQLCompareData; s, s2, FileName, FileName2, sNumber, sCompareData, sCompareNumber: string; begin if Terminated then Exit; FileName := fCompareFileName.Replace('.txt', ':' + fModeStr + '导出结果 2 .txt'); FileName := fExportDirectory + ExtractFileName(FileName); fr := TFileWriter.Create(FileName); try TSQLSourceGroup.AutoFree(Group); TSQLSource.AutoFree(Source); TSQLCompareData.AutoFree(CompareData); TSQLCompareData.AutoFree(CompareData2); Group.FillPrepare(fRest, '', []); while Group.FillOne and not Terminated do begin if Group.FillCurrentRow = 2 then FileName2 := FileName.Replace('.txt', Format('(注:最多相同列数 = %s).txt', [Group.Value])) else begin fr.WriteLn(''); fr.WriteLn(''); end; s := '[ 全部行的首行( 第 %d 行 )( 加上 + )1 ] = [ 第 %d 行 ]( 减去 - )[ 该组首行( 第 %d 行 )] =( 行间差 :%d )'; s := Format(s, [fMaxSourceNumber, fMaxSourceNumber + 1, Group.MaxNumber, fMaxSourceNumber + 1 - Group.MaxNumber]); fr.WriteLn(''); fr.WriteLn(''); fr.WriteLn(''); fr.WriteLn(s); Source.FillPrepare(fRest, 'ValueCountGroup = ? AND RowCount > 0 ORDER BY RowSpacing DESC, Number DESC', [Group.Value]); while Source.FillOne and not Terminated do begin sNumber := Source.Number.ToString; if sNumber.Length < 2 then sNumber := '0' + sNumber; sCompareNumber := ''; sCompareData := ''; s := 'SourceNumber = ? ORDER BY ValueCount DESC, ValueCount2 DESC, CompareNumber'; if fFileIndex > -1 then s := Format('FileIndex = %d AND ', [fFileIndex]) + s; CompareData.FillPrepare(fRest, s, [Source.Number]); while CompareData.FillOne and not Terminated do begin CompareData2.ValueCount := 0; CompareData2.ValueCount2 := 0; if CompareData.FillCurrentRow <= CompareData.FillTable.RowCount then CompareData.FillRow(CompareData.FillCurrentRow, CompareData2); if not sCompareNumber.IsEmpty then sCompareNumber := sCompareNumber + '、'; sCompareNumber := sCompareNumber + CompareData.CompareNumber.ToString; s := CompareData.ValueCount.ToString; if Length(fIntervalValues) > 1 then s := Format('%d + %d', [CompareData.ValueCount, CompareData.ValueCount2]); s2 := CompareData2.ValueCount.ToString; if Length(fIntervalValues) > 1 then s2 := Format('%d + %d', [CompareData2.ValueCount, CompareData2.ValueCount2]); if not s.Equals(s2) then begin if sCompareData <> '' then sCompareData := sCompareData + ' ;'; sCompareData := sCompareData + Format('%s = %s', [sCompareNumber, s]); sCompareNumber := ''; end; end; s := '%s=%s ( 行间差 :%d ) ( %s )'; s := Format(s, [sNumber, Source.ToString(fDataMode), Source.RowSpacing, sCompareData]); if Source.FillCurrentRow = 2 then fr.WriteLn(''); fr.WriteLn(s); end; s := '[ 该组行的末行( 第 %d 行 )( 减去 - )1 ] =( 行间差 :%d )'; s := Format(s, [Group.MinNumber, Group.MinNumber - 1]); fr.WriteLn(''); fr.WriteLn(s); end; fr.WriteFinish; finally fr.Free; end; if TFile.Exists(FileName) then RenameFile(FileName, FileName2); end; procedure TDataComputer.ExportFile3; var fr: TFileWriter; Group: TSQLSourceGroup; Source: TSQLSource; CompareData, CompareData2: TSQLCompareData; s, s2, FileName, FileName2, sNumber, sCompareData, sCompareNumber, sRowSpacingTip: string; begin if Terminated then Exit; FileName := fCompareFileName.Replace('.txt', ':' + fModeStr + '导出结果 3 .txt'); FileName := fExportDirectory + ExtractFileName(FileName); fr := TFileWriter.Create(FileName); try TSQLSourceGroup.AutoFree(Group); TSQLSource.AutoFree(Source); TSQLCompareData.AutoFree(CompareData); TSQLCompareData.AutoFree(CompareData2); Group.FillPrepare(fRest, 'ORDER BY DifferenceValue DESC', []); while Group.FillOne and not Terminated do begin if Group.FillCurrentRow = 2 then FileName2 := FileName.Replace('.txt', Format('(注:最新 - 最大行间差 = %d ).txt', [fMaxSourceNumber + 1 - Group.MaxNumber - Group.MaxRowSpacing])); s := '[ 全部行的首行( 第 %d 行 )( 加上 + )1 ] = [ 第 %d 行 ]( 减去 - )[ 该组首行( 第 %d 行 )] =( 最新行间差 :%d )- ( 最大行间差 :%d ) = ( 行间差 :%d )'; s := Format(s, [ fMaxSourceNumber, fMaxSourceNumber + 1, Group.MaxNumber, fMaxSourceNumber + 1 - Group.MaxNumber, Group.MaxRowSpacing, fMaxSourceNumber + 1 - Group.MaxNumber - Group.MaxRowSpacing ]); fr.WriteLn(''); fr.WriteLn(''); fr.WriteLn(s); Source.FillPrepare(fRest, 'ValueCountGroup = ? AND RowCount > 0 ORDER BY RowSpacing DESC, Number DESC', [Group.Value]); while Source.FillOne and not Terminated do begin sNumber := Source.Number.ToString; if sNumber.Length < 2 then sNumber := '0' + sNumber; sCompareNumber := ''; sCompareData := ''; s := 'SourceNumber = ? ORDER BY ValueCount DESC, ValueCount2 DESC, CompareNumber'; if fFileIndex > -1 then s := Format('FileIndex = %d AND ', [fFileIndex]) + s; CompareData.FillPrepare(fRest, s, [Source.Number]); while CompareData.FillOne and not Terminated do begin CompareData2.ValueCount := 0; CompareData2.ValueCount2 := 0; if CompareData.FillCurrentRow <= CompareData.FillTable.RowCount then CompareData.FillRow(CompareData.FillCurrentRow, CompareData2); if not sCompareNumber.IsEmpty then sCompareNumber := sCompareNumber + '、'; sCompareNumber := sCompareNumber + CompareData.CompareNumber.ToString; s := CompareData.ValueCount.ToString; if Length(fIntervalValues) > 1 then s := Format('%d + %d', [CompareData.ValueCount, CompareData.ValueCount2]); s2 := CompareData2.ValueCount.ToString; if Length(fIntervalValues) > 1 then s2 := Format('%d + %d', [CompareData2.ValueCount, CompareData2.ValueCount2]); if not s.Equals(s2) then begin if sCompareData <> '' then sCompareData := sCompareData + ' ;'; sCompareData := sCompareData + Format('%s = %s', [sCompareNumber, s]); sCompareNumber := ''; end; end; sRowSpacingTip := '行间差'; if Source.RowSpacing = Group.MaxRowSpacing then sRowSpacingTip := '最大行间差'; s := '%s=%s ( %s :%d ) ( %s )'; s := Format(s, [sNumber, Source.ToString(fDataMode), sRowSpacingTip, Source.RowSpacing, sCompareData]); if Source.FillCurrentRow = 2 then fr.WriteLn(''); fr.WriteLn(s); end; s := '[ 该组行的末行( 第 %d 行 )( 减去 - )1 ] =( 行间差 :%d )'; s := Format(s, [Group.MinNumber, Group.MinNumber - 1]); fr.WriteLn(''); fr.WriteLn(s); end; fr.WriteFinish; finally fr.Free; end; if TFile.Exists(FileName) then RenameFile(FileName, FileName2); end; procedure TDataComputer.ExportData; begin if Terminated then Exit; if fFileIndex = -1 then begin fModeStr := '【 各区域(分开)(总合并)】'; if fMode = 1 then fModeStr := '【 各区域(合并)(总合并)】'; end else begin fModeStr := '【 各区域(分开)】'; if fMode = 1 then fModeStr := '【 各区域(合并)】'; end; ExportFile; ExportFile2; ExportFile3; end; constructor TDataComputer.Create; begin inherited Create(True); fDataMode := 0; end; destructor TDataComputer.Destroy; begin if Assigned(fRest) then fRest.Free; inherited Destroy; end; procedure TDataComputer.Execute; var Compare: TSQLCompare; FileName, TotalFileName: string; begin fStopwatch := TStopwatch.StartNew; try try if fSeparateMode then begin fMode := 0; BuildRest; LoadSourceFile; TSQLCompare.AutoFree(Compare); fFileIndex := -1; for FileName in TDirectory.GetFiles(fCompareFileDirectory, '*.txt') do begin if Terminated then Exit; Inc(fFileIndex); fCompareFileName := FileName; fRest.Delete(TSQLCompare, ''); LoadRow(Compare, fCompareFileName); Self.Compare; BuildSourceMaxValueCount; BuildGroup; BuildRowSpacing; ExportData; end; fFileIndex := -1; BuildSourceMaxValueCount; BuildGroup; BuildRowSpacing; TotalFileName := ExtractFileName(FileName); fCompareFileName := TotalFileName.Substring(0, TotalFileName.IndexOf('-')) + '.txt'; ExportData; end; if fMergeMode then begin fMode := 1; BuildRest; LoadSourceFile; TSQLCompare.AutoFree(Compare); fFileIndex := -1; for FileName in TDirectory.GetFiles(fCompareFileDirectory, '*.txt') do begin if Terminated then Exit; Inc(fFileIndex); fCompareFileName := FileName; fRest.Delete(TSQLCompare, ''); LoadRow(Compare, fCompareFileName); Self.Compare; BuildSourceMaxValueCount; BuildGroup; BuildRowSpacing; ExportData; end; fFileIndex := -1; BuildSourceMaxValueCount; BuildGroup; BuildRowSpacing; TotalFileName := ExtractFileName(FileName); fCompareFileName := TotalFileName.Substring(0, TotalFileName.IndexOf('-')) + '.txt'; ExportData; end; if Terminated then Exit; TThread.Queue(nil, procedure begin ShowMessage('处理完成'); end); except on e: Exception do begin TThread.Queue(nil, procedure begin raise Exception.Create(e.Message); end); end; end; finally fStopwatch.Stop; end; end; initialization fRestSettings := TSQLRestServerDB.CreateWithOwnModel( [TSQLKeyValue], fDirectory + 'Data' ); fRestSettings.CreateMissingTables; fKeyValue := TSQLKeyValue.Create; fKeyValue.SetRest(fRestSettings); finalization if Assigned(fKeyValue) then FreeAndNil(fKeyValue); if Assigned(fRestSettings) then FreeAndNil(fRestSettings); end.
unit Service.UserLaboratory; interface uses System.SysUtils, System.Classes, System.Threading, System.UITypes, FMX.DialogService, FireDAC.Comp.Client, UDM, REST.Backend.ServiceTypes, System.JSON, REST.Client, REST.Types, Data.Bind.Components, Data.Bind.ObjectScope, REST.Backend.EndPoint; type TsrvUserLaboratory = class(TDataModule) BackEndpointPostItem: TBackendEndpoint; rRespPostItem: TRESTResponse; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private { Private declarations } FDM: TDM; procedure ResetBackEndpoint(ABackEndpoint: TBackendEndpoint); public { Public declarations } procedure DoPostLabSuggestion(var ADataSet: TFDMemTable); end; const EMS_GET_ITEM_PARAM_NAME = 'RequestedItem'; EMS_POST_ITEM_PARAM_NAME_DATATYPE = 'datatype'; EMS_POST_ITEM_PARAM_VALUE_SUGGESTION = 'LabSuggestion'; WARNING_LAB_SUGGESTION_REQUIRED_INFO_NOT_FOUND = 'Por favor, informe os dados completos do laboratório desejado.'; INFORMATION_LAB_SUGGESTION_ACCEPTED = 'Sugestão enviada com sucesso'; var srvUserLaboratory: TsrvUserLaboratory; implementation uses FUser.Profile, UJSONHelper, USharedConsts, USharedUtils, UAppSharedUtils, Classes.AdvJSONObjectWriter; {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} { TsrvUserLaboratory } procedure TsrvUserLaboratory.DataModuleCreate(Sender: TObject); begin FDM := TDM.Create(nil); TAppSharedUtils.SetProvider(TDataModule(Self), FDM.emsLAPProvider); end; procedure TsrvUserLaboratory.DataModuleDestroy(Sender: TObject); begin if Assigned(FDM) then begin FDM.DisposeOf; end; end; procedure TsrvUserLaboratory.DoPostLabSuggestion(var ADataSet: TFDMemTable); {$REGION 'Inner methods'} function _ValidateData: Boolean; begin try Result := (ADataSet.FieldByName('sugg_cname').AsString <> EmptyStr) and (ADataSet.FieldByName('sugg_cphone').AsString <> EmptyStr); except Result := False; end; end; {$ENDREGION} var LTask: ITask; LThread: TThread; LDataSet: TFDMemTable; LAdvJSONObjectWriter: IAdvJSONObjectWriter; begin if _ValidateData then begin LTask := TTask.Create( procedure() begin ResetBackEndpoint(BackEndpointPostItem); BackEndpointPostItem.AllowHTTPErrors := TCustomBackendEndpoint.TAllowHTTPErrors.None; BackEndpointPostItem.Accept := EMS_APPLICATION_JSON; BackEndpointPostItem.AddParameter( EMS_POST_ITEM_PARAM_NAME_DATATYPE, EMS_POST_ITEM_PARAM_VALUE_SUGGESTION, TRESTRequestParameterKind.pkHTTPHEADER); BackEndpointPostItem.Body.Add(LAdvJSONObjectWriter.AsJSONObject); try BackEndpointPostItem.Execute; finally if rRespPostItem.StatusCode <> HTTP_SUCCESSFUL_REQUEST then begin TThread.Synchronize( LThread, procedure() begin TDialogService.MessageDialog( ERROR_ON_INSERT_OPERATION, TMsgDlgType.mtError, [TMsgDlgBtn.mbOk], TMsgDlgBtn.mbOk, 0, procedure(const AResult: TModalResult)begin TAppSharedUtils.HideActivityIndicator; end); end); end else begin TThread.Synchronize( LThread, procedure() begin LDataSet.Close; LDataSet.Open; TDialogService.MessageDialog( INFORMATION_LAB_SUGGESTION_ACCEPTED, TMsgDlgType.mtInformation, [TMsgDlgBtn.mbOk], TMsgDlgBtn.mbOk, 0, procedure(const AResult: TModalResult)begin TAppSharedUtils.HideActivityIndicator; end); end); end; end; end); TAppSharedUtils.ShowActivityIndicator(frmUserProfile); LThread := TThread.CurrentThread; LDataSet := ADataSet; LAdvJSONObjectWriter := TAdvJSONObjectWriter.Create; LAdvJSONObjectWriter.AddStringPair('sugg_cname', ADataSet.FieldByName('sugg_cname').AsString); LAdvJSONObjectWriter.AddStringPair('sugg_cphone', ADataSet.FieldByName('sugg_cphone').AsString); LTask.Start; end else begin TThread.Synchronize( nil, procedure() begin TDialogService.MessageDialog( WARNING_LAB_SUGGESTION_REQUIRED_INFO_NOT_FOUND, TMsgDlgType.mtWarning, [TMsgDlgBtn.mbOk], TMsgDlgBtn.mbOk, 0, procedure(const AResult: TModalResult)begin frmUserProfile.edtTabiLaboratoryFocusHelper.SetFocus; end); end); end; end; procedure TsrvUserLaboratory.ResetBackEndpoint(ABackEndpoint: TBackendEndpoint); begin ABackEndpoint.AllowHTTPErrors := TCustomBackendEndpoint.TAllowHTTPErrors.None; ABackEndpoint.Params.Clear; ABackEndpoint.ResourceSuffix := EmptyStr; end; end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit WiRL.Console.Daemon; interface uses System.SysUtils, WiRl.Console.Base, WiRL.Console.Posix.Daemon; type TWiRLConsoleDaemon = class(TWiRLConsoleBase) protected procedure ConsoleSetup; override; procedure ConsoleStart; override; procedure ConsoleHelp; override; public class procedure LogInfo(const AMessage: string); override; class procedure LogWarning(const AMessage: string); override; class procedure LogError(const AMessage: string); override; class procedure LogRaw(const AMessage: string); override; end; implementation { TWiRLConsoleDaemon } procedure TWiRLConsoleDaemon.ConsoleSetup; var LAppName: string; begin LAppName := ExtractFileName(ParamStr(0)); TPosixDaemon.Setup( procedure (ASignal: TPosixSignal) begin case ASignal of TPosixSignal.Termination: begin ServerStop; end; TPosixSignal.Reload: begin ServerStop; //ServerSetup; ServerStart; end; end; end ); ConsoleHelp; end; procedure TWiRLConsoleDaemon.ConsoleStart; begin TPosixDaemon.LogInfo('WiRL Daemon is running...'); TPosixDaemon.Run(1000); end; procedure TWiRLConsoleDaemon.ConsoleHelp; begin LogInfo(TWiRLConsoleDef.Logo); LogInfo(TWiRLConsoleDef.OSVer + OSVersion); end; class procedure TWiRLConsoleDaemon.LogError(const AMessage: string); begin TPosixDaemon.LogError(AMessage); end; class procedure TWiRLConsoleDaemon.LogInfo(const AMessage: string); begin TPosixDaemon.LogInfo(AMessage); end; class procedure TWiRLConsoleDaemon.LogRaw(const AMessage: string); begin TPosixDaemon.LogRaw(AMessage); end; class procedure TWiRLConsoleDaemon.LogWarning(const AMessage: string); begin TPosixDaemon.LogWarning(AMessage); end; end.
namespace KTX; uses System; type ///Представляет клетку консоли KTXPixel = class public PosX, PosY: integer; public Back, Fore: Color; public Symbol: char; public static function FromBytes(value: array of byte; startindex: integer): KTXPixel; begin Result := new KTXPixel; Result.PosX := BitConverter.ToInt32(value, startindex); startindex += 4; Result.PosY := BitConverter.ToInt32(value, startindex); startindex += 4; Result.Back := Color(integer(value[startindex])); startindex += 1; Result.Fore := Color(integer(value[startindex])); startindex += 1; Result.Symbol := BitConverter.ToChar(value, startindex); startindex += 2; end; public function GetBytes: array of byte; begin var num := 0; Result := new byte[12]; foreach var x in BitConverter.GetBytes(PosX) do begin Result[num] := x; num += 1; end; foreach var x in BitConverter.GetBytes(PosY) do begin Result[num] := x; num += 1; end; Result[num] := byte(integer(Back)); num += 1; Result[num] := byte(integer(Fore)); num += 1; foreach var x in BitConverter.GetBytes(Symbol) do begin Result[num] := x; num += 1; end; end; end; end.
unit GraficoEstrategia; interface uses IncrustedDatosLineLayer, Grafico, Tipos, IncrustedItems, TB2Item, dataPanelEstrategia; type TTipoGraficoEstrategia = (tgeLAL, tgeLAC, tgeA11, tgePRUA, tgeA); TGraficoEstrategiaThread = class(TGraficoItemThread) private tipoGrafico: TTipoGraficoEstrategia; tipoGraficoA: integer; dataPanelEstrategia: TPanelEstrategia; protected procedure InternalExecute; override; end; TGraficoEstrategiaLayer = class(TGraficoItemLayer) protected procedure OnGraficoDataChanged; override; procedure Recalculate(const fromPos, toPos: integer); override; public constructor Create(Grafico: TGrafico); reintroduce; end; TGraficoEstrategia = class(TGraficoItem) private tipoGrafico: TTipoGraficoEstrategia; tipoGraficoA: integer; dataPanelEstrategia: TPanelEstrategia; protected function GetLayer: TGraficoItemLayer; override; function GetItemThread: TGraficoItemThread; override; public constructor Create(const Grafico: TGrafico; const itemToNotify: TTBCustomItem; const dataPanelEstrategia: TPanelEstrategia; const tipoGrafico: TTipoGraficoEstrategia; const tipoGraficoA: integer = -1); reintroduce; procedure Run; override; property item: TTBCustomItem read itemToNotify; end; implementation uses dmDataComun, DatosGrafico, Controls, SysUtils; resourcestring TITLE = 'Gráfico estrategia'; { TGraficoEstrategiaLayer } constructor TGraficoEstrategiaLayer.Create(Grafico: TGrafico); begin inherited Create(Grafico, true); end; procedure TGraficoEstrategiaLayer.OnGraficoDataChanged; begin //No hacemos nada, ya que tiene que repintar después de recalcular todo, //no cuando se cambia a un nuevo valor. end; procedure TGraficoEstrategiaLayer.Recalculate(const fromPos, toPos: integer); begin DatosLayer.MaximoManual := Grafico.Datos.Maximo; DatosLayer.MinimoManual := Grafico.Datos.Minimo; inherited Recalculate(fromPos, toPos); end; { TGraficoEstrategia } constructor TGraficoEstrategia.Create(const Grafico: TGrafico; const itemToNotify: TTBCustomItem; const dataPanelEstrategia: TPanelEstrategia; const tipoGrafico: TTipoGraficoEstrategia; const tipoGraficoA: integer); begin inherited Create(Grafico, itemToNotify); Self.tipoGrafico := tipoGrafico; Self.dataPanelEstrategia := dataPanelEstrategia; Self.tipoGraficoA := tipoGraficoA; end; function TGraficoEstrategia.GetItemThread: TGraficoItemThread; begin result := TGraficoEstrategiaThread.Create; TGraficoEstrategiaThread(result).tipoGrafico := tipoGrafico; TGraficoEstrategiaThread(result).tipoGraficoA := tipoGraficoA; TGraficoEstrategiaThread(result).dataPanelEstrategia := dataPanelEstrategia; end; function TGraficoEstrategia.GetLayer: TGraficoItemLayer; begin result := TGraficoEstrategiaLayer.Create(Grafico); end; procedure TGraficoEstrategia.Run; var tipo: string; begin case tipoGrafico of tgeLAL: tipo := 'LAL'; tgeLAC: tipo := 'LAC'; tgeA11: tipo := 'A11'; tgePRUA: tipo := 'PRUA'; tgeA: tipo := 'A' + IntToStr(tipoGraficoA); end; inherited Run(TITLE, tipo); end; { TGraficoEstrategiaThread } procedure TGraficoEstrategiaThread.InternalExecute; var i, num: integer; fecha: TDate; reglaResult: TReglaResult; begin num := Length(FPFechas^); dec(num); //zero based for i := 0 to num do begin if Terminated then exit; fecha := FPFechas^[i]; if (fecha = SIN_FECHA) or (FPCierres^[i] = FDataNull) then begin FPDatos^[i] := SIN_CAMBIO; end else begin reglaResult := dataPanelEstrategia.ReglaResult[i]; case tipoGrafico of tgeLAL: FPDatos^[i] := reglaResult.LAL; tgeLAC: FPDatos^[i] := reglaResult.LAC; tgeA11: FPDatos^[i] := reglaResult.A11; tgePRUA: FPDatos^[i] := reglaResult.PRUA; tgeA: FPDatos^[i] := reglaResult.A[tipoGraficoA]; end; end; end; end; end.
unit Form.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Actions, System.StrUtils, System.Types, Data.DB, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, Vcl.ActnList, Vcl.StdCtrls, Vcl.Menus, Comp.Generator.DataProxy, Comp.Generator.DataSetCode; type TFormMain = class(TForm) grbxAppCommands: TGroupBox; Button1: TButton; PageControl1: TPageControl; tshDataSet: TTabSheet; tshProxyCode: TTabSheet; GridPanel2: TGridPanel; btnGenerateDAO: TButton; DBGrid1: TDBGrid; tmrReady: TTimer; mmProxyCode: TMemo; Label1: TLabel; Splitter1: TSplitter; Button2: TButton; DataSource1: TDataSource; // -------------------------------------------------------------------- ActionList1: TActionList; actGenerateProxy: TAction; actConnect: TAction; actSelectConnectionDef: TAction; actExecSQL: TAction; actQueryBuilder: TAction; // -------------------------------------------------------------------- Panel1: TPanel; Label2: TLabel; mmSqlStatement: TMemo; GridPanel1: TGridPanel; pmnRecentConnections: TPopupMenu; Button3: TButton; Label3: TLabel; Button4: TButton; grbxProxyGenOptions: TGroupBox; edtUnitName: TEdit; Label4: TLabel; Label5: TLabel; tshFakeDataset: TTabSheet; gxbxFakeGenOptions: TGroupBox; rbtnFakeOptionFDMemTable: TRadioButton; rbtnFakeOptionClientDataSet: TRadioButton; rbtnFakeOptionAppendMultiline: TRadioButton; rbtnFakeOptionAppendSingleline: TRadioButton; GroupBox3: TGroupBox; GroupBox4: TGroupBox; mmFakeDataSetCode: TMemo; GroupBox5: TGroupBox; GroupBox6: TGroupBox; rbtnProxyOptionFieldLowerCase: TRadioButton; rbtnProxyOptionFieldUpperCase: TRadioButton; rbtnProxyOptionNoDataSetAccess: TRadioButton; rbtnProxyOptionCommnetedDataSet: TRadioButton; GroupBox7: TGroupBox; cbxProxyOptionIdentation: TComboBox; Label6: TLabel; edtClassName: TEdit; Label7: TLabel; Label8: TLabel; edtDSUnitName: TEdit; Label9: TLabel; GroupBox1: TGroupBox; cbxNumberOfRows: TComboBox; // -------------------------------------------------------------------- // Startup procedure FormCreate(Sender: TObject); procedure tmrReadyTimer(Sender: TObject); // -------------------------------------------------------------------- // Action events procedure actSelectConnectionDefExecute(Sender: TObject); procedure actConnectExecute(Sender: TObject); procedure actExecSQLExecute(Sender: TObject); procedure actGenerateProxyExecute(Sender: TObject); procedure actQueryBuilderExecute(Sender: TObject); procedure edtUnitNameKeyPress(Sender: TObject; var Key: Char); procedure rbtnFakeOptionFDMemTableClick(Sender: TObject); procedure rbtnFakeOptionClientDataSetClick(Sender: TObject); procedure rbtnFakeOptionAppendMultilineClick(Sender: TObject); procedure rbtnFakeOptionAppendSinglelineClick(Sender: TObject); procedure rbtnProxyOptionFieldLowerCaseClick(Sender: TObject); procedure rbtnProxyOptionFieldUpperCaseClick(Sender: TObject); procedure rbtnProxyOptionNoDataSetAccessClick(Sender: TObject); procedure rbtnProxyOptionCommnetedDataSetClick(Sender: TObject); procedure cbxProxyOptionIdentationChange(Sender: TObject); procedure edtClassNameKeyPress(Sender: TObject; var Key: Char); procedure edtDSUnitNameKeyPress(Sender: TObject; var Key: Char); procedure cbxNumberOfRowsChange(Sender: TObject); private fProxyGenerator: TDataProxyGenerator; fDataSetGenerator: TDSGenerator; fCurrentConnDefName: string; fDataSet: TDataSet; fConnectionMruList: string; procedure InitializeControls; procedure UpdateActionEnable; procedure StoreConnectionDefinitionInMRUList(const ConnDefName: string); function GetConnectionDefinitionMRUList: TStringDynArray; procedure FillConnectionMRUPopupMenu; procedure PopupMenuRecentConnectionsItemClick(Sender: TObject); function UpdateMRUList(const ConnDefName: string): boolean; procedure SetCurrentConnectionDefinition(ConnDefName: string); procedure AutomateMainForm; procedure UpdateFakeCode_AfterOptionChange; procedure UpdateProxyCode_AfterOptionChange; public end; var FormMain: TFormMain; implementation {$R *.dfm} uses System.Win.Registry, Helper.TDBGrid, Helper.TApplication, Helper.TFDConnection, App.AppInfo, DataModule.Main, Dialog.SelectDefinition, Dialog.QueryBuilder, Utils.Timer.Interval; const AppRegistryKey = 'Software\DelphiPower\DataSetProxyGenerator'; // -------------------------------------------------------------------------- // Connection Definition MRU List // * Storage level // * Domain level // -------------------------------------------------------------------------- // TODO: Extract because of SOLID #1: SRP (Single Responsibility) function TFormMain.UpdateMRUList(const ConnDefName: string): boolean; var list: System.Types.TStringDynArray; len: Integer; i: Integer; j: Integer; begin // TODO: Separate mru-list as an independent component if fConnectionMruList = '' then begin fConnectionMruList := ConnDefName; Result := True; end else begin list := System.StrUtils.SplitString(fConnectionMruList, ','); len := Length(list); if (list[0] = ConnDefName) then Result := False else begin i := 1; while (i < len) and (list[i] <> ConnDefName) do inc(i); if i < len then begin for j := i + 1 to len - 1 do list[j - 1] := list[j - 1]; SetLength(list, len - 1); end; fConnectionMruList := ConnDefName + ',' + String.Join(',', list); Result := True; end; end; end; procedure TFormMain.SetCurrentConnectionDefinition(ConnDefName: string); var IsSelectedDef: boolean; begin if (fCurrentConnDefName = '') or (ConnDefName <> '') then begin fCurrentConnDefName := ConnDefName; IsSelectedDef := (fCurrentConnDefName <> ''); if IsSelectedDef then actSelectConnectionDef.Caption := 'Definition: ' + fCurrentConnDefName else actSelectConnectionDef.Caption := 'Select Connection'; actConnect.Enabled := IsSelectedDef; end; end; procedure TFormMain.AutomateMainForm; begin // Level1: Select Connection fCurrentConnDefName := 'SQLite_Demo'; actSelectConnectionDef.Caption := 'Definition: ' + fCurrentConnDefName; actConnect.Enabled := True; // Level2: Connect if TAplicationAutomation.IsLevelSupported(2) then actConnect.Execute; // Level3: Open QueryBuilder dialog | Select demo query | Close dialog if TAplicationAutomation.IsLevelSupported(3) then actQueryBuilder.Execute; // Level4: Execute SQL command and shor results in grid if TAplicationAutomation.IsLevelSupported(4) then actExecSQL.Execute; // Level5: Generate proxy if TAplicationAutomation.IsLevelSupported(5) then actGenerateProxy.Execute; end; procedure TFormMain.StoreConnectionDefinitionInMRUList (const ConnDefName: string); var reg: TRegistry; begin if UpdateMRUList(ConnDefName) then begin // ---- // Store MRU list // ---- reg := TRegistry.Create(KEY_READ); try reg.RootKey := HKEY_CURRENT_USER; if not reg.KeyExists(AppRegistryKey) then begin reg.CreateKey(AppRegistryKey); // TODO: Check if CreateKey = True and log error end; reg.Access := KEY_WRITE; if reg.OpenKey(AppRegistryKey, False) then begin reg.WriteString('ConnectionMruList', fConnectionMruList); end; finally reg.Free; end; end; end; function TFormMain.GetConnectionDefinitionMRUList: TStringDynArray; var reg: TRegistry; begin if fConnectionMruList = '' then begin reg := TRegistry.Create(KEY_READ); try reg.RootKey := HKEY_CURRENT_USER; if reg.KeyExists(AppRegistryKey) then if reg.OpenKey(AppRegistryKey, False) then fConnectionMruList := reg.ReadString('ConnectionMruList'); finally reg.Free; end; end; if fConnectionMruList = '' then Result := nil else Result := System.StrUtils.SplitString(fConnectionMruList, ',') end; procedure TFormMain.FillConnectionMRUPopupMenu; var list: System.Types.TStringDynArray; i: Integer; item: TMenuItem; begin list := GetConnectionDefinitionMRUList; pmnRecentConnections.Items.Clear; for i := 0 to High(list) do begin item := TMenuItem.Create(pmnRecentConnections); with item do begin Caption := list[i]; Tag := i; OnClick := PopupMenuRecentConnectionsItemClick; end; pmnRecentConnections.Items.Add(item); end; end; procedure TFormMain.PopupMenuRecentConnectionsItemClick(Sender: TObject); var ConnDefName: string; begin if Sender is TMenuItem then begin ConnDefName := Vcl.Menus.StripHotkey((Sender as TMenuItem).Caption); if DataModule1.GetConnection.IsConnected then actConnect.Execute; SetCurrentConnectionDefinition(ConnDefName); end; end; function ComboBoxToRowsNumber(cbx:TComboBox): integer; var ss: string; idx: Integer; begin ss := cbx.Text; idx := ss.IndexOf(' '); if idx=-1 then Exit(0); Result := StrToInt(ss.Substring(0,idx)); end; // -------------------------------------------------------------------------- // Application start-up // -------------------------------------------------------------------------- procedure TFormMain.InitializeControls; begin PageControl1.ActivePageIndex := 0; PageControl1.Align := alClient; mmProxyCode.Align := alClient; mmSqlStatement.Clear; mmProxyCode.Clear; mmFakeDataSetCode.Clear; Self.Caption := TAppInfo.AppName + ' - ' + TAppInfo.Version; end; procedure TFormMain.FormCreate(Sender: TObject); begin // ------------------------------------------------------- fProxyGenerator := TDataProxyGenerator.Create(Self); fDataSetGenerator := TDSGenerator.Create(Self); // ------------------------------------------------------- fDataSet := DataModule1.GetMainDataQuery; DataSource1.DataSet := fDataSet; fProxyGenerator.NameOfUnit := 'Proxy.Foo'; fProxyGenerator.NameOfClass := 'TFooProxy'; fDataSetGenerator.NameOfUnit := 'Fake.DataSet'; fDataSetGenerator.MaxRows := ComboBoxToRowsNumber(cbxNumberOfRows); edtUnitName.Text := fProxyGenerator.NameOfUnit; edtClassName.Text := fProxyGenerator.NameOfClass; edtDSUnitName.Text := fDataSetGenerator.NameOfUnit; InitializeControls; // ------------------------------------------------------- // Inititialize actions // ------------------------------------------------------- if Application.InDeveloperMode then ReportMemoryLeaksOnShutdown := True; actConnect.Enabled := False; UpdateActionEnable; end; procedure TFormMain.tmrReadyTimer(Sender: TObject); begin tmrReady.Enabled := False; FillConnectionMRUPopupMenu; if TAplicationAutomation.IsActive then AutomateMainForm; end; procedure TFormMain.UpdateActionEnable(); begin actQueryBuilder.Enabled := DataModule1.GetConnection.IsConnected; actExecSQL.Enabled := DataModule1.GetConnection.IsConnected; actGenerateProxy.Enabled := fDataSet.Active; end; // -------------------------------------------------------------------------- // Action events // -------------------------------------------------------------------------- procedure TFormMain.actSelectConnectionDefExecute(Sender: TObject); begin if TDialogSelectDefinition.Execute then begin if DataModule1.GetConnection.IsConnected then actConnect.Execute; SetCurrentConnectionDefinition(TDialogSelectDefinition.ConnectionDef); end; end; procedure TFormMain.actConnectExecute(Sender: TObject); begin if not DataModule1.GetConnection.IsConnected then begin DataModule1.GetConnection.Open(fCurrentConnDefName); // TODO: misleading method name (2 responsibilities) // * AddOrUpdateConnection_MruList = UpdateMRUList // * WriteConnectionMruList StoreConnectionDefinitionInMRUList(fCurrentConnDefName); FillConnectionMRUPopupMenu; actConnect.Caption := 'Disconnect'; end else begin DataModule1.GetConnection.Close; actConnect.Caption := 'Connect'; PageControl1.ActivePageIndex := 0; mmProxyCode.Clear; end; UpdateActionEnable(); end; procedure TFormMain.actExecSQLExecute(Sender: TObject); begin DataModule1.ExecuteSQL(mmSqlStatement.Text); Self.UpdateActionEnable; DBGrid1.AutoSizeColumns(); end; procedure TFormMain.actGenerateProxyExecute(Sender: TObject); begin PageControl1.ActivePage := tshProxyCode; // ---------------------------------------------------- // DataSet Fake generator // ---------------------------------------------------- fProxyGenerator.DataSet := DataSource1.DataSet; fProxyGenerator.NameOfUnit := edtUnitName.Text; fProxyGenerator.NameOfClass := edtClassName.Text; fProxyGenerator.DataSetAccess := dsaNoAccess; fProxyGenerator.FieldNamingStyle := fnsUpperCaseF; fProxyGenerator.IndentationText := ' '; fProxyGenerator.Execute; mmProxyCode.Lines.Text := fProxyGenerator.Code.Text; // ---------------------------------------------------- // DataSet Fake generator // ---------------------------------------------------- fDataSetGenerator.DataSet := DataSource1.DataSet; fDataSetGenerator.NameOfUnit := edtDSUnitName.Text; fDataSetGenerator.GeneratorMode := genUnit; fDataSetGenerator.AppendMode := amMultilineAppends; fDataSetGenerator.DataSetType := dstFDMemTable; fDataSetGenerator.IndentationText := ' '; fDataSetGenerator.MaxRows := ComboBoxToRowsNumber(cbxNumberOfRows); fDataSetGenerator.Execute; mmFakeDataSetCode.Lines.Text := fDataSetGenerator.Code.Text; // ---------------------------------------------------- end; procedure TFormMain.actQueryBuilderExecute(Sender: TObject); var sql: string; begin sql := TDialogQueryBuilder.Execute; if sql <> '' then mmSqlStatement.Text := sql; end; procedure TFormMain.UpdateFakeCode_AfterOptionChange; begin if DataSource1.DataSet.Active then begin mmFakeDataSetCode.Color := clBtnFace; TIntervalTimer.SetTimeout(200, procedure begin fDataSetGenerator.Execute; mmFakeDataSetCode.Lines.Text := fDataSetGenerator.Code.Text; mmFakeDataSetCode.Color := clWindow; end); end; end; procedure TFormMain.UpdateProxyCode_AfterOptionChange; begin if DataSource1.DataSet.Active then begin mmProxyCode.Color := clBtnFace; TIntervalTimer.SetTimeout(200, procedure begin fProxyGenerator.Execute; mmProxyCode.Lines.Text := fProxyGenerator.Code.Text; mmProxyCode.Color := clWindow; end); end; end; procedure TFormMain.edtClassNameKeyPress(Sender: TObject; var Key: Char); begin if (Key = #13) then begin fProxyGenerator.NameOfUnit := edtUnitName.Text; fProxyGenerator.NameOfClass := edtClassName.Text; UpdateProxyCode_AfterOptionChange; Key := #0; end; end; procedure TFormMain.edtDSUnitNameKeyPress(Sender: TObject; var Key: Char); begin if (Key = #13) then begin fDataSetGenerator.NameOfUnit := edtDSUnitName.Text; UpdateFakeCode_AfterOptionChange; Key := #0; end; end; procedure TFormMain.edtUnitNameKeyPress(Sender: TObject; var Key: Char); begin if (Key = #13) then begin fProxyGenerator.NameOfUnit := edtUnitName.Text; fProxyGenerator.NameOfClass := edtClassName.Text; UpdateProxyCode_AfterOptionChange; Key := #0; end; end; procedure TFormMain.cbxNumberOfRowsChange(Sender: TObject); begin fDataSetGenerator.MaxRows := ComboBoxToRowsNumber(cbxNumberOfRows); UpdateFakeCode_AfterOptionChange; end; procedure TFormMain.cbxProxyOptionIdentationChange(Sender: TObject); begin case cbxProxyOptionIdentation.ItemIndex of 0: fProxyGenerator.IndentationText := ' '; 1: fProxyGenerator.IndentationText := ' '; end; UpdateProxyCode_AfterOptionChange; end; procedure TFormMain.rbtnProxyOptionCommnetedDataSetClick(Sender: TObject); begin fProxyGenerator.DataSetAccess := dsaGenComment; UpdateProxyCode_AfterOptionChange; end; procedure TFormMain.rbtnProxyOptionNoDataSetAccessClick(Sender: TObject); begin fProxyGenerator.DataSetAccess := dsaNoAccess; UpdateProxyCode_AfterOptionChange; end; procedure TFormMain.rbtnProxyOptionFieldLowerCaseClick(Sender: TObject); begin fProxyGenerator.FieldNamingStyle := fnsLowerCaseF; UpdateProxyCode_AfterOptionChange; end; procedure TFormMain.rbtnProxyOptionFieldUpperCaseClick(Sender: TObject); begin fProxyGenerator.FieldNamingStyle := fnsUpperCaseF; UpdateProxyCode_AfterOptionChange; end; procedure TFormMain.rbtnFakeOptionAppendMultilineClick(Sender: TObject); begin fDataSetGenerator.AppendMode := amMultilineAppends; UpdateFakeCode_AfterOptionChange; end; procedure TFormMain.rbtnFakeOptionAppendSinglelineClick(Sender: TObject); begin fDataSetGenerator.AppendMode := amSinglelineAppends; UpdateFakeCode_AfterOptionChange; end; procedure TFormMain.rbtnFakeOptionFDMemTableClick(Sender: TObject); begin fDataSetGenerator.DataSetType := dstFDMemTable; UpdateFakeCode_AfterOptionChange; end; procedure TFormMain.rbtnFakeOptionClientDataSetClick(Sender: TObject); begin fDataSetGenerator.DataSetType := dstClientDataSet; UpdateFakeCode_AfterOptionChange; end; // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- end.
unit base_connected_test; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry, connection_util; type TConnectRec = record DBHost: string; DBPath: string; UserName: string; Password: string; end; TBaseConnectedTest = class(TTestCase) protected procedure SetUp; override; end; var mDBConnect: TConnectRec; implementation { TTestUserRoles } procedure TBaseConnectedTest.SetUp; var lConnected: boolean; begin lConnected := ConnectToDatabase(mDBConnect.DBPath, mDBConnect.DBHost, mDBConnect.UserName, mDBConnect.Password); AssertTrue('Could not connect to database', lConnected); end; end.
(* ENUNCIAD0 O tratamento de duplicatas é um fator importante em alguns algoritmos. Um exemplo é um tipo que se pretende a representar um conjunto no sentido da teoria dos conjuntos e matemática. Um conjunto não pode ter elementos repetidos. Escreva um programa em Free Pascal que leia uma quantidade arbitrária de números inteiros positivos do teclado e determine os números repetidos fornecidos na entrada de dados. O programa deve imprimir apenas uma ocorrência de cada número repetido, mesmo que sejam fornecidas várias duplicatas do mesmo número no momento da entrada. O número zero é o último lido e não deve ser levado em conta na determinação de repetidos. Nota: O usuário nunca irá digitar mais do que 100 números para a entrada do programa (excluindo o zero). Um exemplo de entrada e saı́da é: Exemplo de entrada: 3 4 5 5 6 7 8 8 9 10 5 5 5 7 7 3 0 Saı́da esperada para a entrada acima: 3 5 7 8 *) program 1repetidos; const max = 1000; type meuvetor = array [1 .. max] of integer; var lista, ocor, freq: meuvetor; nocor,cont, posi: integer; procedure inicializa(var vetor: meuvetor); var posi:integer; begin for posi:=1 to max do vetor[posi]:=0; end; function ler(var vetor:meuvetor):integer; var cont:integer; begin cont:=0; repeat cont:=cont+1; read(lista[cont]); until lista[cont] = 0; ler:=cont; end; function verifica(cont:integer;var lista,ocor,freq:meuvetor):integer; var nocor,cont2,posi:integer; igual:boolean; begin nocor:=0; for cont2:=1 to (cont-1) do begin posi:=1; igual:=false; while (posi<=nocor) and (not igual) do begin if lista[cont2] = ocor[posi] then begin freq[posi]:=freq[posi]+1; igual:=true; end; posi:=posi+1; end; if not igual then begin nocor:=nocor+1; ocor[nocor]:=lista[cont2]; freq[nocor]:=1; end; end; verifica:=nocor; end; begin cont:= ler(lista); inicializa(ocor); inicializa(freq); nocor:=verifica(cont,lista,ocor,freq); for posi:=1 to nocor do begin if (freq[posi]>1) then write(ocor[posi],' '); end; end.
unit usbio_i_delphi; {************************************************************************ * * Description: declaration of needed types, constants and * functions from setupapi.dll ( refer to setupapi.h in C ) * * Runtime Env.: Win32, Part of UsbioLib * Author(s): Thomas Fröhlich * Company: Thesycon GmbH, Ilmenau ************************************************************************} interface uses Windows; type HDEVINFO = Pointer; function SetupDiGetClassDevsA( ClassGuid : PGUID; Enumerator : PCHAR; hwndParent : HWND; Flags : DWORD ): HDEVINFO; stdcall; external 'setupapi.dll'; //SetupDiGetClassDevsA( // IN LPGUID ClassGuid, OPTIONAL // IN PCSTR Enumerator, OPTIONAL // IN HWND hwndParent, OPTIONAL // IN DWORD Flags // ); const DIGCF_DEFAULT = DWORD($00000001); DIGCF_PRESENT = DWORD($00000002); DIGCF_ALLCLASSES = DWORD($00000004); DIGCF_PROFILE = DWORD($00000008); DIGCF_DEVICEINTERFACE = DWORD($00000010); type SP_DEVICE_INTERFACE_DETAIL_DATA_A = packed record cbSize : DWORD; DevicePath : array [0..0]of char; end; PSP_DEVICE_INTERFACE_DETAIL_DATA_A = ^SP_DEVICE_INTERFACE_DETAIL_DATA_A; //typedef struct _SP_DEVICE_INTERFACE_DETAIL_DATA_A { // DWORD cbSize; // CHAR DevicePath[ANYSIZE_ARRAY]; //} SP_DEVICE_INTERFACE_DETAIL_DATA_A, *PSP_DEVICE_INTERFACE_DETAIL_DATA_A; function SetupDiDestroyDeviceInfoList( DeviceInfoSet : HDEVINFO ): boolean; stdcall; external 'setupapi.dll'; //SetupDiDestroyDeviceInfoList( // IN HDEVINFO DeviceInfoSet // ); type SP_DEVINFO_DATA = packed record cbSize : DWORD; ClassGuid : TGUID; DevInst : DWORD; Reserved : DWORD; end; PSP_DEVINFO_DATA = ^SP_DEVINFO_DATA; //typedef struct _SP_DEVINFO_DATA { // DWORD cbSize; // GUID ClassGuid; // DWORD DevInst; // DEVINST handle // DWORD Reserved; //} SP_DEVINFO_DATA, *PSP_DEVINFO_DATA; type SP_DEVICE_INTERFACE_DATA = packed record cbSize : DWORD; InterfaceClassGuid : TGUID; Flags : DWORD; Reserved : DWORD; end; PSP_DEVICE_INTERFACE_DATA = ^SP_DEVICE_INTERFACE_DATA; //typedef struct _SP_DEVICE_INTERFACE_DATA { // DWORD cbSize; // GUID InterfaceClassGuid; // DWORD Flags; // DWORD Reserved; //} SP_DEVICE_INTERFACE_DATA, *PSP_DEVICE_INTERFACE_DATA; function SetupDiEnumDeviceInterfaces( DeviceInfoSet : HDEVINFO; DeviceInfoData : PSP_DEVINFO_DATA; InterfaceClassGuid : PGUID; MemberIndex : DWORD; DeviceInterfaceData : PSP_DEVICE_INTERFACE_DATA ):boolean;stdcall; external 'setupapi.dll'; //SetupDiEnumDeviceInterfaces( // IN HDEVINFO DeviceInfoSet, // IN PSP_DEVINFO_DATA DeviceInfoData, OPTIONAL // IN LPGUID InterfaceClassGuid, // IN DWORD MemberIndex, // OUT PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData // ); function SetupDiGetDeviceInterfaceDetailA( DeviceInfoSet : HDEVINFO; DeviceInterfaceData : PSP_DEVICE_INTERFACE_DATA; DeviceInterfaceDetailData : PSP_DEVICE_INTERFACE_DETAIL_DATA_A; DeviceInterfaceDetailDataSize : DWORD; RequiredSize : PDWORD; DeviceInfoData : PSP_DEVINFO_DATA ):boolean;stdcall; external 'setupapi.dll'; //SetupDiGetDeviceInterfaceDetailA( // IN HDEVINFO DeviceInfoSet, // IN PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData, // OUT PSP_DEVICE_INTERFACE_DETAIL_DATA_A DeviceInterfaceDetailData, OPTIONAL // IN DWORD DeviceInterfaceDetailDataSize, // OUT PDWORD RequiredSize, OPTIONAL // OUT PSP_DEVINFO_DATA DeviceInfoData OPTIONAL // ); implementation end.
unit SQLite3WrapApi; interface uses Windows, SQLite3; type PSQL3Db = ^TSQL3Db; TSQL3Db = record Handle : PSQLite3; LastError : Integer; IsTransactionOpen: Boolean; end; PSQL3Statement = ^TSQL3Statement; TSQL3Statement = record Handle : PSQLite3Stmt; Db : PSQL3Db; Sql : string; end; PSQL3Blob = ^TSQL3Blob; TSQL3Blob = record Handle : PSQLite3Blob; end; function SQL3DbCheck(ADataBase: PSQL3Db; const AErrCode: Integer; ACheckCode: Integer = SQLITE_OK): Boolean; function CheckOutSQL3Db: PSQL3Db; procedure CheckInSQL3Db(var ASQL3Db: PSQL3Db); function SQL3DbOpen(ADataBase: PSQL3Db; AFileName: WideString; AOpenFlag: integer; //SQLITE_OPEN_CREATE or SQLITE_OPEN_READWRITE or SQLITE_OPEN_NOMUTEX; Key: Pointer = nil; KeyLen: Integer = 0): Boolean; procedure SQL3DbClose(ADataBase: PSQL3Db); function SQL3DbExecute(ADataBase: PSQL3Db; const ASQL: WideString): Boolean; procedure SQL3DbBeginTransaction(ADataBase: PSQL3Db); procedure SQL3DbCommit(ADataBase: PSQL3Db); procedure SQL3DbRollback(ADataBase: PSQL3Db); function CheckOutSql3Statement(ADataBase: PSQL3Db; ASQL: string): PSQL3Statement; procedure CheckInSql3Statement(var AStatement: PSQL3Statement); function SQL3StatementStep(AStatement: PSQL3Statement): Integer; procedure SQL3StatementReset(AStatement: PSQL3Statement); function SQL3Statement_ColumnCount(AStatement: PSQL3Statement): Integer; function SQL3Statement_ColumnName(AStatement: PSQL3Statement; AColumnIndex: Integer): WideString; function SQL3Statement_ColumnType(AStatement: PSQL3Statement; AColumnIndex: Integer): Integer; function SQL3Statement_AsInt(AStatement: PSQL3Statement; AColumnIndex: Integer): Integer; function SQL3Statement_AsInt64(AStatement: PSQL3Statement; AColumnIndex: Integer): Int64; function SQL3Statement_AsDouble(AStatement: PSQL3Statement; AColumnIndex: Integer): Double; function SQL3Statement_AsAnsi(AStatement: PSQL3Statement; AColumnIndex: Integer): AnsiString; function SQL3Statement_AsWide(AStatement: PSQL3Statement; AColumnIndex: Integer): WideString; function SQL3Statement_AsBlob(AStatement: PSQL3Statement; AColumnIndex: Integer): Pointer; procedure SQL3Statement_BindInt(AStatement: PSQL3Statement; const AParamIndex, Value: Integer); procedure SQL3Statement_BindInt64(AStatement: PSQL3Statement; const AParamIndex: Integer; const Value: Int64); procedure SQL3Statement_BindNull(AStatement: PSQL3Statement; const AParamIndex: Integer); procedure SQL3Statement_BindAnsi(AStatement: PSQL3Statement; const AParamIndex: Integer; const Value: AnsiString); procedure SQL3Statement_BindZeroBlob(AStatement: PSQL3Statement; const AParamIndex, ASize: Integer); procedure SQL3Statement_ClearBindings(AStatement: PSQL3Statement); implementation uses SQLite3Utils; function SQL3DBCheck(ADataBase: PSQL3Db; const AErrCode: Integer; ACheckCode: Integer = SQLITE_OK): Boolean; //var // errorMessage: string; begin Result := AErrCode = ACheckCode; ADataBase.LastError := AErrCode; if AErrCode <> ACheckCode then begin //errorMessage := Format(SErrorMessage, [UTF8ToStr(_sqlite3_errmsg(FHandle))]); //if Assigned(SQLiteLogErrorFormat) then //begin //SQLiteLogErrorFormat('SQLite Error: %s. ErrorCode: %d', [errorMessage, ErrCode]); // raise ESQLite3Error.Create(errorMessage, ErrCode); //end; end; end; function CheckOutSQL3Db: PSQL3Db; begin Result := System.New(PSQL3Db); FillChar(Result^, SizeOf(TSQL3Db), 0); end; procedure CheckInSQL3Db(var ASQL3Db: PSQL3Db); begin if nil <> ASQL3Db then begin SQL3DbClose(ASQL3Db); FreeMem(ASQL3Db); ASQL3Db := nil; end; end; function DoSQLite3BusyCallback(ptr: Pointer; count: Integer): Integer; cdecl; begin Result := 0; // G_SqliteAnyBusy := True; // // if GetCurrentThreadId = MainThreadID then // begin // G_SqliteMainBusy := True; // // if count = 0 then // begin // G_BusyStart := GetTickCount; // Result := 1; // end // else if GetTickCount - G_BusyStart > SQLITE_MAINTHREAD_BUSYTIME then // Result := 0 // else // Result := 1; // end else // begin // Result := 1; // 子线程里面就无限等待 // end; end; function SQL3DbOpen(ADataBase: PSQL3Db; AFileName: WideString; AOpenFlag: integer; Key: Pointer = nil; KeyLen: Integer = 0): Boolean; var ret: integer; begin SQL3DbClose(ADataBase); // 采用UTF-8的编码方式 ret := _sqlite3_open_v2(PAnsiChar(SQLite3Utils.StrToUTF8(AFileName)), ADataBase.Handle, AOpenFlag, nil); Result := SQL3DBCheck(ADataBase, ret); if Result then begin if (Key <> nil) and (KeyLen > 0) then try Result := SQL3DBCheck(ADataBase, _sqlite3_key(ADataBase.Handle, Key, KeyLen)); except _sqlite3_close(ADataBase.Handle); ADataBase.Handle := nil; raise; end; SQL3DBCheck(ADataBase, _sqlite3_busy_handler(ADataBase.Handle, @DoSQLite3BusyCallback, ADataBase)); end; end; procedure SQL3DbClose(ADataBase: PSQL3Db); begin if nil <> ADataBase.Handle then begin if ADataBase.IsTransactionOpen then SQL3DbRollback(ADataBase); // Delete all statements //for I := FStatementList.Count - 1 downto 0 do // TSQLite3Statement(FStatementList[I]).Free; // Delete all blob handlers //for I := FBlobHandlerList.Count - 1 downto 0 do // TSQLite3BlobHandler(FBlobHandlerList[I]).Free; // Delete all blob writestreams //for I := FBlobStreamList.Count - 1 downto 0 do // TSQLite3BlobStream(FBlobStreamList[I]).Free; _sqlite3_close(ADataBase.Handle); ADataBase.Handle := nil; end; //ADataBase.FileName := ''; end; function SQL3DbExecute(ADataBase: PSQL3Db; const ASQL: WideString): Boolean; begin //CheckHandle; Result := SQL3DBCheck(ADataBase, _sqlite3_exec(ADataBase.Handle, PAnsiChar(StrToUTF8(ASQL)), nil, nil, nil)); end; procedure SQL3DbBeginTransaction(ADataBase: PSQL3Db); begin if not ADataBase.IsTransactionOpen then begin SQL3DbExecute(ADataBase, 'BEGIN TRANSACTION;'); // TODO: BEGIN TRANSACTION ADataBase.IsTransactionOpen := True; end else begin //if Assigned(SQLiteLogError) then // SQLiteLogError('SQLite: Transaction is already open.'); // raise ESQLite3Error.Create(STransactionAlreadyOpen); end; end; procedure SQL3DbCommit(ADataBase: PSQL3Db); begin if ADataBase.IsTransactionOpen then begin SQL3DbExecute(ADataBase, 'COMMIT;'); ADataBase.IsTransactionOpen := False; end else begin //raise ESQLite3Error.Create(SNoTransactionOpen); end; end; procedure SQL3DbRollback(ADataBase: PSQL3Db); begin if ADataBase.IsTransactionOpen then begin SQL3DbExecute(ADataBase, 'ROLLBACK;'); ADataBase.IsTransactionOpen := False; end else begin //raise ESQLite3Error.Create(SNoTransactionOpen); end; end; function CheckOutSql3Statement(ADataBase: PSQL3Db; ASQL: string): PSQL3Statement; begin Result := System.New(PSQL3Statement); FillChar(Result^, SizeOf(TSQL3Statement), 0); Result.Db := ADataBase; Result.Sql := ASQL; //FOwnerDatabase.CheckHandle; SQL3DBCheck( ADataBase, _sqlite3_prepare_v2(ADataBase.Handle, PAnsiChar(StrToUTF8(Result.Sql)), -1, Result.Handle, nil) ); //FOwnerDatabase.FStatementList.Add(Self); //FStrList := TList.Create; end; procedure CheckInSql3Statement(var AStatement: PSQL3Statement); begin if nil <> AStatement then begin if nil <> AStatement.Handle then begin _sqlite3_finalize(AStatement.Handle); AStatement.Handle := 0; end; FreeMem(AStatement); AStatement := nil; end; end; function SQL3StatementStep(AStatement: PSQL3Statement): Integer; //var // errnum: Integer; begin Result := _sqlite3_step(AStatement.Handle); if Result = SQLITE_FULL then begin end; end; procedure SQL3StatementReset(AStatement: PSQL3Statement); begin _sqlite3_reset(AStatement.Handle); //ClearStrList; end; function SQL3Statement_ColumnCount(AStatement: PSQL3Statement): Integer; begin Result := _sqlite3_column_count(AStatement.Handle); end; function SQL3Statement_ColumnName(AStatement: PSQL3Statement; AColumnIndex: Integer): WideString; begin Result := UTF8ToStr(_sqlite3_column_name(AStatement.Handle, AColumnIndex)); end; function SQL3Statement_ColumnType(AStatement: PSQL3Statement; AColumnIndex: Integer): Integer; begin Result := _sqlite3_column_type(AStatement.Handle, AColumnIndex); end; function SQL3Statement_ColumnBytes(AStatement: PSQL3Statement; AColumnIndex: Integer): Integer; begin Result := _sqlite3_column_bytes(AStatement.Handle, AColumnIndex); end; function SQL3Statement_AsInt(AStatement: PSQL3Statement; AColumnIndex: Integer): Integer; begin Result := _sqlite3_column_int(AStatement.Handle, AColumnIndex); end; function SQL3Statement_AsInt64(AStatement: PSQL3Statement; AColumnIndex: Integer): Int64; begin Result := _sqlite3_column_int64(AStatement.Handle, AColumnIndex); end; function SQL3Statement_AsDouble(AStatement: PSQL3Statement; AColumnIndex: Integer): Double; begin Result := _sqlite3_column_double(AStatement.Handle, AColumnIndex); end; function SQL3Statement_AsAnsi(AStatement: PSQL3Statement; AColumnIndex: Integer): AnsiString; var tmpLen: Integer; P: PAnsiChar; begin tmpLen := SQL3Statement_ColumnBytes(AStatement, AColumnIndex); SetLength(Result, tmpLen); if tmpLen > 0 then begin P := _sqlite3_column_text(AStatement.Handle, AColumnIndex); Move(P^, PAnsiChar(Result)^, tmpLen); end; end; function SQL3Statement_AsWide(AStatement: PSQL3Statement; AColumnIndex: Integer): WideString; var tmpLen: Integer; begin tmpLen := SQL3Statement_ColumnBytes(AStatement, AColumnIndex); Result := UTF8ToStr(_sqlite3_column_text(AStatement.Handle, AColumnIndex), tmpLen); end; function SQL3Statement_AsBlob(AStatement: PSQL3Statement; AColumnIndex: Integer): Pointer; begin Result := _sqlite3_column_blob(AStatement.Handle, AColumnIndex); end; procedure SQL3Statement_BindInt(AStatement: PSQL3Statement; const AParamIndex, Value: Integer); begin //FOwnerDatabase.Check( _sqlite3_bind_int(AStatement.Handle, AParamIndex, Value); end; procedure SQL3Statement_BindInt64(AStatement: PSQL3Statement; const AParamIndex: Integer; const Value: Int64); begin //FOwnerDatabase.Check( _sqlite3_bind_int64(AStatement.Handle, AParamIndex, Value); end; procedure SQL3Statement_BindNull(AStatement: PSQL3Statement; const AParamIndex: Integer); begin //FOwnerDatabase.Check( _sqlite3_bind_null(AStatement.Handle, AParamIndex); end; procedure SQL3Statement_BindAnsi(AStatement: PSQL3Statement; const AParamIndex: Integer; const Value: AnsiString); var P: PAnsiString; begin New(P); // FStrList.Add(P); P^ := Value; //FOwnerDatabase.Check( _sqlite3_bind_text(AStatement.Handle, AParamIndex, PAnsiChar(P^), Length(P^), SQLITE_STATIC); end; procedure SQL3Statement_BindZeroBlob(AStatement: PSQL3Statement; const AParamIndex, ASize: Integer); begin //FOwnerDatabase.Check( _sqlite3_bind_zeroblob(AStatement.Handle, AParamIndex, ASize); end; procedure SQL3Statement_ClearBindings(AStatement: PSQL3Statement); begin //FOwnerDatabase.Check( _sqlite3_clear_bindings(AStatement.Handle); end; end.
// **************************************************************************** // // Program Name : - AT Library - // Program Version: 1.00 // Filenames : AT.Windows.pas // File Version : 1.00 // Date Created : 26-JAN-2014 // Author : Matthew S. Vesperman // // Description: // // Windows OS functions... (Migrated from SSWindows.pas) // // Revision History: // // v1.00 : Initial version for Delphi XE5 // // **************************************************************************** // // COPYRIGHT © 2013-Present Angelic Technology // ALL RIGHTS RESERVED WORLDWIDE // // **************************************************************************** unit AT.Windows; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils; type /// <summary> /// Stores the name of the current workstation. /// </summary> TComputerName = String; /// <summary> /// Stores a directory (folder) name. /// </summary> TDirectoryName = String; // folder name /// <summary> /// Type of Windows Explorer window to show. /// </summary> TExploreType = ( /// <summary> /// Display Explorer in explore mode. /// </summary> etExplore, /// <summary> /// Display Explorer in folder mode. /// </summary> etFolder); /// <summary> /// Operating System Platform Type. /// </summary> TOSPlatform = ( /// <summary> /// Unknown OS. /// </summary> osUnknown, /// <summary> /// Windows 3.x /// </summary> osWin3x, /// <summary> /// Windows 9x/ME /// </summary> osWin9x, /// <summary> /// Windows NT based. /// </summary> osWinNT); // platform /// <summary> /// Currently logged in username. /// </summary> TOSUserName = String; /// <summary> /// OS registered owner. /// </summary> TRegOwner = String; // registered owner /// <summary> /// OS registered company. /// </summary> TRegCompany = String; // registered company EExploreBadAssoc = class(Exception) end; EExploreGenError = class(Exception) private FErrorCode: Integer; FFolder: string; public constructor CreateErr(const Msg: String; const iErrCode: Integer; const sFolder: String); property ErrorCode: Integer read FErrorCode write FErrorCode; property Folder: string read FFolder write FFolder; end; EExploreNoAccess = class(Exception) end; EExploreNotFound = class(Exception) end; ERegCompanyError = class(Exception) end; ERegUserError = class(Exception) end; EOSVersionError = class(Exception) end; EURLBadAssoc = class(Exception) end; EURLGenError = class(Exception) private FErrorCode: Integer; FURL: string; public constructor CreateErr(const Msg: String; const iErrCode: Integer; const sURL: String); property ErrorCode: Integer read FErrorCode write FErrorCode; property URL: string read FURL write FURL; end; EURLNoAccess = class(Exception) end; EURLNotFound = class(Exception) end; /// <summary> /// Deletes the file(s) specified in AFilename. /// </summary> /// <param name="AFilename"> /// The file(s) to delete. If more than 1 file is specified they must be /// separated by #0. You may also specify a folder name (to recurively empty /// the folder) and you may specify wildcards as well. The wildcard *.* WILL /// recursively empty the folder. /// </param> /// <param name="AHWND"> /// Handle to the parent window. Default: 0 (no parent) /// </param> /// <param name="AUndo"> /// Flag to indicate if the action can be reversed. (If TRUE then files are /// moved to the recycle bin, otherwise they are permanently removed.) /// Default: FALSE /// </param> /// <returns> /// Returns TRUE if the file(s) were removed, FALSE otherwise. /// </returns> /// <remarks> /// Calls the Windows Shell to delete the file(s). /// </remarks> function DeleteFile(AFilename: String; AHWND: THandle = 0; AUndo: Boolean = False): Boolean; /// <summary> /// Removes all files/folders contained in AFolder. /// </summary> /// <param name="AFolder"> /// The name of the folder to empty. /// </param> /// <param name="AHWND"> /// Handle to the parent window. Default: 0 (no parent) /// </param> /// <param name="AUndo"> /// Flag to indicate if the action can be reversed. (If TRUE then files are /// moved to the recycle bin, otherwise they are permanently removed.) /// Default: FALSE /// </param> /// <returns> /// Returns TRUE if the folder was emptied, FALSE otherwise. /// </returns> /// <remarks> /// Calls ATWindows.DeleteFile to empty the folder after checking to make /// sure the folder exists. /// </remarks> function EmptyFolder(const AFolder: String; AHWND: THandle = 0; AUndo: Boolean = False): Boolean; /// <summary> /// Opens a Windows Explorer window displaying the contents of AFolder. /// </summary> /// <param name="AFolder"> /// The name of the folder whos conents you wish to display. /// </param> /// <param name="AHWND"> /// Handle to the parent window. Default: 0 (no parent) /// </param> /// <param name="AExploreType"> /// The type of Explorer window to display. Default: etFolder /// </param> /// <param name="AShowCmd"> /// The windows show type. Default: SW_NORMAL /// </param> /// <returns> /// Returns TRUE if successful, FALSE otherwise. /// </returns> function ExploreFolder(const AFolder: String; const AHWND: THandle = 0; const AExploreType: TExploreType = etFolder; const AShowCmd: Integer = SW_NORMAL): Boolean; /// <summary> /// Retrieves the name of the workstation. /// </summary> /// <returns> /// Returns a string containing the name of the workstation. /// </returns> function GetComputer: TComputerName; /// <summary> /// Retrieves the name of the folder where the application's executable /// resides. /// </summary> /// <returns> /// Returns a string containing the name of the folder where the /// application's executable is located. /// </returns> function GetExeFolder: String; /// <summary> /// Retrieves the name of the application's executable /// </summary> /// <returns> /// Returns a string containing the name of the application's executable. /// </returns> function GetExeName: String; /// <summary> /// Retrieves the long version of a filename in 8.3 format. /// </summary> /// <param name="AFileName"> /// A filename in 8.3 format. /// </param> /// <returns> /// Returns a string containing the long version of AFileName. /// </returns> function GetLongFileName(Const AFilename: String): String; /// <summary> /// Retrieves the OS version information. /// </summary> /// <returns> /// Returns a TOSVersionInfor structure containing the OS version information. /// </returns> function GetOSVersion: TOSVersionInfo; /// <summary> /// Retrieves the OS platform information. /// </summary> /// <returns> /// Returns a TOSPlatform value containing the platform type. /// </returns> function GetOSPlatform: TOSPlatform; /// <summary> /// Retrieves the name of the currently logged in user. /// </summary> /// <returns> /// Returns a string containing the name of the currently logged in user. /// </returns> function GetOSUserName: TOSUserName; /// <summary> /// Retrieves the name of the company that Windows is registered to. /// </summary> /// <returns> /// Returns a string containing the name of the company that Windows is /// registered to. /// </returns> function GetRegCompany: TRegCompany; /// <summary> /// Retrieves the name of the person that Windows is registered to. /// </summary> /// <remarks> /// Returns a string containing the name of the person that Windows is /// registered to. /// </remarks> function GetRegOwner: TRegOwner; /// <summary> /// Retrieves the short (8.3) name of AFileName. /// </summary> /// <param name="AFileName"> /// The name of a file. /// </param> /// <returns> /// Returns a string containing the short (8.3) version of AFileName. /// </returns> function GetShortFileName(Const AFilename: String): String; /// <summary> /// Retrieves the location of the Windows System folder. /// </summary> /// <returns> /// Returns a string containing the name of the Windows System folder. /// </returns> function GetSysDir: TDirectoryName; /// <summary> /// Retrieves the location of the Windows Temporary folder. /// </summary> /// <returns> /// Returns a string containing the name of the Windows Temporary folder. /// </returns> function GetTempDir: TDirectoryName; /// <summary> /// Calculates a name for a temporary file, and optionally creates the file. /// </summary> /// <param name="bCreate"> /// Should the temp file be created? Default: TRUE /// </param> /// <param name="sPrefix"> /// Prefix for the temp filename. Default: 'tmp' /// </param> /// <returns> /// Returns a string containing the name of the temp file. /// </returns> function GetTempFile(const bCreate: Boolean = True; const sPrefix: String = 'tmp'): TFileName; /// <summary> /// Retrieves the location of the Windows folder. /// </summary> /// <returns> /// Returns a string containing the name of the Windows folder. /// </returns> function GetWinDir: TDirectoryName; /// <summary> /// Opens the default web browser and navigates the to specified URL. /// </summary> /// <param name="sURL"> /// The URL to navigate to. /// </param> /// <param name="aHWND"> /// Handle to the parent window. Default: 0 (no parent) /// </param> /// <param name="iShowCmd"> /// The windows show type. Default: SW_NORMAL /// </param> /// <returns> /// Returns TRUE if successful, FALSE otherwise. /// </returns> function GotoURL(const sURL: String; const AHWND: THandle = 0; const iShowCmd: Integer = SW_NORMAL): Boolean; /// <summary> /// Check if Caps Lock is enabled. /// </summary> /// <returns> /// Returns TRUE if Caps Lock is enabled, FALSE otherwise. /// </returns> function IsCapsLockOn: Boolean; /// <summary> /// Check if Control is pressed. /// </summary> /// <remarks> /// Returns TRUE if the Control Key is pressed, FALSE otherwise. /// </remarks> function IsControlPressed: Boolean; /// <summary> /// Check if Num Lock is enabled. /// </summary> /// <returns> /// Returns TRUE if Num Lock is enabled, FALSE otherwise. /// </returns> function IsNumLockOn: Boolean; /// <summary> /// Check if Scroll Lock is enabled. /// </summary> /// <remarks> /// Returns TRUE if Scroll Lock is enabled, FALSE otherwise. /// </remarks> function IsScrollLockOn: Boolean; function SelectFolder(const ATitle: string; var ADir: string): Boolean; /// <summary> /// Opens the system Date/Time properties control panel. /// </summary> procedure SetSystemDateTime; /// <summary> /// Runs an external application using the ShellExecuteEx windows /// API call and waits for it to finish. /// </summary> /// <param name="ACommand"> /// The name of the executable or file to run/open. /// </param> /// <param name="AParams"> /// Any parameters to pass to the executable. /// </param> /// <param name="AVisibility"> /// The visibility constant. /// </param> /// <param name="ARunElevated"> /// Should the program run as administrator? True for admin, False /// for normal. /// </param> /// <returns> /// True if the app ran successfully, false otherwise. /// </returns> /// <remarks> /// This function blocks the calling thread until the external app /// closes. /// </remarks> function ShellExecuteAndWait(const ACommand, AParams: String; const AVisibility: Integer; const ARunElevated: Boolean = False): Boolean; /// <summary> /// Replaces all occurrences of ACharToChange in AVal with ACharToUse. /// </summary> /// <param name="AVal"> /// The string to search in. /// </param> /// <param name="ACharToChange"> /// The character to search for. /// </param> /// <param name="ACharToUse"> /// The character to change ACharToChange to. /// </param> /// <returns> /// Returns a copy of AVal where all instance of ACharToChange have been /// replaced with ACharToUse. /// </returns> function SubstChar(const AVal: String; const ACharToChange, ACharToUse: Char): String; /// <summary> /// Toggles the state of the Caps Lock key. /// </summary> procedure ToggleCapsLock; /// <summary> /// Toggles the state of the Num Lock key. /// </summary> procedure ToggleNumLock; /// <summary> /// Toggles the state of the Scroll Lock key. /// </summary> procedure ToggleScrollLock; /// <summary> /// Retrieves the maximum size of an OS user name. /// </summary> /// <remarks> /// Returns the maximum size of an OS user name. /// </remarks> function UserNameSize: LongInt; /// <summary> /// Executes the command passed in APath and waits for it to finish. /// </summary> /// <param name="APath"> /// The path to the executable to run. You may pass parameters to the /// command here. /// </param> /// <param name="AVisibility"> /// The windows show value. Can pass any SW_xxx value. /// </param> /// <returns> /// Returns 0 if successful, otherwise returns an error code. /// </returns> function WinExecAndWait32(APath: PChar; AVisibility: Word): Integer; implementation uses Winapi.ShellAPI, System.Win.Registry, AT.Windows.System, AT.Strings.Replace, Winapi.ShlObj, WinApi.ActiveX, AT.GarbageCollector; type TRegInfoData = String; TRegInfoItem = (riOwner, riCompany); function DeleteFile(AFilename: String; AHWND: THandle = 0; AUndo: Boolean = False): Boolean; var FOp: TShFileOpStruct; begin ZeroMemory(@FOp, SizeOf(TShFileOpStruct)); FOp.Wnd := AHWND; FOp.wFunc := FO_DELETE; FOp.pFrom := PChar(AFilename + #0); FOp.fFlags := FOF_NOCONFIRMATION OR FOF_SILENT; if (AUndo) then FOp.fFlags := FOp.fFlags OR FOF_ALLOWUNDO; Result := (SHFileOperation(FOp) = 0); end; // DeleteFile function EmptyFolder(const AFolder: String; AHWND: THandle = 0; AUndo: Boolean = False): Boolean; var sFldr: String; begin sFldr := IncludeTrailingPathDelimiter(AFolder); // Save folder name to local storage... Result := DirectoryExists(sFldr); // Check if folder exists... // Result is FALSE if folder does not exist, TRUE if it does... if (Result) then // if folder exists... begin sFldr := Format('%s*.*', [AFolder]); // Append \*.* to folder name... Result := DeleteFile(sFldr, AHWND, AUndo); // Delete files... end; end; // EmptyFolder... function ExploreFolder(const AFolder: String; const AHWND: THandle = 0; const AExploreType: TExploreType = etFolder; const AShowCmd: Integer = SW_NORMAL): Boolean; const sBadFormat = 'The .EXE file is invalid (non-Win32 .EXE or error in .EXE ' + 'image.'; sDDEBusy = 'The DDE transaction could not be completed because other ' + 'DDE transactions were being processed.'; sDDEFail = 'The DDE transaction failed.'; sDDETimeOut = 'The DDE transaction could not be completed because the ' + 'request timed out.'; sDLLNotFound = 'The specified dynamic-link library was not found.'; sOutOfMemory = 'The operating system is out of memory.'; sPathNotFound = 'The specified path was not found.'; sShareError = 'A sharing voilation occurred.'; sUnknownErr = 'An unexpected error occurred.'; sURLBadAssoc = 'The application association for folders is incomplete ' + 'or invalid.'; sURLNoAccess = 'Access to folder "%s" has been denied.'; sURLNotFound = 'The specified folder "%s" was not found.'; var Res: HINST; sVal: String; sCmd: String; begin try if (AExploreType = etExplore) then sCmd := 'EXPLORE' else sCmd := 'OPEN'; Res := ShellExecute(AHWND, PChar(sCmd), PChar(AFolder), '', '', AShowCmd); Result := (Res > 32); if (NOT Result) then begin case Res of 0, SE_ERR_OOM: EOutOfMemory.Create(sOutOfMemory); ERROR_FILE_NOT_FOUND: EExploreNotFound.CreateFmt(sURLNotFound, [AFolder]); SE_ERR_ACCESSDENIED: EExploreNoAccess.CreateFmt(sURLNoAccess, [AFolder]); SE_ERR_NOASSOC, SE_ERR_ASSOCINCOMPLETE: EExploreBadAssoc.Create(sURLBadAssoc); else case Res of ERROR_PATH_NOT_FOUND: sVal := sPathNotFound; ERROR_BAD_FORMAT: sVal := sBadFormat; SE_ERR_DDEBUSY: sVal := sDDEBusy; SE_ERR_DDEFAIL: sVal := sDDEFail; SE_ERR_DDETIMEOUT: sVal := sDDETimeOut; SE_ERR_DLLNOTFOUND: sVal := sDLLNotFound; SE_ERR_SHARE: sVal := sShareError; else sVal := sUnknownErr; end; EExploreGenError.CreateErr(sVal, Res, AFolder) end; end; except Result := False; end; end; // ExploreFolder... function GetComputer: TComputerName; var iSize: Cardinal; sName: String; bOk: Boolean; sRes: String; begin iSize := 1024; SetLength(sName, iSize); bOk := GetComputerName(PChar(sName), iSize); if (bOk) then begin SetLength(sName, iSize); sRes := sName; end else sRes := ''; Result := sRes; end; function GetExeFolder: String; var sFolder: String; begin sFolder := ParamStr(0); sFolder := ExpandFileName(sFolder); sFolder := ExtractFilePath(sFolder); sFolder := IncludeTrailingPathDelimiter(sFolder); Result := sFolder; end; function GetExeName: String; var sFilename: String; begin sFilename := ParamStr(0); sFilename := ExpandFileName(sFilename); sFilename := ExtractFileName(sFilename); Result := sFilename; end; function GetLongFileName(Const AFilename: String): String; var aInfo: TSHFileInfo; begin if SHGetFileInfo(PChar(AFilename), 0, aInfo, SizeOf(aInfo), SHGFI_DISPLAYNAME) <> 0 then Result := String(aInfo.szDisplayName) else Result := AFilename; end; function GetOSVersion: TOSVersionInfo; begin Result.dwOSVersionInfoSize := SizeOf(TOSVersionInfo); if (NOT(GetVersionEx(Result))) then raise EOSVersionError.Create ('Could not retrieve OS Version information.'); end; function GetOSPlatform: TOSPlatform; begin case GetOSVersion.dwPlatformId of VER_PLATFORM_WIN32s: Result := osWin3x; VER_PLATFORM_WIN32_WINDOWS: Result := osWin9x; VER_PLATFORM_WIN32_NT: Result := osWinNT; else Result := osUnknown; end; end; function GetOSUserName: TOSUserName; var iSize: Cardinal; UserName: String; bOk: Boolean; sRes: String; begin iSize := 1024; SetLength(UserName, iSize); bOk := GetUserName(PChar(UserName), iSize); if (bOk) then begin SetLength(UserName, iSize - 1); sRes := UserName; end else sRes := ''; Result := sRes; end; function GetRegInfo(const aItem: TRegInfoItem; var sValue: TRegInfoData): Boolean; const sWin95Key = '\SOFTWARE\Microsoft\Windows\CurrentVersion'; sWinNTKey = '\SOFTWARE\Microsoft\Windows NT\CurrentVersion'; var sKey: String; Reg: TRegistry; sItem: String; begin case GetOSPlatform of osWin9x: sKey := sWin95Key; osWinNT: sKey := sWinNTKey; else sValue := ''; Result := False; Exit; end; Result := False; Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if (Reg.OpenKey(sKey, False)) then begin case aItem of riOwner: sItem := 'RegisteredOwner'; riCompany: sItem := 'RegisteredOrganization'; end; sValue := Reg.ReadString(sItem); Result := True; end; finally Reg.Free; end; end; function GetRegCompany: TRegCompany; const sMsg = 'Could not find the registered company in the Windows registry'; var sValue: String; begin if (GetRegInfo(riCompany, sValue)) then Result := sValue else raise ERegCompanyError.Create(sMsg); end; function GetRegOwner: TRegOwner; const sMsg = 'Could not find the registered owner in the Windows registry'; var sValue: String; begin if (GetRegInfo(riOwner, sValue)) then Result := sValue else raise ERegUserError.Create(sMsg); end; function GetShortFileName(Const AFilename: String): String; var aTmp: array [0 .. 255] of Char; sRes: String; begin if (GetShortPathName(PChar(AFilename), aTmp, SizeOf(aTmp) - 1) = 0) then sRes := AFilename else sRes := StrPas(aTmp); Result := sRes; end; function GetSysDir: TDirectoryName; var iSize: Cardinal; sDir: String; bOk: Boolean; sRes: String; begin iSize := MAX_PATH; SetLength(sDir, iSize); iSize := GetSystemDirectory(PChar(sDir), iSize); bOk := (iSize > 0); if (bOk) then begin SetLength(sDir, iSize); sRes := sDir; end else sRes := ''; Result := sRes; end; function GetTempDir: TDirectoryName; var iSize: Cardinal; sDir: String; bOk: Boolean; sRes: String; begin iSize := MAX_PATH; SetLength(sDir, iSize); iSize := GetTempPath(iSize, PChar(sDir)); bOk := (iSize > 0); if (bOk) then begin SetLength(sDir, iSize); sRes := sDir; end else sRes := 'C:\'; Result := ExcludeTrailingPathDelimiter(sRes); end; function GetTempFile(const bCreate: Boolean = True; const sPrefix: String = 'tmp'): TFileName; var iSize: Cardinal; sFN: String; bOk: Boolean; sRes: String; begin iSize := MAX_PATH; SetLength(sFN, iSize); iSize := GetTempFileName(PChar(GetTempDir), PChar(sPrefix), 0, PChar(sFN)); bOk := (iSize > 0); if (bOk) then begin SetLength(sFN, iSize); sRes := sFN; end else sRes := ''; if (NOT bCreate) then DeleteFile(sRes); Result := sRes; end; function GetWinDir: TDirectoryName; var iSize: Cardinal; sDir: String; bOk: Boolean; sRes: String; begin iSize := MAX_PATH; SetLength(sDir, iSize); iSize := GetWindowsDirectory(PChar(sDir), iSize); bOk := (iSize > 0); if (bOk) then begin SetLength(sDir, iSize); sRes := sDir; end else sRes := ''; Result := sRes; end; function GotoURL(const sURL: String; const AHWND: THandle = 0; const iShowCmd: Integer = SW_NORMAL): Boolean; const sBadFormat = 'The .EXE file is invalid (non-Win32 .EXE or error in .EXE ' + 'image.'; sDDEBusy = 'The DDE transaction could not be completed because other ' + 'DDE transactions were being processed.'; sDDEFail = 'The DDE transaction failed.'; sDDETimeOut = 'The DDE transaction could not be completed because the ' + 'request timed out.'; sDLLNotFound = 'The specified dynamic-link library was not found.'; sOutOfMemory = 'The operating system is out of memory.'; sPathNotFound = 'The specified path was not found.'; sShareError = 'A sharing voilation occurred.'; sUnknownErr = 'An unexpected error occurred.'; sURLBadAssoc = 'The application association for web pages is incomplete ' + 'or invalid.'; sURLNoAccess = 'Access to URL "%s" has been denied.'; sURLNotFound = 'The specified URL "%s" was not found.'; var Res: HINST; sVal: String; begin try Res := ShellExecute(AHWND, 'OPEN', PChar(sURL), '', '', iShowCmd); Result := (Res > 32); if (NOT Result) then begin case Res of 0, SE_ERR_OOM: EOutOfMemory.Create(sOutOfMemory); ERROR_FILE_NOT_FOUND: EURLNotFound.CreateFmt(sURLNotFound, [sURL]); SE_ERR_ACCESSDENIED: EURLNoAccess.CreateFmt(sURLNoAccess, [sURL]); SE_ERR_NOASSOC, SE_ERR_ASSOCINCOMPLETE: EURLBadAssoc.Create(sURLBadAssoc); else case Res of ERROR_PATH_NOT_FOUND: sVal := sPathNotFound; ERROR_BAD_FORMAT: sVal := sBadFormat; SE_ERR_DDEBUSY: sVal := sDDEBusy; SE_ERR_DDEFAIL: sVal := sDDEFail; SE_ERR_DDETIMEOUT: sVal := sDDETimeOut; SE_ERR_DLLNOTFOUND: sVal := sDLLNotFound; SE_ERR_SHARE: sVal := sShareError; else sVal := sUnknownErr; end; EURLGenError.CreateErr(sVal, Res, sURL) end; end; except Result := False; end; end; function IsCapsLockOn: Boolean; var KeyState: TKeyboardState; begin GetKeyboardState(KeyState); // simulate key events (down + up) Result := (KeyState[VK_CAPITAL] = 1); end; function IsControlPressed: Boolean; // const // V: SmallInt = $FFFFFF80; var I: SmallInt; // J: SmallInt; begin I := GetKeyState(VK_CONTROL); // J := I AND V; // Result := (J = V); Result := (I > 0); end; function IsNumLockOn: Boolean; var KeyState: TKeyboardState; begin GetKeyboardState(KeyState); // simulate key events (down + up) Result := (KeyState[VK_NUMLOCK] = 1); end; function IsScrollLockOn: Boolean; var KeyState: TKeyboardState; begin GetKeyboardState(KeyState); // simulate key events (down + up) Result := (KeyState[VK_SCROLL] = 1); end; function SelectFolder(const ATitle: string; var ADir: string): Boolean; var FolderDialog : IFileDialog; hr: HRESULT; IResult: IShellItem; FileName: PChar; Settings: DWORD; lpItemID : PItemIDList; BrowseInfo : TBrowseInfo; DisplayName : array[0..MAX_PATH] of char; TempPath : array[0..MAX_PATH] of char; begin //Is Vista+? if (Win32MajorVersion >= 6) then begin hr := CoCreateInstance(CLSID_FileOpenDialog, nil, CLSCTX_INPROC_SERVER, IFileDialog, FolderDialog); Result := (hr = S_OK); if (Result) then begin FolderDialog.GetOptions(Settings); FolderDialog.SetOptions(Settings or FOS_PICKFOLDERS); FolderDialog.GetOptions(Settings); FolderDialog.SetOptions(Settings or FOS_FORCEFILESYSTEM); FolderDialog.SetOkButtonLabel(PChar('Select')); FolderDialog.SetTitle(PChar(ATitle)); hr := FolderDialog.Show(0); Result := (hr = S_OK); if (Result) then begin hr := FolderDialog.GetResult(IResult); Result := (hr = S_OK); if (Result) then begin IResult.GetDisplayName(SIGDN_FILESYSPATH,FileName); ADir := FileName; end; end; end; end else //Win XP... begin FillChar(BrowseInfo, sizeof(TBrowseInfo), #0); with BrowseInfo do begin hwndOwner := 0; pszDisplayName := @DisplayName; lpszTitle := PChar(ATitle); ulFlags := BIF_USENEWUI OR BIF_RETURNONLYFSDIRS; end; lpItemID := SHBrowseForFolder(BrowseInfo); Result := (Assigned(lpItemID)); if (Result) then begin SHGetPathFromIDList(lpItemID, TempPath); ADir := TempPath; GlobalFreePtr(lpItemID); end; end; end; procedure SetSystemDateTime; begin ShellExecuteAndWait('control.exe', 'date/time', SW_SHOW); end; function ShellExecuteAndWait(const ACommand, AParams: String; const AVisibility: Integer; const ARunElevated: Boolean = False): Boolean; var AProcInfo: TShellExecuteInfo; begin FillChar(AProcInfo, SizeOf(TShellExecuteInfo), 0); AProcInfo.cbSize := SizeOf(TShellExecuteInfo); if (ARunElevated) then AProcInfo.lpVerb := 'runas' else AProcInfo.lpverb := 'open'; AProcInfo.lpFile := PChar(ACommand); AProcInfo.lpParameters := PChar(AParams); AProcInfo.nShow := AVisibility; Result := ShellExecuteEx(@AProcInfo); if (Result) then begin WaitForSingleObject(AProcInfo.hProcess, INFINITE); CloseHandle(AProcInfo.hProcess); end; end; function SubstChar(const AVal: String; const ACharToChange, ACharToUse: Char): String; var iPos: LongInt; begin Result := AVal; iPos := Pos(ACharToChange, Result); while (iPos > 0) do begin Result[iPos] := ACharToUse; iPos := Pos(ACharToChange, Result); end; end; function UserNameSize: LongInt; begin Result := SizeOf(TOSUserName); end; procedure ToggleStateKey(AKey: Byte); var KeyState: TKeyboardState; begin GetKeyboardState(KeyState); // simulate key events (down + up) if (KeyState[AKey] = 0) then begin Keybd_Event(AKey, 1, KEYEVENTF_EXTENDEDKEY or 0, 0); Keybd_Event(AKey, 1, KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0); end else begin Keybd_Event(AKey, 0, KEYEVENTF_EXTENDEDKEY or 0, 0); Keybd_Event(AKey, 0, KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0); end; end; procedure ToggleCapsLock; var Key: Byte; begin Key := VK_CAPITAL; ToggleStateKey(Key); end; procedure ToggleNumLock; var Key: Byte; begin Key := VK_NUMLOCK; ToggleStateKey(Key); end; procedure ToggleScrollLock; var Key: Byte; begin Key := VK_SCROLL; ToggleStateKey(Key); end; function WinExecAndWait32(APath: PChar; AVisibility: Word): Integer; var Msg: TMsg; lpExitCode: Cardinal; StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; begin FillChar(StartupInfo, SizeOf(TStartupInfo), 0); with StartupInfo do begin cb := SizeOf(TStartupInfo); dwFlags := STARTF_USESHOWWINDOW or STARTF_FORCEONFEEDBACK; wShowWindow := AVisibility; { you could pass sw_show or sw_hide as parameter } end; if CreateProcess(nil, APath, nil, nil, False, NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo) then begin repeat while PeekMessage(Msg, 0, 0, 0, pm_Remove) do begin if Msg.Message = wm_Quit then Halt(Msg.WParam); TranslateMessage(Msg); DispatchMessage(Msg); end; GetExitCodeProcess(ProcessInfo.hProcess, lpExitCode); until lpExitCode <> Still_Active; with ProcessInfo do { not sure this is necessary but seen in in some code elsewhere } begin CloseHandle(hThread); CloseHandle(hProcess); end; Result := 0; { success } end else Result := GetLastError; { error occurs during CreateProcess see help for details } end; { EURLGenError } { ********************************* EURLGenError ********************************* } { ********************************* EURLGenError ********************************* } constructor EURLGenError.CreateErr(const Msg: String; const iErrCode: Integer; const sURL: String); begin inherited Create(Msg); FErrorCode := iErrCode; FURL := sURL; end; { EExploreGenError } { ******************************* EExploreGenError ******************************* } { ******************************* EExploreGenError ******************************* } constructor EExploreGenError.CreateErr(const Msg: String; const iErrCode: Integer; const sFolder: String); begin inherited Create(Msg); FErrorCode := iErrCode; FFolder := sFolder; end; end.
unit DW.FileWriter; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses System.Classes; type /// <summary> /// Specialised TStreamWriter that writes to a file /// </summary> /// <remarks> /// Set the AutoFlush property (of TStreamWriter) to True for immediate writes /// </remarks> TFileWriter = class(TStreamWriter) private FStream: TStream; public constructor Create(const Filename: string; Append: Boolean = False); overload; virtual; destructor Destroy; override; end; implementation uses System.IOUtils, System.SysUtils; { TFileWriter } constructor TFileWriter.Create(const Filename: string; Append: Boolean); var LShareMode: Word; begin if TOSVersion.Platform <> TOSVersion.TPlatform.pfiOS then LShareMode := fmShareDenyWrite else LShareMode := 0; if (not TFile.Exists(Filename)) or (not Append) then FStream := TFileStream.Create(Filename, fmCreate or LShareMode) else begin FStream := TFileStream.Create(Filename, fmOpenWrite or LShareMode); FStream.Seek(0, soEnd); end; inherited Create(FStream); end; destructor TFileWriter.Destroy; begin FStream.Free; inherited; end; end.
unit EscenarioController; interface uses Classes, GraficoEscenario, Escenario, Tipos, dmTareas, Windows; type TEscenariosFactory = class(TTarea) strict private FEscenario: TEscenario; FNoEncontrado: boolean; FSintonizacion: Integer; FDesviacionSintonizacion: Currency; FIntentosSintonizacion: Integer; private FEscenarioMultiple: TEscenarioMultiple; Grafico: TGraficoEscenario; EscenarioMultipleCreator: TEscenarioMultipleCreator; EscenarioCreator: TEscenarioCreator; RecalcularEscenarioMultiple: boolean; protected procedure InternalCancel; override; procedure FreeResources; override; procedure InitializeResources; override; public procedure InternalExecute; override; property EscenarioMultiple: TEscenarioMultiple read FEscenarioMultiple; property Escenario: TEscenario read FEscenario; property NoEncontrado: boolean read FNoEncontrado; property Sintonizacion: Integer read FSintonizacion write FSintonizacion; property IntentosSintonizacion: Integer read FIntentosSintonizacion write FIntentosSintonizacion; property DesviacionSintonizacion: Currency read FDesviacionSintonizacion write FDesviacionSintonizacion; end; TEscenarioController = class private EscenarioMultipleCreator: TEscenarioMultipleCreator; EscenariosFactory: TEscenariosFactory; EscenarioMultiple: TEscenarioMultiple; Escenario: TEscenario; Grafico: TGraficoEscenario; FOnTerminate: TNotifyEvent; FSintonizacion: integer; FDesviacionSintonizacion: currency; FIntentosSintonizacion: integer; FCanceled: boolean; FNoEncontrado: boolean; criticalSection: TRTLCriticalSection; procedure OnTerminateEscenario; procedure OnTerminateEscenarioFactory(Sender: TObject); procedure OnConfiguracionEscenariosChanged; public constructor Create(const Grafico: TGraficoEscenario); destructor Destroy; override; procedure Crear(recalcularEscenarioMultiple: boolean); procedure Cancelar; procedure Borrar; property Sintonizacion: integer read FSintonizacion write FSintonizacion; property IntentosSintonizacion: integer read FIntentosSintonizacion write FIntentosSintonizacion; property DesviacionSintonizacion: currency read FDesviacionSintonizacion write FDesviacionSintonizacion; property OnTerminate: TNotifyEvent read FOnTerminate write FOnTerminate; property Canceled: boolean read FCanceled; property NoEncontrado: boolean read FNoEncontrado; end; implementation uses uPanelEscenario, SysUtils, uAcciones, DatosGrafico, dmConfiguracion, dmData, BusCommunication, frModuloEscenarios; const MAX_CAMBIOS_PARA_CREAR_ESCENARIO = 640; { TEscenarioController } procedure TEscenarioController.Borrar; begin FreeAndNil(Escenario); FreeAndNil(EscenarioMultiple); end; procedure TEscenarioController.Cancelar; begin FCanceled := true; if EscenariosFactory <> nil then begin EscenariosFactory.OnTerminate := nil; EscenariosFactory.Cancel; end; OnTerminateEscenario; end; procedure TEscenarioController.Crear(recalcularEscenarioMultiple: boolean); begin FNoEncontrado := true; Grafico.Creando := true; FreeAndNil(Escenario); if EscenariosFactory = nil then begin if recalcularEscenarioMultiple then FreeAndNil(EscenarioMultiple); FCanceled := False; EscenarioMultipleCreator.Initialize; EscenariosFactory := TEscenariosFactory.Create; EscenariosFactory.SetNilOnFree(@EscenariosFactory); EscenariosFactory.FreeOnTerminate := true; EscenariosFactory.OnTerminate := OnTerminateEscenarioFactory; EscenariosFactory.Grafico := Grafico; EscenariosFactory.EscenarioMultipleCreator := EscenarioMultipleCreator; EscenariosFactory.FEscenarioMultiple := EscenarioMultiple; EscenariosFactory.RecalcularEscenarioMultiple := EscenarioMultiple = nil; EscenariosFactory.Sintonizacion := FSintonizacion; EscenariosFactory.IntentosSintonizacion := FIntentosSintonizacion; EscenariosFactory.DesviacionSintonizacion := FDesviacionSintonizacion; Tareas.EjecutarTarea(EscenariosFactory, 'Escenario', 'Creando escenario'); end else begin EscenariosFactory.OnTerminate := nil; EscenariosFactory.Cancel; OnTerminateEscenario; end; end; constructor TEscenarioController.Create(const Grafico: TGraficoEscenario); begin inherited Create; InitializeCriticalSection(criticalSection); Self.Grafico := Grafico; EscenarioMultiple := nil; EscenarioMultipleCreator := TEscenarioMultipleCreator.Create; Bus.RegisterEvent(MessageConfiguracionEscenarios, OnConfiguracionEscenariosChanged); OnConfiguracionEscenariosChanged; end; destructor TEscenarioController.Destroy; begin if Escenario <> nil then Escenario.Free; EscenarioMultipleCreator.Free; if EscenarioMultiple <> nil then EscenarioMultiple.Free; DeleteCriticalSection(criticalSection); inherited; end; procedure TEscenarioController.OnConfiguracionEscenariosChanged; begin FSintonizacion := Configuracion.Escenarios.Sintonizacion; FIntentosSintonizacion := Configuracion.Escenarios.Intentos; if Configuracion.Escenarios.DesviacionAutomatico then begin // En el porcentaje de filtro para encontrar los días sincronizados en los escenarios // examinar los porcentajes de variabilidad y volatilidad y tomar por defecto EL MENOR DE LOS DOS if Data.CotizacionEstadoVARIABILIDAD.Value > Data.CotizacionEstadoVOLATILIDAD.Value then FDesviacionSintonizacion := Data.CotizacionEstadoVOLATILIDAD.Value else FDesviacionSintonizacion := Data.CotizacionEstadoVARIABILIDAD.Value; end else FDesviacionSintonizacion := Configuracion.Escenarios.DesviacionPerCent; end; procedure TEscenarioController.OnTerminateEscenario; begin EnterCriticalSection(criticalSection); try Grafico.Creando := false; if Assigned(FOnTerminate) then FOnTerminate(Self); finally LeaveCriticalSection(criticalSection); end; end; procedure TEscenarioController.OnTerminateEscenarioFactory(Sender: TObject); var factory: TEscenariosFactory; begin factory := Sender as TEscenariosFactory; FCanceled := factory.Canceled; FNoEncontrado := factory.NoEncontrado; EscenarioMultiple := factory.EscenarioMultiple; Escenario := factory.Escenario; if (not FCanceled) and (not FNoEncontrado) then begin TDatosGraficoEscenario(Grafico.Datos).EscenarioMultiple := EscenarioMultiple; TDatosGraficoEscenario(Grafico.Datos).Escenario := Escenario; end else begin TDatosGraficoEscenario(Grafico.Datos).EscenarioMultiple := nil; TDatosGraficoEscenario(Grafico.Datos).Escenario := nil; end; OnTerminateEscenario; end; { TEscenarioCreator } procedure TEscenariosFactory.InternalExecute; var Cambios: array of currency; i, j: integer; DatosGrafico: TDatosGrafico; begin i := TDatosGraficoEscenario(Grafico.Datos).UltimoIData; j := MAX_CAMBIOS_PARA_CREAR_ESCENARIO; SetLength(Cambios, MAX_CAMBIOS_PARA_CREAR_ESCENARIO); dec(j); //zero based DatosGrafico := Grafico.Datos; while (i >= 0) and (j >= 0) do begin if DatosGrafico.IsCambio[i] then begin Cambios[j] := DatosGrafico.Cambio[i]; dec(j); end; dec(i); end; //Hay menos cambios que MAX_CAMBIOS_PARA_CREAR_ESCENARIO, por lo que se ha de //reducir el array para que contenga solo los cambios. if j > 0 then begin Inc(j); for i := j to MAX_CAMBIOS_PARA_CREAR_ESCENARIO - 1 do begin Cambios[i - j] := Cambios[i]; end; SetLength(Cambios, MAX_CAMBIOS_PARA_CREAR_ESCENARIO - j); end; if (RecalcularEscenarioMultiple) or (FEscenarioMultiple = nil) then begin EscenarioMultipleCreator.Cambios := @Cambios; FreeAndNil(FEscenarioMultiple); EscenarioMultipleCreator.CrearEscenarioMultiple; FEscenarioMultiple := EscenarioMultipleCreator.EscenarioMultiple; end; FreeAndNil(FEscenario); EscenarioCreator.Cambios := @Cambios; EscenarioCreator.CrearEscenario(FEscenarioMultiple); FEscenario := EscenarioCreator.Escenario; FNoEncontrado := EscenarioCreator.NoEncontrado; end; procedure TEscenariosFactory.FreeResources; begin if Canceled or FNoEncontrado then begin if FEscenario = nil then begin if (EscenarioCreator <> nil) and (EscenarioCreator.Escenario <> nil) then EscenarioCreator.Escenario.Free; end else FreeAndNil(FEscenario); end; EscenarioCreator.Free; inherited; end; procedure TEscenariosFactory.InitializeResources; begin inherited; EscenarioCreator := TEscenarioCreator.Create; EscenarioCreator.Sintonizacion := FSintonizacion; EscenarioCreator.IntentosSintonizacion := FIntentosSintonizacion; EscenarioCreator.DesviacionSintonizacion := FDesviacionSintonizacion; end; procedure TEscenariosFactory.InternalCancel; begin inherited; EscenarioMultipleCreator.Cancelar; EscenarioCreator.Cancelar; end; end.
unit uMap; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Windows; const MINWORD = 0; BUFFER_SIZE = 1024; type TBuffer = array[0 .. BUFFER_SIZE - 1] of byte; PBuffer = ^TBuffer; TPdu = TBuffer; PPdu = ^TPdu; TTable = array [MINWORD .. MAXWORD] of word; PTable = ^TTable; TTypeTable = (ttHolding, ttInput); TTables = array [ttHolding .. ttInput] of TTable; IBaseMap = interface ['{DA9DDABD-10F3-4F91-A9C8-32BA4A0016DA}'] function Lock(const aTypeTable: TTypeTable = TTypeTable.ttInput): PTable; procedure UnLock; end; { IMap } IMap = interface(IBaseMap) ['{B239D504-0D7F-4BDB-9ECC-6AB304425BF0}'] procedure WriteToTable(const aOffSet: word; const aRequestPdu: PPdu); procedure WriteData(const aOffSet: word; const aPdu: PPdu); function ReadIpAddress(const aTypeTable: TTypeTable; const aOffSet: word): string; function ReadIoData(const aTypeTable: TTypeTable; const aOffSet: word; const aMultipler: dword = 1): string; function ReadUint8l(const aTypeTable: TTypeTable; const aOffSet: word): byte; function ReadUint8l(const aTypeTable: TTypeTable; const aOffSet: word; const aMultipler: dword): single; function ReadUint8h(const aTypeTable: TTypeTable; const aOffSet: word): byte; function ReadUint8h(const aTypeTable: TTypeTable; const aOffSet: word; const aMultipler: dword): single; function ReadUint16(const aTypeTable: TTypeTable; const aOffSet: word): word; function ReadUint16(const aTypeTable: TTypeTable; const aOffSet: word; const aMultipler: dword): single; function ReadUint32(const aTypeTable: TTypeTable; const aOffSet: word): dword; function ReadUint32(const aTypeTable: TTypeTable; const aOffSet: word; const aMultipler: dword): single; function ReadSint16(const aTypeTable: TTypeTable; const aOffSet: word): smallint; function ReadSint16(const aTypeTable: TTypeTable; const aOffSet: word; const aMultipler: dword): single; function ReadSint32(const aTypeTable: TTypeTable; const aOffSet: word): longint; function ReadSint32(const aTypeTable: TTypeTable; const aOffSet: word; const aMultipler: dword): single; function ReadBitmap16(const aTypeTable: TTypeTable; const aOffSet: word): word; function ReadBitmap32(const aTypeTable: TTypeTable; const aOffSet: word): dword; function ReadFloat(const aTypeTable: TTypeTable; const aOffSet: word): single; function ReadBool(const aTypeTable: TTypeTable; const aOffSet: word): boolean; procedure Clear; end; function GetMap: IMap; external 'map.dll'; function NumberDecimals(const aMultipler: dword): byte; implementation function NumberDecimals(const aMultipler: dword): byte; var Value: dword; begin // Множитель Value := aMultipler; Result := 0; // Количество разрядов множителя 10 - 1, 100 - 2, 1000 - 3 while Value > 1 do begin Value := Value div 10; Inc(Result); end; end; end.
{==============================================================================} { } { OpenGL Video Renderer Sample Loader Class } { Version 1.0 } { Date : 2010-06-22 } { } {==============================================================================} { } { Copyright (C) 2010 Torsten Spaete } { All Rights Reserved } { } { Uses dglOpenGL (MPL 1.1) from the OpenGL Delphi Community } { http://delphigl.com } { } {==============================================================================} { The contents of this file are used with permission, subject to } { the Mozilla Public License Version 1.1 (the "License"); you may } { not use this file except in compliance with the License. You may } { obtain a copy of the License at } { http://www.mozilla.org/MPL/MPL-1.1.html } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or } { implied. See the License for the specific language governing } { rights and limitations under the License. } {==============================================================================} { History : } { Version 1.0 Initial Release } {==============================================================================} unit sampleloader; {$mode objfpc}{$H+} interface uses Classes, SysUtils, dshowtypes; type TSampleHeader = record VIH : TVideoInfoHeader; SubType : TGUID; DataLength : Integer; end; PSample = ^TSample; TSample = record Header : TSampleHeader; Data : PByte; end; PSampleArray = array of PSample; procedure LoadSamples(ADir : String; var ASamples : PSampleArray; var ASampleCount : Integer); function LoadSample(AFilename : String; out ASample : PSample) : Boolean; implementation function LoadSample(AFilename : String; out ASample : PSample) : Boolean; var Str : TFileStream; begin if FileExists(AFilename) then begin New(ASample); Str := TFileStream.Create(AFilename, fmOpenRead); try Str.Read(ASample^.Header.VIH, SizeOf(TVideoInfoHeader)); Str.Read(ASample^.Header.SubType, SizeOf(TGUID)); Str.Read(ASample^.Header.DataLength, SizeOf(Integer)); ASample^.Data := AllocMem(ASample^.Header.DataLength); Str.Read(ASample^.Data^, ASample^.Header.DataLength); finally Str.Free; end; Result := True; end else begin ASample := nil; Result := False; end; end; procedure LoadSamples(ADir : String; var ASamples : PSampleArray; var ASampleCount : Integer); var SR : TSearchRec; Lst : TStrings; I : Integer; begin if FindFirst(IncludeTrailingBackslash(ADir) + '*.data', faAnyFile, SR) = 0 then begin Lst := TStringList.Create; try repeat if SR.Attr and faDirectory <> faDirectory then Lst.Add(IncludeTrailingPathDelimiter(ADir) + SR.Name); until FindNext(SR) <> 0; ASampleCount := Lst.Count; SetLength(ASamples, ASampleCount); For I := 0 to ASampleCount-1 do LoadSample(Lst[I], ASamples[I]); finally FindClose(SR); Lst.Free; end; end; end; end.
(* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Abbrevia * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1997-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) unit _ZipItem; interface uses ComObj, Abbrevia_TLB, AbZipTyp, AbZipKit; type TZipItem = class(TAutoIntfObject, IZipItem) private FOwner : TAbZipItem; FParent : TAbZipKit; public constructor Create(AOwner : TAbZipItem; AParent : TAbZipKit); protected {IArchiveItem} function Get_Action: TArchiveAction; safecall; function Get_CompressedSize: Integer; safecall; function Get_CRC32: Integer; safecall; function Get_CRC32St: WideString; safecall; function Get_DiskFileName: WideString; safecall; function Get_DiskPath: WideString; safecall; function Get_ExternalFileAttributes: TFileAttributes; safecall; procedure Set_ExternalFileAttributes(Value: TFileAttributes); safecall; function Get_FileName: WideString; safecall; procedure Set_FileName(const Value: WideString); safecall; function Get_IsEncrypted: WordBool; safecall; function Get_LastModFileDateTime: TDateTime; safecall; function Get_StoredPath: WideString; safecall; function Get_Tagged: WordBool; safecall; procedure Set_Tagged(Value: WordBool); safecall; function Get_UnCompressedSize: Integer; safecall; function Get_Password: WideString; safecall; procedure Set_Password(const Value: WideString); safecall; {IZipItem} function Get_CompressionMethod: TZipCompressionMethod; safecall; function Get_CompressionRatio: Double; safecall; function Get_DeflateOption: TZipDeflateOption; safecall; function Get_DictionarySize: TZipDictionarySize; safecall; function Get_DiskNumberStart: Integer; safecall; function Get_ExtraField: WideString; safecall; procedure Set_ExtraField(const Value: WideString); safecall; function Get_FileComment: WideString; safecall; procedure Set_FileComment(const Value: WideString); safecall; function Get_InternalFileAttributes: Integer; safecall; procedure Set_InternalFileAttributes(Value: Integer); safecall; function Get_VersionMadeBy: Integer; safecall; function Get_VersionNeededToExtract: Integer; safecall; end; implementation uses ComServ, SysUtils; {------------------------------------------------------------------------------} constructor TZipItem.Create(AOwner : TAbZipItem; AParent : TAbZipKit); begin inherited Create(ComServer.TypeLib, IZipItem); FOwner := AOwner; FParent := AParent; end; {------------------------------------------------------------------------------} {IArchiveItem} {------------------------------------------------------------------------------} function TZipItem.Get_Action: TArchiveAction; begin Result := TArchiveAction(FOwner.Action); end; {------------------------------------------------------------------------------} function TZipItem.Get_CompressedSize: Integer; begin result := FOwner.CompressedSize; end; {------------------------------------------------------------------------------} function TZipItem.Get_CRC32: Integer; begin result := FOwner.CRC32; end; {------------------------------------------------------------------------------} function TZipItem.Get_CRC32St: WideString; begin result := IntToHex(FOwner.CRC32, 8); end; {------------------------------------------------------------------------------} function TZipItem.Get_DiskFileName: WideString; begin result := FOwner.DiskFileName; end; {------------------------------------------------------------------------------} function TZipItem.Get_DiskPath: WideString; begin result := FOwner.DiskPath; end; {------------------------------------------------------------------------------} function TZipItem.Get_ExternalFileAttributes: TFileAttributes; begin result := TFileAttributes(FOwner.ExternalFileAttributes); end; {------------------------------------------------------------------------------} procedure TZipItem.Set_ExternalFileAttributes(Value: TFileAttributes); begin FOwner.ExternalFileAttributes := LongInt(Value); FParent.ZipArchive.IsDirty := True; end; {------------------------------------------------------------------------------} function TZipItem.Get_FileName: WideString; begin result := FOwner.FileName; end; {------------------------------------------------------------------------------} procedure TZipItem.Set_FileName(const Value: WideString); begin FOwner.FileName := Value; end; {------------------------------------------------------------------------------} function TZipItem.Get_IsEncrypted: WordBool; begin result := FOwner.IsEncrypted; end; {------------------------------------------------------------------------------} function TZipItem.Get_LastModFileDateTime: TDateTime; begin result := FileDateToDateTime((FOwner.LastModFileDate shl 16) + FOwner.LastModFileTime); end; {------------------------------------------------------------------------------} function TZipItem.Get_StoredPath: WideString; begin result := FOwner.StoredPath; end; {------------------------------------------------------------------------------} function TZipItem.Get_Tagged: WordBool; begin result := FOwner.Tagged; end; {------------------------------------------------------------------------------} procedure TZipItem.Set_Tagged(Value: WordBool); begin FOwner.Tagged := Value; end; {------------------------------------------------------------------------------} function TZipItem.Get_UnCompressedSize: Integer; begin result := FOwner.UncompressedSize; end; {------------------------------------------------------------------------------} function TZipItem.Get_Password: WideString; begin Result := WideString(FParent.Password); end; {------------------------------------------------------------------------------} procedure TZipItem.Set_Password(const Value: WideString); begin FParent.Password := AnsiString(Value); FParent.ZipArchive.IsDirty := True; end; {------------------------------------------------------------------------------} {IZipItem} {------------------------------------------------------------------------------} function TZipItem.Get_CompressionMethod: TZipCompressionMethod; begin Result := TZipCompressionMethod(FOwner.CompressionMethod); end; {------------------------------------------------------------------------------} function TZipItem.Get_CompressionRatio: Double; begin result := FOwner.CompressionRatio; end; {------------------------------------------------------------------------------} function TZipItem.Get_DeflateOption: TZipDeflateOption; begin result := TZipDeflateOption(FOwner.DeflationOption); end; {------------------------------------------------------------------------------} function TZipItem.Get_DictionarySize: TZipDictionarySize; begin result := TZipDictionarySize(FOwner.DictionarySize); end; {------------------------------------------------------------------------------} function TZipItem.Get_DiskNumberStart: Integer; begin result := FOwner.DiskNumberStart; end; {------------------------------------------------------------------------------} function TZipItem.Get_ExtraField: WideString; begin result := ''; end; {------------------------------------------------------------------------------} procedure TZipItem.Set_ExtraField(const Value: WideString); begin end; {------------------------------------------------------------------------------} function TZipItem.Get_FileComment: WideString; begin result := WideString(FOwner.FileComment); end; {------------------------------------------------------------------------------} procedure TZipItem.Set_FileComment(const Value: WideString); begin FOwner.FileComment := AnsiString(Value); FParent.ZipArchive.IsDirty := True; end; {------------------------------------------------------------------------------} function TZipItem.Get_InternalFileAttributes: Integer; begin result := FOwner.InternalFileAttributes; end; {------------------------------------------------------------------------------} procedure TZipItem.Set_InternalFileAttributes(Value: Integer); begin FOwner.InternalFileAttributes := Value; FParent.ZipArchive.IsDirty := True; end; {------------------------------------------------------------------------------} function TZipItem.Get_VersionMadeBy: Integer; begin result := FOwner.VersionMadeBy; end; {------------------------------------------------------------------------------} function TZipItem.Get_VersionNeededToExtract: Integer; begin result := FOwner.VersionNeededToExtract; end; {------------------------------------------------------------------------------} end.
unit UntOpStrings; interface type TOpStrings = class public function RemoveEspacoDuplicados(cNome: String): string; function removerEspacos(AValue: String): String; end; implementation uses System.SysUtils, System.Classes; { TCompararListaStrings } function TOpStrings.RemoveEspacoDuplicados(cNome: String): string; Const cDouble = ' '; cOne = ' '; Begin Result := cNome; While Pos(cDouble, Result) > 0 Do Result := StringReplace(Result, cDouble, cOne, [rfReplaceAll]); end; function TOpStrings.removerEspacos(AValue: String): String; begin Result := RemoveEspacoDuplicados(Trim(AValue)); end; end.
PROGRAM Start(INPUT, OUTPUT); VAR ToolDigit, Min, Max, SumArith, CountDigits: INTEGER; IsOverflow: BOOLEAN; PROCEDURE ReadDigit(VAR SourceFile: TEXT; VAR Digit: INTEGER); VAR Ch: CHAR; BEGIN { ReadDigit } IF NOT EOLN(SourceFile) THEN READ(SourceFile, Ch); Digit := -1; IF (Ch = '0') THEN Digit := 0; IF (Ch = '1') THEN Digit := 1; IF (Ch = '2') THEN Digit := 2; IF (Ch = '3') THEN Digit := 3; IF (Ch = '4') THEN Digit := 4; IF (Ch = '5') THEN Digit := 5; IF (Ch = '6') THEN Digit := 6; IF (Ch = '7') THEN Digit := 7; IF (Ch = '8') THEN Digit := 8; IF (Ch = '9') THEN Digit := 9 END; { ReadDigit } PROCEDURE ReadNumber(VAR SourceFile: TEXT; VAR Number: INTEGER); VAR Digit: INTEGER; IsOverflow: BOOLEAN; BEGIN { ReadNumber } Number := 0; Digit := 0; IsOverflow := FALSE; WHILE (NOT EOLN(SourceFile)) AND (NOT IsOverflow) DO BEGIN ReadDigit(SourceFile, Digit); IF ((Number >= 3276) AND (Digit > 7)) OR ((Number >= 10000) AND (Digit >= 0)) THEN IsOverflow := TRUE; IF (Digit <> -1) AND (NOT IsOverflow) THEN Number := Number * 10 + Digit; IF IsOverflow THEN BREAK END; IF IsOverflow THEN Number := -1 END; { ReadNumber } BEGIN { Start } Min := 0; Max := 0; SumArith := 0; CountDigits := 0; ToolDigit := 0; IsOverflow := FALSE; WHILE (NOT EOF(INPUT)) AND (NOT IsOverflow) DO BEGIN WHILE NOT EOLN(INPUT) DO BEGIN ReadNumber(INPUT, ToolDigit); IsOverflow := ((ToolDigit = -1) OR (ToolDigit < 0)); CountDigits := CountDigits + 1; IF (IsOverflow) THEN BREAK ELSE BEGIN SumArith := SumArith + ToolDigit; IF ToolDigit > Max THEN Max := ToolDigit; IF ToolDigit < Min THEN Min := ToolDigit END END; IF (IsOverflow) THEN BREAK ELSE READLN(INPUT) END; IF (IsOverflow) THEN WRITELN(OUTPUT, 'Not correct input, one of number is more than 32767') ELSE BEGIN WRITELN(OUTPUT, 'Max = ', Max); WRITELN(OUTPUT, 'Min = ', Min); SumArith := (SumArith) DIV (CountDigits); WRITELN(OUTPUT, 'SumArith = ', SumArith) END END. { Start }
unit MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, LogViewFrame, Vcl.ExtCtrls, Vcl.StdCtrls, DemoInterfaces, Vcl.ToolWin, Vcl.ComCtrls, System.Actions, Vcl.ActnList, Vcl.ImgList, MemoFrame, System.ImageList, Vcl.AppEvnts; type TMainWindow = class(TForm, IClipboardProvider) Panel1: TPanel; LogFrame1: TLogFrame; Button1: TButton; Button2: TButton; ToolBar1: TToolBar; ImageList1: TImageList; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ActionList1: TActionList; actEditCut: TAction; actEditCopy: TAction; actEditPaste: TAction; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; AMemoFrame1: TAMemoFrame; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure LogFrame1LogMemoEnter(Sender: TObject); procedure LogFrame1LogMemoExit(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormDeactivate(Sender: TObject); procedure actEditCutExecute(Sender: TObject); procedure actEditCopyExecute(Sender: TObject); procedure actEditPasteExecute(Sender: TObject); procedure ActionList1Update(Action: TBasicAction; var Handled: Boolean); private { Private declarations } FLogger : ILogger; FClipboardProvider : IClipboardProvider; protected function CanCopy: Boolean; function CanCut: Boolean; function CanPaste: Boolean; procedure Copy; procedure Cut; procedure Paste; public { Public declarations } end; var MainWindow: TMainWindow; implementation uses ClipbrdController, SecondForm; {$R *.dfm} var count : Int64; procedure TMainWindow.actEditCopyExecute(Sender: TObject); begin ClipboardController.Copy; end; procedure TMainWindow.actEditCutExecute(Sender: TObject); begin ClipboardController.Cut; end; procedure TMainWindow.actEditPasteExecute(Sender: TObject); begin ClipboardController.Paste; end; procedure TMainWindow.ActionList1Update(Action: TBasicAction; var Handled: Boolean); begin actEditCut.Enabled := ClipboardController.CanCut; actEditCopy.Enabled := ClipboardController.CanCopy; actEditPaste.Enabled := ClipboardController.CanPaste; Handled := true; end; procedure TMainWindow.Button1Click(Sender: TObject); begin FLogger.Log(Debug, 'Debug message'); end; procedure TMainWindow.Button2Click(Sender: TObject); begin if AnotherForm = nil then AnotherForm := TAnotherForm.Create(Application, FLogger); AnotherForm.Show; end; function TMainWindow.CanCopy: Boolean; begin result := FClipboardProvider.CanCopy; end; function TMainWindow.CanCut: Boolean; begin result := FClipboardProvider.CanCut; end; function TMainWindow.CanPaste: Boolean; begin result := FClipboardProvider.CanPaste; end; procedure TMainWindow.Copy; begin FClipboardProvider.Copy; end; procedure TMainWindow.Cut; begin FClipboardProvider.Cut; end; procedure TMainWindow.FormActivate(Sender: TObject); begin ClipboardController.SetProvider(Self); end; procedure TMainWindow.FormCreate(Sender: TObject); begin FLogger := LogFrame1 as ILogger; FClipboardProvider := LogFrame1 as IClipboardProvider; AMemoFrame1.SetLogger(FLogger); end; procedure TMainWindow.FormDeactivate(Sender: TObject); begin ClipboardController.UnSetProvider(Self); end; procedure TMainWindow.LogFrame1LogMemoEnter(Sender: TObject); begin ClipboardController.SetProvider(Self); end; procedure TMainWindow.LogFrame1LogMemoExit(Sender: TObject); begin ClipboardController.UnSetProvider(Self); end; procedure TMainWindow.Paste; begin FClipboardProvider.Paste; end; end.
{$MODESWITCH RESULT+} {$GOTO ON} (************************************************************************* Copyright (c) 2007, Sergey Bochkanov (ALGLIB project). >>> SOURCE LICENSE >>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (www.fsf.org); either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************) unit stest; interface uses Math, Sysutils, Ap, gammafunc, normaldistr, ibetaf, nearunityunit, binomialdistr; procedure OneSampleSignTest(const X : TReal1DArray; N : AlglibInteger; Median : Double; var BothTails : Double; var LeftTail : Double; var RightTail : Double); implementation (************************************************************************* Sign test This test checks three hypotheses about the median of the given sample. The following tests are performed: * two-tailed test (null hypothesis - the median is equal to the given value) * left-tailed test (null hypothesis - the median is greater than or equal to the given value) * right-tailed test (null hypothesis - the median is less than or equal to the given value) Requirements: * the scale of measurement should be ordinal, interval or ratio (i.e. the test could not be applied to nominal variables). The test is non-parametric and doesn't require distribution X to be normal Input parameters: X - sample. Array whose index goes from 0 to N-1. N - size of the sample. Median - assumed median value. Output parameters: BothTails - p-value for two-tailed test. If BothTails is less than the given significance level the null hypothesis is rejected. LeftTail - p-value for left-tailed test. If LeftTail is less than the given significance level, the null hypothesis is rejected. RightTail - p-value for right-tailed test. If RightTail is less than the given significance level the null hypothesis is rejected. While calculating p-values high-precision binomial distribution approximation is used, so significance levels have about 15 exact digits. -- ALGLIB -- Copyright 08.09.2006 by Bochkanov Sergey *************************************************************************) procedure OneSampleSignTest(const X : TReal1DArray; N : AlglibInteger; Median : Double; var BothTails : Double; var LeftTail : Double; var RightTail : Double); var I : AlglibInteger; GTCnt : AlglibInteger; NECnt : AlglibInteger; begin if N<=1 then begin BothTails := Double(1.0); LeftTail := Double(1.0); RightTail := Double(1.0); Exit; end; // // Calculate: // GTCnt - count of x[i]>Median // NECnt - count of x[i]<>Median // GTCnt := 0; NECnt := 0; I:=0; while I<=N-1 do begin if AP_FP_Greater(X[I],Median) then begin GTCnt := GTCnt+1; end; if AP_FP_Neq(X[I],Median) then begin NECnt := NECnt+1; end; Inc(I); end; if NECnt=0 then begin // // all x[i] are equal to Median. // So we can conclude that Median is a true median :) // BothTails := Double(0.0); LeftTail := Double(0.0); RightTail := Double(0.0); Exit; end; BothTails := 2*BinomialDistribution(Min(GTCnt, NECnt-GTCnt), NECnt, Double(0.5)); LeftTail := BinomialDistribution(GTCnt, NECnt, Double(0.5)); RightTail := BinomialCDistribution(GTCnt-1, NECnt, Double(0.5)); end; end.
unit frmMain; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, Process; //Incluir a biblioteca Process type { TForm1 } TForm1 = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private public end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.Button1Click(Sender: TObject); var AProcess: TProcess; //Objeto do tipo TProcess begin // Agora nós criaremos o objeto TProcess, e // associamos ele à variável AProcess. AProcess := TProcess.Create(nil); // Mostraremos ao novo AProcess qual é o comando para ele executar. // Vamos usar o Compilador FreePascal AProcess.CommandLine := 'ppc386 -h'; //Executa um programa externo // Nós definiremos uma opção para onde o programa // é executado. Esta opção verificará que nosso programa // não continue enquanto o programa que nós executamos // não pare de executar. vvvvvvvvvvvvvv AProcess.Options := AProcess.Options + [poWaitOnExit]; // Agora que AProcess sabe qual é a linha de comando // nós executaremos ele. AProcess.Execute; // Esta parte não é alcançada enquanto ppc386 não parar a execução. AProcess.Free; end; procedure TForm1.Button2Click(Sender: TObject); // Neste ponto é definida a variável "AProcess" como uma variável // do tipo "TProcess" // Também agora nós adicionamos uma TStringList para armazenar os // dados lidos da saida do programa. var AProcess: TProcess; AStringList: TStringList; begin // Agora nós criaremos o objeto TProcess, e // associamos ele à variável AProcess. AProcess := TProcess.Create(nil); // Cria o objeto TStringList. AStringList := TStringList.Create; // Mostraremos ao novo AProcess qual é o comando para ele executar. // Vamos usar o Compilador FreePascal // AProcess.CommandLine := 'ppc386 -h'; AProcess.CommandLine := 'date'; // Nós definiremos uma opção para onde o programa // é executado. Esta opção verificará que nosso programa // não continue enquanto o programa que nós executamos // não pare de executar. Também agora vamos mostrar a ele que // que nós precisamos ler a saída do arquivo. AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes]; // Agora que AProcess sabe qual é a linha de comando // nós executaremos ele. AProcess.Execute; // Esta parte não é alcançada enquanto ppc386 não parar a execução. // Agora lida a saida do programa nós colocaremos // ela na TStringList. AStringList.LoadFromStream(AProcess.Output); // Salvamos a saida para um arquivo. AStringList.SaveToFile('output.txt'); //Retorna o conteúdo da saída padrão em uma String Button2.Caption:=AStringList.Text; // Agora que o arquivo foi salvo nós podemos liberar a // TStringList e o TProcess. AStringList.Free; AProcess.Free; end; procedure TForm1.Button3Click(Sender: TObject); var cmd: TProcess; begin try cmd:= TProcess.Create(Self); cmd.CommandLine := 'firefox'; cmd.Execute; finally cmd.Free; end; end; end. //FONTE: //https://wiki.freepascal.org/Executing_External_Programs/pt
unit UConfiguracoes; interface uses KRK.Lib.Rtl.Common.Classes, Classes; type TConfiguracoes = class(TObjectFile) private FServidor: String; FServico: String; FEnderecoProxy: String; FUsuarioProxy: String; FSenhaProxy: String; FModulo: String; FUsarCompressao: Boolean; function GetServicoWeb: String; function GetModuloWeb: String; public constructor Create(aOwner: TComponent; aAutoSaveMode: TAutoSaveMode = asmNone); override; property ServicoWeb: String read GetServicoWeb; property ModuloWeb: String read GetModuloWeb; property UsarCompressao: Boolean read FUsarCompressao write FUsarCompressao default True; published property Servico: String read FServico write FServico; property Servidor: String read FServidor write FServidor; property Modulo: String read FModulo write FModulo; property EnderecoProxy: String read FEnderecoProxy write FEnderecoProxy; property UsuarioProxy: String read FUsuarioProxy write FUsuarioProxy; property SenhaProxy: String read FSenhaProxy write FSenhaProxy; end; var Configuracoes: TConfiguracoes; implementation uses SysUtils, Forms; const SERVIDOR_PADRAO = 'http://127.0.0.1'; SERVICO_PADRAO = '/iaf/IAFServer.dll'; MODULO_PADRAO = '/soap/ISODMPrincipal'; { TConfiguracoes } constructor TConfiguracoes.Create(aOwner: TComponent; aAutoSaveMode: TAutoSaveMode = asmNone); begin inherited; FServidor := SERVIDOR_PADRAO; FEnderecoProxy := ''; FUsuarioProxy := ''; FSenhaProxy := ''; FServico := SERVICO_PADRAO; FModulo := MODULO_PADRAO; FUsarCompressao := True; end; function TConfiguracoes.GetModuloWeb: String; begin Result := GetServicoWeb + FModulo; end; function TConfiguracoes.GetServicoWeb: String; begin Result := FServidor + FServico; end; initialization Configuracoes := TConfiguracoes.Create(nil,asmText); Configuracoes.LoadFromTextFile(ChangeFileExt(Application.ExeName,'.Configs')); finalization Configuracoes.Free; end.
unit Embroidery_Viewer; interface uses Classes, Embroidery_Items, gmCore_Viewer, GR32_Image; type TgmEmbroideryViewer = class(TgmCoreViewer) private FShapeList: TEmbroideryList; procedure DrawStitchs; protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; //for universal file dialog procedure LoadFromFile(const FileName: string); override; function GetReaderFilter : string; override; function GetWriterFilter : string; override; published end; implementation uses gmCore_Items, Embroidery_Painter, Embroidery_Fill; { TgmGraphicViewer } constructor TgmEmbroideryViewer.Create(AOwner: TComponent); begin inherited; FShapeList := TEmbroideryList.Create(self); ScaleMode := smOptimal; ScrollBars.Visibility := svHidden; end; destructor TgmEmbroideryViewer.Destroy; begin FShapeList.Free; inherited; end; procedure TgmEmbroideryViewer.DrawStitchs; var LPainter : TEmbroideryPainter ; j : Integer; LShapeItem : TEmbroideryItem; begin LPainter := TEmbroideryPhotoPainter.Create(Self) ;//TEmbroideryPainter ; LPainter.WantToCalcRect := True; BeginUpdate; try Bitmap.SetSize(Round(FShapeList.HupWidth), Round(FShapeList.HupHeight)); {LPainter.BeginPaint(Bitmap); if FShapeList.Count > 0 then //for i := 0 to FStitchs.Header.fpnt -1 do for j := 0 to FShapeList.Count -1 do begin LShapeItem := FShapeList[j]; if Length(LShapeItem.Stitchs^) <= 0 then fnhrz(LShapeItem, nil); LPainter.Paint(Bitmap, LShapeItem); end; LPainter.EndPaint(Bitmap);} LPainter.Paint(FShapeList, epsPaint); LPainter.CropDrawnRect(); finally EndUpdate; Changed; LPainter.Free; end; end; function TgmEmbroideryViewer.GetReaderFilter: string; begin Result := TEmbroideryList.ReadersFilter; end; function TgmEmbroideryViewer.GetWriterFilter: string; begin Result := TEmbroideryList.WritersFilter; end; procedure TgmEmbroideryViewer.LoadFromFile(const FileName: string); begin FShapeList.LoadFromFile(FileName); DrawStitchs(); //Self.Bitmap.Assign(FPicture.Graphic); end; initialization RegisterCoreViewer(TgmEmbroideryViewer); end.
unit uListaObjeto; interface uses System.Classes, System.Generics.Collections; type TListaObjeto = class private FOListaDeObjetos: TObjectList<TObject>; public constructor Create(ADestruirObjetos: Boolean = True); destructor Destroy; override; property OListaDeObjetos: TObjectList<TObject> read FOListaDeObjetos; procedure AdicionarItemNaLista(AObjeto: TObject); end; implementation uses System.SysUtils; { TListaObjeto } procedure TListaObjeto.AdicionarItemNaLista(AObjeto: TObject); begin FOListaDeObjetos.Add(AObjeto); end; constructor TListaObjeto.Create(ADestruirObjetos: Boolean); begin FOListaDeObjetos := TObjectList<TObject>.Create(ADestruirObjetos); end; destructor TListaObjeto.Destroy; begin FreeAndNil(FOListaDeObjetos); inherited; end; end.
unit XStratCals; interface uses StratTypes, Classes, Strategy; type TXStrategyCals = class(TStrategyCals) private procedure CreateDefaultSchedule; override; procedure ReadFromFile; override; procedure SaveToFile; override; function AllowSpecial(pStrat: string): boolean; override; public constructor Create; end; const stXFrogProj = 'XFROG Projections'; implementation uses SysUtils, BasicFrog, XProj, Expo; // I had to butcher the parent class to make this work. It's not elegant, but // I couldn't figure out how to extend the enumeration type (TStrategyTypes). constructor TXStrategyCals.Create; begin inherited Create; // Fill out the name list mAvailableStrategies.Clear; mAvailableStrategies.AddObject(stBasic, TStratClassHolder.Create(TBasicStrategy)); mAvailableStrategies.AddObject(stXFrogProj, TStratClassHolder.Create(TXFrogProjection)); mAvailableStrategies.AddObject(stExpo, TStratClassHolder.Create(TExpoStrategy)); CreateDefaultSchedule; end; procedure TXStrategyCals.CreateDefaultSchedule; begin mNames[1] := stBasic; mSwitchAfter[1] := DEFAULT_SWITCH_AFTER; mNewField[1] := 0; mSpecial[1] := 0; mNames[2] := stXFrogProj; mSwitchAfter[2] := DEFAULT_SWITCH_AFTER; mNewField[2] := 0; mSpecial[2] := 5; mNames[3] := stExpo; mSwitchAfter[3] := DEFAULT_SWITCH_AFTER; mNewField[3] := 0; mSpecial[3] := 0; mNames[4] := stXFrogProj; mSwitchAfter[4] := DEFAULT_SWITCH_AFTER; mNewField[4] := 0; mSpecial[4] := 0; mNumStrats := 4; end; procedure TXStrategyCals.ReadFromFile; begin // We always want it to use the default schedule raise Exception.Create('No file for XFrog'); end; procedure TXStrategyCals.SaveToFile; begin end; function TXStrategyCals.AllowSpecial(pStrat: string): boolean; begin if pStrat = stXFrogProj then AllowSpecial := True else AllowSpecial := inherited AllowSpecial(pStrat); end; end.
unit CMW.OSInfo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Dialogs, ExtCtrls, ComCtrls, taskSchd, taskSchdXP, TLHelp32, PSAPI, ShlObj, ValEdit, Vcl.StdCtrls; type TOSVersion = (winUnknown, winOld, win2000, winXP, winServer2003, winCE, winVista, win7, win8, win8p1, win10, winNewer); TOSBits = (x32, x64); PNetInfo = ^TNetInfo; TNetInfo = record PlatformID :DWORD; Computername:PWideChar; Langroup :PWideChar; VerMajor :DWORD; VerMinor :DWORD; end; TDriveSpaceInfoType = record FreeBytesAvailableToCaller:Int64; FreeSize:Int64; TotalSize:Int64; end; TCurrentOS = class private FVersion:TOSVersion; FBits:TOSBits; FCurrentUserName:string; FWinVersionStr:string; FUsers:TStringList; FUsersPath:string; FWindowsPath:string; FSys32:string; FSys64:string; FHostsFileName:string; FOSVersionInfo:OSVERSIONINFO; FLicStstus:string; function GetUser(index:Integer):string; function FMemoryInfo:string; function FUserCount:Word; function FCPU:string; function FWindowsTimeWork:string; function FMachineName:string; function FLanGroup:string; function FWinUpdate:string; function FWinActivateStatus:string; function FSysDriveInfo:string; function FUserIsAdmin:Boolean; function FGetRollAccessLvl:Byte; public constructor Create; function GetAppExe:string; property Version:TOSVersion read FVersion; property Bits:TOSBits read FBits; property CurrentUserName:string read FCurrentUserName; property UsersPath:string read FUsersPath; property WindowsPath:string read FWindowsPath; property Sys32:string read FSys32; property Sys64:string read FSys64; property WinVersion:string read FWinVersionStr; property HostsFileName:string read FHostsFileName; property Users[index:Integer]:string read GetUser; property UserCount:Word read FUserCount; property MemoryInfo:string read FMemoryInfo; property MachineName:string read FMachineName; property LanGroup:string read FLanGroup; property WinUpdate:string read FWinUpdate; property WinActivateStatus:string read FLicStstus; property SysDriveInfo:string read FSysDriveInfo; property CPU:string read FCPU; property UserIsAdmin:Boolean read FUserIsAdmin; property RollAccessLevel:Byte read FGetRollAccessLvl; property OSVInfo:OSVERSIONINFO read FOSVersionInfo; property WindowsTimeWork:string read FWindowsTimeWork; end; const VER_PLATFORM_WIN32_NT = 2; ErGetStr = '<не доступно>'; var OSVersion:TOSVersion; CurrentDir:string; WindowsBits:TOSBits; AppBits:TOSBits; LogFileName:string; C:string; var Info:TCurrentOS; function GetDriveSpaceInfo(Drive:string = ''):TDriveSpaceInfoType; function BitsToStr(V:TOSBits):string; procedure Init; implementation uses CMW.Main, System.Win.Registry, Forms, CMW.Utils, System.Win.ComObj, WbemScripting_TLB, Winapi.ActiveX; //--------------------------------TCurrentOS------------------------------------ function TCurrentOS.FUserCount:Word; begin Result:=FUsers.Count; end; function TCurrentOS.GetAppExe:string; begin case Bits of x32:Result:=App32; x64:Result:=App64; else Result:=App32; end; end; constructor TCurrentOS.Create; var a:array[0..254] of char; lenBuf:Cardinal; FRoll:TRegistry; NoUserPlace:Boolean; begin GetWindowsDirectory(a, sizeof(a)); FWindowsPath:=StrPas(a); lenBuf:=255; GetUserName(a, lenBuf); FCurrentUserName:=StrPas(a); FVersion:=OSVersion; FSys32:=FWindowsPath+'\System32'; FSys64:=FWindowsPath+'\SysWOW64'; try try FRoll:=TRegistry.Create(KEY_READ); FRoll.RootKey:=HKEY_LOCAL_MACHINE; if FRoll.OpenKeyReadOnly('SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList') then begin FUsersPath:=FRoll.ReadString('ProfilesDirectory'); ReplaceSysVar(FUsersPath); end else NoUserPlace:=True; finally FreeAndNil(FRoll); end; NoUserPlace:=False; except NoUserPlace:=True; end; if NoUserPlace then begin Log(['Каталог пользователей выбран исходя из значений "По умолчанию". Нет доступа к HKLM.']); case FVersion of winXP: FUsersPath:=Copy(FWindowsPath, 1, 3)+'Documents and Settings\'; winOld: begin FUsersPath:=Copy(FWindowsPath, 1, 3)+'Documents and Settings\'; MessageBox(Application.Handle, PChar(LangText(104, 'Программа пока не имеет возможности работать с Windows')+' '+WinVersion), PChar(LangText(103, 'Прошу прощения')), MB_ICONSTOP or MB_OK); end; else FUsersPath:=Copy(FWindowsPath, 1, 3)+'Users\'; end; end; Log(['Каталог пользователей', FUsersPath]); FHostsFileName:=FSys32+'\drivers\etc\hosts'; FBits:=WindowsBits; FUsers:=GetDirectores(FUsersPath); case FVersion of winXP: FWinVersionStr:='Windows XP/Embedded'; winServer2003:FWinVersionStr:='Windows Server 2003'; winCE: FWinVersionStr:='Windows Compact Edition'; winVista: FWinVersionStr:='Windows Vista/Server 2008'; win7: FWinVersionStr:='Windows 7/Server 2008 R2'; win8: FWinVersionStr:='Windows 8/Server 2012'; win8p1: FWinVersionStr:='Windows 8.1'; win10: FWinVersionStr:='Windows 10'; else FWinVersionStr:='Windows '+WinVersion; end; FWinVersionStr:=FWinVersionStr + ' ('+ IntToStr(Win32MajorVersion)+'.'+ IntToStr(Win32MinorVersion)+'.'+ IntToStr(Win32BuildNumber)+') ' + BitsToStr(Bits); GetVersionEx(FOSVersionInfo); FLicStstus:=FWinActivateStatus; end; function TCurrentOS.FMemoryInfo:string; var lpMemoryStatus : TMemoryStatus; begin try lpMemoryStatus.dwLength:=SizeOf(lpMemoryStatus); GlobalMemoryStatus(lpMemoryStatus); with lpMemoryStatus do begin Result:=Result+ 'Всего: '+Format('%0.0f Мбайт', [dwTotalPhys div 1024 / 1024])+' | '+ 'Файл подкачки: '+Format('%0.0f Мбайт', [dwTotalPageFile div 1024 / 1024]); end; except begin Log(['Не смог получить информацию об оперативной памяти.', SysErrorMessage(GetLastError)]); Exit(ErGetStr); end; end; end; function TCurrentOS.FUserIsAdmin:Boolean; const SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5)); SECURITY_BUILTIN_DOMAIN_RID = $00000020; DOMAIN_ALIAS_RID_ADMINS = $00000220; var hAccessToken: THandle; ptgGroups: PTokenGroups; dwInfoBufferSize: DWORD; psidAdministrators: PSID; x: Integer; bSuccess: BOOL; begin Result:=False; try begin bSuccess:=OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, hAccessToken); if not bSuccess then begin if GetLastError = ERROR_NO_TOKEN then bSuccess:=OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, hAccessToken); end; if bSuccess then begin GetMem(ptgGroups, 1024); bSuccess := GetTokenInformation(hAccessToken, TokenGroups, ptgGroups, 1024, dwInfoBufferSize); CloseHandle(hAccessToken); if bSuccess then begin AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, psidAdministrators); {$R-} for x := 0 to ptgGroups.GroupCount - 1 do if EqualSid(psidAdministrators, ptgGroups.Groups[x].Sid) then begin Result:=True; Break; end; {$R+} FreeSid(psidAdministrators); end; FreeMem(ptgGroups); end; end; except begin Log(['Не смог получить информацию о правах пользователя.', SysErrorMessage(GetLastError)]); Exit(False); end; end; end; function TCurrentOS.FGetRollAccessLvl:Byte; var Roll:TRegistry; begin //---------------------Реестр-------------------------------------------------- try begin Result:=0; Roll:=TRegistry.Create(KEY_READ); try Roll:=TRegistry.Create(KEY_READ); if Roll.OpenKey('Software', False) then Result:=1; except Result:=0; end; if Result > 0 then begin try Roll:=TRegistry.Create(KEY_WRITE); Roll.RootKey:=HKEY_CURRENT_USER; if Roll.OpenKey('Software', False) then Result:=2; except Result:=1; end; end; if Result > 1 then begin try Roll:=TRegistry.Create(KEY_ALL_ACCESS); Roll.RootKey:=HKEY_CURRENT_USER; if Roll.OpenKey('Software', False) then Result:=3; except Result:=2; end; end; if Result > 2 then begin try Roll:=TRegistry.Create(KEY_READ); Roll.RootKey:=HKEY_LOCAL_MACHINE; if Roll.OpenKey('Software', False) then Result:=4; except Result:=3; end; end; if Result > 3 then begin try Roll:=TRegistry.Create(KEY_WRITE); Roll.RootKey:=HKEY_LOCAL_MACHINE; if Roll.OpenKey('Software', False) then Result:=5; except Result:=4; end; end; if Result > 4 then begin try Roll:=TRegistry.Create(KEY_ALL_ACCESS); Roll.RootKey:=HKEY_LOCAL_MACHINE; if Roll.OpenKey('Software', False) then Result:=6; except Result:=5; end; end; if Assigned(Roll) then Roll.Free; end; except begin Log(['Не смог получить информацию об уровне доступа к реестру.', SysErrorMessage(GetLastError)]); //Exit(ErGetStr); end; end; end; function TCurrentOS.FWindowsTimeWork:string; const DivSec = 1000; DivMin = DivSec * 60; DivHur = DivMin * 60; DivDay = DivHur * 24; var SysTime:UInt64; D, H, M, S:Integer; begin try SysTime:=GetTickCount; D:=SysTime div DivDay; Dec(SysTime, D * DivDay); H:=SysTime div DivHur; Dec(SysTime, H * DivHur); M:=SysTime div DivMin; Dec(SysTime, M * DivMin); S:=SysTime div DivSec; Dec(SysTime, S * DivSec); Result:=IntToStr(D)+' дн. '+IntToStr(H)+' час. '+IntToStr(M)+' мин. '+IntToStr(S)+' сек. '+IntToStr(SysTime)+' мсек.'; except begin Log(['Не смог получить информацию о времени работы системы.', SysErrorMessage(GetLastError)]); Exit(ErGetStr); end; end; end; function TCurrentOS.FCPU:string; var lpSystemInfo:TSystemInfo; Roll:TRegistry; begin try Roll:=TRegistry.Create(KEY_READ); Roll.RootKey:=HKEY_LOCAL_MACHINE; FillChar(lpSystemInfo, SizeOf(TSystemInfo), '#'); GetSystemInfo(lpSystemInfo); if Roll.OpenKey('HARDWARE\DESCRIPTION\System\CentralProcessor\0', False) then begin Result:=Roll.ReadString('ProcessorNameString')+' x'+IntToStr(lpSystemInfo.dwNumberOfProcessors); end else Result:='Класс x'+IntToStr(lpSystemInfo.dwProcessorType); Roll.CloseKey; Roll.Destroy; except begin Log(['Не смог получить информацию о процессоре.', SysErrorMessage(GetLastError)]); Exit(ErGetStr); end; end; end; function TCurrentOS.FMachineName:string; var Size:Cardinal; PRes:PChar; BRes:Boolean; begin try Result:='Не определено'; Size:=MAX_COMPUTERNAME_LENGTH + 1; PRes:=StrAlloc(Size); BRes:=GetComputerName(PRes, Size); if BRes then Result:=StrPas(PRes); except begin Log(['Не смог получить информацию об имени компьютера.', SysErrorMessage(GetLastError)]); Exit(ErGetStr); end; end; end; function TCurrentOS.FLanGroup:string; var Info:PNetInfo; Error:DWORD; begin try Error:=GetNetInfo(PChar(FMachineName), 100, @Info); if Error <> 0 then raise Exception.Create(SysErrorMessage(Error)); Result:= Info^.LanGroup; except begin Log(['Не смог получить информацию о названии текущей группы.', SysErrorMessage(GetLastError)]); Exit(ErGetStr); end; end; end; function TCurrentOS.FWinUpdate:string; var Roll:TRegistry; begin try Roll:=TRegistry.Create(KEY_READ or KEY_WOW64_64KEY); Roll.RootKey:=HKEY_LOCAL_MACHINE; if Roll.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update', False) then begin try case Roll.ReadInteger('AUOptions') of 1:Result:='Отключено'; 2:Result:='Включено частично (Поиск обновлений)'; 3:Result:='Включено частично (Поиск и загрузка обновлений)'; 4:Result:='Автоматически'; end; except Result:='Не определено'; end; end else Result:='Не определено'; Roll.CloseKey; Roll.Destroy; except begin Log(['Не смог получить информацию о состоянии автоматического обновления.', SysErrorMessage(GetLastError)]); Exit(ErGetStr); end; end; end; function TCurrentOS.FWinActivateStatus:string; var Service:ISWbemServices; SObject:ISWbemObject; ls:Integer; ENum:IEnumVariant; TempObj:OleVariant; Value:Cardinal; ObjectSet:ISWbemObjectSet; SWbemLocator:TSWbemLocator; sQuery, sValue:string; begin try if OSVersion = winXP then begin sQuery:='win32_WindowsProductActivation'; sValue:='ActivationRequired' end else begin sQuery:='SoftwareLicensingProduct'; sValue:='LicenseStatus' end; SWbemLocator:=TSWbemLocator.Create(nil); Service:=SWbemLocator.ConnectServer('', 'root\CIMV2', '', '', '', '', 0, nil); SObject:=Service.Get(sQuery, wbemFlagUseAmendedQualifiers, nil); //win32_WindowsProductActivation ObjectSet:=SObject.Instances_(0, nil); Enum:=(ObjectSet._NewEnum) as IEnumVariant; Enum.Next(1, TempObj, Value); SObject:=IUnknown(TempObj) as SWBemObject; ls:=SObject.Properties_.Item(sValue, 0).Get_Value; //ActivationRequired SWbemLocator.Free; if ls = 0 then Result:='Активация Windows выполнена' else Result:='Активация Windows не выполнена'; except begin Log(['Не удалось определить статус активации Windows', SysErrorMessage(GetLastError)]); Result:=ErGetStr; end; end; end; function TCurrentOS.FSysDriveInfo:string; begin try Result:='Диск "'+C+'", свободно '+GetSpacedInt(IntToStr(GetDriveSpaceInfo(C[1]+':').FreeSize div (1024 * 1024)))+' из '+GetSpacedInt(IntToStr(GetDriveSpaceInfo(C[1]+':').TotalSize div (1024 * 1024)))+' '+LangText(48, 'Мбайт'); except Result:=ErGetStr; end; end; function TCurrentOS.GetUser(index:Integer):string; begin Result:=''; if FUsers.Count <= 0 then begin Log(['Список пользователей не доступен.']); Exit; end; if (index < 0) or (index > FUsers.Count - 1) then begin Log([index, 'выходит за границы масива пользователей.']); Exit; end; try Result:=FUsers[index]; except Log(['Не смог получить пользователя под индексом', index]); end; end; procedure GetOSVersion; begin OSVersion:=winUnknown; if Win32Platform = VER_PLATFORM_WIN32_NT then//Win NTx begin case Win32MajorVersion of 5: //Win NT5x begin case Win32MinorVersion of 0:OSVersion:=win2000; //Windows 2000 (Win2k) Professional, Server, Advanced Server, Datacenter Server 1:OSVersion:=winXP; //Windows XP Home, Professional, Tablet PC Edition, Media Center Edition, Embedded 2:OSVersion:=winServer2003; //Windows Server 2003, Compute Cluster Server 2003 end; end; 6: //Win NT6x begin case Win32MinorVersion of 0:OSVersion:=winVista; //Windows Vista, Server 2008, HPC Server 2008, Home Server, Vista for Embedded Systems 1:OSVersion:=win7; //Windows 7, Server 2008 R2 2:OSVersion:=win8; //Windows 8, Server 2012 3:OSVersion:=win8p1; //Windows 8.1 end; end; 7: //Win NT7x begin case Win32MinorVersion of 0:OSVersion:=winCE; //Windows Compact Edition end; end; 10: //Win NT10x begin case Win32MinorVersion of 0:OSVersion:=win10; //Windows 10 else OSVersion:=winNewer; end; end; else if Win32MajorVersion < 5 then OSVersion:=winOld else if Win32MajorVersion > 10 then OSVersion:=winNewer; end; end else OSVersion:=winOld; //Более ранние операционные системы (программа всё равно на них не будет работать) end; procedure GetCurrentDir; begin CurrentDir:=ExtractFilePath(ParamStr(0)); LogFileName:=CurrentDir+'cwm.log'; end; procedure GetWindowsBits; function FIs64BitWindows:Boolean; var Wow64Process1:Bool; begin Result:=False; {$IF Defined(Win64)} Result:=True; Exit; {$ELSEIF Defined(CPU16)} Result:=False; {$ELSE} Wow64Process1:=False; Result:=IsWow64Process(GetCurrentProcess, Wow64Process1) and Wow64Process1; {$ENDIF} end; begin if FIs64BitWindows then WindowsBits:=x64 else WindowsBits:=x32; end; procedure GetApplicationBits; begin {$IFDEF WIN64} AppBits:=x64; {$ELSE} AppBits:=x32; {$ENDIF} end; procedure InitLog; begin NotUseLog:=False; try if not FileExists(LogFileName) then FileClose(FileCreate(LogFileName)); AssignFile(LogFile, LogFileName); Append(LogFile); except NotUseLog:=True; end; end; function GetC:string; var Buffer:array[0..254] of Char; begin GetWindowsDirectory(Buffer, SizeOf(Buffer)); Result:=Copy(StrPas(Buffer), 1, 3); end; function GetDriveSpaceInfo(Drive:string):TDriveSpaceInfoType; var FreeBytesAvailableToCaller:TLargeInteger; FreeSize:TLargeInteger; TotalSize:TLargeInteger; begin if Drive = '' then Drive:=GetC; GetDiskFreeSpaceEx(PChar(Drive), FreeBytesAvailableToCaller, Totalsize, @FreeSize); Result.FreeBytesAvailableToCaller:=FreeBytesAvailableToCaller; Result.FreeSize:=FreeSize; Result.TotalSize:=TotalSize; end; function BitsToStr(V:TOSBits):string; begin if V = x32 then Result:='x32' else Result:='x64'; end; procedure Init; begin //Loading... GetCurrentDir; //Установка текущего каталога InitLog; GetOSVersion; //Установка версии ОС GetWindowsBits; //Установка разрядности ОС GetApplicationBits; //Установка разрядности приложения C:=GetC; Info:=TCurrentOS.Create; end; end.
../statement/multicore.pas
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Ported to Delphi by Michal Wojcik. // // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved. // Released under the terms of the GNU General Public License version 2 or later. {$H+} unit FitProtocol; interface uses StrUtils, SysUtils, StringTokenizer, OutputStream, Counts, StreamReader; const format : string = '%10.10d'; type TFitProtocol = class public constructor Create; destructor Destroy; override; class procedure writeData(data : string; output : TOutputStream); overload; // procedure writeData(bytes : byte; output : TOutputStream); overload; class procedure writeSize(length : integer; output : TOutputStream); class procedure writeCounts(count : TCounts; output : TOutputStream); class function readSize(reader : TStreamReader) : integer; class function readDocument(reader : TStreamReader; size : integer) : string; class function readCounts(reader : TStreamReader) : TCounts; end; implementation { TFitProtocol } constructor TFitProtocol.Create(); begin inherited Create; end; destructor TFitProtocol.Destroy(); begin inherited Destroy; end; class procedure TFitProtocol.writeData(data : string; output : TOutputStream); //var // bytes : byte; begin // bytes:=data.getBytes('UTF-8'); // writeData(bytes,output); writeSize(length(data), output); output.write(data); output.flush(); end; { procedure TFitProtocol.writeData(bytes : byte; output : TOutputStream); var length : integer; begin length:=bytes.length; writeSize(length,output); output.write(bytes); output.flush(); end; } class procedure TFitProtocol.writeSize(length : integer; output : TOutputStream); var formattedLength : string; // lengthBytes : byte; begin formattedLength := SysUtils.Format('%10.10d', [length]); // lengthBytes:=formattedLength.getBytes(); output.write(formattedLength {lengthBytes}); //TODO output.flush(); end; class procedure TFitProtocol.writeCounts(count : TCounts; output : TOutputStream); begin writeSize(0, output); writeSize(count.right, output); writeSize(count.wrong, output); writeSize(count.ignores, output); writeSize(count.exceptions, output); end; class function TFitProtocol.readSize(reader : TStreamReader) : Integer; var sizeString : string; begin sizeString := reader.read(10); if (length(sizeString) < 10) then begin raise Exception.Create('A size value could not be read. Fragment=|' + sizeString + '|'); end else begin result := StrToInt(sizeString); end; end; class function TFitProtocol.readDocument(reader : TStreamReader; size : integer) : string; begin result := reader.read(size); end; class function TFitProtocol.readCounts(reader : TStreamReader) : TCounts; var counts : TCounts; begin counts := TCounts.Create(); counts.right := readSize(reader); counts.wrong := readSize(reader); counts.ignores := readSize(reader); counts.exceptions := readSize(reader); result := counts; end; end.
unit uHoldingsForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls, StdCtrls, EditBtn, Buttons, Windows, uModbus, uLibrary, uHoldings, uConfiguratorData, uFrameListFactory, uHoldingsData; type TTypeOperation = (toSave, toRestore); THoldingsThread = class; { THoldingsForm } THoldingsForm = class(TForm) FileNameBox: TGroupBox; FileNameEdit: TFileNameEdit; ImageList: TImageList; ProgressBar: TProgressBar; StartButton: TSpeedButton; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure StartButtonClick(Sender: TObject); private fFrameListFactory: TFrameListFactory; fHoldingsWriterFrameListFactory: THoldingsWriterFrameListFactory; fFrameList: TFrameList; fDeviceData: TDeviceData; fModbusData: TModbusData; fHoldings: IHoldings; fHoldingsThread: THoldingsThread; fTypeOperation: TTypeOperation; private procedure CreateFrameList; procedure CreateWriteFrameList; procedure OnTerminate(Sender: TObject); procedure Stop(Sender: TObject); public procedure SaveHoldings(const aModbusData: TModbusData; const aDeviceData: TDeviceData; const aTypeOperation: TTypeOperation); end; { THoldingsThread } THoldingsThread = class(TThread) private fCurrentFrame: Integer; fClosed: Integer; fSavedHoldingsForm: THoldingsForm; private procedure DoUpdate; public constructor Create(const aSavedHoldingsForm: THoldingsForm); reintroduce; public function IsClosed: Boolean; procedure Close; end; { THoldingsRestorer } THoldingsRestorer = class(THoldingsThread) protected procedure Execute; override; end; { THoldingsSaver } THoldingsSaver = class(THoldingsThread) private procedure DoCreateHoldings; protected procedure Execute; override; end; implementation {$R *.lfm} resourcestring sFilter = 'Holding register files|*.hrf|All files|*.*'; { THoldingsForm } procedure THoldingsForm.FormCreate(Sender: TObject); begin fFrameListFactory := TFrameListFactory.Create; fHoldingsWriterFrameListFactory := THoldingsWriterFrameListFactory.Create; fFrameList := TFrameList.Create; FileNameEdit.Filter := sFilter; FileNameEdit.InitialDir := ExtractFilePath(ParamStr(0)); end; procedure THoldingsForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin Screen.Cursor := crHourGlass; try if (fHoldingsThread <> nil) then begin while not fHoldingsThread.IsClosed do begin Application.ProcessMessages; Sleep(10); CanClose := False; end; fHoldingsThread.Free; fHoldingsThread := nil; end; finally Screen.Cursor := crDefault; CanClose := True; end; end; procedure THoldingsForm.FormDestroy(Sender: TObject); begin FreeAndNil(fHoldingsWriterFrameListFactory); FreeAndNil(fFrameListFactory); FreeAndNil(fFrameList); end; procedure THoldingsForm.StartButtonClick(Sender: TObject); begin if fHoldingsThread <> nil then begin while not fHoldingsThread.IsClosed do begin Application.ProcessMessages; Sleep(10); end; fHoldingsThread.Free; fHoldingsThread := nil; end; try case fTypeOperation of toSave: begin CreateFrameList; fHoldingsThread := THoldingsSaver.Create(Self); end; toRestore: begin fHoldings := GetHoldings(FileNameEdit.FileName); CreateWriteFrameList; fHoldingsThread := THoldingsRestorer.Create(Self); end; end; ImageList.GetBitmap(1, StartButton.Glyph); StartButton.Hint := 'Остановить'; fHoldingsThread.OnTerminate := @OnTerminate; fHoldingsThread.Start; StartButton.OnClick := @Stop; except on E: Exception do MessageBox(Handle, PChar(Utf8ToAnsi(E.Message)), PChar(Utf8ToAnsi('Ошибка')), MB_ICONERROR + MB_OK); end; end; procedure THoldingsForm.OnTerminate(Sender: TObject); begin ImageList.GetBitmap(0, StartButton.Glyph); StartButton.Hint := 'Запустить'; StartButton.OnClick := @StartButtonClick; end; procedure THoldingsForm.Stop(Sender: TObject); begin fHoldingsThread.Close; end; procedure THoldingsForm.CreateFrameList; var Vars: IVars; VarDefine: IVarDefine; P: Pointer; FoundIndex: Integer; begin if fDeviceData.Module = nil then raise Exception.Create('Отсутствует описание устройства'); FoundIndex := fDeviceData.Module.ModuleDefine.Registers.IndexOf(TTypeRegister.trHolding); if FoundIndex < 0 then raise Exception.Create(Format('В модуле ''%s'' отсутствует описание Holding-регистров', [fDeviceData.Module.Name])); Vars := fDeviceData.Module.ModuleDefine.Registers.Data[FoundIndex]; for P in Vars do begin VarDefine := Vars.ExtractData(P); fFrameListFactory.VarList.Add(VarDefine); end; fFrameListFactory.CreateFrameList(fDeviceData.SlaveId, fFrameList); end; procedure THoldingsForm.CreateWriteFrameList; begin fHoldingsWriterFrameListFactory.Holdings := fHoldings; fHoldingsWriterFrameListFactory.CreateFrameList(fDeviceData.SlaveId, fFrameList); end; procedure THoldingsForm.SaveHoldings(const aModbusData: TModbusData; const aDeviceData: TDeviceData; const aTypeOperation: TTypeOperation); begin fModbusData := aModbusData; fDeviceData := aDeviceData; fTypeOperation := aTypeOperation; case aTypeOperation of toSave: Caption := 'Сохранить Holding-регистры в файл'; toRestore: Caption := 'Восстановить Holding-регистры'; end; ShowModal; end; { THoldingsThread } constructor THoldingsThread.Create(const aSavedHoldingsForm: THoldingsForm); begin inherited Create(False); fSavedHoldingsForm := aSavedHoldingsForm; fClosed := 1; fCurrentFrame := 0; FreeOnTerminate := False; end; procedure THoldingsThread.DoUpdate; begin with fSavedHoldingsForm do begin ProgressBar.Min := 0; ProgressBar.Max := fFrameList.Count - 1; ProgressBar.Position := fCurrentFrame; if ProgressBar.Position = Integer(fFrameList.Count - 1) then ProgressBar.Position := 0; end; end; function THoldingsThread.IsClosed: Boolean; begin Result := Windows.InterlockedCompareExchange(fClosed, 0, 0) = 1; end; procedure THoldingsThread.Close; begin Windows.InterLockedExchange(fClosed, 1); WaitForSingleObject(Handle, 1000); end; { THoldingsRestorer } const WM_COUNT = WM_USER + 1; procedure THoldingsRestorer.Execute; var Frame: IFrame; begin Windows.InterlockedExchange(fClosed, 0); try for Frame in fSavedHoldingsForm.fFrameList do begin // Пока не отправлен запрос while not fSavedHoldingsForm.fModbusData.Controller.InQueue(Frame) do begin Sleep(20); if IsClosed then Exit; end; // Обработка ответа if Frame.Responded then begin PostMessage(Application.MainFormHandle, WM_COUNT, 1, 0); Inc(fCurrentFrame); Synchronize(@DoUpdate); end else PostMessage(Application.MainFormHandle, WM_COUNT, 0, 1); if IsClosed then Exit; end; PostMessage(fSavedHoldingsForm.Handle, WM_CLOSE, 0, 0); finally Windows.InterlockedExchange(fClosed, 1); end; end; procedure THoldingsSaver.DoCreateHoldings; var Holdings: IHoldings; VarDefine: IVarDefine; begin Holdings := CreateHoldings; Holdings.Created := Now; Holdings.ModuleName := fSavedHoldingsForm.fDeviceData.Module.Name; Holdings.Uid := fSavedHoldingsForm.fDeviceData.Module.Uid; for VarDefine in fSavedHoldingsForm.fFrameListFactory.VarList do THoldingBuilder.BuildHolding(Holdings.AddNew, VarDefine, fSavedHoldingsForm.fDeviceData.Map); SaveHoldings(Holdings, fSavedHoldingsForm.FileNameEdit.FileName); end; procedure THoldingsSaver.Execute; var Frame: IFrame; begin Windows.InterlockedExchange(fClosed, 0); try for Frame in fSavedHoldingsForm.fFrameList do begin // Пока не отправлен запрос while not fSavedHoldingsForm.fModbusData.Controller.InQueue(Frame) do begin Sleep(20); if IsClosed then Exit; end; // Обработка ответа if Frame.Responded then begin fSavedHoldingsForm.fDeviceData.Map.WriteData(Swap(PWord(@Frame.RequestPdu^[1])^), Frame.ResponsePdu); PostMessage(Application.MainFormHandle, WM_COUNT, 1, 0); Inc(fCurrentFrame); Synchronize(@DoUpdate); end else PostMessage(Application.MainFormHandle, WM_COUNT, 0, 1); if IsClosed then Exit; end; Synchronize(@DoCreateHoldings); PostMessage(fSavedHoldingsForm.Handle, WM_CLOSE, 0, 0); finally Windows.InterlockedExchange(fClosed, 1); end; end; end.
unit MobilePrefsForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.IniFiles, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.Edit, CCR.PrefsIniFile; type TfrmMobilePrefs = class(TForm) Label1: TLabel; edtSection: TEdit; Label2: TLabel; edtKey: TEdit; Label3: TLabel; edtValue: TEdit; lyoReadWriteButtons: TGridLayout; btnReadBool: TButton; btnWriteBool: TButton; btnReadFloat: TButton; btnWriteFloat: TButton; btnReadInt: TButton; btnWriteInt: TButton; btnReadStr: TButton; btnWriteStr: TButton; btnReadSection: TButton; btnReadSectionVals: TButton; btnReadSections: TButton; btnUpdateFile: TButton; procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure btnReadBoolClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnReadFloatClick(Sender: TObject); procedure btnReadIntClick(Sender: TObject); procedure btnReadStrClick(Sender: TObject); procedure btnReadSectionClick(Sender: TObject); procedure btnReadSectionValsClick(Sender: TObject); procedure btnReadSectionsClick(Sender: TObject); procedure btnWriteBoolClick(Sender: TObject); procedure btnWriteFloatClick(Sender: TObject); procedure btnWriteIntClick(Sender: TObject); procedure btnWriteStrClick(Sender: TObject); procedure btnUpdateFileClick(Sender: TObject); private FIniFile: TCustomIniFile; procedure ReportValue(const Value: string); end; var frmMobilePrefs: TfrmMobilePrefs; implementation {$R *.fmx} procedure TfrmMobilePrefs.FormCreate(Sender: TObject); begin FIniFile := CreateUserPreferencesIniFile; end; procedure TfrmMobilePrefs.FormDestroy(Sender: TObject); begin FIniFile.Free; end; procedure TfrmMobilePrefs.FormResize(Sender: TObject); begin lyoReadWriteButtons.ItemWidth := lyoReadWriteButtons.Width / 2; end; procedure TfrmMobilePrefs.ReportValue(const Value: string); begin ShowMessageFmt('The value for %s -> %s is %s', [edtSection.Text, edtKey.Text, Value]); end; procedure TfrmMobilePrefs.btnReadBoolClick(Sender: TObject); const Strs: array[Boolean] of string = ('False', 'True'); begin ReportValue(Strs[FIniFile.ReadBool(edtSection.Text, edtKey.Text, StrToBoolDef(edtValue.Text, False))]); end; procedure TfrmMobilePrefs.btnReadFloatClick(Sender: TObject); begin ReportValue(FIniFile.ReadFloat(edtSection.Text, edtKey.Text, StrToFloatDef(edtValue.Text, 0)).ToString); end; procedure TfrmMobilePrefs.btnReadIntClick(Sender: TObject); begin ReportValue(FIniFile.ReadInteger(edtSection.Text, edtKey.Text, StrToIntDef(edtValue.Text, 0)).ToString); end; procedure TfrmMobilePrefs.btnReadSectionClick(Sender: TObject); var Strings: TStringList; begin Strings := TStringList.Create; FIniFile.ReadSection(edtSection.Text, Strings); if Strings.Count = 0 then ShowMessage('The specified section either does not exist or has no keys.') else begin Strings.Insert(0, 'The specified section has the following keys:'); ShowMessage(Strings.Text); end; end; procedure TfrmMobilePrefs.btnReadSectionsClick(Sender: TObject); var Strings: TStringList; begin Strings := TStringList.Create; FIniFile.ReadSections(edtSection.Text, Strings); if Strings.Count = 0 then ShowMessage('The preferences data is either empty or contains no recognised sections.') else begin Strings.Insert(0, 'The preferences data contains the following sections:'); ShowMessage(Strings.Text); end; end; procedure TfrmMobilePrefs.btnReadSectionValsClick(Sender: TObject); var Strings: TStringList; begin Strings := TStringList.Create; FIniFile.ReadSectionValues(edtSection.Text, Strings); if Strings.Count = 0 then ShowMessage('The specified section either does not exist or has no keys.') else begin Strings.Insert(0, 'The specified section has the following key/value pairs:'); ShowMessage(Strings.Text); end; end; procedure TfrmMobilePrefs.btnReadStrClick(Sender: TObject); begin ReportValue('''' + FIniFile.ReadString(edtSection.Text, edtKey.Text, edtValue.Text) + ''''); end; procedure TfrmMobilePrefs.btnUpdateFileClick(Sender: TObject); begin FIniFile.UpdateFile; end; procedure TfrmMobilePrefs.btnWriteBoolClick(Sender: TObject); begin FIniFile.WriteBool(edtSection.Text, edtKey.Text, StrToBoolDef(edtValue.Text, False)); end; procedure TfrmMobilePrefs.btnWriteFloatClick(Sender: TObject); begin FIniFile.WriteFloat(edtSection.Text, edtKey.Text, StrToFloatDef(edtValue.Text, 0)); end; procedure TfrmMobilePrefs.btnWriteIntClick(Sender: TObject); begin FIniFile.WriteInteger(edtSection.Text, edtKey.Text, StrToIntDef(edtValue.Text, 0)); end; procedure TfrmMobilePrefs.btnWriteStrClick(Sender: TObject); begin FIniFile.WriteString(edtSection.Text, edtKey.Text, edtValue.Text); end; end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, uSbSpeechRecognize, Vcl.ComCtrls; type TFrmMain = class(TForm) Panel1: TPanel; BtnRun: TButton; MemResult: TMemo; ProgressBar1: TProgressBar; procedure BtnRunClick(Sender: TObject); procedure FormCreate(Sender: TObject); private procedure CstResultEvent(Sender: TObject; SpeechResult:TSpeechResult); procedure CstProcessEvent(Sender: TObject; Position:Integer); public { Public declarations } end; var FrmMain: TFrmMain; SbSpeechRecognize : TSbSpeechRecognize; implementation uses Soap.EncdDecd, System.NetEncoding; {$R *.dfm} function EncodeFile(const FileName: string): String; var MemStream: TMemoryStream; begin MemStream := TMemoryStream.Create; try MemStream.LoadFromFile(Filename); MemStream.Position := 0; Result := TNetEncoding.Base64.EncodeBytesToString(MemStream.Memory, MemStream.Size); finally MemStream.Free; end; end; procedure TFrmMain.BtnRunClick(Sender: TObject); var xSpeechParam : TSpeechParam; begin { Çok büyük dosyalarda cloud storage upload etmek gerekli Cloud storage entegrasyonu token + upload file Cloud storage entegrasyonu sonra yapılacak Geçici olarak TMS Cloud Pack kullanılabilir } BtnRun.Enabled := False; MemResult.Lines.Clear; xSpeechParam.SoundSource := EncodeFile('C:\Users\narkotik\Desktop\Kayit.flac'); SbSpeechRecognize.ApiKey := ''; SbSpeechRecognize.OnResult := CstResultEvent; SbSpeechRecognize.OnProcess := CstProcessEvent; TThread.CreateAnonymousThread( procedure() begin SbSpeechRecognize.GetSpeechRecognize(xSpeechParam); end).Start; end; procedure TFrmMain.CstProcessEvent(Sender: TObject; Position: Integer); begin ProgressBar1.Position := Position; end; procedure TFrmMain.CstResultEvent(Sender: TObject; SpeechResult: TSpeechResult); var Ind : Integer; begin BtnRun.Enabled := True; if SpeechResult.Error then ShowMessage(SpeechResult.ErrorStr) else begin for Ind := Low(SpeechResult.TextArr) to High(SpeechResult.TextArr) do MemResult.Lines.Add(Trim(SpeechResult.TextArr[Ind])); end; end; procedure TFrmMain.FormCreate(Sender: TObject); begin SbSpeechRecognize := TSbSpeechRecognize.Create(nil); end; end.
(* Name: UfrmDownloadProgress Copyright: Copyright (C) SIL International. Documentation: Description: Create Date: 4 Dec 2006 Modified Date: 18 May 2012 Authors: mcdurdin Related Files: Dependencies: Bugs: Todo: Notes: History: 04 Dec 2006 - mcdurdin - Initial version 31 Mar 2011 - mcdurdin - I2855 - Keyman Developer online update crashes with Integer Overflow 18 May 2012 - mcdurdin - I3306 - V9.0 - Remove TntControls + Win9x support *) unit UfrmDownloadProgress; // I3306 interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, httpuploader, UfrmTike, UserMessages; type TfrmDownloadProgress = class; TDownloadProgressCallback = procedure(Owner: TfrmDownloadProgress; var Result: Boolean) of object; TfrmDownloadProgress = class(TTIKEForm) progress: TProgressBar; cmdCancel: TButton; lblStatus: TLabel; procedure TntFormShow(Sender: TObject); procedure cmdCancelClick(Sender: TObject); private FCallback: TDownloadProgressCallback; FCancel: Boolean; procedure WMUserFormShown(var Message: TMessage); message WM_USER_FormShown; public procedure HTTPCheckCancel(Sender: THTTPUploader; var Cancel: Boolean); //procedure HTTPFileProgress(Sender: THTTPUploader; const FileName: string; dwFileBytesSent, dwLocalFileSize, dwSecondsToFileCompletion, dwOverallBytesSent, dwOverallBytesTotal, dwSecondsToOverallCompletion, dwBytesPerSecond: DWord); procedure HTTPStatus(Sender: THTTPUploader; const Message: string; Position, Total: Int64); // I2855 property Callback: TDownloadProgressCallback read FCallback write FCallback; property Cancel: Boolean read FCancel; end; implementation {$R *.dfm} procedure TfrmDownloadProgress.cmdCancelClick(Sender: TObject); begin inherited; FCancel := True; end; procedure TfrmDownloadProgress.HTTPCheckCancel(Sender: THTTPUploader; var Cancel: Boolean); begin Cancel := FCancel; end; {procedure TfrmDownloadProgress.HTTPFileProgress( Sender: THTTPUploader; const FileName: string; dwFileBytesSent, dwLocalFileSize, dwSecondsToFileCompletion, dwOverallBytesSent, dwOverallBytesTotal, dwSecondsToOverallCompletion, dwBytesPerSecond: DWord); begin progress.Max := dwOverallBytesTotal; progress.Position := dwOverallBytesSent; progress.Update; Application.ProcessMessages; end;} procedure TfrmDownloadProgress.HTTPStatus(Sender: THTTPUploader; const Message: string; Position, Total: Int64); // I2855 begin if Total = 0 then progress.Max := 100 else progress.Max := Total; progress.Position := Position; progress.Update; lblStatus.Caption := Message; lblStatus.Update; Application.ProcessMessages; end; procedure TfrmDownloadProgress.TntFormShow(Sender: TObject); begin inherited; PostMessage(Handle, WM_USER_FormShown, 0, 0); end; procedure TfrmDownloadProgress.WMUserFormShown(var Message: TMessage); var Result: Boolean; begin Result := False; FCancel := False; try if Assigned(FCallback) then FCallback(Self, Result); if Result then ModalResult := mrOk else ModalResult := mrCancel; except on EHTTPUploaderCancel do ModalResult := mrCancel; on E:EHTTPUploader do begin ShowMessage(E.Message); ModalResult := mrCancel; end; end; end; end.
{******************************************************************************} { } { Indy (Internet Direct) - Internet Protocols Simplified } { } { https://www.indyproject.org/ } { https://gitter.im/IndySockets/Indy } { } {******************************************************************************} { } { This file is part of the Indy (Internet Direct) project, and is offered } { under the dual-licensing agreement described on the Indy website. } { (https://www.indyproject.org/license/) } { } { Copyright: } { (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { } {******************************************************************************} { } { Originally written by: Fabian S. Biehn } { fbiehn@aagon.com (German & English) } { } { Contributers: } { Here could be your name } { } {******************************************************************************} // This File is auto generated! // Any change to this file should be made in the // corresponding unit in the folder "intermediate"! // Generation date: 28.10.2020 15:24:13 unit IdOpenSSLHeaders_storeerr; interface // Headers for OpenSSL 1.1.1 // storeerr.h {$i IdCompilerDefines.inc} uses Classes, IdCTypes, IdGlobal, IdOpenSSLConsts; const (* * OSSL_STORE function codes. *) OSSL_STORE_F_FILE_CTRL = 129; OSSL_STORE_F_FILE_FIND = 138; OSSL_STORE_F_FILE_GET_PASS = 118; OSSL_STORE_F_FILE_LOAD = 119; OSSL_STORE_F_FILE_LOAD_TRY_DECODE = 124; OSSL_STORE_F_FILE_NAME_TO_URI = 126; OSSL_STORE_F_FILE_OPEN = 120; OSSL_STORE_F_OSSL_STORE_ATTACH_PEM_BIO = 127; OSSL_STORE_F_OSSL_STORE_EXPECT = 130; OSSL_STORE_F_OSSL_STORE_FILE_ATTACH_PEM_BIO_INT = 128; OSSL_STORE_F_OSSL_STORE_FIND = 131; OSSL_STORE_F_OSSL_STORE_GET0_LOADER_INT = 100; OSSL_STORE_F_OSSL_STORE_INFO_GET1_CERT = 101; OSSL_STORE_F_OSSL_STORE_INFO_GET1_CRL = 102; OSSL_STORE_F_OSSL_STORE_INFO_GET1_NAME = 103; OSSL_STORE_F_OSSL_STORE_INFO_GET1_NAME_DESCRIPTION = 135; OSSL_STORE_F_OSSL_STORE_INFO_GET1_PARAMS = 104; OSSL_STORE_F_OSSL_STORE_INFO_GET1_PKEY = 105; OSSL_STORE_F_OSSL_STORE_INFO_NEW_CERT = 106; OSSL_STORE_F_OSSL_STORE_INFO_NEW_CRL = 107; OSSL_STORE_F_OSSL_STORE_INFO_NEW_EMBEDDED = 123; OSSL_STORE_F_OSSL_STORE_INFO_NEW_NAME = 109; OSSL_STORE_F_OSSL_STORE_INFO_NEW_PARAMS = 110; OSSL_STORE_F_OSSL_STORE_INFO_NEW_PKEY = 111; OSSL_STORE_F_OSSL_STORE_INFO_SET0_NAME_DESCRIPTION = 134; OSSL_STORE_F_OSSL_STORE_INIT_ONCE = 112; OSSL_STORE_F_OSSL_STORE_LOADER_NEW = 113; OSSL_STORE_F_OSSL_STORE_OPEN = 114; OSSL_STORE_F_OSSL_STORE_OPEN_INT = 115; OSSL_STORE_F_OSSL_STORE_REGISTER_LOADER_INT = 117; OSSL_STORE_F_OSSL_STORE_SEARCH_BY_ALIAS = 132; OSSL_STORE_F_OSSL_STORE_SEARCH_BY_ISSUER_SERIAL = 133; OSSL_STORE_F_OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT = 136; OSSL_STORE_F_OSSL_STORE_SEARCH_BY_NAME = 137; OSSL_STORE_F_OSSL_STORE_UNREGISTER_LOADER_INT = 116; OSSL_STORE_F_TRY_DECODE_PARAMS = 121; OSSL_STORE_F_TRY_DECODE_PKCS12 = 122; OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED = 125; (* * OSSL_STORE reason codes. *) OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE = 107; OSSL_STORE_R_BAD_PASSWORD_READ = 115; OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC = 113; OSSL_STORE_R_FINGERPRINT_SIZE_DOES_NOT_MATCH_DIGEST = 121; OSSL_STORE_R_INVALID_SCHEME = 106; OSSL_STORE_R_IS_NOT_A = 112; OSSL_STORE_R_LOADER_INCOMPLETE = 116; OSSL_STORE_R_LOADING_STARTED = 117; OSSL_STORE_R_NOT_A_CERTIFICATE = 100; OSSL_STORE_R_NOT_A_CRL = 101; OSSL_STORE_R_NOT_A_KEY = 102; OSSL_STORE_R_NOT_A_NAME = 103; OSSL_STORE_R_NOT_PARAMETERS = 104; OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR = 114; OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE = 108; OSSL_STORE_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES = 119; OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED = 109; OSSL_STORE_R_UNREGISTERED_SCHEME = 105; OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE = 110; OSSL_STORE_R_UNSUPPORTED_OPERATION = 118; OSSL_STORE_R_UNSUPPORTED_SEARCH_TYPE = 120; OSSL_STORE_R_URI_AUTHORITY_UNSUPPORTED = 111; procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList); procedure UnLoad; var ERR_load_OSSL_STORE_strings: function: TIdC_INT cdecl = nil; implementation procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList); function LoadFunction(const AMethodName: string; const AFailed: TStringList): Pointer; begin Result := LoadLibFunction(ADllHandle, AMethodName); if not Assigned(Result) then AFailed.Add(AMethodName); end; begin ERR_load_OSSL_STORE_strings := LoadFunction('ERR_load_OSSL_STORE_strings', AFailed); end; procedure UnLoad; begin ERR_load_OSSL_STORE_strings := nil; end; end.
PROGRAM EXEMPLO8; USES CRT; VAR TEXTO1 : STRING; BEGIN CLRSCR; {A vari vel TEXTO1 recebe a cadeia de caracteres: PROGRAMA DE COMPUTADOR} TEXTO1:='PROGRAMA DE COMPUTADOR'; {A fun‡ao DELETE apaga, a partir da posi‡ao 9, 3 caracteres da cadeia TEXTO1} DELETE(TEXTO1,9,3); {Mostra o conte£do da vari vel TEXTO1} WRITELN('Nova cadeia TEXTO1 = ',TEXTO1); READLN; END.
PROGRAM TheMissingElement; CONST MAX_ELEMENTS = 100; TYPE IntArray = ARRAY[1..MAX_ELEMENTS] OF INTEGER; VAR testElements: IntArray; (* Searches the missing element in a row of unsorted numbers *) FUNCTION MissingElement(VAR a: IntArray; n: INTEGER): INTEGER; VAR sum: INTEGER; arraySum: INTEGER; i: SMALLINT; BEGIN IF n > 0 THEN BEGIN (* use a sum formula for determining the sum of the row *) sum := ((n + 1) * (n + 2)) DIV 2; (* calculate the sum of the row excluding the missing element *) FOR i := 1 TO n DO BEGIN arraySum := arraySum + a[i]; END; (* determine the missing element *) MissingElement := (sum - arraySum); END ELSE BEGIN MissingElement := (-1); END; END; BEGIN (* WriteLn(MissingElement(testElements, 0)); *) testElements[1] := 3; testElements[2] := 2; testElements[3] := 4; testElements[4] := 5; WriteLn(MissingElement(testElements, 4)); testElements[1] := 3; testElements[2] := 2; testElements[3] := 4; testElements[4] := 1; WriteLn(MissingElement(testElements, 4)); testElements[1] := 3; testElements[2] := 2; testElements[3] := 1; testElements[4] := 5; WriteLn(MissingElement(testElements, 4)); testElements[1] := 5; testElements[2] := 2; testElements[3] := 4; testElements[4] := 1; testElements[5] := 6; WriteLn(MissingElement(testElements, 5)); END.
{ Copyright (C) 2001-2008 Benito van der Zander, www.benibela.de This file is part of API Manager. API Manager 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. API Manager 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 API Manager. If not, see <http://www.gnu.org/licenses/>. } unit winconstwindow; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls,LCLType; type { TwindowConstForm } TwindowConstForm = class(TForm) Edit1: TEdit; ListBox1: TListBox; procedure Edit1Change(Sender: TObject); procedure Edit1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Edit1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure ListBox1DblClick(Sender: TObject); private { private declarations } winConsts: TStringList; public { public declarations } currentConst: string; end; var windowConstForm: TwindowConstForm; implementation uses applicationConfig,FileUtil,ptranslateutils,LazFileUtils; {$I winconstwindow.atr} { TwindowConstForm } procedure TwindowConstForm.FormCreate(Sender: TObject); begin initUnitTranslation(CurrentUnitName,tr); end; procedure TwindowConstForm.FormDestroy(Sender: TObject); begin winConsts.Free; end; procedure TwindowConstForm.FormShow(Sender: TObject); var i:longint; path,s:string; searchRec:TSearchRec; tempSL:TStringList; begin if left+width>Screen.width then left:=screen.width-width; if top+height>Screen.height then top:=screen.height-height; if winConsts=nil then begin winConsts:=TStringList.Create; try path:=winConstPath; if not FilenameIsAbsolute(winConstPath) then path:=IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)))+path; path:=IncludeTrailingPathDelimiter(path); if DirectoryExistsUTF8(ExcludeTrailingPathDelimiter(path)) then begin tempSL:=TStringList.Create; FindFirst(path+'*.*',faAnyFile,searchRec); repeat if searchRec.Name='' then continue; if searchRec.Name[1]='.' then continue; tempSL.LoadFromFile(path+searchRec.Name); for i:=0 to tempSL.count-1 do begin s:=trim(tempSL[i]); if s='' then continue; //skip empty if ((s[1]='{') and (s[length(s)]='}')) or ((s[1]='/') and (s[2] = '/')) then continue; //skip comment only winConsts.Add(s); end; until FindNext(searchRec)<>0; FindClose(searchRec); tempSL.Free; end; except end; end; if winConsts.Count=0 then begin winConsts.free; winConsts:=nil; ListBox1.items.text:=tr['Keine Windowskonstanten gefunden'#13#10'Überprüfen Sie den Pfad: ']+winConstPath; end else ListBox1.Items.Text:=tr['Suche in der FreePascal Windows Unit']; Edit1.text:=currentConst; edit1.SetFocus; edit1.SelStart:=length(edit1.text); end; procedure TwindowConstForm.ListBox1DblClick(Sender: TObject); begin if ListBox1.ItemIndex<0 then exit; Edit1.Text:=ListBox1.items[ListBox1.ItemIndex]; end; procedure TwindowConstForm.Edit1Change(Sender: TObject); var s:string; i:longint; begin if winConsts=nil then exit; s:=LowerCase(Edit1.Text); if s='' then exit; ListBox1.Clear; ListBox1.Items.BeginUpdate; for i:=0 to winConsts.Count-1 do if pos(s,LowerCase(winConsts[i]))>0 then ListBox1.Items.Add(winConsts[i]); ListBox1.Items.EndUpdate; ListBox1.ItemIndex:=0; end; procedure TwindowConstForm.Edit1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key=vk_up then begin if ListBox1.ItemIndex>0 then ListBox1.ItemIndex:=ListBox1.ItemIndex-1; key:=0; end else if key=VK_DOWN then begin ListBox1.ItemIndex:=ListBox1.ItemIndex+1; key:=0; end else if key=VK_PRIOR then begin if ListBox1.ItemIndex>=10 then ListBox1.ItemIndex:=ListBox1.ItemIndex-10 else ListBox1.ItemIndex:=0; end else if key=VK_NEXT then begin if ListBox1.ItemIndex<=ListBox1.Items.Count-11 then ListBox1.ItemIndex:=ListBox1.ItemIndex+10 else ListBox1.ItemIndex:=ListBox1.Items.Count-1; end // Application.ControlKeyDown(ListBox1,Key,shift); // ListBox1.ControlKeyDown(key,shift); end; procedure TwindowConstForm.Edit1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key=VK_RETURN then begin ModalResult:=mrOK; if ListBox1.ItemIndex>=0 then if shift = [ssCtrl] then currentConst+=ListBox1.items[ListBox1.ItemIndex] else currentConst:=ListBox1.items[ListBox1.ItemIndex]; key:=0; close end else if key=VK_ESCAPE then begin ModalResult:=mrCancel; currentConst:=''; close end ; end; initialization {$I winconstwindow.lrs} end.
(* * This code was generated by the TaskGen tool from file * "CommonOptionsTask.xml" * Version: 19.0.0.0 * Runtime Version: v2.0.50727 * Changes to this file may cause incorrect behavior and will be * overwritten when the code is regenerated. *) unit CommonOptionStrs; interface const sTaskName = 'commonoptions'; // PathsAndDefines sDefines = 'Defines'; sIncludePath = 'IncludePath'; sFinalOutputDir = 'FinalOutputDir'; sIntermediateOutputDir = 'IntermediateOutputDir'; // MiscInternalOptions sShowGeneralMessages = 'ShowGeneralMessages'; // CommonPackageOpts sPackageImports = 'PackageImports'; sAllPackageLibs = 'AllPackageLibs'; sPackageLibs = 'PackageLibs'; sDesignOnlyPackage = 'DesignOnlyPackage'; sRuntimeOnlyPackage = 'RuntimeOnlyPackage'; // DelphiInternalOptions sGenPackage = 'GenPackage'; sGenDll = 'GenDll'; sUsePackages = 'UsePackages'; sHasTypeLib = 'HasTypeLib'; sAutoGenImportAssembly = 'AutoGenImportAssembly'; sAutoRegisterTLB = 'AutoRegisterTLB'; sImageDebugInfo = 'ImageDebugInfo'; sDebugSourcePath = 'DebugSourcePath'; // OutputFilenameModifiers sOutputExt = 'OutputExt'; sOutputName = 'OutputName'; sDllPrefixDefined = 'DllPrefixDefined'; sDllPrefix = 'DllPrefix'; sDllVersion = 'DllVersion'; sDllSuffix = 'DllSuffix'; // C++InternalOptions sMultithreaded = 'Multithreaded'; sDynamicRTL = 'DynamicRTL'; sUsingDelphiRTL = 'UsingDelphiRTL'; sLinkCodeGuard = 'LinkCodeGuard'; sRunBCCOutOfProcess = 'RunBCCOutOfProcess'; // WindowsVersionInformation sVerInfo_IncludeVerInfo = 'VerInfo_IncludeVerInfo'; sVerInfo_MajorVer = 'VerInfo_MajorVer'; sVerInfo_MinorVer = 'VerInfo_MinorVer'; sVerInfo_Release = 'VerInfo_Release'; sVerInfo_Build = 'VerInfo_Build'; sVerInfo_Debug = 'VerInfo_Debug'; sVerInfo_PreRelease = 'VerInfo_PreRelease'; sVerInfo_Special = 'VerInfo_Special'; sVerInfo_Private = 'VerInfo_Private'; sVerInfo_DLL = 'VerInfo_DLL'; sVerInfo_Locale = 'VerInfo_Locale'; sVerInfo_CodePage = 'VerInfo_CodePage'; sVerInfo_CompanyName = 'VerInfo_CompanyName'; sVerInfo_FileDescription = 'VerInfo_FileDescription'; sVerInfo_FileVersion = 'VerInfo_FileVersion'; sVerInfo_InternalName = 'VerInfo_InternalName'; sVerInfo_LegalCopyright = 'VerInfo_LegalCopyright'; sVerInfo_LegalTrademarks = 'VerInfo_LegalTrademarks'; sVerInfo_OriginalFilename = 'VerInfo_OriginalFilename'; sVerInfo_ProductName = 'VerInfo_ProductName'; sVerInfo_ProductVersion = 'VerInfo_ProductVersion'; sVerInfo_Comments = 'VerInfo_Comments'; sVerInfo_Keys = 'VerInfo_Keys'; sVerInfo_AutoGenVersion = 'VerInfo_AutoGenVersion'; sVerInfo_AutoIncVersion = 'VerInfo_AutoIncVersion'; sVerInfo_BundleId = 'VerInfo_BundleId'; sVerInfo_UIDeviceFamily = 'VerInfo_UIDeviceFamily'; sIcon_MainIcon = 'Icon_MainIcon'; sIcns_MainIcns = 'Icns_MainIcns'; sManifest_File = 'Manifest_File'; sVCL_Custom_Styles = 'VCL_Custom_Styles'; // DebuggerProjectOptions sDebugger_RunParams = 'Debugger_RunParams'; sDebugger_RemoteRunParams = 'Debugger_RemoteRunParams'; sDebugger_HostApplication = 'Debugger_HostApplication'; sDebugger_RemotePath = 'Debugger_RemotePath'; sDebugger_RemoteHost = 'Debugger_RemoteHost'; sDebugger_EnvVars = 'Debugger_EnvVars'; sDebugger_SymTabs = 'Debugger_SymTabs'; sDebugger_Launcher = 'Debugger_Launcher'; sDebugger_RemoteLauncher = 'Debugger_RemoteLauncher'; sDebugger_IncludeSystemVars = 'Debugger_IncludeSystemVars'; sDebugger_UseLauncher = 'Debugger_UseLauncher'; sDebugger_UseRemoteLauncher = 'Debugger_UseRemoteLauncher'; sDebugger_CWD = 'Debugger_CWD'; sDebugger_RemoteCWD = 'Debugger_RemoteCWD'; sDebugger_RemoteDebug = 'Debugger_RemoteDebug'; sDebugger_DebugSourcePath = 'Debugger_DebugSourcePath'; sDebugger_LoadAllSymbols = 'Debugger_LoadAllSymbols'; sDebugger_LoadUnspecifiedSymbols = 'Debugger_LoadUnspecifiedSymbols'; sDebugger_SymbolSourcePath = 'Debugger_SymbolSourcePath'; // BuildEvents sPreBuildEvent = 'PreBuildEvent'; sPreBuildEventCancelOnError = 'PreBuildEventCancelOnError'; sPreLinkEvent = 'PreLinkEvent'; sPreLinkEventCancelOnError = 'PreLinkEventCancelOnError'; sPostBuildEvent = 'PostBuildEvent'; sPostBuildEventExecuteWhen = 'PostBuildEventExecuteWhen'; sPostBuildEventExecuteWhen_Always = 'Always'; sPostBuildEventExecuteWhen_TargetOutOfDate = 'TargetOutOfDate'; sPostBuildEventCancelOnError = 'PostBuildEventCancelOnError'; // BuildTypeProperties sPF_DevDebug = 'PF_DevDebug'; sENV_PF_DevDebug = 'ENV_PF_DevDebug'; sPF_AdHoc = 'PF_AdHoc'; sENV_PF_AdHoc = 'ENV_PF_AdHoc'; sENV_PF_AppStore = 'ENV_PF_AppStore'; sPF_AppStore = 'PF_AppStore'; sPF_DevAdHoc = 'PF_DevAdHoc'; sENV_PF_DevAdHoc = 'ENV_PF_DevAdHoc'; sPF_DevAppStore = 'PF_DevAppStore'; sENV_PF_DevAppStore = 'ENV_PF_DevAppStore'; sPF_DevTeamIdAppStore = 'PF_DevTeamIdAppStore'; sENV_PF_DevTeamIdAppStore = 'ENV_PF_DevTeamIdAppStore'; sPF_SandBox = 'PF_SandBox'; sENV_PF_SandBox = 'ENV_PF_SandBox'; sPF_DevSandBox = 'PF_DevSandBox'; sENV_PF_DevSandBox = 'ENV_PF_DevSandBox'; sPF_KeyStore = 'PF_KeyStore'; sENV_PF_KeyStore = 'ENV_PF_KeyStore'; sPF_KeyStorePass = 'PF_KeyStorePass'; sENV_PF_KeyStorePass = 'ENV_PF_KeyStorePass'; sPF_AliasKey = 'PF_AliasKey'; sENV_PF_AliasKey = 'ENV_PF_AliasKey'; sPF_AliasKeyPass = 'PF_AliasKeyPass'; sENV_PF_AliasKeyPass = 'ENV_PF_AliasKeyPass'; // AndroidUsesPermissions sAUP_ACCESS_CHECKIN_PROPERTIES = 'AUP_ACCESS_CHECKIN_PROPERTIES'; sAUP_ACCESS_SURFACE_FLINGER = 'AUP_ACCESS_SURFACE_FLINGER'; sAUP_ACCOUNT_MANAGER = 'AUP_ACCOUNT_MANAGER'; sAUP_BIND_APPWIDGET = 'AUP_BIND_APPWIDGET'; sAUP_BRICK = 'AUP_BRICK'; sAUP_BROADCAST_PACKAGE_REMOVED = 'AUP_BROADCAST_PACKAGE_REMOVED'; sAUP_BROADCAST_SMS = 'AUP_BROADCAST_SMS'; sAUP_BROADCAST_WAP_PUSH = 'AUP_BROADCAST_WAP_PUSH'; sAUP_CALL_PRIVILEGED = 'AUP_CALL_PRIVILEGED'; sAUP_CHANGE_COMPONENT_ENABLED_STATE = 'AUP_CHANGE_COMPONENT_ENABLED_STATE'; sAUP_CLEAR_APP_USER_DATA = 'AUP_CLEAR_APP_USER_DATA'; sAUP_CONTROL_LOCATION_UPDATES = 'AUP_CONTROL_LOCATION_UPDATES'; sAUP_DELETE_CACHE_FILES = 'AUP_DELETE_CACHE_FILES'; sAUP_DELETE_PACKAGES = 'AUP_DELETE_PACKAGES'; sAUP_DEVICE_POWER = 'AUP_DEVICE_POWER'; sAUP_DIAGNOSTIC = 'AUP_DIAGNOSTIC'; sAUP_DUMP = 'AUP_DUMP'; sAUP_FACTORY_TEST = 'AUP_FACTORY_TEST'; sAUP_FORCE_BACK = 'AUP_FORCE_BACK'; sAUP_HARDWARE_TEST = 'AUP_HARDWARE_TEST'; sAUP_INJECT_EVENTS = 'AUP_INJECT_EVENTS'; sAUP_INSTALL_LOCATION_PROVIDER = 'AUP_INSTALL_LOCATION_PROVIDER'; sAUP_INSTALL_PACKAGES = 'AUP_INSTALL_PACKAGES'; sAUP_INTERNAL_SYSTEM_WINDOW = 'AUP_INTERNAL_SYSTEM_WINDOW'; sAUP_MANAGE_APP_TOKENS = 'AUP_MANAGE_APP_TOKENS'; sAUP_MASTER_CLEAR = 'AUP_MASTER_CLEAR'; sAUP_MODIFY_PHONE_STATE = 'AUP_MODIFY_PHONE_STATE'; sAUP_MOUNT_FORMAT_FILESYSTEMS = 'AUP_MOUNT_FORMAT_FILESYSTEMS'; sAUP_MOUNT_UNMOUNT_FILESYSTEMS = 'AUP_MOUNT_UNMOUNT_FILESYSTEMS'; sAUP_READ_FRAME_BUFFER = 'AUP_READ_FRAME_BUFFER'; sAUP_READ_LOGS = 'AUP_READ_LOGS'; sAUP_REBOOT = 'AUP_REBOOT'; sAUP_SET_ACTIVITY_WATCHER = 'AUP_SET_ACTIVITY_WATCHER'; sAUP_SET_ALWAYS_FINISH = 'AUP_SET_ALWAYS_FINISH'; sAUP_SET_ANIMATION_SCALE = 'AUP_SET_ANIMATION_SCALE'; sAUP_SET_DEBUG_APP = 'AUP_SET_DEBUG_APP'; sAUP_SET_ORIENTATION = 'AUP_SET_ORIENTATION'; sAUP_SET_POINTER_SPEED = 'AUP_SET_POINTER_SPEED'; sAUP_SET_PROCESS_LIMIT = 'AUP_SET_PROCESS_LIMIT'; sAUP_SET_TIME = 'AUP_SET_TIME'; sAUP_SIGNAL_PERSISTENT_PROCESSES = 'AUP_SIGNAL_PERSISTENT_PROCESSES'; sAUP_STATUS_BAR = 'AUP_STATUS_BAR'; sAUP_UPDATE_DEVICE_STATS = 'AUP_UPDATE_DEVICE_STATS'; sAUP_WRITE_APN_SETTINGS = 'AUP_WRITE_APN_SETTINGS'; sAUP_WRITE_GSERVICES = 'AUP_WRITE_GSERVICES'; sAUP_WRITE_SECURE_SETTINGS = 'AUP_WRITE_SECURE_SETTINGS'; sAUP_ACCESS_COARSE_LOCATION = 'AUP_ACCESS_COARSE_LOCATION'; sAUP_ACCESS_FINE_LOCATION = 'AUP_ACCESS_FINE_LOCATION'; sAUP_ACCESS_LOCATION_EXTRA_COMMANDS = 'AUP_ACCESS_LOCATION_EXTRA_COMMANDS'; sAUP_ACCESS_MOCK_LOCATION = 'AUP_ACCESS_MOCK_LOCATION'; sAUP_ACCESS_NETWORK_STATE = 'AUP_ACCESS_NETWORK_STATE'; sAUP_ACCESS_WIFI_STATE = 'AUP_ACCESS_WIFI_STATE'; sAUP_ADD_VOICEMAIL = 'AUP_ADD_VOICEMAIL'; sAUP_AUTHENTICATE_ACCOUNTS = 'AUP_AUTHENTICATE_ACCOUNTS'; sAUP_BATTERY_STATS = 'AUP_BATTERY_STATS'; sAUP_BIND_ACCESSIBILITY_SERVICE = 'AUP_BIND_ACCESSIBILITY_SERVICE'; sAUP_BIND_DEVICE_ADMIN = 'AUP_BIND_DEVICE_ADMIN'; sAUP_BIND_INPUT_METHOD = 'AUP_BIND_INPUT_METHOD'; sAUP_BIND_REMOTEVIEWS = 'AUP_BIND_REMOTEVIEWS'; sAUP_BIND_TEXT_SERVICE = 'AUP_BIND_TEXT_SERVICE'; sAUP_BIND_VPN_SERVICE = 'AUP_BIND_VPN_SERVICE'; sAUP_BIND_WALLPAPER = 'AUP_BIND_WALLPAPER'; sAUP_BLUETOOTH = 'AUP_BLUETOOTH'; sAUP_BLUETOOTH_ADMIN = 'AUP_BLUETOOTH_ADMIN'; sAUP_BROADCAST_STICKY = 'AUP_BROADCAST_STICKY'; sAUP_CALL_PHONE = 'AUP_CALL_PHONE'; sAUP_CAMERA = 'AUP_CAMERA'; sAUP_CHANGE_CONFIGURATION = 'AUP_CHANGE_CONFIGURATION'; sAUP_CHANGE_NETWORK_STATE = 'AUP_CHANGE_NETWORK_STATE'; sAUP_CHANGE_WIFI_MULTICAST_STATE = 'AUP_CHANGE_WIFI_MULTICAST_STATE'; sAUP_CHANGE_WIFI_STATE = 'AUP_CHANGE_WIFI_STATE'; sAUP_CLEAR_APP_CACHE = 'AUP_CLEAR_APP_CACHE'; sAUP_DISABLE_KEYGUARD = 'AUP_DISABLE_KEYGUARD'; sAUP_EXPAND_STATUS_BAR = 'AUP_EXPAND_STATUS_BAR'; sAUP_FLASHLIGHT = 'AUP_FLASHLIGHT'; sAUP_GET_ACCOUNTS = 'AUP_GET_ACCOUNTS'; sAUP_GET_PACKAGE_SIZE = 'AUP_GET_PACKAGE_SIZE'; sAUP_GET_TASKS = 'AUP_GET_TASKS'; sAUP_GLOBAL_SEARCH = 'AUP_GLOBAL_SEARCH'; sAUP_INTERNET = 'AUP_INTERNET'; sAUP_KILL_BACKGROUND_PROCESSES = 'AUP_KILL_BACKGROUND_PROCESSES'; sAUP_MANAGE_ACCOUNTS = 'AUP_MANAGE_ACCOUNTS'; sAUP_MODIFY_AUDIO_SETTINGS = 'AUP_MODIFY_AUDIO_SETTINGS'; sAUP_NFC = 'AUP_NFC'; sAUP_PROCESS_OUTGOING_CALLS = 'AUP_PROCESS_OUTGOING_CALLS'; sAUP_READ_CALENDAR = 'AUP_READ_CALENDAR'; sAUP_READ_CALL_LOG = 'AUP_READ_CALL_LOG'; sAUP_READ_CONTACTS = 'AUP_READ_CONTACTS'; sAUP_READ_EXTERNAL_STORAGE = 'AUP_READ_EXTERNAL_STORAGE'; sAUP_READ_HISTORY_BOOKMARKS = 'AUP_READ_HISTORY_BOOKMARKS'; sAUP_READ_PHONE_STATE = 'AUP_READ_PHONE_STATE'; sAUP_READ_PROFILE = 'AUP_READ_PROFILE'; sAUP_READ_SMS = 'AUP_READ_SMS'; sAUP_READ_SOCIAL_STREAM = 'AUP_READ_SOCIAL_STREAM'; sAUP_READ_SYNC_SETTINGS = 'AUP_READ_SYNC_SETTINGS'; sAUP_READ_SYNC_STATS = 'AUP_READ_SYNC_STATS'; sAUP_READ_USER_DICTIONARY = 'AUP_READ_USER_DICTIONARY'; sAUP_RECEIVE_BOOT_COMPLETED = 'AUP_RECEIVE_BOOT_COMPLETED'; sAUP_RECEIVE_MMS = 'AUP_RECEIVE_MMS'; sAUP_RECEIVE_SMS = 'AUP_RECEIVE_SMS'; sAUP_RECEIVE_WAP_PUSH = 'AUP_RECEIVE_WAP_PUSH'; sAUP_RECORD_AUDIO = 'AUP_RECORD_AUDIO'; sAUP_REORDER_TASKS = 'AUP_REORDER_TASKS'; sAUP_SEND_SMS = 'AUP_SEND_SMS'; sAUP_SET_ALARM = 'AUP_SET_ALARM'; sAUP_SET_TIME_ZONE = 'AUP_SET_TIME_ZONE'; sAUP_SET_WALLPAPER = 'AUP_SET_WALLPAPER'; sAUP_SET_WALLPAPER_HINTS = 'AUP_SET_WALLPAPER_HINTS'; sAUP_SUBSCRIBED_FEEDS_READ = 'AUP_SUBSCRIBED_FEEDS_READ'; sAUP_SUBSCRIBED_FEEDS_WRITE = 'AUP_SUBSCRIBED_FEEDS_WRITE'; sAUP_SYSTEM_ALERT_WINDOW = 'AUP_SYSTEM_ALERT_WINDOW'; sAUP_USE_CREDENTIALS = 'AUP_USE_CREDENTIALS'; sAUP_USE_SIP = 'AUP_USE_SIP'; sAUP_COM_VENDING_BILLING = 'AUP_COM_VENDING_BILLING'; sAUP_VIBRATE = 'AUP_VIBRATE'; sAUP_WAKE_LOCK = 'AUP_WAKE_LOCK'; sAUP_WRITE_CALENDAR = 'AUP_WRITE_CALENDAR'; sAUP_WRITE_CALL_LOG = 'AUP_WRITE_CALL_LOG'; sAUP_WRITE_CONTACTS = 'AUP_WRITE_CONTACTS'; sAUP_WRITE_EXTERNAL_STORAGE = 'AUP_WRITE_EXTERNAL_STORAGE'; sAUP_WRITE_HISTORY_BOOKMARKS = 'AUP_WRITE_HISTORY_BOOKMARKS'; sAUP_WRITE_PROFILE = 'AUP_WRITE_PROFILE'; sAUP_WRITE_SETTINGS = 'AUP_WRITE_SETTINGS'; sAUP_WRITE_SMS = 'AUP_WRITE_SMS'; sAUP_WRITE_SOCIAL_STREAM = 'AUP_WRITE_SOCIAL_STREAM'; sAUP_WRITE_SYNC_SETTINGS = 'AUP_WRITE_SYNC_SETTINGS'; sAUP_WRITE_USER_DICTIONARY = 'AUP_WRITE_USER_DICTIONARY'; // EntitlementList sEL_ReadOnlyMovies = 'EL_ReadOnlyMovies'; sEL_ReadWriteMovies = 'EL_ReadWriteMovies'; sEL_ReadOnlyMusic = 'EL_ReadOnlyMusic'; sEL_ReadWriteMusic = 'EL_ReadWriteMusic'; sEL_ReadOnlyPictures = 'EL_ReadOnlyPictures'; sEL_ReadWritePictures = 'EL_ReadWritePictures'; sEL_CaptureCamera = 'EL_CaptureCamera'; sEL_RecordingMicrophone = 'EL_RecordingMicrophone'; sEL_USBDevices = 'EL_USBDevices'; sEL_ReadWriteDownloads = 'EL_ReadWriteDownloads'; sEL_ReadOnlyFileDialog = 'EL_ReadOnlyFileDialog'; sEL_ReadWriteFileDialog = 'EL_ReadWriteFileDialog'; sEL_ChildProcessInheritance = 'EL_ChildProcessInheritance'; sEL_OutgoingNetwork = 'EL_OutgoingNetwork'; sEL_IncomingNetwork = 'EL_IncomingNetwork'; sEL_ReadWriteAddressBook = 'EL_ReadWriteAddressBook'; sEL_ReadWriteCalendars = 'EL_ReadWriteCalendars'; sEL_Location = 'EL_Location'; sEL_Printing = 'EL_Printing'; // iOSArtwork siPhone_AppIcon57 = 'iPhone_AppIcon57'; siPhone_AppIcon114 = 'iPhone_AppIcon114'; siPhone_Launch320 = 'iPhone_Launch320'; siPhone_Launch640 = 'iPhone_Launch640'; siPhone_Launch640x1136 = 'iPhone_Launch640x1136'; siPhone_Spotlight29 = 'iPhone_Spotlight29'; siPhone_Spotlight58 = 'iPhone_Spotlight58'; siOS_AppStore512 = 'iOS_AppStore512'; siOS_AppStore1024 = 'iOS_AppStore1024'; siPad_AppIcon72 = 'iPad_AppIcon72'; siPad_AppIcon144 = 'iPad_AppIcon144'; siPad_Launch768 = 'iPad_Launch768'; siPad_Launch1024 = 'iPad_Launch1024'; siPad_Launch1536 = 'iPad_Launch1536'; siPad_Launch2048 = 'iPad_Launch2048'; siPad_SpotLight50 = 'iPad_SpotLight50'; siPad_SpotLight100 = 'iPad_SpotLight100'; siPad_Setting29 = 'iPad_Setting29'; siPad_Setting58 = 'iPad_Setting58'; // BuildType sBT_BuildType = 'BT_BuildType'; // AndroidArtwork sAndroid_LauncherIcon36 = 'Android_LauncherIcon36'; sAndroid_LauncherIcon48 = 'Android_LauncherIcon48'; sAndroid_LauncherIcon72 = 'Android_LauncherIcon72'; sAndroid_LauncherIcon96 = 'Android_LauncherIcon96'; sAndroid_LauncherIcon144 = 'Android_LauncherIcon144'; // Orientation sOrientationPortrait = 'OrientationPortrait'; sOrientationPortraitUpsideDown = 'OrientationPortraitUpsideDown'; sOrientationLandscapeLeft = 'OrientationLandscapeLeft'; sOrientationLandscapeRight = 'OrientationLandscapeRight'; implementation end.
{----------------------------------------------------------------------------- Unit Name: DUTimeFormat Author: Sebastian Hütter Date: 2006-08-01 Purpose: Convert time to string History: 2006-08-01 initial relase -----------------------------------------------------------------------------} unit DUTimeFormat; interface uses SysUtils; function GetGermanTimeString1(Time:TDateTime):string; function GetGermanTimeString2(Time:TDateTime):string; function FormatTime(Time:integer; const FormatStr:string='mm:ss.cc'):string; implementation const sOClock = 'um %d'; sAfterOClock = '%d nach %d'; sBefHalf = '%d vor halb %d'; sAfterHalf = '%d nach halb %d'; sBefOClock = '%d vor um %d'; sQuarterAfter= 'viertel nach %d'; sQuarterBefore1='viertel vor %d'; sQuarterBefore2='dreiviertel %d'; sHalf = 'halb %d'; function GetGermanTimeString1(Time:TDateTime):string; var h, mm, s, ms:word; begin DecodeTime(Time,h,mm,s,ms); if h > 11 then h:= h-12; case mm of 0 : Result:= Format(sOClock ,[h]); 1..14 : Result:= Format(sAfterOClock,[mm,h]); 15 : Result:= Format(sQuarterAfter,[h]); 16..29 : Result:= Format(sBefHalf,[30-mm,h+1]); 30 : Result:= Format(sHalf,[h+1]); 31..44 : Result:= Format(sAfterHalf,[mm-30,h+1]); 45 : Result:= Format(sQuarterBefore1,[h+1]); 46..59 : Result:= Format(sBefOClock,[60-mm,h+1]); end; end; function GetGermanTimeString2(Time:TDateTime):string; var h, mm, s, ms:word; begin DecodeTime(Time,h,mm,s,ms); if h > 11 then h:= h-12; case mm of 0 : Result:= Format(sOClock ,[h]); 1..14 : Result:= Format(sAfterOClock,[mm,h]); 15 : Result:= Format(sQuarterAfter,[h]); 16..29 : Result:= Format(sBefHalf,[30-mm,h+1]); 30 : Result:= Format(sHalf,[h+1]); 31..44 : Result:= Format(sAfterHalf,[mm-30,h+1]); 45 : Result:= Format(sQuarterBefore2,[h+1]); 46..59 : Result:= Format(sBefOClock,[60-mm,h+1]); end; end; function FormatTime(Time:integer; const FormatStr:string='mm:ss.cc'):string; const DAYS = 1000 * 60 * 60 * 24; HOURS = 1000 * 60 * 60; MINUTES = 1000 * 60; SECONDS = 1000; var day, hour, min, sec, msec:integer; Tic, counter, Chrcount:integer; a, fmt, fmtstr:String; chr, chrLast:char; begin Result:= ''; tic:= time; day:= Tic div DAYS; //Tage dec(Tic, day * DAYS); hour := Tic div HOURS; //Stunden dec(Tic, hour * HOURS); min := Tic div MINUTES; //Minuten dec(Tic, min * MINUTES); sec := Tic div SECONDS; //Sekunden dec(tic, sec * seconds); msec:= tic; fmtStr:=trim(FormatStr)+#32; counter:= 1; Chrcount:= 1; chrLast:= #32; repeat a:= ''; Chr:= fmtstr[counter]; if chr=chrLast then begin inc(chrCount); end else begin fmt:= '%.'+IntTostr(chrcount)+'d'; case chrLast of 'd','D': a:= format(fmt,[day]); 'h','H': a:= format(fmt,[hour]); 'm','M': a:= format(fmt,[min]); 's','S': a:= format(fmt,[sec]); 'c','C': a:= format(fmt,[MSec]); ':': a:= TimeSeparator; else a:= chrLast; end; result:= result+a; chrcount:= 1; end; chrLast:= chr; inc(counter); until counter= Length(FmtStr)+1; delete(result,1,1); end; end.
unit untMainExem01; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.ScrollBox, FMX.Memo; type TConfiguracao = record Host : String; Path : String; Usuario : String; Senha : String; end; TCaneca = class end; TGarrafa = class Private Cor : String; Modelo : String; Tampa : String; Caneca : TCaneca; public constructor Create; destructor Destroy; override; procedure ArmazenarLiquido(Liquido : String); end; TRoda = class Tamanho : Integer; Material : String; end; TMotor = class Potencia : Integer; Combustivel : String; end; TCarro = class Cor : String; Marca : String; Modelo : String; Roda : TRoda; Motor : TMotor; constructor Create; destructor Destroy; override; end; TForm1 = class(TForm) Button1: TButton; Button2: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private procedure ExibeMemo(Configuracao: TConfiguracao); { Private declarations } public { Public declarations } end; TLivro = class public Titulo: String; Autor: String; function Paginacao(Pagina: Integer): String; end; TAutor = class public Livro: untMainExem01.TLivro; end; TGibi = class(TLivro) end; var Form1: TForm1; implementation {$R *.fmx} function TLivro.Paginacao(Pagina: Integer): String; begin end; { TGarrafa } procedure TGarrafa.ArmazenarLiquido(Liquido: String); begin // end; procedure TForm1.Button1Click(Sender: TObject); var MinhaGarrafa : TGarrafa; begin MinhaGarrafa := nil; if Assigned(MinhaGarrafa) then ShowMessage('Estou Instanciado') Else MinhaGarrafa := TGarrafa.Create; Try MinhaGarrafa.Modelo := 'Vidro'; MinhaGarrafa.Cor := 'Vermelha'; Finally FreeAndNil(MinhaGarrafa); End; end; procedure TForm1.Button2Click(Sender: TObject); var Configuracao : TConfiguracao; begin Configuracao.Host := 'teste'; Configuracao.Path := 'novo'; Configuracao.Usuario := 'Roney'; Configuracao.Senha := 'Delphi'; ExibeMemo(Configuracao); end; procedure TForm1.ExibeMemo(Configuracao: TConfiguracao); begin Memo1.Lines.Clear; Memo1.Lines.Add(Configuracao.Host); Memo1.Lines.Add(Configuracao.Path); Memo1.Lines.Add(Configuracao.Usuario); Memo1.Lines.Add(Configuracao.Senha); end; constructor TGarrafa.Create; begin Caneca := TCaneca.Create; end; destructor TGarrafa.Destroy; begin FreeAndNil(Caneca); inherited; end; { TCarro } constructor TCarro.Create; begin Roda := TRoda.Create; Motor := TMotor.Create; end; destructor TCarro.Destroy; begin Motor.Free; Roda.Free; inherited; end; end.
unit BasePath; interface type TBasePath = class protected function GetDataBasePath(ADBType: integer; ADataSrc: integer): WideString; virtual; function GetInstallPath: WideString; virtual; procedure SetDataBasePath(ADBType: integer; ADataSrc: integer; const Value: WideString); virtual; procedure SetInstallPath(const Value: WideString); virtual; public function IsFileExists(AFileUrl: WideString): Boolean; virtual; function IsPathExists(APathUrl: WideString): Boolean; virtual; function GetRootPath: WideString; virtual; function GetFileRelativePath(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; virtual; function GetFilePath(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; virtual; function GetFileName(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; virtual; function GetFileExt(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; virtual; function GetFileUrl(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; overload; virtual; function GetFileUrl(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; overload; virtual; function CheckOutFileUrl(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; virtual; property InstallPath: WideString read GetInstallPath write SetInstallPath; property DataBasePath[ADBType: integer; ADataSrc: integer]: WideString read GetDataBasePath write SetDataBasePath; end; implementation function TBasePath.GetDataBasePath(ADBType: integer; ADataSrc: integer): WideString; begin Result := ''; end; function TBasePath.GetFileUrl(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; begin Result := GetFileUrl(ADBType, ADataSrc, AParamType, AParam, ''); end; function TBasePath.CheckOutFileUrl(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; begin Result := ''; end; function TBasePath.GetRootPath: WideString; begin Result := ''; end; function TBasePath.GetFileRelativePath(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; begin Result := ''; end; function TBasePath.GetFilePath(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; begin Result := ''; end; function TBasePath.GetFileName(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; begin Result := ''; end; function TBasePath.GetFileExt(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; begin Result := ''; end; function TBasePath.GetFileUrl(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; begin Result := ''; end; function TBasePath.GetInstallPath: WideString; begin Result := ''; end; function TBasePath.IsFileExists(AFileUrl: WideString): Boolean; begin Result := false; end; function TBasePath.IsPathExists(APathUrl: WideString): Boolean; begin Result := false; end; procedure TBasePath.SetDataBasePath(ADBType: integer; ADataSrc: integer; const Value: WideString); begin end; procedure TBasePath.SetInstallPath(const Value: WideString); begin end; end.
unit BaseModel; interface uses Attributes, Helpers, RTTI, Dialogs, BasicMsSQLText; type TBaseModel = class private public function Insert():string; function Update():string; function Delete():string; function Select(Entry:Integer):string; procedure Assign(Model:TBaseModel); end; implementation { TBaseModel } procedure TBaseModel.Assign(Model: TBaseModel); var propA,propB : TRttiProperty; begin for propA in TRttiContext.Create.GetType(Self.ClassType).GetProperties do begin propB := TRttiContext.Create.GetType(Model.ClassType).GetProperty(propA.Name); propB.SetValue(propB,propA.GetValue(PropA)); end; end; function TBaseModel.Delete: string; var s : string; begin DeleteSQL .&With<TDelphicanMsSQLText> (procedure (A:TDelphicanMsSQLText) var prop : TRttiProperty; begin A.Table(TRttiContext.Create.GetType(Self.ClassType).GetAttrValue<DCTableAttribute>('TableName').ToString()); for prop in TRttiContext.Create.GetType(Self.ClassType).GetProperties do begin if not prop.GetValue(Self).IsEmpty then begin if (prop.GetAttrValue<DCFieldAttribute>('Mandatory').AsBoolean = True) and (prop.GetValue(Self).ToString = '') then Showmessage('Lütfen '+prop.GetAttrValue<DCFieldAttribute>('FieldName').ToString + ' alanını giriniz'); if (prop.GetAttrValue<DCFieldAttribute>('PK').AsBoolean = True) then A.Where[prop.GetAttrValue<DCFieldAttribute>('FieldName').ToString, IFF(prop.PropertyType.ToString = 'TDateTime',prop.GetValue(Self).ToString, prop.GetValue(Self).AsVariant)]; end; end; s := A.AsString; end); Result := s; end; function TBaseModel.Select(Entry: Integer):string; var s:string; begin SelectSQL .&With<TDelphicanMsSQLText> (procedure (A:TDelphicanMsSQLText) var prop : TRttiProperty; begin A.Table(TRttiContext.Create.GetType(Self.ClassType).GetAttrValue<DCTableAttribute>('TableName').ToString()); for prop in TRttiContext.Create.GetType(Self.ClassType).GetProperties do begin if not prop.GetValue(Self).IsEmpty then begin if (prop.GetAttrValue<DCFieldAttribute>('PK').AsBoolean = True) then A.Where[prop.GetAttrValue<DCFieldAttribute>('FieldName').ToString,Entry] end; end; s := A.AsString; end); Result := s; end; function TBaseModel.Insert: string; var s:string; begin InsertSQL .&With<TDelphicanMsSQLText> (procedure (A:TDelphicanMsSQLText) var prop : TRttiProperty; begin A.Table(TRttiContext.Create.GetType(Self.ClassInfo).GetAttrValue<DCTableAttribute>('TableName').ToString()); for prop in TRttiContext.Create.GetType(Self.ClassInfo).GetProperties do begin if not prop.GetValue(Self).IsEmpty then begin if (prop.GetAttrValue<DCFieldAttribute>('Mandatory').AsBoolean = True) and (prop.GetValue(Self).ToString = '') then Showmessage('Lütfen '+prop.GetAttrValue<DCFieldAttribute>('FieldName').ToString + ' alanını giriniz'); if (prop.GetAttrValue<DCFieldAttribute>('PK').AsBoolean = False) then A.Values[prop.GetAttrValue<DCFieldAttribute>('FieldName').ToString, IFF(prop.PropertyType.ToString = 'TDateTime',prop.GetValue(Self).ToString, prop.GetValue(Self).AsVariant)]; end; end; s := A.AsString; end); Result := s; end; function TBaseModel.Update: string; var s:string; begin UpdateSQL .&With<TDelphicanMsSQLText> (procedure (A:TDelphicanMsSQLText) var prop : TRttiProperty; begin A.Table(TRttiContext.Create.GetType(Self.ClassType).GetAttrValue<DCTableAttribute>('TableName').ToString()); for prop in TRttiContext.Create.GetType(Self.ClassType).GetProperties do begin //*if prop.GetValue(Self).TypeData <> null then begin if (prop.GetAttrValue<DCFieldAttribute>('Mandatory').AsBoolean = True) and (prop.GetValue(Self).ToString = '') then Showmessage('Lütfen '+prop.GetAttrValue<DCFieldAttribute>('FieldName').ToString + ' alanını giriniz'); if (prop.GetAttrValue<DCFieldAttribute>('PK').AsBoolean = True) then A.Where[prop.GetAttrValue<DCFieldAttribute>('FieldName').ToString, IFF(prop.PropertyType.ToString = 'TDateTime',prop.GetValue(Self).ToString, prop.GetValue(Self).AsVariant)] else A.Values[prop.GetAttrValue<DCFieldAttribute>('FieldName').ToString, IFF(prop.PropertyType.ToString = 'TDateTime',prop.GetValue(Self).ToString, prop.GetValue(Self).AsVariant)]; end end; s := A.AsString; end); Result := s; end; end.
unit Unitincluir; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TfrmInserir = class(TForm) edt_nomeInserir: TEdit; edt_enderecoInserir: TEdit; edt_cidadeInserir: TEdit; lbl_cidadeInserir: TLabel; lbl_nomeInserir: TLabel; lbl_enderecoInserir: TLabel; btn_gravar: TButton; btn_sair: TButton; procedure btn_sairClick(Sender: TObject); procedure btn_gravarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmInserir: TfrmInserir; implementation {$R *.dfm} uses UnitAlterar, UnitPrincipal; procedure TfrmInserir.btn_gravarClick(Sender: TObject); { Autor: Rafhael Prates Email: rafhael@rafhaprates.dev Data: 17/01/2021 Função: Essa Procedure tem como o objetivo incluir novas informações ao DB Observações: Ele faz a validação dos campos em Branco, e posteriormente grava, ele não faz nehuma validação para saber se tem campos repetidos, pois o unico campo que não se repete é o 'Código' o 'Código' ele é chave primaria e auto incremental realizado pelo MSSQL } begin if (edt_nomeInserir.Text = '') or (edt_enderecoInserir.Text = '') or (edt_cidadeInserir.Text = '') then Begin Application.MessageBox('Os campos não podem ficar em branco!', 'Atenção!', MB_OK); End else begin with Form1.ADOQuery1 do Begin Close; SQL.Clear; SQL.Add('insert into clientes ( clienteNome, clienteEndereco, clienteCidade, D_E_L_E_T) values (:Cliente, :Endereco, :Cidade, :Delete)' ); Parameters.ParamByName('Cliente').Value := edt_nomeInserir.Text; Parameters.ParamByName('Endereco').Value := edt_enderecoInserir.Text; Parameters.ParamByName('Cidade').Value := edt_cidadeInserir.Text; Parameters.ParamByName('Delete').Value := ''; ExecSQL; Close; SQL.Clear; SQL.Add('select clientesCodigo as ''Código'', clienteNome as ''Nome'' , clienteEndereco as ''Endereço'' , clienteCidade as ''Cidade'' from clientes where D_E_L_E_T = '''''); Open(); Application.MessageBox('Registro inserido com Sucesso com sucesso!', 'Atenção!', MB_OK); edt_nomeInserir.Clear; edt_enderecoInserir.Clear; edt_cidadeInserir.Clear; End; end; end; procedure TfrmInserir.btn_sairClick(Sender: TObject); { Autor: Rafhael Prates Email: rafhael@rafhaprates.dev Data: 17/01/2021 Função: Essa Procedure tem como o objetivo de sair do form Observações: } begin frmInserir.Close; end; end.
unit SmsBO; interface type TSMS = class(TObject) private FDESTINATION: String; FFROM: String; FTEXT: String; procedure SetDESTINATION(const Value: String); procedure SetFROM(const Value: String); procedure SetTEXT(const Value: String); public property FROM: String read FFROM write SetFROM; property DESTINATION: String read FDESTINATION write SetDESTINATION; property TEXT: String read FTEXT write SetTEXT; end; implementation { TSMS } procedure TSMS.SetDESTINATION(const Value: String); begin FDESTINATION := Value; end; procedure TSMS.SetFROM(const Value: String); begin FFROM := Value; end; procedure TSMS.SetTEXT(const Value: String); begin FTEXT := Value; end; end.
{*******************************************************} { } { FluentSQL } { } { Copyright (C) 2013 Allan Gomes } { } {*******************************************************} unit FluentSQLInterfaces; interface uses FluentSQLTypes, SqlExpr; type IMetaDataSQL = interface; IBaseSQL = interface ['{7D201638-38ED-4044-927E-CD6431FB174B}'] function ToSQL: string; function Metadata: IMetaDataSQL; end; IOrderSQL = interface(IBaseSQL) ['{9443813F-2C74-479E-9E67-68F56569B6F8}'] end; IGroupSQL = interface(IBaseSQL) ['{1F7C99F0-0051-4D3B-AF32-23AD718D95A0}'] function Order(Fields: string): IOrderSQL; end; IWhereSQL = interface(IBaseSQL) ['{8A15FEDB-DB18-4247-BD3A-0DE87A60AE2F}'] //Conditions function Eq(Field: string): IWhereSQL; overload; function EqField(FieldLeft, FieldRight: string): IWhereSQL; function BeginIF(Condition: Boolean): IWhereSQL; function ElseIF(Condition: Boolean = True): IWhereSQL; function EndIF: IWhereSQL; function IfThen(Condition: Boolean): IWhereSQL; function Andd(Condition: string): IWhereSQL; function Nott: IWhereSQL; function Inn(Field: string; Values: string): IWhereSQL; overload; function Inn(Field: string; Values: array of Variant): IWhereSQL; overload; function Gt(Field: string): IWhereSQL; overload; function Lt(Field: string): IWhereSQL; overload; function GtOrEq(Field: string): IWhereSQL; overload; function LtOrEq(Field: string): IWhereSQL; overload; function Lk(Field: string): IWhereSQL; overload; function Eq(Field: string; Value: Variant; ValueEmpty: TValueEmpty = veDefault): IWhereSQL; overload; function Gt(Field: string; Value: Variant; ValueEmpty: TValueEmpty = veDefault): IWhereSQL; overload; function Lt(Field: string; Value: Variant; ValueEmpty: TValueEmpty = veDefault): IWhereSQL; overload; function GtOrEq(Field: string; Value: Variant; ValueEmpty: TValueEmpty = veDefault): IWhereSQL; overload; function LtOrEq(Field: string; Value: Variant; ValueEmpty: TValueEmpty = veDefault): IWhereSQL; overload; function LtOrEqField(Field: string; FieldValue: string): IWhereSQL; overload; function Between(Field: string; MinValue, MaxValue: Variant): IWhereSQL; overload; function Between(Value: Variant; MinField, MaxField: String): IWhereSQL; overload; function Lk(Field: string; Value: string; ValueEmpty: TValueEmpty = veDefault): IWhereSQL; overload; function Group(Fields: string): IGroupSQL; function Order(Fields: string): IOrderSQL; end; IJoinSQL = interface(IBaseSQL) ['{8AE812F6-4EC9-4EBC-9AF9-58ACE4E47B9F}'] function Eq(FieldInner: string; FieldFrom: string): IJoinSQL; function EqValue(FieldInner: string; Value: Variant; ValueEmpty: TValueEmpty = veDefault): IJoinSQL; function EqSQL(FieldInner: string; SQL: string): IJoinSQL; function Onn(SQLJoin: string): IJoinSQL; function Inner(Table: string; Alias: string = ''): IJoinSQL; function Left(Table: string; Alias: string = ''): IJoinSQL; overload; function Left(Condition:Boolean; Table: string; Alias: string = ''): IJoinSQL; overload; function Outer(Table: string; Alias: string = ''): IJoinSQL; function Right(Table: string; Alias: string = ''): IJoinSQL; function Where: IWhereSQL; function Group(Fields: string): IGroupSQL; function Order(Fields: string): IOrderSQL; end; IFromSQL = interface(IBaseSQL) ['{008603FF-1186-4242-93A9-8CCBEEB132E5}'] function Inner(Table: string; Alias: string = ''): IJoinSQL; function Left(Table: string; Alias: string = ''): IJoinSQL; overload; function Left(Condition:Boolean; Table: string; Alias: string = ''): IJoinSQL; overload; function Outer(Table: string; Alias: string = ''): IJoinSQL; function Right(Table: string; Alias: string = ''): IJoinSQL; function Where: IWhereSQL; function Group(Fields: string): IGroupSQL; function Order(Fields: string): IOrderSQL; end; ISelectSQL = interface(IBaseSQL) ['{F75FD8C0-4CBE-415E-8294-C92D51ABCFB0}'] function From(Table: string; Alias: string = ''): IFromSQL; end; IDeleteSQL = interface(IBaseSQL) ['{50BDDA33-D228-4D12-B9C1-B8E7928745AB}'] function Where: IWhereSQL; end; IUpdateSQL = interface(IBaseSQL) ['{AF46177D-2EE0-4AD4-A0C2-72DD0DB1F59A}'] function Value(Field: string; Value: Variant; ValueEmpty: TValueEmpty = veConsider): IUpdateSQL; overload; function Param(Field: string): IUpdateSQL; overload; function IfThen(Condition: Boolean): IUpdateSQL; overload; function Where: IWhereSQL; end; IInsertSQL = interface(IBaseSQL) ['{E1F5FBCF-FBB8-44EE-9AF0-B3F64ABF103F}'] function Value(Field: string; Value: Variant; ValueEmpty: TValueEmpty = veConsider): IInsertSQL; overload; function Param(Field: string): IInsertSQL; overload; function IfThen(Condition: Boolean): IInsertSQL; overload; end; IMetaDataSQL = interface function Select(Fields: string): ISelectSQL; function From(Table: string; Alias: string = ''): IFromSQL; function Where: IWhereSQL; function Inner(Table: string; Alias: string = ''): IJoinSQL; function Left(Table: string; Alias: string = ''): IJoinSQL; function Outer(Table: string; Alias: string = ''): IJoinSQL; end; implementation end.
unit Progress_u; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, Buttons, Advanced; type TdlgProgress = class(TForm) btnAbort: TBitBtn; pbArchive: TProgressBar; pbFile: TProgressBar; lbCurrent: TLabel; lbFileIndex: TLabel; lbTotal: TLabel; procedure FormCreate(Sender: TObject); procedure btnAbortClick(Sender: TObject); private { Private declarations } public Abort:Boolean; { Public declarations } end; var dlgProgress: TdlgProgress; implementation {$R *.dfm} procedure TdlgProgress.FormCreate(Sender: TObject); begin Abort:=False; btnAbort.Caption:=ReadFromLanguage('Buttons','btnAbort',btnAbort.Caption); lbFileIndex.Caption:=Format(ReadFromLanguage('Status','FileIndex','File index %d'),[0]); lbTotal.Caption:=Format(ReadFromLanguage('Status','TotalProgress','Total progress %d'),[0])+'%'; lbCurrent.Caption:=Format(ReadFromLanguage('Status','CurrentProgress','Current progress %d'),[0])+'%'; end; procedure TdlgProgress.btnAbortClick(Sender: TObject); begin Abort:=True; end; end.
unit UArrow; interface uses W3System, UEnemy, UGameVariables, UTextures, UScalingInfo; type TArrow = class(TObject) public X, Y, XVol, YVol : float; Active : boolean; constructor Create(newX, newY, newXVol, newYVol : float); procedure Move(); function GetAngle(deg : boolean = false) : float; function MaxX() : float; function MinX() : float; function MaxY() : float; function MinY() : float; function GetRect() : TRectF; procedure CheckCollisions(enemies : array of TEnemy; prevX, prevY : float); private function CheckCollision(enemy : TEnemy; prevX, prevY : float) : boolean; overload; function RectsIntersect(rect1, rect2 : TRectF) : boolean; function SidesOverlap(sides1, sides2 : array [0 .. 1] of float) : boolean; end; implementation constructor TArrow.Create(newX, newY, newXVol, newYVol : float); begin X := newX; Y := newY; XVol := newXVol; YVol := newYVol; Active := true; end; procedure TArrow.Move(); begin // Update x and y coordinates X += XVol; Y += YVol; // Add gravity affect YVol += GRAVITY; // Make the bullet inactive if off screen if (MaxX() < 0) or (MinX() > GAMEWIDTH) or (MinY() > GAMEHEIGHT) then begin Active := false; end; end; function TArrow.GetAngle(deg : boolean = false) : float; var retVal : float; begin // Get the angle from the velocity retVal := ArcTan2(YVol, XVol); // Convert to degrees if ordered to if deg then begin retVal *= 180 / Pi(); end; exit(retVal); end; function TArrow.MaxX() : float; begin // Get the current angle (stops us running the same method over and over again) var currAng := FloatMod(GetAngle(true), 360); // Work out the max x value if (currAng <= 90) or ((currAng > 180) and (currAng <= 270)) then begin exit(X + Cos((currAng mod 90) * Pi() / 180) * ArrowTexture.Handle.width); end else begin exit(X + Sin((currAng mod 90) * Pi() / 180) * ArrowTexture.Handle.width + Cos((currAng mod 90) * Pi() / 180) * ArrowTexture.Handle.height); end; end; function TArrow.MinX() : float; begin // Get the current angle (stops us running the same method over and over again) var currAng := FloatMod(GetAngle(true), 360); // Work out the min x value if (currAng <= 90) or ((currAng > 180) and (currAng <= 270)) then begin exit(X - Sin((currAng mod 90) * Pi() / 180) * ArrowTexture.Handle.height); end else begin exit(X); end; end; function TArrow.MaxY() : float; begin // Get the current angle (stops us running the same method over and over again) var currAng := FloatMod(GetAngle(true), 360); // Work out the max y value if (currAng <= 90) or ((currAng > 180) and (currAng <= 270)) then begin exit(Y + Cos((currAng mod 90) * Pi() / 180) * ArrowTexture.Handle.height + Sin((currAng mod 90) * Pi() / 180) * ArrowTexture.Handle.width); end else begin exit(Y + Sin((currAng mod 90) * Pi() / 180) * ArrowTexture.Handle.height); end; end; function TArrow.MinY() : float; begin // Get the current angle (stops us running the same method over and over again) var currAng := FloatMod(GetAngle(true), 360); // Work out the min y value if (currAng <= 90) or ((currAng > 180) and (currAng <= 270)) then begin exit(Y); end else begin exit(Y - Cos((currAng mod 90) * Pi() / 180) * ArrowTexture.Handle.width); end; end; function TArrow.GetRect() : TRectF; begin exit(TRectF.Create(MinX(), MinY(), MaxX(), MaxY())); end; procedure TArrow.CheckCollisions(enemies : array of TEnemy; prevX, prevY : float); var pathRect : TRectF; // The rectangle of which the arrow has moved begin // Create the path rect pathRect := TRectF.Create(prevX, prevY, MaxX(), MaxY()); // Check over each enemy for var i := 0 to High(enemies) do begin // Only check enemies that are active with health if enemies[i].Health > 0 then begin // If the enemy was in the flight path of the arrow perform more detailed analysis if RectsIntersect(pathRect, enemies[i].GetRect()) then begin if CheckCollision(enemies[i], prevX, prevY) then begin // If the arrow did actually hit the enemy run the hit procedure on it and exit the loop enemies[i].Hit(ArrowDamage, XVol, YVol); // Freeze the enemy if the arrows freeze enemies if ArrowsFreeze then begin enemies[i].Freeze(ArrowFreezeDuration, ArrowFreezeDuration + ARROW_FREEZE_DURATION_RANGE); end; // Tell the arrow it is inactive now Active := false; break; end; end; end; end; end; function TArrow.CheckCollision(enemy : TEnemy; prevX, prevY : float) : boolean; var distance : integer; arrowsInDistance : integer; xChangePerLoop, yChangePerLoop : float; testArrow : TArrow; begin // Get the distance the arrow has travelled distance := Ceil(Sqrt(Sqr(MaxX() - prevX) + Sqr(MaxY - prevY))); // Get how many arrows fit in the distance (add 1 so it does at least 2 arrows) arrowsInDistance := Ceil(distance / ArrowTexture.Handle.width) + 1; // Use the distance as the divider xChangePerLoop := (MaxX() - prevX) / arrowsInDistance; yChangePerLoop := (MaxY() - prevY) / arrowsInDistance; // Create an arrow in the original position with the previous velocity testArrow := TArrow.Create(prevX, prevY, XVol, YVol - GRAVITY); // Move the arrow in small steps to see if it hits the enemy for var i := 0 to arrowsInDistance do begin // Test to see if it has collided if RectsIntersect(testArrow.GetRect(), enemy.GetRect()) then begin exit(true); end else begin // If it did not move the arrow by a small amout testArrow.X += xChangePerLoop; testArrow.Y += yChangePerLoop; end end; // If the arrow did not in fact hit return false exit(false); end; function TArrow.RectsIntersect(rect1, rect2 : TRectF) : boolean; var xSides1, xSides2, ySides1, ySides2 : array [0 .. 1] of float; begin // Get rect1's sides xSides1 := [rect1.Left, rect1.Right]; ySides1 := [rect1.Top, rect1.Bottom]; // Get rect2's sides xSides2 := [rect2.Left, rect2.Right]; ySides2 := [rect2.Top, rect2.Bottom]; // Return if the x sides and the y sides both overlap exit(SidesOverlap(xSides1, xSides2) and SidesOverlap(ySides1, ySides2)); end; function TArrow.SidesOverlap(sides1, sides2 : array [0 .. 1] of float) : boolean; var leftDoesntOverlap, rightDoesntOverlap : boolean; begin // Work out if the left doesn't overlap leftDoesntOverlap := (sides2[0] < sides1[0]) and (sides2[1] < sides1[0]); // Work out if the left doesn't overlap rightDoesntOverlap := (sides2[0] > sides1[1]) and (sides2[1] > sides1[1]); // Return if the sides did overlap exit(not (leftDoesntOverlap or rightDoesntOverlap)); end; end.
(* ***************************************************************************** Copyright (C) 2010-2014 - Bambu Code SA de CV - Ing. Luis Carrasco Este archivo pertenece al proyecto de codigo abierto de Bambu Code: http://bambucode.com/codigoabierto La licencia de este codigo fuente se encuentra en: http://github.com/bambucode/tfacturaelectronica/blob/master/LICENCIA ***************************************************************************** *) unit TestComprobanteFiscalv32; interface uses TestFramework, ComprobanteFiscal, FacturaTipos, TestPrueba; type TestTFEComprobanteFiscalV32 = class(TTestPrueba) strict private fComprobanteFiscalv32: TFEComprobanteFiscal; fFechaEntradaVigenciaCatalogo : TDate; private procedure ConfigurarCertificadoDePrueba(var Certificado: TFECertificado); public procedure SetUp; override; procedure TearDown; override; published procedure CadenaOriginalDeTimbre_DeComprobanteV32_SeaCorrecta; procedure Create_NuevoComprobantev32_GenereEstructuraXMLBasica; procedure SelloDigital_DeMilConceptos_SeaCorrecto; procedure CadenaOriginal_DeComprobanteV32_SeaCorrecta; procedure SelloDigital_DespuesDeVariosSegundos_SeaElMismo; procedure SelloDigital_DeComprobante_SeaCorrecto; procedure GuardarEnArchivo_DeComprobanteTimbrado_GenereXMLIgualAlLeido; procedure setXML_DeComprobanteTimbrado_AsignePropiedadesDelTimbre; procedure setXML_DeComprobanteV32_EstablezcaLasPropiedadesCorrectamente; procedure setXML_DeComprobanteConImpuestosLocales_EstablezcaImpuestosCorrectamente; procedure AgregarImpuestoLocal_Retenido_LoGuardeEnXML; procedure AgregarImpuestoLocal_Trasladado_LoGuardeEnXML; procedure Importe_DeCantidadesConMuchosDecimales_SeaElCorrecto; procedure MetodoDePago_CadenaEfectivo_ConviertaANumero; procedure MetodoDePago_CadenaEfectivo_FechaMenorACambioCatalogoLaDejeIgual; procedure MetodoDePago_EspecificandoNumero_LoDejeIgual; procedure MetodoDePago_Inexistente_GenereExcepcion; procedure MetodoDePago_MenorADiez_AgregueCeroAlPrincipio; procedure MetodoDePago_VariosMetodosNumericos_LosDejeIntactos; procedure MetodoDePago_VariosMetodos_ConviertaAlCatalogoCorrectamente; procedure SelloDigital_ConConfiguracionDecimalIncorrecta_NoFalle; procedure setSerie_Serie_LaGuardeEnXML; end; implementation uses Windows, SysUtils, Classes, ConstantesFixtures, dialogs, DateUtils, XmlDom, XMLIntf, Xml.win.MsXmlDom, XMLDoc, {$IFNDEF VER300} // Si estamos en Delphi 10 Seattle, este archivo ya no es necesario XSLProd, {$ENDIF} FeCFD, FeCFDv22, FeCFDv32, FeCFDv2, FacturacionHashes, {$IFDEF CODESITE} CodeSiteLogging, {$ENDIF} FacturaReglamentacion, UtileriasPruebas, System.Math; procedure TestTFEComprobanteFiscalV32.CadenaOriginalDeTimbre_DeComprobanteV32_SeaCorrecta; var Certificado: TFECertificado; cadenaOriginalDeTimbreEsperada: TStringCadenaOriginal; begin ConfigurarCertificadoDePrueba(Certificado); cadenaOriginalDeTimbreEsperada := leerArchivoEnUTF8(fRutaFixtures + 'comprobante_fiscal/v32/factura_cadena_original_de_timbre.txt'); // Llenamos el comprobante fiscal con datos usados para generar la factura LeerXMLDePruebaEnComprobante(fRutaFixtures + 'comprobante_fiscal/v32/comprobante_timbrado.xml', Certificado, fComprobanteFiscalv32); // Quitamos la cadena original y sellos del XML para re-calcularlos fComprobanteFiscalv32.FacturaGenerada:=False; fComprobanteFiscalv32.fCadenaOriginalCalculada:=''; fComprobanteFiscalv32.fSelloDigitalCalculado:=''; // Comparamos el resultado del metodo de la clase con el del archivo codificado con la funcion CheckEquals(cadenaOriginalDeTimbreEsperada, fComprobanteFiscalv32.CadenaOriginalTimbre, 'La cadena original del timbre no fue generada correctamente'); end; procedure TestTFEComprobanteFiscalV32.SetUp; begin inherited; fComprobanteFiscalv32 := TFEComprobanteFiscal.Create(fev32); // Especificamos la cadena de efectivo fFechaEntradaVigenciaCatalogo := EncodeDate(_ANO_CAMBIO_METODO_PAGO, _MES_CAMBIO_METODO_PAGO, _DIA_CAMBIO_METODO_PAGO); end; procedure TestTFEComprobanteFiscalV32.TearDown; begin FreeAndNil(fComprobanteFiscalv32); end; procedure TestTFEComprobanteFiscalV32.ConfigurarCertificadoDePrueba(var Certificado: TFECertificado); begin Certificado.Ruta := fRutaFixtures + _CERTIFICADO_PRUEBAS_SAT; Certificado.LlavePrivada.Ruta := fRutaFixtures + _LLAVE_PRIVADA_PRUEBAS_SAT; Certificado.LlavePrivada.Clave := _CLAVE_LLAVE_PRIVADA_PRUEBAS_SAT; end; procedure TestTFEComprobanteFiscalV32.CadenaOriginal_DeComprobanteV32_SeaCorrecta; var sCadenaOriginalCorrecta: TStringCadenaOriginal; Certificado: TFECertificado; begin // Leemos la cadena original generada de ejemplo generada previamente con otra aplicacion sCadenaOriginalCorrecta := leerArchivoEnUTF8(fRutaFixtures + 'comprobante_fiscal/v32/factura_cadena_original_utf8.txt'); ConfigurarCertificadoDePrueba(Certificado); // Llenamos el comprobante fiscal con datos usados para generar la factura LeerXMLDePruebaEnComprobante(fRutaFixtures + 'comprobante_fiscal/v32/comprobante_cadena_original.xml', Certificado, fComprobanteFiscalv32); // Quitamos la cadena original y sellos del XML para re-calcularlos fComprobanteFiscalv32.FacturaGenerada:=False; fComprobanteFiscalv32.fCadenaOriginalCalculada:=''; fComprobanteFiscalv32.fSelloDigitalCalculado:=''; // Comparamos el resultado del metodo de la clase con el del archivo codificado con la funcion CheckEquals(sCadenaOriginalCorrecta, fComprobanteFiscalv32.CadenaOriginal, 'La cadena original no fue generada correctamente'); end; procedure TestTFEComprobanteFiscalV32.AgregarImpuestoLocal_Retenido_LoGuardeEnXML; var xmlFixture: WideString; totalImpuestosLocalesRetenidosAnterior: Currency; nuevoImpuestoLocal: TFEImpuestoLocal; begin xmlFixture := leerContenidoDeFixture('comprobante_fiscal/v32/agregarimpuestolocal_retenido.xml'); totalImpuestosLocalesRetenidosAnterior := fComprobanteFiscalv32.TotalImpuestosLocalesRetenidos; nuevoImpuestoLocal.Nombre := 'ISH'; nuevoImpuestoLocal.Tasa := 3; nuevoImpuestoLocal.Importe := 100; nuevoImpuestoLocal.Tipo := tiRetenido; //********************************************** fComprobanteFiscalv32.AgregarImpuestoLocal(nuevoImpuestoLocal); fComprobanteFiscalv32.AsignarImpuestosLocales; {$IFDEF CODESITE} Codesite.Send('XML', fComprobanteFiscalv32.fXmlComprobante.XML); {$ENDIF} CheckEquals(xmlFixture, fComprobanteFiscalv32.fXmlComprobante.XML, 'El contenido XML del comprobante no incluyo los impuestos retenidos locales correctamente'); CheckEquals(totalImpuestosLocalesRetenidosAnterior + nuevoImpuestoLocal.Importe, fComprobanteFiscalv32.TotalImpuestosLocalesRetenidos, 'El total de los impuestos locales retenidos no se le sumo el total del nuevo impuesto local'); end; procedure TestTFEComprobanteFiscalV32.AgregarImpuestoLocal_Trasladado_LoGuardeEnXML; var xmlFixture: WideString; totalImpuestosLocalesTrasladadosAnterior: Currency; nuevoImpuestoLocal: TFEImpuestoLocal; begin xmlFixture := leerContenidoDeFixture('comprobante_fiscal/v32/agregarimpuestolocal_trasladado.xml'); totalImpuestosLocalesTrasladadosAnterior := fComprobanteFiscalv32.TotalImpuestosLocalesTrasladados; nuevoImpuestoLocal.Nombre := 'IVA'; nuevoImpuestoLocal.Tasa := 16; nuevoImpuestoLocal.Importe := 100; nuevoImpuestoLocal.Tipo := tiTrasladado; //********************************************** fComprobanteFiscalv32.AgregarImpuestoLocal(nuevoImpuestoLocal); fComprobanteFiscalv32.AsignarImpuestosLocales; {$IFDEF CODESITE} Codesite.Send('XML', fComprobanteFiscalv32.fXmlComprobante.XML); {$ENDIF} CheckEquals(xmlFixture, fComprobanteFiscalv32.fXmlComprobante.XML, 'El contenido XML del comprobante no incluyo los impuestos trasladados locales correctamente'); CheckEquals(totalImpuestosLocalesTrasladadosAnterior + nuevoImpuestoLocal.Importe, fComprobanteFiscalv32.TotalImpuestosLocalesTrasladados, 'El total de los impuestos locales trasladados no se le sumo el total del nuevo impuesto local'); end; procedure TestTFEComprobanteFiscalV32.SelloDigital_DeMilConceptos_SeaCorrecto; var sSelloDigitalDelXML, sSelloCalculado: String; Certificado: TFECertificado; begin ConfigurarCertificadoDePrueba(Certificado); // Leemos el comprobante del XML (que no tiene conceptos) sSelloDigitalDelXML := LeerXMLDePruebaEnComprobante(fRutaFixtures + 'comprobante_fiscal/v32/comprobante_para_sello_digital_con_mil_conceptos.xml', Certificado, fComprobanteFiscalv32); // Quitamos la cadena original y sellos del XML para re-calcularlos fComprobanteFiscalv32.FacturaGenerada:=False; fComprobanteFiscalv32.fCadenaOriginalCalculada:=''; fComprobanteFiscalv32.fSelloDigitalCalculado:=''; // Mandamos calcular el sello digital del XML el cual ya tiene mil artículos sSelloCalculado:=fComprobanteFiscalv32.SelloDigital; // Verificamos que el sello sea correcto CheckEquals(sSelloDigitalDelXML, sSelloCalculado, 'El sello digital no fue calculado correctamente'); end; procedure TestTFEComprobanteFiscalV32.SelloDigital_DeComprobante_SeaCorrecto; var sSelloDigitalCorrecto: String; Certificado: TFECertificado; begin ConfigurarCertificadoDePrueba(Certificado); // Llenamos el comprobante fiscal con datos usados para generar la factura sSelloDigitalCorrecto := LeerXMLDePruebaEnComprobante (fRutaFixtures + 'comprobante_fiscal/v32/comprobante_para_sello_digital.xml', Certificado, fComprobanteFiscalv32); CheckEquals(sSelloDigitalCorrecto, fComprobanteFiscalv32.SelloDigital, 'El sello digital no fue calculado correctamente'); end; procedure TestTFEComprobanteFiscalV32.SelloDigital_ConConfiguracionDecimalIncorrecta_NoFalle; var sSelloDigitalCorrecto: String; Certificado: TFECertificado; textoFalla: String; separadorDecimalAnterior: Char; xmlFacturaGenerada: WideString; comprobanteNuevo: TFEComprobanteFiscal; {$IFDEF VER300} // A partir de Delphi Seattle es necesario usar esta constante formatSettings : TFormatSettings; {$ENDIF} begin ConfigurarCertificadoDePrueba(Certificado); // Intentamos generar el sello {$IFDEF VER300} with formatSettings do begin {$ENDIF} try // Llenamos el comprobante fiscal con datos usados para generar la factura LeerXMLDePruebaEnComprobante(fRutaFixtures + 'comprobante_fiscal/v32/comprobante_con_impuestos_locales.xml', Certificado, fComprobanteFiscalv32); textoFalla := ''; // Creamos un comprobante para leer el XML generado con el decimal incorrecto comprobanteNuevo := TFEComprobanteFiscal.Create(); try // Leemos el XML generado con la configuracion de "DecimalSeparator" incorrecta // Configuramos el decimal para que sea incorrecto forzosamente separadorDecimalAnterior := DecimalSeparator; DecimalSeparator := ','; xmlFacturaGenerada := fComprobanteFiscalv32.XML; DecimalSeparator := '.'; xmlFacturaGenerada := fComprobanteFiscalv32.XML; // Lo intemos leer en un nuevo comprobante comprobanteNuevo.XML := xmlFacturaGenerada; except on E:Exception do textoFalla := E.Message; end; finally DecimalSeparator := separadorDecimalAnterior; comprobanteNuevo.Free; end; {$IFDEF VER300} end; {$ENDIF} CheckEquals('', textoFalla, 'No debio haber fallado al usar una configuracion decimal incorrecta'); end; procedure TestTFEComprobanteFiscalV32.SelloDigital_DespuesDeVariosSegundos_SeaElMismo; var sSelloDigitalCorrecto: String; Certificado: TFECertificado; begin ConfigurarCertificadoDePrueba(Certificado); // Llenamos el comprobante fiscal con datos usados para generar la factura LeerXMLDePruebaEnComprobante(fRutaFixtures + 'comprobante_fiscal/v32/comprobante_para_sello_digital.xml', Certificado, fComprobanteFiscalv32); // Establecemos la propiedad de DEBUG solamente para que use la fecha/hora actual // para la generacion del comprobante y corroborar este funcionamiento fComprobanteFiscalv32._USAR_HORA_REAL := True; // Obtenemos el sello por primera vez... sSelloDigitalCorrecto:=fComprobanteFiscalv32.SelloDigital; // Nos esperamos 2 segundos (para forzar que la fecha de generacion sea diferente) Sleep(2500); // Verificamos obtener el sello digital de nuevo y que sea el mismo CheckEquals(sSelloDigitalCorrecto, fComprobanteFiscalv32.SelloDigital, 'El sello digital no fue calculado correctamente la segunda ocasion'); end; procedure TestTFEComprobanteFiscalV32.setXML_DeComprobanteTimbrado_AsignePropiedadesDelTimbre; var contenidoXML: WideString; Certificado: TFECertificado; const // ToDo: Leer estas propiedades de forma alternativa desde el XML de prueba para no tenerlas fijas // y pode cambiar el XML de prueba facilmente _TIMBRE_VERSION = '1.0'; _TIMBRE_SELLO_SAT = 'JFZQYjO+ta+R/gH+w7lqunZLzHNeqYWGQvcvJ+Dbvuk6KTCQgvkTP5tIKzqS7v4tXu1o1Rs6u+8p1Uo4jg4LZqvjZUbT14ZYzgE78wlVwz1aJFohHFRB9L4Fh1bcgqgYaJW+62npRq5Lt8EZanKnAdlxAdOHgTgyIzP/6jFtosM='; _TIMBRE_NOCERTIFICADO_SAT = '20001000000100005868'; _TIMBRE_UUID = '64A89088-CFD7-42C1-8ABE-F0BDCFA85EB8'; _TIMBRE_FECHA = '2016-03-14T12:14:20'; begin ConfigurarCertificadoDePrueba(Certificado); // Leemos un CFDI ya timbrado contenidoXML := leerContenidoDeFixture('comprobante_fiscal/v32/comprobante_timbrado.xml'); //*** Asignamos el XML al comprobante ** fComprobanteFiscalv32.XML:=UTF8ToString(contenidoXML); // Verificamos que se haya asignado la propiedad del XML correctamente CheckEquals(_TIMBRE_VERSION, fComprobanteFiscalv32.Timbre.Version, 'La version del timbrado del CFDI fue diferente!'); CheckEquals(_TIMBRE_SELLO_SAT, fComprobanteFiscalv32.Timbre.SelloSAT, 'El sello del SAT del timbre no fue el correcto'); CheckEquals(_TIMBRE_NOCERTIFICADO_SAT, fComprobanteFiscalv32.Timbre.NoCertificadoSAT, 'El No Certificado del SAT no fue el correcto'); CheckEquals(_TIMBRE_UUID, fComprobanteFiscalv32.Timbre.UUID, 'El UUID del timbre no fue el correcto'); CheckEquals(_TIMBRE_FECHA, TFeReglamentacion.ComoFechaHora(fComprobanteFiscalv32.Timbre.FechaTimbrado), 'La fecha del timbrado no fue correcta'); CheckNotEquals('', fComprobanteFiscalv32.Timbre.XML, 'El XML del timbre fue vacio!'); end; procedure TestTFEComprobanteFiscalV32.setXML_DeComprobanteConImpuestosLocales_EstablezcaImpuestosCorrectamente; var contenidoXML: WideString; Certificado: TFECertificado; fComprobanteComparacion: TFEComprobanteFiscal; begin ConfigurarCertificadoDePrueba(Certificado); // Leemos el XML de nuestro Fixture en memoria contenidoXML := leerContenidoDeFixture('comprobante_fiscal/v32/comprobante_con_impuestos_locales.xml'); // Leemos el XML en nuestro comprobante fComprobanteFiscalv32.XML:=UTF8ToString(contenidoXML); // Corroboramos tener los impuestos configurados correctamente CheckTrue(Length(fComprobanteFiscalv32.ImpuestosLocales) > 0, 'Se debio de haber tenido al menos 1 impuesto local'); end; procedure TestTFEComprobanteFiscalV32.setXML_DeComprobanteV32_EstablezcaLasPropiedadesCorrectamente; var sContenidoXML: WideString; Certificado: TFECertificado; fComprobanteComparacion: TFEComprobanteFiscal; procedure CompararDireccionContribuyente(Direccion1, Direccion2 : TFEDireccion; Nombre: String); begin CheckEquals(Direccion1.Calle, Direccion2.Calle, 'La Calle del ' + Nombre + 'no fue el mismo'); CheckEquals(Direccion1.NoExterior , Direccion2.NoExterior, 'El No Ext del ' + Nombre + 'no fue el mismo'); CheckEquals(Direccion1.NoInterior , Direccion2.NoInterior, 'El No Interior del ' + Nombre + 'no fue el mismo'); CheckEquals(Direccion1.CodigoPostal , Direccion2.CodigoPostal, 'El CP de ' + Nombre + 'no fue el mismo'); CheckEquals(Direccion1.Colonia , Direccion2.Colonia, 'La Colonia del ' + Nombre + 'no fue el mismo'); CheckEquals(Direccion1.Municipio , Direccion2.Municipio, 'El Municipio del ' + Nombre + 'no fue el mismo'); CheckEquals(Direccion1.Estado , Direccion2.Estado, 'El Estado del ' + Nombre + 'no fue el mismo'); CheckEquals(Direccion1.Pais , Direccion2.Pais, 'El Pais del ' + Nombre + 'no fue el mismo'); CheckEquals(Direccion1.Localidad , Direccion2.Localidad, 'La Localidad del ' + Nombre + 'no fue el mismo'); CheckEquals(Direccion1.Referencia , Direccion2.Referencia, 'La Referencia del ' + Nombre + 'no fue el mismo'); end; begin ConfigurarCertificadoDePrueba(Certificado); // Leemos el XML de nuestro Fixture en memoria sContenidoXML := leerContenidoDeFixture('comprobante_fiscal/v32/comprobante_timbrado.xml'); Assert(AnsiPos('version="3.2"', sContenidoXML) > 0, 'El XML de pruebas tiene que ser un CFD 3.2 para poder ejecutar la prueba'); fComprobanteFiscalv32.XML:=UTF8ToString(sContenidoXML); // Leemos el comprobante de ejemplo con el metodo alternativo usado en las pruebas fComprobanteComparacion:=TFEComprobanteFiscal.Create(fev32); LeerXMLDePruebaEnComprobante(fRutaFixtures + 'comprobante_fiscal/v32/comprobante_timbrado.xml', Certificado, fComprobanteComparacion); // Comparamos algunas de sus propiedades las cuales deben de ser las mismas CheckEquals(fComprobanteComparacion.Folio, fComprobanteFiscalv32.Folio, 'Los folios no fueron los mismos'); CheckEquals(fComprobanteComparacion.Serie, fComprobanteFiscalv32.Serie, 'La serie no fue la misma'); CheckTrue(CompareDate(fComprobanteComparacion.FechaGeneracion, fComprobanteFiscalv32.FechaGeneracion) = 0, 'Las fechas de generacion no fueron las mismas'); CheckTrue(fComprobanteComparacion.Tipo = fComprobanteFiscalv32.Tipo, 'El tipo no fue el mismo'); CheckTrue(fComprobanteComparacion.FormaDePago = fComprobanteFiscalv32.FormaDePago, 'La forma de pago no fue la misma'); CheckEquals(fComprobanteComparacion.CondicionesDePago, fComprobanteFiscalv32.CondicionesDePago, 'Las condiciones de pago no fueron las mismas'); CheckEquals( RoundTo(fComprobanteComparacion.Subtotal, -2), fComprobanteFiscalv32.Subtotal, 'El subtotal no fue el mismo'); CheckEquals( RoundTo(fComprobanteComparacion.Total, -2), fComprobanteFiscalv32.Total, 'El total no fue el mismo'); CheckEquals(fComprobanteComparacion.Emisor.RFC, fComprobanteFiscalv32.Emisor.RFC, 'El RFC del Emisor no fue el mismo'); CheckEquals(fComprobanteComparacion.Emisor.Nombre, fComprobanteFiscalv32.Emisor.Nombre, 'El Nombre del Emisor no fue el mismo'); CompararDireccionContribuyente(fComprobanteComparacion.Emisor.Direccion, fComprobanteFiscalv32.Emisor.Direccion, 'Emisor'); CheckEquals(fComprobanteComparacion.Receptor.RFC, fComprobanteFiscalv32.Receptor.RFC, 'El RFC del Receptor no fue el mismo'); CheckEquals(fComprobanteComparacion.Receptor.Nombre, fComprobanteFiscalv32.Receptor.Nombre, 'El Nombre del Receptor no fue el mismo'); CompararDireccionContribuyente(fComprobanteComparacion.Receptor.Direccion, fComprobanteFiscalv32.Receptor.Direccion, 'Receptor'); //Check(False,'Comparar lugar de expedicion'); //Check(False,'Comparar metodo de pago'); //Check(False,'Comparar regimenes'); FreeAndNil(fComprobanteComparacion); end; procedure TestTFEComprobanteFiscalV32.GuardarEnArchivo_DeComprobanteTimbrado_GenereXMLIgualAlLeido; var sSelloDigitalCorrecto, archivoComprobanteGuardado, hashComprobanteOriginal, hashComprobanteGuardado: String; archivoComprobantePrueba : string; Certificado: TFECertificado; begin ConfigurarCertificadoDePrueba(Certificado); archivoComprobantePrueba := fRutaFixtures + 'comprobante_fiscal/v32/comprobante_timbrado.xml'; // Leemos el CFDI de pruebas ya timbrado sSelloDigitalCorrecto := LeerXMLDePruebaEnComprobante(archivoComprobantePrueba, Certificado, fComprobanteFiscalV32); // Calculamos el MD5 del comprobante original hashComprobanteOriginal := TFacturacionHashing.CalcularHashArchivo(archivoComprobantePrueba, haMD5); // ****** Guardamos de nuevo el XML ********* Randomize; archivoComprobanteGuardado := fDirTemporal + 'comprobante_prueba_v32_' + IntToStr(Random(9999999999)) + '.xml'; fComprobanteFiscalV32.GuardarEnArchivo(archivoComprobanteGuardado); hashComprobanteGuardado := TFacturacionHashing.CalcularHashArchivo(archivoComprobanteGuardado, haMD5); // Comprobamos el MD5 de ambos archivos para corroborar que tengan exactamente el mismo contenido CheckEquals(hashComprobanteOriginal, hashComprobanteGuardado, 'El contenido del comprobante v3.2 guardado fue difernete al original. Sus hashes MD5 fueron diferentes!'); end; procedure TestTFEComprobanteFiscalV32.Create_NuevoComprobantev32_GenereEstructuraXMLBasica; var sXMLEncabezadoBasico: WideString; NuevoComprobante: TFEComprobanteFiscal; begin // Leemos el contenido de nuestro 'Fixture' para comparar que sean iguales... sXMLEncabezadoBasico := leerContenidoDeFixture('comprobante_fiscal/v32/nuevo.xml'); NuevoComprobante := TFEComprobanteFiscal.Create(fev32); // Checamos que sea igual que nuestro Fixture... CheckEquals(sXMLEncabezadoBasico, fComprobanteFiscalv32.fXmlComprobante.XML, 'El encabezado del XML basico para un comprobante no fue el correcto'); FreeAndNil(NuevoComprobante); end; procedure TestTFEComprobanteFiscalV32.Importe_DeCantidadesConMuchosDecimales_SeaElCorrecto; var xmlDeComprobante: WideString; comprobanteNuevo, comprobanteGuardado: TFEComprobanteFiscal; importeEsperado, importeCalculado : Currency; archivoComprobanteGuardado: String; conceptoConCantidadesConMuchosDecimales : TFEConcepto; Certificado: TFECertificado; begin xmlDeComprobante := leerContenidoDeFixture('comprobante_fiscal/v32/comprobante_timbrado.xml'); comprobanteNuevo := TFEComprobanteFiscal.Create(fev32); comprobanteNuevo.XML:=UTF8ToString(xmlDeComprobante); // Configuramos el certificado de prueba Certificado.Ruta := fRutaFixtures + _RUTA_CERTIFICADO; Certificado.LlavePrivada.Ruta := fRutaFixtures + _LLAVE_PRIVADA_PRUEBAS_SAT; Certificado.LlavePrivada.Clave := _CLAVE_LLAVE_PRIVADA_PRUEBAS_SAT; comprobanteNuevo.Certificado := Certificado; comprobanteNuevo.ValidarCertificadoYLlavePrivada := False; // Eliminamos los conceptos del comprobante leido comprobanteNuevo.BorrarConceptos; try // Agregamos un concepto con cantidad y precio a granel para forzar que se calcule un importe con mas de 6 decimales de exactitud conceptoConCantidadesConMuchosDecimales.Cantidad := 0.12; conceptoConCantidadesConMuchosDecimales.Unidad := 'PZA'; conceptoConCantidadesConMuchosDecimales.Descripcion := 'Articulo de Prueba'; conceptoConCantidadesConMuchosDecimales.ValorUnitario := 129.9876; conceptoConCantidadesConMuchosDecimales.NoIdentificacion := '1'; importeEsperado := conceptoConCantidadesConMuchosDecimales.Cantidad * conceptoConCantidadesConMuchosDecimales.ValorUnitario; comprobanteNuevo.AgregarConcepto(conceptoConCantidadesConMuchosDecimales); // Generamos el archivo Randomize; archivoComprobanteGuardado := fDirTemporal + 'comprobante_cantidad_v32_' + IntToStr(Random(9999999999)) + '.xml'; comprobanteNuevo.GuardarEnArchivo(archivoComprobanteGuardado); // Leemos el XML recien generado para leer la cantidad y precio directo de los conceptos XML xmlDeComprobante := leerContenidoDeArchivo(archivoComprobanteGuardado); comprobanteGuardado := TFEComprobanteFiscal.Create(fev32); comprobanteGuardado.XML:=UTF8ToString(xmlDeComprobante); // Calculamos el importe segun la cantidad y valor unitario leidos del nodo concepto del XML importeCalculado := comprobanteGuardado.Conceptos[0].Cantidad * comprobanteGuardado.Conceptos[0].ValorUnitario; CheckTrue(Length(comprobanteGuardado.Conceptos) > 0, 'El comprobante recien guardado debio haber tenido conceptos'); // Checamos que el importe esperado sea el correcto CheckEquals(importeEsperado, importeCalculado, 'El importe del concepto no fue calculado correctamente. Verificar que CANTIDAD y PRECIO se guardaran correctamente en XML'); finally FreeAndNil(comprobanteNuevo); end; end; procedure TestTFEComprobanteFiscalV32.MetodoDePago_CadenaEfectivo_ConviertaANumero; var xmlGenerado, cadenaEsperada: WideString; comprobanteNuevo: TFEComprobanteFiscal; fechaGeneracionComprobante: TDate; const _CADENA_EFECTIVO = 'EfeCtivO'; _NUMERO_METODO_EFECTIVO = '01'; begin comprobanteNuevo := TFEComprobanteFiscal.Create(fev32); comprobanteNuevo.FechaGeneracion := fFechaEntradaVigenciaCatalogo; comprobanteNuevo.AutoAsignarFechaGeneracion := False; comprobanteNuevo.MetodoDePago := _CADENA_EFECTIVO; comprobanteNuevo.AsignarMetodoDePago; // Checamos que se haya incluido el numero de catalogo de "Efectivo" y no dicha cadena xmlGenerado := comprobanteNuevo.fXmlComprobante.XML; cadenaEsperada := 'metodoDePago="' + _NUMERO_METODO_EFECTIVO + '"'; CheckTrue(AnsiPos(cadenaEsperada, xmlGenerado) > 0, 'No se incluyo el número de método de pago para Efectivo:' + _NUMERO_METODO_EFECTIVO); end; procedure TestTFEComprobanteFiscalV32.MetodoDePago_VariosMetodos_ConviertaAlCatalogoCorrectamente; var xmlGenerado, cadenaEsperada, cadenaObtenida: WideString; comprobanteNuevo: TFEComprobanteFiscal; fechaGeneracionComprobante: TDate; const _CADENA_XML_METODO_PAGO = 'metodoDePago="'; _CADENA_VARIOS = 'Efectivo, Tarjeta de credito, Vales, Otros'; _NUMERO_METODO_PAGO_ESPERADOS = '01,04,08,99'; begin comprobanteNuevo := TFEComprobanteFiscal.Create(fev32); comprobanteNuevo.FechaGeneracion := fFechaEntradaVigenciaCatalogo; comprobanteNuevo.AutoAsignarFechaGeneracion := False; comprobanteNuevo.MetodoDePago := _CADENA_VARIOS; comprobanteNuevo.AsignarMetodoDePago; // Checamos que se haya incluido el numero de catalogo de "Efectivo" y no dicha cadena xmlGenerado := comprobanteNuevo.fXmlComprobante.XML; cadenaEsperada := _CADENA_XML_METODO_PAGO + _NUMERO_METODO_PAGO_ESPERADOS + '"'; cadenaObtenida := _CADENA_XML_METODO_PAGO + Copy(xmlGenerado, AnsiPos(_CADENA_XML_METODO_PAGO, string(xmlGenerado)) + Length(_CADENA_XML_METODO_PAGO), Length(_NUMERO_METODO_PAGO_ESPERADOS) + 1); CheckEquals(cadenaEsperada, cadenaObtenida, 'No se convirtió la cadena de metodos de pago a sus equivalentes del catálogo:' + _NUMERO_METODO_PAGO_ESPERADOS); end; procedure TestTFEComprobanteFiscalV32.MetodoDePago_CadenaEfectivo_FechaMenorACambioCatalogoLaDejeIgual; var comprobanteNuevo: TFEComprobanteFiscal; fechaPreviaAEntradaCatalogo : TDate; cadenaEsperada: String; const _CADENA_INVENTADA_METODO_PAGO = 'Efectivo y Cheque'; begin fechaPreviaAEntradaCatalogo := EncodeDate(_ANO_CAMBIO_METODO_PAGO, _MES_CAMBIO_METODO_PAGO, _DIA_CAMBIO_METODO_PAGO - 1); comprobanteNuevo := TFEComprobanteFiscal.Create(fev32); comprobanteNuevo.FechaGeneracion := fechaPreviaAEntradaCatalogo; comprobanteNuevo.AutoAsignarFechaGeneracion := False; try comprobanteNuevo.MetodoDePago := _CADENA_INVENTADA_METODO_PAGO; comprobanteNuevo.AsignarMetodoDePago; cadenaEsperada := 'metodoDePago="' + _CADENA_INVENTADA_METODO_PAGO + '"'; CheckTrue(AnsiPos(cadenaEsperada, comprobanteNuevo.fXmlComprobante.XML) > 0, 'No se respeto la cadena de metodo de pago previo a catalogo: ' + _CADENA_INVENTADA_METODO_PAGO); finally comprobanteNuevo.Free; end; end; procedure TestTFEComprobanteFiscalV32.MetodoDePago_EspecificandoNumero_LoDejeIgual; var xmlGenerado, cadenaEsperada: WideString; comprobanteNuevo: TFEComprobanteFiscal; numeroInventado: Integer; begin comprobanteNuevo := TFEComprobanteFiscal.Create(fev32); comprobanteNuevo.FechaGeneracion := fFechaEntradaVigenciaCatalogo; comprobanteNuevo.AutoAsignarFechaGeneracion := False; Randomize; // Generamos un numero aleatorio mayor a 10 ya que los menores a 10 // les agregamos un cero al principio y se prueban en otro método numeroInventado := 0; while numeroInventado < 10 do numeroInventado := Random(999); comprobanteNuevo.MetodoDePago := IntToStr(numeroInventado); comprobanteNuevo.AsignarMetodoDePago; xmlGenerado := comprobanteNuevo.fXmlComprobante.XML; cadenaEsperada := 'metodoDePago="' + IntToStr(numeroInventado) + '"'; CheckTrue(AnsiPos(cadenaEsperada, xmlGenerado) > 0, 'No se incluyo el número de método de pago que se asigno manualmente'); end; procedure TestTFEComprobanteFiscalV32.MetodoDePago_Inexistente_GenereExcepcion; var comprobanteNuevo: TFEComprobanteFiscal; const _CADENA_INEXISTENTE = 'METODO INVALIDO'; begin comprobanteNuevo := TFEComprobanteFiscal.Create(fev32); comprobanteNuevo.FechaGeneracion := fFechaEntradaVigenciaCatalogo; comprobanteNuevo.AutoAsignarFechaGeneracion := False; try comprobanteNuevo.MetodoDePago := _CADENA_INEXISTENTE; StartExpectingException(EFECadenaMetodoDePagoNoEnCatalogoException); comprobanteNuevo.AsignarMetodoDePago; StopExpectingException('No se lanzo la excepcion EFECadenaMetodoDePagoNoEnCatalogoException con un metodo de pago inválido'); finally comprobanteNuevo.Free; end; end; procedure TestTFEComprobanteFiscalV32.MetodoDePago_MenorADiez_AgregueCeroAlPrincipio; var xmlGenerado, cadenaEsperada: WideString; comprobanteNuevo: TFEComprobanteFiscal; numeroInventado: Integer; const _NUMERO_METODO_PAGO_SIN_CERO = '3'; _NUMERO_METODO_PAGO_CON_CERO = '03'; // El SAT espera que tengan cero al principio los menores a 10 begin comprobanteNuevo := TFEComprobanteFiscal.Create(fev32); comprobanteNuevo.FechaGeneracion := fFechaEntradaVigenciaCatalogo; comprobanteNuevo.AutoAsignarFechaGeneracion := False; comprobanteNuevo.MetodoDePago := _NUMERO_METODO_PAGO_SIN_CERO; comprobanteNuevo.AsignarMetodoDePago; xmlGenerado := comprobanteNuevo.fXmlComprobante.XML; cadenaEsperada := 'metodoDePago="' + _NUMERO_METODO_PAGO_CON_CERO + '"'; CheckTrue(AnsiPos(cadenaEsperada, xmlGenerado) > 0, 'No se agrego el cero al principio del numero de pago menor a 10'); end; procedure TestTFEComprobanteFiscalV32.MetodoDePago_VariosMetodosNumericos_LosDejeIntactos; var xmlGenerado, cadenaEsperada, cadenaObtenida: WideString; comprobanteNuevo: TFEComprobanteFiscal; fechaGeneracionComprobante: TDate; const _CADENA_XML_METODO_PAGO = 'metodoDePago="'; _NUMERO_METODO_PAGO_INGRESADOS = '01,04, 8, 99'; _NUMERO_METODO_PAGO_ESPERADOS = '01,04,08,99'; begin comprobanteNuevo := TFEComprobanteFiscal.Create(fev32); comprobanteNuevo.FechaGeneracion := fFechaEntradaVigenciaCatalogo; comprobanteNuevo.AutoAsignarFechaGeneracion := False; comprobanteNuevo.MetodoDePago := _NUMERO_METODO_PAGO_INGRESADOS; comprobanteNuevo.AsignarMetodoDePago; // Checamos que se haya incluido el numero de catalogo de "Efectivo" y no dicha cadena xmlGenerado := comprobanteNuevo.fXmlComprobante.XML; cadenaEsperada := _CADENA_XML_METODO_PAGO + _NUMERO_METODO_PAGO_ESPERADOS + '"'; cadenaObtenida := _CADENA_XML_METODO_PAGO + Copy(xmlGenerado, AnsiPos(_CADENA_XML_METODO_PAGO, string(xmlGenerado)) + Length(_CADENA_XML_METODO_PAGO), Length(_NUMERO_METODO_PAGO_ESPERADOS) + 1); CheckEquals(cadenaEsperada, cadenaObtenida, 'No se dejó intacta la cadena de metodos de pago ya numéricos: ' + _NUMERO_METODO_PAGO_ESPERADOS); end; procedure TestTFEComprobanteFiscalV32.setSerie_Serie_LaGuardeEnXML; var sXMLFixture: WideString; Serie: TFESerie; comprobanteNuevo, comprobanteGuardado: TFEComprobanteFiscal; begin comprobanteNuevo := TFEComprobanteFiscal.Create(fev32); // Leemos el contenido de nuestro 'Fixture' para comparar que sean iguales... sXMLFixture := leerContenidoDeFixture('comprobante_fiscal/v32/serie.xml'); Serie := 'ABC'; comprobanteNuevo.Serie := Serie; comprobanteNuevo.AsignarDatosFolios; CheckEquals(sXMLFixture, comprobanteNuevo.fXmlComprobante.XML, 'No se guardo la serie en la estructura del XML'); end; initialization // Registra la prueba de esta unidad en la suite de pruebas RegisterTest(TestTFEComprobanteFiscalV32.Suite); end.
unit UGhosts; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 2005 by Bradford Technologies, Inc.} interface uses Windows, Controls, Classes, SysUtils, Graphics, Types, Messages, ExtCtrls; type TGhost = class(TCustomControl) private FMouseDown: Boolean; FMouseDownPt: TPoint; //FStartX, FStartY: Integer; FColor: TColor; FText: string; FParent: TObject; FScale: Integer; FAngle: Integer; protected procedure SetGhostText(Value: String); procedure SetGhostColor(Value: TColor); procedure SetGhostParent(Value: TObject); virtual; public constructor Create(AOwner: TComponent); override; procedure Paint; override; 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; property GhostText: String read FText write SetGhostText; property GhostColor: TColor read FColor write SetGhostColor; property GhostParent: TObject read FParent write SetGhostParent; property Angle: Integer read FAngle write FAngle; end; { TGhostFreeText } TGhostFreeText = class(TGhost) private FFontName: String; FFontSize: Integer; FFontStyle: TFontStyles; protected procedure SetGhostParent(Value: TObject); override; public procedure Paint; override; end; { TGhostMapPtr1 } TGhostMapPtr1 = class(TGhost) private FScrPt: TPoint; //when rotating, this is screen origin FTipPt: TPoint; //when rotating, this is doc scaled origin FPts: Array of TPoint; FPtTxOut: Array of TPoint; FRotateHdl: Array of TPoint; FDispPts: Array of TPoint; FDispTxPts: Array of TPoint; FDispRHdl: Array of TPoint; FRotating: Boolean; protected procedure SetGhostParent(Value: TObject); override; public constructor Create(AOwner: TComponent); Override; destructor Destroy; override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; function RotationAngle(Shift: TShiftState; X, Y: Integer): Integer; procedure Rotate(Deg: Integer); procedure Paint; override; end; (* TGhostMapPtr2 = class(TGhost) *) implementation uses Math, RzCommon, UGlobals, UUtil1, UPgAnnotation; { TGhost } constructor TGhost.Create(AOwner: TComponent); begin inherited; Parent := TWinControl(AOwner); Hide; //no drawing SetBounds(0,0,72,20); //min initial size FAngle := 0; //not rotated FColor := clYellow; //clRed; FText := 'Untitled'; Canvas.Font.Name := 'ARIAL'; end; procedure TGhost.MouseDown(Button: TMouseButton; Shift: TShiftState; X,Y: Integer); begin inherited; FMouseDownPt := Point(x,y); FMouseDown := True; end; procedure TGhost.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; if FMouseDown then begin SetBounds(Left + X-FMouseDownPt.x, Top + Y-FMouseDownPt.y, Width, Height); FMouseDownPt := Point(X,Y); end; end; procedure TGhost.MouseUp(Button: TMouseButton; Shift: TShiftState; X,Y: Integer); begin inherited; FMouseDown := False; end; procedure TGhost.Paint; begin Canvas.Brush.Color := FColor; Canvas.Brush.Style := bsSolid; Canvas.FrameRect(ClientRect) // Canvas.FillRect(ClientRect); end; procedure TGhost.SetGhostColor(Value: TColor); begin FColor := Value; end; procedure TGhost.SetGhostText(Value: String); begin FText := Value; end; procedure TGhost.SetGhostParent(Value: TObject); begin FParent := Value; //this is the TMarkupItem that is being ghosted end; { TGhostMapPtr1 } constructor TGhostMapPtr1.Create(AOwner: TComponent); begin inherited; FRotating := False; //normalized points SetLength(FPts, 5); //5 pts define this ghost SetLength(FPtTxOut, 2); //2 pts for text out positions SetLength(FRotateHdl, 4); //4 pts that define rotation handle //rotated display points SetLength(FDispPts, 5); SetLength(FDispTxPts, 2); SetLength(FDispRHdl, 4); end; destructor TGhostMapPtr1.Destroy; begin Finalize(FPts); Finalize(FPtTxOut); Finalize(FRotateHdl); Finalize(FDispPts); Finalize(FDispTxPts); Finalize(FDispRHdl); inherited; end; function TGhostMapPtr1.RotationAngle(Shift: TShiftState; X, Y: Integer): Integer; var Pt: TPoint; begin Pt := ScalePt(Point(X,Y), FScale, cNormScale); //undo scale X := Pt.X - FTipPt.X; //rotate about the tip Y := FTipPt.Y - Pt.Y; result := Round(ArcTan2(Y,X) * 180 / pi); if result < 0 then result := 360 + result; //need pos degees for Font rotation end; procedure TGhostMapPtr1.Rotate(Deg: Integer); var i: Integer; WPts: Array[0..4] of TPoint; WRgn: THandle; BRect: TRect; OPt: TPoint; begin //Rotate the Polygon points for i := 0 to 4 do begin FDispPts[i] := FPts[i]; //copy FDispPts[i] := RotatePt(FDispPts[i], Deg); //rorate points end; //Rotate TextOut Points for i := 0 to 1 do begin FDispTxPts[i] := FPtTxOut[i]; FDispTxPts[i] := RotatePt(FDispTxPts[i], Deg); end; //Rotate Rotation handle for i := 0 to 3 do begin FDispRHdl[i] := FRotateHdl[i]; FDispRHdl[i] := RotatePt(FDispRHdl[i], Deg); end; //expand bounding area by one pixel if (FAngle > 90) and (FAngle < 270) then begin WPts[0] := Point(FDispPts[0].x+1, FDispPts[0].Y); //bounding region WPts[1] := Point(FDispPts[1].X+1, FDispPts[1].Y-1); WPts[2] := Point(FDispPts[2].X-1, FDispPts[2].Y-1); WPts[3] := Point(FDispPts[3].X-1, FDispPts[3].Y+1); WPts[4] := Point(FDispPts[4].X+1, FDispPts[4].Y+1); end else //FAngle > 270 and less then 90 begin WPts[0] := Point(FDispPts[0].x-1, FDispPts[0].Y); //bounding region WPts[1] := Point(FDispPts[1].X-1, FDispPts[1].Y+1); WPts[2] := Point(FDispPts[2].X+1, FDispPts[2].Y+1); WPts[3] := Point(FDispPts[3].X+1, FDispPts[3].Y-1); WPts[4] := Point(FDispPts[4].X-1, FDispPts[4].Y-1); end; BRect := PtArrayBoundsRect(FDispPts); //get the pts boundRect OPt := BRect.TopLeft; OffsetRect(BRect, FScrPt.x, FScrPt.y); //place correctly on screen BRect.right := BRect.right + 1; //include bottom lines BRect.Bottom := BRect.Bottom + 1; for i := 0 to 4 do //offset off origin FDispPts[i] := Point(FDispPts[i].x-OPt.x, FDispPts[i].y-Opt.y); for i := 0 to 1 do FDispTxPts[i] := Point(FDispTxPts[i].x-OPt.x, FDispTxPts[i].y-Opt.y); for i := 0 to 3 do FDispRHdl[i] := Point(FDispRHdl[i].x-OPt.x, FDispRHdl[i].y-Opt.y); for i := 0 to 4 do //normalize WPts[i] := Point(WPts[i].x-OPt.x, WPts[i].y-Opt.y); BoundsRect := BRect; //set it WRgn := CreatePolygonRgn(WPts, Length(WPts), ALTERNATE); SetWindowRgn(Handle, WRgn, True); FAngle := Deg; Visible := True; Paint; end; procedure TGhostMapPtr1.MouseMove(Shift: TShiftState; X, Y: Integer); var NewAngle: Integer; begin if not FRotating then inherited //do normal translation else begin NewAngle := RotationAngle(Shift, X, Y); if NewAngle <> FAngle then Rotate(NewAngle); //do rotation end; end; procedure TGhostMapPtr1.SetGhostParent(Value: TObject); var N: Integer; begin inherited; if assigned(Value) then begin FScale := TMapPtr1(FParent).docScale; FText := TMapPtr1(FParent).Text; FColor := TMapPtr1(FParent).FColor; FAngle := TMapPtr1(FParent).FAngle; FRotating := TMapPtr1(FParent).FRotating; FTipPt := TMapPtr1(FParent).FTipPt; FScrPt := TMapPtr1(FParent).FPts[0]; FScrPt := TMapPtr1(FParent).ItemPt2Sceen(FScrPt); //screen rotation pt //work with points normalized to rotation point for n := 0 to 4 do begin FPts[n] := TMapPtr1(FParent).FPts[n]; //assign non-rotated FPts[n] := OffsetPt(FPts[n], -FTipPt.x, -FTipPt.y); //normalize FPts[n] := ScalePt(FPts[n], cNormScale, FScale); //visual scaling FDispPts[n] := FPts[n]; //copy to retain original pts end; for n := 0 to 1 do begin FPtTxOut[n] := TMapPtr1(FParent).FTxOutPt[n]; FPtTxOut[n] := OffsetPt(FPtTxOut[n], -FTipPt.x, -FTipPt.y); //normalize FPtTxOut[n] := ScalePt(FPtTxOut[n], cNormScale, FScale); FDispTxPts[n] := FPtTxOut[n]; end; for n := 0 to 3 do begin FRotateHdl[n] := TMapPtr1(FParent).FRotateHdl[n]; FRotateHdl[n] := OffsetPt(FRotateHdl[n], -FTipPt.x, -FTipPt.y); //normalize FRotateHdl[n] := ScalePt(FRotateHdl[n], cNormScale, FScale); FDispRHdl[n] := FRotateHdl[n]; end; Rotate(FAngle); end; end; procedure TGhostMapPtr1.Paint; var FontHandle: HFont; idx: Integer; begin with Canvas do begin Pen.Color := clBlack; Pen.Width := 1; pen.Style := psSolid; Brush.Color := FColor; Brush.Style := bsSolid; Polygon(FDispPts); //draw the arrow outline & fill if FRotating then Brush.Color := clRed else Brush.Color := clBlack; Polygon(FDispRHdl); //draw rotation handle in red, outline in black //now draw the rotated text idx := 0; FontHandle := 0; Brush.Style := bsClear; Font.Height := -MulDiv(12, FScale, cNormScale); Font.Style := [fsBold]; if (FAngle >= 0) and (FAngle <= 90) then begin FontHandle := RotateFont(Font, FAngle); idx := 0; end else if (FAngle > 90) and (FAngle <= 180) then begin FontHandle := RotateFont(Font, FAngle + 180); idx := 1; end else if (FAngle > 180) and (FAngle <= 270) then begin FontHandle := RotateFont(Font, FAngle - 180); idx := 1; end else if (FAngle > 270) and (FAngle <= 360) then begin FontHandle := RotateFont(Font, FAngle); idx := 0; end; if FontHandle <> 0 then Canvas.Font.Handle := FontHandle; TextOut(FDispTxPts[idx].x, FDispTxPts[idx].y, FText); end; end; { TGhostFreeText } procedure TGhostFreeText.Paint; var sbox : TRect; strlen : tagSIZE; begin with Canvas do begin Brush.Color := clWhite; sbox := ClientRect; strlen := Canvas.TextExtent(FText); FillRect(ClientRect); sbox.Right := sbox.Left + strlen.cx; Font.Name := FFontName; Font.Height := -MulDiv(FFontSize, FScale, cNormScale); Font.Style := FFontStyle; Font.Color := clRed; TextRect(sBox, ClientRect.Left, ClientRect.Top, FText); end; end; procedure TGhostFreeText.SetGhostParent(Value: TObject); var BRect: TRect; ScrPt: TPoint; begin inherited; if assigned(Value) then begin FScale := TFreeText(FParent).docScale; FText := TFreeText(FParent).Text; FColor := TFreeText(FParent).FColor; FFontName := TFreeText(FParent).FFontName; FFontSize := TFreeText(FParent).FFontSize; FFontStyle := TFreeText(FParent).FFontStyle; BRect := TFreeText(FParent).Bounds; ScrPt := TFreeText(FParent).ItemPt2Sceen(BRect.TopLeft); OffsetRect(BRect, -BRect.Left, -BRect.Top); //normalize BRect.Left := BRect.Left +1; BRect := ScaleRect(BRect, cNormScale, FScale); //scale OffsetRect(BRect, ScrPt.x, ScrPt.y); //place correctly on screen BoundsRect := BRect; //set it end; Visible := True; Paint; end; end.
program SwapValues(Input, Output); uses wincrt; var First, Second : real; procedure Title; begin writeln(' Swap Values'); writeln('This program takes in two'); writeln('numbers and swaps them'); readln; end; procedure GetInput(var First, Second : real); begin clrscr; writeln('What two numbers do you wish to swap?'); readln(First, Second); end; procedure Swap(var First, Second : real); var Temp : real; begin Temp := First; First := Second; Second := Temp; end; procedure Display(First, Second : real); begin clrscr; writeln('First: ', First:5:2); writeln('Second: ', Second:5:2); readln; end; begin Title; GetInput(First, Second); Swap(First, Second); Display(First, Second); donewincrt; end. {SwapValues} {Kaleb Haslam}
unit userver; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, DB, ADODB,IniFiles, StrUtils; type TServerInfo = Record sv101_platform_id : DWORD; sv101_name : LPWSTR; sv101_version_major : DWORD; sv101_version_minor : DWORD; sv101_type : DWORD; sv101_comment : LPWSTR; End; WKSTA_INFO_100 = Record wki100_platform_id : DWORD; wki100_computername : LPWSTR; wki100_langroup : LPWSTR; wki100_ver_major : DWORD; wki100_ver_minor : DWORD; End; LPWKSTA_INFO_100 = ^WKSTA_INFO_100; _USER_INFO_0 = record usri0_name: LPWSTR; end; PUserInfo0 = ^TUserInfo0; TUserInfo0 = _USER_INFO_0; TServerArr = array[0..100] of TServerInfo;//(MaxInt - 4) div SizeOf(TServerInfo)] of TServerInfo;// function GetNetParam(AParam : integer) : string; function GetComputerName : string; function GetDomainName : string; function GetDomainControllerName(const ADomainName : string) : string; procedure GetUsers(Users : TStringList; AServer : string); function GetServer(ATipe : LongWord):String; function NetApiBufferAllocate(ByteCount: DWORD; var Buffer: Pointer): DWORD; stdcall; external 'netapi32.dll'; function NetGetDCName(servername: LPCWSTR; domainname: LPCWSTR; bufptr: Pointer): DWORD; stdcall; external 'netapi32.dll'; function NetApiBufferFree (Buffer: Pointer): DWORD ; stdcall; external 'netapi32.dll'; Function NetWkstaGetInfo (ServerName : LPWSTR; Level : DWORD; BufPtr : Pointer) : Longint; Stdcall; external 'netapi32.dll' Name 'NetWkstaGetInfo'; function NetUserEnum(servername: LPCWSTR; level: DWORD; filter: DWORD; var bufptr: Pointer; prefmaxlen: DWORD; var entriesread: DWORD; var totalentries: DWORD; resume_handle: PDWORD): DWORD; stdcall; external 'netapi32.dll'; function NetServerEnum(servername : LPWSTR; level : DWORD; var bufptr : Pointer; prefmaxlen : DWORD; var entriesread : DWORD; var totalentries: DWORD; servertype : DWORD; domain : LPWSTR; resume_handle: PDWORD): DWORD; stdcall; external 'netapi32.dll'; Const NERR_Success = 0; ArrTipeServer: array [0..23] of Longword = ($1,$2,$4,$8,$10,$20,$40,$80, $100,$40000000,$200,$400,$800,$4000, $1000,$2000,$8000,$10000,$20000,$40000,$80000, $80000000,$400000,$FFFFFFFF); var cch : integer; strSQL:String; ShortMonthNamesID: array[1..12] of String=('Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agust','Sep','Okt','Nov','Des'); LongMonthNamesID: array[1..12] of string=('Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'); LongDayNamesID: array[1..7] of string=('Senin','Selasa','Rabu','Kamis','Jum''at','Sabtu','Minggu'); ShortDayNamesID: array[1..7] of string=('Sen','Sel','Rabu','Kam','Jum','Sab','Mng'); implementation function GetNetParam(AParam : Integer) : string; Var PBuf : LPWKSTA_INFO_100; Res : LongInt; begin result := ''; // Res := NetWkstaGetInfo (Nil, 100, @PBuf); If Res = NERR_Success Then begin case AParam of 0: Result := string(PBuf^.wki100_computername); 1: Result := string(PBuf^.wki100_langroup); end; end; end; function GetComputerName : string; begin Result := GetNetParam(0); end; function GetDomainName : string; begin Result := GetNetParam(1); end; function GetDomainControllerName(const ADomainName : string) : string; var wDomainName : WideString; Controller : PWideChar; begin wDomainName := AdomainName; NetGetDCName (Nil, PWideChar (wDomainName), @Controller); Result := WideCharToString(controller); // NetAPIBufferFree (Controller); end; procedure GetUsers(Users : TStringList; AServer : string); type TUserInfoArr = array[0..(MaxInt - 4) div SizeOf(TUserInfo0)] of TUserInfo0; var UserInfo: Pointer; EntriesRead, TotalEntries, ResumeHandle: DWORD; Res: DWORD; i: Integer; FServer : WideString; begin FServer := AServer; ResumeHandle := 0; repeat Res := NetUserEnum(PWideChar(FServer), 0, 0, UserInfo, 64 * SizeOf(TUserInfo0), EntriesRead, TotalEntries, @ResumeHandle); if (Res = NERR_SUCCESS) or (Res = ERROR_MORE_DATA) then begin for i := 0 to EntriesRead - 1 do Users.Add(TUserInfoArr(UserInfo^)[i].usri0_name); // NetApiBufferFree(UserInfo); end; until Res <> ERROR_MORE_DATA; end; function GetServer(ATipe : LongWord):String; var UserInfo: Pointer; EntriesRead, TotalEntries, ResumeHandle: DWORD; Res: DWORD; i: Integer; FServer : WideString; Servers:TStringList; begin Servers:=TStringList.Create; FServer := GetDomainName; ResumeHandle := 0; repeat try // Res := NetServerEnum('',101 ,UserInfo,64 * SizeOf(TServerInfo), // EntriesRead, TotalEntries, ATipe, PWideChar(FServer), @ResumeHandle); except // NetApiBufferFree(UserInfo); // exit; end; if (Res = NERR_SuCCESS) or (Res = ERROR_MORE_DATA) then begin for i := 0 to EntriesRead - 1 do Servers.Add(TServerArr(UserInfo^)[i].sv101_name); // NetApiBufferFree(UserInfo); end; until Res <> ERROR_MORE_DATA; Result:=Servers.text; Servers.Free; UserInfo := nil; end; end.
unit Alcinoe.FMX.Firebase.Core; interface implementation uses system.Messaging, system.Classes, system.SysUtils, Fmx.Platform, {$IF defined(ios)} Alcinoe.iOSApi.FirebaseCore, {$ENDIF} Alcinoe.Common, Alcinoe.StringUtils; {*******************************************************************************************} procedure ALFmxFirebaseCoreApplicationEventHandler(const Sender: TObject; const M: TMessage); begin {$REGION ' IOS'} {$IF defined(ios)} if (M is TApplicationEventMessage) then begin if ((M as TApplicationEventMessage).Value.Event = TApplicationEvent.FinishedLaunching) then begin // Initialize Firebase in your app // Configure a FIRApp shared instance, typically in your application's // application:didFinishLaunchingWithOptions: method: // This is the normal flow: // 1) Unit initialization // 2) didFinishLaunchingWithOptions // 3) main form create // 4) BecameActive event received {$IF defined(debug)} allog( 'ALFmxFirebaseCoreApplicationEventHandler', 'FinishedLaunching', TalLogType.VERBOSE); {$ENDIF} TFIRApp.OCClass.configure; end end; {$ENDIF} {$ENDREGION} end; initialization TMessageManager.DefaultManager.SubscribeToMessage(TApplicationEventMessage, ALFmxFirebaseCoreApplicationEventHandler); finalization TMessageManager.DefaultManager.Unsubscribe(TApplicationEventMessage, ALFmxFirebaseCoreApplicationEventHandler); end.
unit IcmsSn101; interface uses TributacaoItemNotaFiscal, TipoOrigemMercadoria; type TIcmsSn101 = class private FOrigemMercadoria :TTipoOrigemMercadoria; FAliquotaCreditoSN :Real; FValorCreditoSN :Real; FBaseCalculo: Real; FCodigoItem: integer; procedure SetAliquotaCreditoSN(const Value: Real); procedure SetValorCreditoSN(const Value: Real); private function GetValorCreditoSN :Real; function GetCSOSN :String; public constructor Create(OrigemMercadoria :TTipoOrigemMercadoria; AliquotaCreditoSN :Real);overload; constructor Create(OrigemMercadoria :TTipoOrigemMercadoria; AliquotaCreditoSN, pBaseCalculo :Real; pCodigoItem :integer);overload; public property CodigoItem :integer read FCodigoItem write FCodigoItem; property OrigemMercadoria :TTipoOrigemMercadoria read FOrigemMercadoria; property AliquotaCreditoSN :Real read FAliquotaCreditoSN write SetAliquotaCreditoSN; // Esse valor aqui não é destacado no total da NF property ValorCreditoSN :Real read GetValorCreditoSN write SetValorCreditoSN; property CSOSN :String read GetCSOSN; property BaseCalculo :Real read FBaseCalculo write FBaseCalculo; end; implementation uses ExcecaoParametroInvalido, SysUtils; { TIcmsSn101 } constructor TIcmsSn101.Create(OrigemMercadoria: TTipoOrigemMercadoria; AliquotaCreditoSN, pBaseCalculo :Real; pCodigoItem :integer); begin self.Create(OrigemMercadoria, AliquotaCreditoSN); self.FAliquotaCreditoSN := AliquotaCreditoSN; self.FCodigoItem := pCodigoItem; self.FBaseCalculo := pBaseCalculo; end; constructor TIcmsSn101.Create(OrigemMercadoria: TTipoOrigemMercadoria; AliquotaCreditoSN: Real); begin { if (AliquotaCreditoSN <= 0) then raise TExcecaoParametroInvalido.Create(self.ClassName, 'Create(OrigemMercadoria: TTipoOrigemMercadoria; AliquotaCreditoSN: Real)', 'AliquotaCreditoSN'); fabricio} self.FOrigemMercadoria := OrigemMercadoria; end; function TIcmsSn101.GetCSOSN: String; begin result := '101'; end; function TIcmsSn101.GetValorCreditoSN: Real; begin result := ((self.BaseCalculo * self.AliquotaCreditoSN) / 100); end; procedure TIcmsSn101.SetAliquotaCreditoSN(const Value: Real); begin FAliquotaCreditoSN := Value; end; procedure TIcmsSn101.SetValorCreditoSN(const Value: Real); begin FValorCreditoSN := Value; end; end.
program ejercicio_4; const precioMBS=1.35; precioMinutos=3.40; type cliente=record codigo:integer; cantidad_lineas:integer; end; linea=record numero:longint; cant_minutos:integer; cant_MBs:integer; end; procedure leerLinea(var regLinea:linea); begin write('Ingrese el numero de la linea: '); readln(regLinea.numero); write('Ingrese la cantidad de minutos consumidos en la linea: '); readln(regLinea.cant_minutos); write('Ingrese la cantidad de MBs consumidos en la linea: '); readln(regLinea.cant_MBs); end; procedure leerCliente(var regCliente:cliente); begin write('Ingrese el codigo de cliente: '); readln(regCliente.codigo); write('Ingrese la cantidad de lineas que tiene el cliente: '); readln(regCliente.cantidad_lineas); end; procedure calcular_cliente(var regCliente:cliente;var regLinea:linea; var totalMinutos:double;var totalMBS:double); var i:integer; begin leerCliente(regCliente); for i:=1 to regCliente.cantidad_lineas do begin leerLinea(regLinea); totalMBS:=totalMBS+(precioMBS*regLinea.cant_MBs); totalMinutos:=totalMinutos+(precioMinutos*regLinea.cant_minutos); end; end; var regCliente:cliente; regLinea:linea; totalMinutos:double; totalMBS:double; i:integer; begin for i:=1 to 3 do begin totalMinutos:=0; totalMBS:=0; calcular_cliente(regCliente,regLinea,totalMinutos,totalMBS); writeln('El precio total de los MBS consumidos del cliente ',regCliente.codigo,' es: ',totalMBS:1:2); writeln('El precio total de los minutos consumidos del cliente ',regCliente.codigo,' es: ',totalMinutos:1:2); writeln; writeln('FIN DEL PROGRAMA'); readln; end; end.
unit BlockRotate; interface uses Project; procedure RotateSelected( Project : TveProject ); implementation uses Outlines, Rotations, Types; procedure RotateSelected( Project : TveProject ); var Bounds : TRect; i : integer; Item : TveBoardItem; begin // find enclosing rectange which contains all selected component //Project.GetSelectedItemsBoundary( Left, Top, Right, Bottom ); // Don't use GetSelectedItemsPaintBoundary() because the paint rectangle // for component text can extend way out the side, causing the rotated // block to jump sideways on screen rather than rotating in place. Project.GetSelectedItemsBoundary( Bounds ); // convert bounding rectangle to "cells inside border" dec( Bounds.Right ); dec( Bounds.Bottom ); // rotate and reposition each selected item for i := 0 to Project.BoardItemCount - 1 do begin Item := Project.BoardItems[i]; if Item.Selected then begin // adjust coords so new position relative to right becomes position // relative to left (ie move to Left + (Right - X) Item.X := Bounds.Left + Bounds.Right - Item.X; Item.Y := Bounds.Top + Bounds.Bottom - Item.Y; // rotate item through 180 degrees Item.EndDeltaX := -Item.EndDeltaX; Item.EndDeltaY := -Item.EndDeltaY; end; end; end; end.
// ****************************************************************** // // Program Name : AT Library // Platform(s) : Android, iOS, Linux, MacOS, Windows // Framework : Console, FMX, VCL // // Filename : AT.Rtti.Automate.pas // Date Created : 22-Nov-2020 // Author : Matthew Vesperman // // Description: // // Defines managed record types to manage RTTI objects. // // Revision History: // // v1.00 : Initial version // // ****************************************************************** // // COPYRIGHT © 2020 - PRESENT Angelic Technology // ALL RIGHTS RESERVED WORLDWIDE // // ****************************************************************** /// <summary> /// Defines managed record types to manage RTTI objects. /// </summary> unit AT.Rtti.Automate; interface uses System.Classes, System.SysUtils, System.Rtti; type TATRttiAutoFreeCtx = record private FContext: TRttiContext; public constructor Create(var AContext: TRttiContext); class operator Initialize(out ADest: TATRttiAutoFreeCtx); class operator Finalize(var ADest: TATRttiAutoFreeCtx); class operator Assign(var ADest: TATRttiAutoFreeCtx; const [ref] ASrc: TATRttiAutoFreeCtx); end; implementation constructor TATRttiAutoFreeCtx.Create(var AContext: TRttiContext); begin FContext := AContext; end; class operator TATRttiAutoFreeCtx.Initialize(out ADest: TATRttiAutoFreeCtx); begin FillChar(ADest.FContext, SizeOf(TRttiContext), 0);// := nil; end; class operator TATRttiAutoFreeCtx.Finalize(var ADest: TATRttiAutoFreeCtx); begin ADest.FContext.Free; end; class operator TATRttiAutoFreeCtx.Assign(var ADest: TATRttiAutoFreeCtx; const [ref] ASrc: TATRttiAutoFreeCtx); begin raise EInvalidOperation.Create( 'TATRttiAutoFreeCtx records cannot be copied') end; end.
unit Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.Types, System.Math, System.Sensors, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.pngimage, Vcl.ExtCtrls; type TPointArray = array of TPoint; TForm1 = class(TForm) Image1: TImage; PaintBox1: TPaintBox; Timer1: TTimer; procedure PaintBox1Paint(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FAngle: Double; FSensor : TCustomOrientationSensor; procedure DrawCompass; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var SensorManager: TSensorManager; Sensors: TSensorArray; Sensor : TCustomSensor; begin SensorManager := TSensorManager.Current; SensorManager.Activate; Sensors := SensorManager.GetSensorsByCategory(TSensorCategory.Orientation); for Sensor in Sensors do if TCustomOrientationSensor(Sensor).SensorType = TOrientationSensorType.Compass3D then begin FSensor := TCustomOrientationSensor(Sensor); Timer1.Enabled := true; break; end; end; procedure TForm1.FormDestroy(Sender: TObject); begin TSensorManager.Current.Deactivate; end; procedure TForm1.PaintBox1Paint(Sender: TObject); begin DrawCompass; end; procedure TForm1.Timer1Timer(Sender: TObject); begin if Assigned(FSensor) then begin FAngle := FSensor.CompMagHeading / 180 * Pi; PaintBox1.Invalidate; end; end; const Offset: Integer = 7; function Rotate(const angle: Double; const aValues: TPointArray; const centerX, centerY: Double): TPointArray; var i: Integer; r, p: Double; begin if Length(aValues) > 0 then begin SetLength(result, Length(aValues)); for i := 0 to Length(aValues) - 1 do begin r := sqrt(sqr(aValues[i].X - centerX) + sqr(aValues[i].Y - centerY)); p := angle + arcTan2(aValues[i].Y - centerY, aValues[i].X - centerX); result[i].X := Round(centerX + r * cos(p)); result[i].Y := Round(centerY + r * sin(p)); end; end; end; procedure TForm1.DrawCompass; var Points: TPointArray; AWidth: Integer; AHeight: Integer; begin AWidth := ClientWidth; AHeight := ClientHeight; SetLength(Points, 3); Points[0] := Point(AWidth div 2 + Offset, 50); Points[1] := Point(AWidth div 2 - 35 + Offset, AHeight div 2); Points[2] := Point(AWidth div 2 + 35 + Offset, AHeight div 2); PaintBox1.Canvas.Brush.Color := clRed; PaintBox1.Canvas.Polygon(Rotate(FAngle,Points,AWidth div 2 + Offset, AHeight div 2)); Points[0] := Point(AWidth div 2 + Offset, AHeight - 50); Points[1] := Point(AWidth div 2 - 35 + Offset, AHeight div 2); Points[2] := Point(AWidth div 2 + 35 + Offset, AHeight div 2); PaintBox1.Canvas.Brush.Color := clNavy; PaintBox1.Canvas.Polygon(Rotate(FAngle,Points,AWidth div 2 + Offset, AHeight div 2)); end; end.
unit Frm_Mensaje; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIForm, uniMemo, uniToolBar, uniGUIBaseClasses, Funciones, uniHTMLMemo, uniPanel; type TFrmMensaje = class(TUniForm) UniToolBar1: TUniToolBar; UBSalir: TUniToolButton; UniMemoMensaje: TUniMemo; UniHTMLMemo1: TUniHTMLMemo; procedure UBSalirClick(Sender: TObject); procedure UniFormCreate(Sender: TObject); procedure UniFormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure UniFormClose(Sender: TObject; var Action: TCloseAction); procedure UniFormShow(Sender: TObject); private { Private declarations } FCaption:string; public { Public declarations } constructor Crear(Mensaje:String;qCaption:String='Mensaje';HTML:Boolean=False); end; implementation uses uniGUIApplication; {$R *.dfm} constructor TFrmMensaje.Crear(Mensaje:String;qCaption:String='Mensaje';HTML:Boolean=False); begin inherited Create(uniGUIApplication.UniApplication); FCaption:=qCaption; if HTML then begin UniMemoMensaje.Visible:=False; UniHTMLMemo1.Lines.Text:=Mensaje; end else begin UniHTMLMemo1.Visible:=False; UniMemoMensaje.Lines.Text:=Mensaje; end; end; procedure TFrmMensaje.UBSalirClick(Sender: TObject); begin Close; end; procedure TFrmMensaje.UniFormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TFrmMensaje.UniFormCreate(Sender: TObject); begin MonitorizarTeclas(Self,[VK_ESCAPE],False); end; procedure TFrmMensaje.UniFormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=VK_ESCAPE then Self.Close; end; procedure TFrmMensaje.UniFormShow(Sender: TObject); begin Self.Caption:=fCaption; end; end.
unit UImpl6502; interface uses Generics.Collections , UIntBus , UInt6502; type TUint8Func = function: UInt8 of object; T6502Flags = ( cfCarry = 1 shl 0, cfZero = 1 shl 1, cfDisableInterrupts = 1 shl 2, cfDecimalMode = 1 shl 3, // unused cfBreak = 1 shl 4, cfUnused = 1 shl 5, cfOverflow = 1 shl 6, cfNegative = 1 shl 7 ); T6502Opcode = record Name: string; OperateFunc: TUint8Func; AddressModeFunc: TUint8Func; TotalCycle: UInt8; constructor Create(const AName: string; AOpFunc, AAddFunc: TUint8Func; ATotalCycle: UInt8); end; T6502 = class(TInterfacedObject, I6502) private [weak] FBus: IBus; FStatus: UInt8; Fa, Fx, Fy, FStckP: UInt8; FPc: UInt16; FFetched: UInt8; FAbsoluteAddress, FRelativAddress: UInt16; FCurrentOpcode, FRemainningCycleForCurrOpcd: UInt8; // adressing mode function IMP(): UInt8; function IMM(): UInt8; function ZP0(): UInt8; function ZPX(): UInt8; function ZPY(): UInt8; function REL(): UInt8; function ABS(): UInt8; function ABX(): UInt8; function ABY(): UInt8; function IND(): UInt8; function IZX(): UInt8; function IZY(): UInt8; // opcode function ADC(): UInt8; function &AND(): UInt8; function ASL(): UInt8; function BCC(): UInt8; function BCS(): UInt8; function BEQ(): UInt8; function BIT(): UInt8; function BMI(): UInt8; function BNE(): UInt8; function BPL(): UInt8; function BRK(): UInt8; function BVC(): UInt8; function BVS(): UInt8; function CLC(): UInt8; function CLD(): UInt8; function CLI(): UInt8; function CLV(): UInt8; function CMP(): UInt8; function CPX(): UInt8; function CPY(): UInt8; function DEC(): UInt8; function DEX(): UInt8; function DEY(): UInt8; function EOR(): UInt8; function Inc(): UInt8; function INX(): UInt8; function INY(): UInt8; function JMP(): UInt8; function JSR(): UInt8; function LDA(): UInt8; function LDX(): UInt8; function LDY(): UInt8; function LSR(): UInt8; function NOP(): UInt8; function ORA(): UInt8; function PHA(): UInt8; function PHP(): UInt8; function PLA(): UInt8; function PLP(): UInt8; function ROL(): UInt8; function ROR(): UInt8; function RTI(): UInt8; function RTS(): UInt8; function SBC(): UInt8; function SEC(): UInt8; function SED(): UInt8; function SEI(): UInt8; function STA(): UInt8; function STX(): UInt8; function STY(): UInt8; function TAX(): UInt8; function TAY(): UInt8; function TSX(): UInt8; function TXA(): UInt8; function TXS(): UInt8; function TYA(): UInt8; function XXX(): UInt8; procedure Clock; procedure Reset; procedure Irq; procedure Nmi; function Fetch: UInt8; function GetFlag(AFlag: T6502Flags): UInt8; procedure SetFlag(AFlag: T6502Flags; AIsSet: Boolean = True); function InternalBranching(AFlagToTest: T6502Flags; AValueOfFlag: Boolean = True): UInt8; public FLookupOpcode: TArray<T6502Opcode>; constructor Create(ABus: IBus); destructor Destroy; override; procedure Write(AAdress: UInt16; AData: UInt8); function Read(AAdress: UInt16): UInt8; function GetStatus: UInt8; function GetA: UInt8; function GetX: UInt8; function GetY: UInt8; function GetStackP: UInt8; function GetPC: UInt16; function GetCurrentOpcode: string; end; implementation const STACK_BASE_ADDRESS = $0100; { T6502 } function T6502.ABS: UInt8; var LHighAdr, LLowAdr: UInt16; begin LLowAdr := Read(FPc); System.Inc(FPc); LHighAdr := Read(FPc); System.Inc(FPc); FAbsoluteAddress := (LHighAdr shl 8) or LLowAdr; Result := 0; end; function T6502.ABX: UInt8; var LHighAdr, LLowAdr: UInt16; begin LLowAdr := Read(FPc); System.Inc(FPc); LHighAdr := Read(FPc); System.Inc(FPc); FAbsoluteAddress := (LHighAdr shl 8) or LLowAdr; System.Inc(FAbsoluteAddress, Fx); if (FAbsoluteAddress and $FF00) <> (LHighAdr shl 8) then Result := 1 else Result := 0; end; function T6502.ABY: UInt8; var LHighAdr, LLowAdr: UInt16; begin LLowAdr := Read(FPc); System.Inc(FPc); LHighAdr := Read(FPc); System.Inc(FPc); FAbsoluteAddress := (LHighAdr shl 8) or LLowAdr; System.Inc(FAbsoluteAddress, Fy); if (FAbsoluteAddress and $FF00) <> (LHighAdr shl 8) then Result := 1 else Result := 0; end; function T6502.ADC: UInt8; var LTempResult: UInt16; LOverflow1, LOverflow2: Boolean; begin Fetch; LTempResult := UInt16(Fa) + UInt16(FFetched) + UInt16(GetFlag(cfCarry)); SetFlag(cfCarry, LTempResult > 255); SetFlag(cfZero, (LTempResult and $00FF) = 0); SetFlag(cfNegative, (LTempResult and $80) > 0); // MSB is set // (~((uint16_t)a ^ (uint16_t)fetched) & ((uint16_t)a ^ (uint16_t)temp)) & 0x0080); // (~((uint16_t)a ^ (uint16_t)fetched) LOverflow1 := (UInt16(Fa) xor UInt16(FFetched)) = 0; // ((uint16_t)a ^ (uint16_t)temp)) & 0x0080); LOverflow2 := ((UInt16(Fa) xor UInt16(LTempResult)) and $0080) <> 0; SetFlag(cfOverflow, LOverflow1 and LOverflow2); Fa := LTempResult and $00FF; Result := 1; end; function T6502.&AND: UInt8; begin Fetch; Fa := (Fa and FFetched); SetFlag(cfZero, Fa = 0); SetFlag(cfNegative, (Fa and $80) > 0); Result := 1; end; function T6502.ASL: UInt8; var LTemp: Uint16; begin Fetch; LTemp := UInt16(FFetched) shl 1; SetFlag(cfCarry, (LTemp and $FF00) > 0); SetFlag(cfZero, (LTemp and $00FF) = $00); SetFlag(cfNegative, (LTemp and $80) > 0); if FLookupOpcode[FCurrentOpcode].AddressModeFunc = IMP then Fa := LTemp and $00FF else Write(FAbsoluteAddress, LTemp and $00FF); Result := 0; end; function T6502.BCC: UInt8; begin Result := InternalBranching(cfCarry, False); end; function T6502.BCS: UInt8; begin Result := InternalBranching(cfCarry); end; function T6502.BEQ: UInt8; begin Result := InternalBranching(cfZero); end; function T6502.BIT: UInt8; var LTemp: UInt16; begin Fetch; LTemp := Fa and FFetched; SetFlag(cfZero, (LTemp and $00FF) > 0); SetFlag(cfNegative, (FFetched and (1 shl 7)) > 0); SetFlag(cfOverflow, (FFetched and (1 shl 6)) > 0); Result := 0; end; function T6502.BMI: UInt8; begin Result := InternalBranching(cfNegative); end; function T6502.BNE: UInt8; begin Result := InternalBranching(cfZero, False); end; function T6502.BPL: UInt8; begin Result := InternalBranching(cfNegative, False); end; function T6502.BRK: UInt8; begin System.Inc(FPc); SetFlag(cfDisableInterrupts); Write(STACK_BASE_ADDRESS + FStckP, (FPc shr 8) and $00FF); System.Dec(FStckP); Write(STACK_BASE_ADDRESS + FStckP, FPc and $00FF); System.Dec(FStckP); SetFlag(cfBreak); Write(STACK_BASE_ADDRESS + FStckP, FStatus); System.Dec(FStckP); SetFlag(cfBreak, False); FPc := (Uint16(Read($FFFE))) or (UInt16(Read($FFFF)) shl 8); Result := 0; end; function T6502.BVC: UInt8; begin Result := InternalBranching(cfOverflow, False); end; function T6502.BVS: UInt8; begin Result := InternalBranching(cfOverflow); end; function T6502.CLC: UInt8; begin SetFlag(cfCarry, False); Result := 0; end; function T6502.CLD: UInt8; begin SetFlag(cfDecimalMode, False); Result := 0; end; function T6502.CLI: UInt8; begin SetFlag(cfDisableInterrupts, False); Result := 0; end; procedure T6502.Clock; var LAdditionnalCycleOperate, LAdditionnalCycleAddressMode: UInt8; begin // if FRemainningCycleForCurrOpcd = 0 then begin FCurrentOpcode := Read(FPc); System.Inc(FPC); FRemainningCycleForCurrOpcd := FLookupOpcode[FCurrentOpcode].TotalCycle; LAdditionnalCycleAddressMode := FLookupOpcode[FCurrentOpcode].AddressModeFunc; LAdditionnalCycleOperate := FLookupOpcode[FCurrentOpcode].OperateFunc; System.Inc(FRemainningCycleForCurrOpcd, LAdditionnalCycleAddressMode and LAdditionnalCycleOperate); end; System.Dec(FRemainningCycleForCurrOpcd); end; function T6502.CLV: UInt8; begin SetFlag(cfOverflow, False); Result := 0; end; function T6502.CMP: UInt8; var LTemp: UInt16; begin Fetch; LTemp := UInt16(Fa) - UInt16(FFetched); SetFlag(cfCarry, Fa >= FFetched); SetFlag(cfZero, (LTemp and $00FF) = 0); SetFlag(cfNegative, (LTemp and $80) > 0); Result := 1; end; function T6502.CPX: UInt8; var LTemp: UInt16; begin Fetch; LTemp := UInt16(Fx) - UInt16(FFetched); SetFlag(cfCarry, Fx >= FFetched); SetFlag(cfZero, (LTemp and $00FF) = 0); SetFlag(cfNegative, (LTemp and $80) > 0); Result := 0; end; function T6502.CPY: UInt8; var LTemp: UInt16; begin Fetch; LTemp := UInt16(Fy) - UInt16(FFetched); SetFlag(cfCarry, Fy >= FFetched); SetFlag(cfZero, (LTemp and $00FF) = 0); SetFlag(cfNegative, (LTemp and $80) > 0); Result := 0; end; constructor T6502.Create(ABus: IBus); begin FBus := ABus; FLookupOpcode := [T6502Opcode.Create('BRK', BRK, IMM, 7 )]+[T6502Opcode.Create( 'ORA', ORA, IZX, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 8 )]+[T6502Opcode.Create( '???', NOP, IMP, 3 )]+[T6502Opcode.Create( 'ORA', ORA, ZP0, 3 )]+[T6502Opcode.Create( 'ASL', ASL, ZP0, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 5 )]+[T6502Opcode.Create( 'PHP', PHP, IMP, 3 )]+[T6502Opcode.Create( 'ORA', ORA, IMM, 2 )]+[T6502Opcode.Create( 'ASL', ASL, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( '???', NOP, IMP, 4 )]+[T6502Opcode.Create( 'ORA', ORA, ABS, 4 )]+[T6502Opcode.Create( 'ASL', ASL, ABS, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]+ [T6502Opcode.Create( 'BPL', BPL, REL, 2 )]+[T6502Opcode.Create( 'ORA', ORA, IZY, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 8 )]+[T6502Opcode.Create( '???', NOP, IMP, 4 )]+[T6502Opcode.Create( 'ORA', ORA, ZPX, 4 )]+[T6502Opcode.Create( 'ASL', ASL, ZPX, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]+[T6502Opcode.Create( 'CLC', CLC, IMP, 2 )]+[T6502Opcode.Create( 'ORA', ORA, ABY, 4 )]+[T6502Opcode.Create( '???', NOP, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 7 )]+[T6502Opcode.Create( '???', NOP, IMP, 4 )]+[T6502Opcode.Create( 'ORA', ORA, ABX, 4 )]+[T6502Opcode.Create( 'ASL', ASL, ABX, 7 )]+[T6502Opcode.Create( '???', XXX, IMP, 7 )]+ [T6502Opcode.Create( 'JSR', JSR, ABS, 6 )]+[T6502Opcode.Create( '&AND', &AND, IZX, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 8 )]+[T6502Opcode.Create( 'BIT', BIT, ZP0, 3 )]+[T6502Opcode.Create( '&AND', &AND, ZP0, 3 )]+[T6502Opcode.Create( 'ROL', ROL, ZP0, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 5 )]+[T6502Opcode.Create( 'PLP', PLP, IMP, 4 )]+[T6502Opcode.Create( '&AND', &AND, IMM, 2 )]+[T6502Opcode.Create( 'ROL', ROL, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( 'BIT', BIT, ABS, 4 )]+[T6502Opcode.Create( '&AND', &AND, ABS, 4 )]+[T6502Opcode.Create( 'ROL', ROL, ABS, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]+ [T6502Opcode.Create( 'BMI', BMI, REL, 2 )]+[T6502Opcode.Create( '&AND', &AND, IZY, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 8 )]+[T6502Opcode.Create( '???', NOP, IMP, 4 )]+[T6502Opcode.Create( '&AND', &AND, ZPX, 4 )]+[T6502Opcode.Create( 'ROL', ROL, ZPX, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]+[T6502Opcode.Create( 'SEC', SEC, IMP, 2 )]+[T6502Opcode.Create( '&AND', &AND, ABY, 4 )]+[T6502Opcode.Create( '???', NOP, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 7 )]+[T6502Opcode.Create( '???', NOP, IMP, 4 )]+[T6502Opcode.Create( '&AND', &AND, ABX, 4 )]+[T6502Opcode.Create( 'ROL', ROL, ABX, 7 )]+[T6502Opcode.Create( '???', XXX, IMP, 7 )]+ [T6502Opcode.Create( 'RTI', RTI, IMP, 6 )]+[T6502Opcode.Create( 'EOR', EOR, IZX, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 8 )]+[T6502Opcode.Create( '???', NOP, IMP, 3 )]+[T6502Opcode.Create( 'EOR', EOR, ZP0, 3 )]+[T6502Opcode.Create( 'LSR', LSR, ZP0, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 5 )]+[T6502Opcode.Create( 'PHA', PHA, IMP, 3 )]+[T6502Opcode.Create( 'EOR', EOR, IMM, 2 )]+[T6502Opcode.Create( 'LSR', LSR, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( 'JMP', JMP, ABS, 3 )]+[T6502Opcode.Create( 'EOR', EOR, ABS, 4 )]+[T6502Opcode.Create( 'LSR', LSR, ABS, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]; FLookupOpcode := FLookupOpcode + [T6502Opcode.Create( 'BVC', BVC, REL, 2 )]+[T6502Opcode.Create( 'EOR', EOR, IZY, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 8 )]+[T6502Opcode.Create( '???', NOP, IMP, 4 )]+[T6502Opcode.Create( 'EOR', EOR, ZPX, 4 )]+[T6502Opcode.Create( 'LSR', LSR, ZPX, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]+[T6502Opcode.Create( 'CLI', CLI, IMP, 2 )]+[T6502Opcode.Create( 'EOR', EOR, ABY, 4 )]+[T6502Opcode.Create( '???', NOP, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 7 )]+[T6502Opcode.Create( '???', NOP, IMP, 4 )]+[T6502Opcode.Create( 'EOR', EOR, ABX, 4 )]+[T6502Opcode.Create( 'LSR', LSR, ABX, 7 )]+[T6502Opcode.Create( '???', XXX, IMP, 7 )]+ [T6502Opcode.Create( 'RTS', RTS, IMP, 6 )]+[T6502Opcode.Create( 'ADC', ADC, IZX, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 8 )]+[T6502Opcode.Create( '???', NOP, IMP, 3 )]+[T6502Opcode.Create( 'ADC', ADC, ZP0, 3 )]+[T6502Opcode.Create( 'ROR', ROR, ZP0, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 5 )]+[T6502Opcode.Create( 'PLA', PLA, IMP, 4 )]+[T6502Opcode.Create( 'ADC', ADC, IMM, 2 )]+[T6502Opcode.Create( 'ROR', ROR, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( 'JMP', JMP, IND, 5 )]+[T6502Opcode.Create( 'ADC', ADC, ABS, 4 )]+[T6502Opcode.Create( 'ROR', ROR, ABS, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]+ [T6502Opcode.Create( 'BVS', BVS, REL, 2 )]+[T6502Opcode.Create( 'ADC', ADC, IZY, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 8 )]+[T6502Opcode.Create( '???', NOP, IMP, 4 )]+[T6502Opcode.Create( 'ADC', ADC, ZPX, 4 )]+[T6502Opcode.Create( 'ROR', ROR, ZPX, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]+[T6502Opcode.Create( 'SEI', SEI, IMP, 2 )]+[T6502Opcode.Create( 'ADC', ADC, ABY, 4 )]+[T6502Opcode.Create( '???', NOP, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 7 )]+[T6502Opcode.Create( '???', NOP, IMP, 4 )]+[T6502Opcode.Create( 'ADC', ADC, ABX, 4 )]+[T6502Opcode.Create( 'ROR', ROR, ABX, 7 )]+[T6502Opcode.Create( '???', XXX, IMP, 7 )]+ [T6502Opcode.Create( '???', NOP, IMP, 2 )]+[T6502Opcode.Create( 'STA', STA, IZX, 6 )]+[T6502Opcode.Create( '???', NOP, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]+[T6502Opcode.Create( 'STY', STY, ZP0, 3 )]+[T6502Opcode.Create( 'STA', STA, ZP0, 3 )]+[T6502Opcode.Create( 'STX', STX, ZP0, 3 )]+[T6502Opcode.Create( '???', XXX, IMP, 3 )]+[T6502Opcode.Create( 'DEY', DEY, IMP, 2 )]+[T6502Opcode.Create( '???', NOP, IMP, 2 )]+[T6502Opcode.Create( 'TXA', TXA, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( 'STY', STY, ABS, 4 )]+[T6502Opcode.Create( 'STA', STA, ABS, 4 )]+[T6502Opcode.Create( 'STX', STX, ABS, 4 )]+[T6502Opcode.Create( '???', XXX, IMP, 4 )]+ [T6502Opcode.Create( 'BCC', BCC, REL, 2 )]+[T6502Opcode.Create( 'STA', STA, IZY, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]+[T6502Opcode.Create( 'STY', STY, ZPX, 4 )]+[T6502Opcode.Create( 'STA', STA, ZPX, 4 )]+[T6502Opcode.Create( 'STX', STX, ZPY, 4 )]+[T6502Opcode.Create( '???', XXX, IMP, 4 )]+[T6502Opcode.Create( 'TYA', TYA, IMP, 2 )]+[T6502Opcode.Create( 'STA', STA, ABY, 5 )]+[T6502Opcode.Create( 'TXS', TXS, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 5 )]+[T6502Opcode.Create( '???', NOP, IMP, 5 )]+[T6502Opcode.Create( 'STA', STA, ABX, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 5 )]+ [T6502Opcode.Create( 'LDY', LDY, IMM, 2 )]+[T6502Opcode.Create( 'LDA', LDA, IZX, 6 )]+[T6502Opcode.Create( 'LDX', LDX, IMM, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]+[T6502Opcode.Create( 'LDY', LDY, ZP0, 3 )]+[T6502Opcode.Create( 'LDA', LDA, ZP0, 3 )]+[T6502Opcode.Create( 'LDX', LDX, ZP0, 3 )]+[T6502Opcode.Create( '???', XXX, IMP, 3 )]+[T6502Opcode.Create( 'TAY', TAY, IMP, 2 )]+[T6502Opcode.Create( 'LDA', LDA, IMM, 2 )]+[T6502Opcode.Create( 'TAX', TAX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( 'LDY', LDY, ABS, 4 )]+[T6502Opcode.Create( 'LDA', LDA, ABS, 4 )]+[T6502Opcode.Create( 'LDX', LDX, ABS, 4 )]+[T6502Opcode.Create( '???', XXX, IMP, 4 )]+ [T6502Opcode.Create( 'BCS', BCS, REL, 2 )]+[T6502Opcode.Create( 'LDA', LDA, IZY, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 5 )]+[T6502Opcode.Create( 'LDY', LDY, ZPX, 4 )]+[T6502Opcode.Create( 'LDA', LDA, ZPX, 4 )]+[T6502Opcode.Create( 'LDX', LDX, ZPY, 4 )]+[T6502Opcode.Create( '???', XXX, IMP, 4 )]+[T6502Opcode.Create( 'CLV', CLV, IMP, 2 )]+[T6502Opcode.Create( 'LDA', LDA, ABY, 4 )]+[T6502Opcode.Create( 'TSX', TSX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 4 )]+[T6502Opcode.Create( 'LDY', LDY, ABX, 4 )]+[T6502Opcode.Create( 'LDA', LDA, ABX, 4 )]+[T6502Opcode.Create( 'LDX', LDX, ABY, 4 )]+[T6502Opcode.Create( '???', XXX, IMP, 4 )]+ [T6502Opcode.Create( 'CPY', CPY, IMM, 2 )]+[T6502Opcode.Create( 'CMP', CMP, IZX, 6 )]+[T6502Opcode.Create( '???', NOP, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 8 )]+[T6502Opcode.Create( 'CPY', CPY, ZP0, 3 )]+[T6502Opcode.Create( 'CMP', CMP, ZP0, 3 )]+[T6502Opcode.Create( 'DEC', DEC, ZP0, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 5 )]+[T6502Opcode.Create( 'INY', INY, IMP, 2 )]+[T6502Opcode.Create( 'CMP', CMP, IMM, 2 )]+[T6502Opcode.Create( 'DEX', DEX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( 'CPY', CPY, ABS, 4 )]+[T6502Opcode.Create( 'CMP', CMP, ABS, 4 )]+[T6502Opcode.Create( 'DEC', DEC, ABS, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]+ [T6502Opcode.Create( 'BNE', BNE, REL, 2 )]+[T6502Opcode.Create( 'CMP', CMP, IZY, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 8 )]+[T6502Opcode.Create( '???', NOP, IMP, 4 )]+[T6502Opcode.Create( 'CMP', CMP, ZPX, 4 )]+[T6502Opcode.Create( 'DEC', DEC, ZPX, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]+[T6502Opcode.Create( 'CLD', CLD, IMP, 2 )]+[T6502Opcode.Create( 'CMP', CMP, ABY, 4 )]+[T6502Opcode.Create( 'NOP', NOP, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 7 )]+[T6502Opcode.Create( '???', NOP, IMP, 4 )]+[T6502Opcode.Create( 'CMP', CMP, ABX, 4 )]+[T6502Opcode.Create( 'DEC', DEC, ABX, 7 )]+[T6502Opcode.Create( '???', XXX, IMP, 7 )]+ [T6502Opcode.Create( 'CPX', CPX, IMM, 2 )]+[T6502Opcode.Create( 'SBC', SBC, IZX, 6 )]+[T6502Opcode.Create( '???', NOP, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 8 )]+[T6502Opcode.Create( 'CPX', CPX, ZP0, 3 )]+[T6502Opcode.Create( 'SBC', SBC, ZP0, 3 )]+[T6502Opcode.Create( 'System.Inc', Inc, ZP0, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 5 )]+[T6502Opcode.Create( 'INX', INX, IMP, 2 )]+[T6502Opcode.Create( 'SBC', SBC, IMM, 2 )]+[T6502Opcode.Create( 'NOP', NOP, IMP, 2 )]+[T6502Opcode.Create( '???', SBC, IMP, 2 )]+[T6502Opcode.Create( 'CPX', CPX, ABS, 4 )]+[T6502Opcode.Create( 'SBC', SBC, ABS, 4 )]+[T6502Opcode.Create( 'Inc', Inc, ABS, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]+ [T6502Opcode.Create( 'BEQ', BEQ, REL, 2 )]+[T6502Opcode.Create( 'SBC', SBC, IZY, 5 )]+[T6502Opcode.Create( '???', XXX, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 8 )]+[T6502Opcode.Create( '???', NOP, IMP, 4 )]+[T6502Opcode.Create( 'SBC', SBC, ZPX, 4 )]+[T6502Opcode.Create( 'System.Inc', Inc, ZPX, 6 )]+[T6502Opcode.Create( '???', XXX, IMP, 6 )]+[T6502Opcode.Create( 'SED', SED, IMP, 2 )]+[T6502Opcode.Create( 'SBC', SBC, ABY, 4 )]+[T6502Opcode.Create( 'NOP', NOP, IMP, 2 )]+[T6502Opcode.Create( '???', XXX, IMP, 7 )]+[T6502Opcode.Create( '???', NOP, IMP, 4 )]+[T6502Opcode.Create( 'SBC', SBC, ABX, 4 )]+[T6502Opcode.Create( 'Inc', Inc, ABX, 7 )]+[T6502Opcode.Create( '???', XXX, IMP, 7 )]; end; function T6502.DEC: UInt8; var LTemp: UInt16; begin Fetch; LTemp := FFetched - 1; Write(FAbsoluteAddress, LTemp and $00FF); SetFlag(cfZero, (LTemp and $00FF) = 0); SetFlag(cfNegative, (LTemp and $80) > 0); Result := 0; end; destructor T6502.Destroy; begin inherited; end; function T6502.DEX: UInt8; begin System.Dec(Fx); SetFlag(cfZero, Fx = 0); SetFlag(cfNegative, (Fx and $80) <> 0); Result := 0; end; function T6502.DEY: UInt8; begin System.Dec(Fy); SetFlag(cfZero, Fy = 0); SetFlag(cfNegative, (Fy and $80) <> 0); Result := 0; end; function T6502.EOR: UInt8; begin Fetch; Fa := Fa xor FFetched; SetFlag(cfZero, Fa = 0); SetFlag(cfNegative, (Fa and $80) <> 0); Result := 0; end; function T6502.Fetch: UInt8; begin FFetched := 0; if ((TMethod(FLookupOpcode[FCurrentOpcode].AddressModeFunc).Code) <> @T6502.IMP) then begin FFetched := Read(FAbsoluteAddress); end; Result := FFetched; end; function T6502.GetA: UInt8; begin Result := Fa; end; function T6502.GetCurrentOpcode: string; begin Result := FLookupOpcode[FCurrentOpcode].Name; end; function T6502.GetFlag(AFlag: T6502Flags): UInt8; begin if ((FStatus and Ord(AFlag)) > 0) then Result := 1 else Result := 0; end; function T6502.GetPC: UInt16; begin Result := FPc; end; function T6502.GetStackP: UInt8; begin Result := FStckP; end; function T6502.GetStatus: UInt8; begin Result := FStatus; end; function T6502.GetX: UInt8; begin Result := Fx; end; function T6502.GetY: UInt8; begin Result := Fy; end; function T6502.IMM: UInt8; begin FAbsoluteAddress := FPc; System.Inc(FPc); Result := 0; end; function T6502.IMP: UInt8; begin FFetched := FA; Result := 0; end; function T6502.Inc: UInt8; var LTemp: UInt16; begin Fetch; LTemp := FFetched + 1; Write(FAbsoluteAddress, LTemp and $00FF); SetFlag(cfZero, (LTemp and $00FF) = 0); SetFlag(cfNegative, (LTemp and $80) > 0); Result := 0; end; function T6502.IND: UInt8; var LFinalPtr, LHighPtr, LLowPtr: UInt16; begin LLowPtr := Read(FPc); System.Inc(FPc); LHighPtr := Read(FPc); System.Inc(FPc); LFInalPtr := (LHighPtr shl 8) or LLowPtr; if LLowPtr = $00FF then // Simulate page boundary HW bug FAbsoluteAddress := (Read(LFinalPtr and $FF00) shl 8) or (Read(LFinalPtr)) else FAbsoluteAddress := (Read(LFinalPtr + 1) shl 8) or (Read(LFinalPtr)); Result := 0; end; function T6502.InternalBranching(AFlagToTest: T6502Flags; AValueOfFlag: Boolean = True): UInt8; var LValueToTest: UInt8; begin if AValueOfFlag then LValueToTest := 1 else LValueToTest := 0; if GetFlag(AFlagToTest) = LValueToTest then begin System.Inc(FRemainningCycleForCurrOpcd); FAbsoluteAddress := FPc + FRelativAddress; if (FAbsoluteAddress and $FF00) <> (FPc and $FF00) then begin System.Inc(FRemainningCycleForCurrOpcd); end; FPc := FAbsoluteAddress; end; Result := 0; end; function T6502.INX: UInt8; begin System.Inc(Fx); SetFlag(cfZero, Fx = 0); SetFlag(cfNegative, (Fx and $80) <> 0); Result := 0; end; function T6502.INY: UInt8; begin System.Inc(Fy); SetFlag(cfZero, Fy = 0); SetFlag(cfNegative, (Fy and $80) <> 0); Result := 0; end; procedure T6502.Irq; var LLow, LHigh: UInt16; begin if GetFlag(cfDisableInterrupts) = 0 then begin Write(STACK_BASE_ADDRESS + FStckP, (FPc shr 8) and $00FF); System.Dec(FStckP); Write(STACK_BASE_ADDRESS + FStckP, FPc and $00FF); System.Dec(FStckP); SetFlag(cfBreak, False); SetFlag(cfUnused); SetFlag(cfDisableInterrupts); Write(STACK_BASE_ADDRESS + FStckP, FStatus); System.Dec(FStckP); FAbsoluteAddress := $FFFE; LLow := Read(FAbsoluteAddress); LHigh := Read(FAbsoluteAddress + 1); FPc := (LHigh shl 8) or LLow; FRemainningCycleForCurrOpcd := 7; end; end; function T6502.IZX: UInt8; var LAdd, LLowAdr, LHighAdr: UInt16; begin LAdd := Read(FPc); System.Inc(FPc); LLowAdr := Read(Uint16(LAdd + UInt16(Fx)) and $00FF); LHighAdr := Read(Uint16(LAdd + UInt16(Fx) + 1) and $00FF); FAbsoluteAddress := (LHighAdr shl 8) or LLowAdr; Result := 0; end; function T6502.IZY: UInt8; var LAdrWhereActualAdrIs, LLowAdr, LhighAdr: UInt16; begin LAdrWhereActualAdrIs := Read(FPc); LLowAdr := Read(LAdrWhereActualAdrIs and $00FF); LHighAdr := Read(LAdrWhereActualAdrIs + 1) and $00FF; FAbsoluteAddress := (LhighAdr shl 8) or LLowAdr; System.Inc(FAbsoluteAddress, FY); if ((FAbsoluteAddress and $FF00) <> (LhighAdr shl 8)) then Result := 1 else Result := 0; end; function T6502.JMP: UInt8; begin Fpc := FAbsoluteAddress; Result := 0; end; function T6502.JSR: UInt8; begin System.Dec(FPc); Write(STACK_BASE_ADDRESS + FStckP, (FPc shr 8) and $00FF); System.Dec(FStckP); Write(STACK_BASE_ADDRESS + FStckP, FPc and $00FF); System.Dec(FStckP); Fpc := FAbsoluteAddress; Result := 0; end; function T6502.LDA: UInt8; begin Fetch; Fa := FFetched; SetFlag(cfZero, Fa = 0); SetFlag(cfNegative, (Fa and $80) <> 0); Result := 1; end; function T6502.LDX: UInt8; begin Fetch; Fx:= FFetched; SetFlag(cfZero, Fx = 0); SetFlag(cfNegative, (Fx and $80) <> 0); Result := 1; end; function T6502.LDY: UInt8; begin Fetch; Fy:= FFetched; SetFlag(cfZero, Fy = 0); SetFlag(cfNegative, (Fy and $80) <> 0); Result := 1; end; function T6502.LSR: UInt8; var LTemp: UInt16; begin Fetch; SetFlag(cfCarry, (FFetched and $0001) <> 0); LTemp := FFetched shr 1; SetFlag(cfZero, (LTemp and $00FF) = 0); SetFlag(cfNegative, (LTemp and $0080) <> 0); if FLookupOpcode[FCurrentOpcode].AddressModeFunc = IMP then Fa := LTemp and $00FF else Write(FAbsoluteAddress, LTemp and $00FF); Result := 0; end; procedure T6502.Nmi; var LLow, LHigh: UInt16; begin Write(STACK_BASE_ADDRESS + FStckP, (FPc shr 8) and $00FF); System.Dec(FStckP); Write(STACK_BASE_ADDRESS + FStckP, FPc and $00FF); System.Dec(FStckP); SetFlag(cfBreak, False); SetFlag(cfUnused); SetFlag(cfDisableInterrupts); Write(STACK_BASE_ADDRESS + FStckP, FStatus); System.Dec(FStckP); FAbsoluteAddress := $FFFA; LLow := Read(FAbsoluteAddress); LHigh := Read(FAbsoluteAddress + 1); FPc := (LHigh shl 8) or LLow; FRemainningCycleForCurrOpcd := 7; end; function T6502.NOP: UInt8; begin case FCurrentOpcode of $1C, $3C, $5C, $7C, $DC, $FC: Result := 1; else Result := 0; end; end; function T6502.ORA: UInt8; begin Fetch; Fa := Fa or FFetched; SetFlag(cfZero, Fa = 0); SetFlag(cfNegative, (Fa and $80) <> 0); Result := 1; end; function T6502.PHA: UInt8; begin Write(STACK_BASE_ADDRESS + FStckP, Fa); System.Dec(FStckP); Result := 0; end; function T6502.PHP: UInt8; begin Write(STACK_BASE_ADDRESS + FStckP, (FStatus or Ord(cfBreak)) or Ord(cfUnused)); SetFlag(cfBreak, False); SetFlag(cfUnused, False); System.Dec(FStckP); Result := 0; end; function T6502.PLA: UInt8; begin System.Inc(FStckP); Fa := Read(STACK_BASE_ADDRESS+ FStckP); SetFlag(cfZero, Fa = $00); SetFlag(cfNegative, (Fa and $80) <> 0); Result := 0; end; function T6502.PLP: UInt8; begin System.Inc(FStckP); FStatus := Read(STACK_BASE_ADDRESS+ FStckP); SetFlag(cfUnused); Result := 0; end; function T6502.Read(AAdress: UInt16): UInt8; begin Result := FBus.Read(AAdress); end; function T6502.REL: UInt8; begin FRelativAddress := Read(FPc); System.Inc(FPc); if ((FRelativAddress and $80) <> 0) then FRelativAddress := FRelativAddress or $FF00; Result := 0; end; procedure T6502.Reset; var LLow, LHigh: UInt16; begin Fa := 0; Fx := 0; Fy := 0; FStckP := $FD; FStatus := $00 or Ord(cfUnused); FAbsoluteAddress := $FFFC; LLow := Read(FAbsoluteAddress + 0); LHigh := Read(FAbsoluteAddress + 1); FPc := (LHigh shl 8) or LLow; FRelativAddress := 0; FAbsoluteAddress := 0; FFetched := $00; FRemainningCycleForCurrOpcd := 8; end; function T6502.ROL: UInt8; var LTemp: Uint16; begin Fetch; LTemp := UInt16(FFetched shl 1) or GetFlag(cfCarry); SetFlag(cfCarry, (LTemp and $FF00) <> 0); SetFlag(cfZero, (LTemp and $00FF) = 0); SetFlag(cfNegative, (LTemp and $0080) <> 0); if FLookupOpcode[FCurrentOpcode].AddressModeFunc = IMP then Fa := LTemp and $00FF else Write(FAbsoluteAddress, LTemp and $00FF); Result := 0; end; function T6502.ROR: UInt8; var LTemp: UInt16; begin Fetch; LTemp := UInt16(GetFlag(cfCarry) shl 7) or (FFetched shl 1); SetFlag(cfCarry, (FFetched and $01) <> 0); SetFlag(cfZero, (LTemp and $00FF) = 0); SetFlag(cfNegative, (LTemp and $0080) <> 0); if FLookupOpcode[FCurrentOpcode].AddressModeFunc = IMP then Fa := LTemp and $00FF else Write(FAbsoluteAddress, LTemp and $00FF); Result := 0; end; function T6502.RTI: UInt8; begin System.Inc(FStckP); FStatus := Read(STACK_BASE_ADDRESS + FStckP); FStatus := FStatus and (not Ord(cfBreak)); FStatus := FStatus and (not Ord(cfUnused)); System.Inc(FStckP); FStckP := UInt16(Read(STACK_BASE_ADDRESS + FStckP)); System.Inc(FStckP); FStckP := FStckP or (UInt16(STACK_BASE_ADDRESS + FStckP) shl 8); Result := 0; end; function T6502.RTS: UInt8; begin System.Inc(FStckP); FStckP := UInt16(Read(STACK_BASE_ADDRESS + FStckP)); System.Inc(FStckP); FStckP := FStckP or (UInt16(STACK_BASE_ADDRESS + FStckP) shl 8); System.Inc(FPc); Result := 0; end; function T6502.SBC: UInt8; var LTempResult: UInt16; LValue: Uint16; LOverflow1: Boolean; LOverflow2: Boolean; begin Fetch; LValue := Uint16(FFetched) xor $00FF; LTempResult := UInt16(Fa) + LValue + UInt16(GetFlag(cfCarry)); SetFlag(cfCarry, LTempResult > 255); SetFlag(cfZero, (LTempResult and $00FF) = 0); SetFlag(cfNegative, (LTempResult and $80) > 0); // MSB is set // (~((uint16_t)a ^ (uint16_t)fetched) & ((uint16_t)a ^ (uint16_t)temp)) & 0x0080); // (~((uint16_t)a ^ (uint16_t)fetched) LOverflow1 := (UInt16(Fa) xor UInt16(FFetched)) = 0; // ((uint16_t)a ^ (uint16_t)temp)) & 0x0080); LOverflow2 := ((UInt16(Fa) xor UInt16(LTempResult)) and $0080) <> 0; SetFlag(cfOverflow, LOverflow1 and LOverflow2); Fa := LTempResult and $00FF; Result := 1; end; function T6502.SEC: UInt8; begin SetFlag(cfCarry); Result := 0; end; function T6502.SED: UInt8; begin SetFlag(cfDecimalMode); Result := 0; end; function T6502.SEI: UInt8; begin SetFlag(cfDisableInterrupts); Result := 0; end; procedure T6502.SetFlag(AFlag: T6502Flags; AIsSet: Boolean); begin if AIsSet then FStatus := (FStatus or Ord(AFlag)) else FStatus := FStatus and (not Ord(AFlag)); end; function T6502.STA: UInt8; begin Write(FAbsoluteAddress, Fa); Result := 0; end; function T6502.STX: UInt8; begin Write(FAbsoluteAddress, Fx); Result := 0; end; function T6502.STY: UInt8; begin Write(FAbsoluteAddress, Fy); Result := 0; end; function T6502.TAX: UInt8; begin Fx := Fa; SetFlag(cfZero, Fx = $00); SetFlag(cfNegative, (Fx and $80) <> 0); Result := 0; end; function T6502.TAY: UInt8; begin Fy := Fa; SetFlag(cfZero, Fy = $00); SetFlag(cfNegative, (Fy and $80) <> 0); Result := 0; end; function T6502.TSX: UInt8; begin Fx := FStckP; SetFlag(cfZero, Fx = $00); SetFlag(cfNegative, (Fx and $80) <> 0); Result := 0; end; function T6502.TXA: UInt8; begin Fa := Fx; SetFlag(cfZero, Fa = $00); SetFlag(cfNegative, (Fa and $80) <> 0); Result := 0; end; function T6502.TXS: UInt8; begin FStckP := Fx; Result := 0; end; function T6502.TYA: UInt8; begin Fa := Fy; SetFlag(cfZero, Fa = $00); SetFlag(cfNegative, (Fa and $80) <> 0); Result := 0; end; procedure T6502.Write(AAdress: UInt16; AData: UInt8); begin FBus.Write(AAdress, AData); end; function T6502.XXX: UInt8; begin Result := 0; end; function T6502.ZP0: UInt8; begin FAbsoluteAddress := Read(Fpc); System.Inc(Fpc); FAbsoluteAddress := FAbsoluteAddress and $00FF; Result := 0; end; function T6502.ZPX: UInt8; begin FAbsoluteAddress := (Read(Fpc)) + Fx; System.Inc(Fpc); FAbsoluteAddress := FAbsoluteAddress and $00FF; Result := 0; end; function T6502.ZPY: UInt8; begin FAbsoluteAddress := (Read(Fpc)) + Fy; System.Inc(Fpc); FAbsoluteAddress := FAbsoluteAddress and $00FF; Result := 0; end; { T6502Opcode } constructor T6502Opcode.Create(const AName: string; AOpFunc, AAddFunc: TUint8Func; ATotalCycle: UInt8); begin Name := AName; AddressModeFunc := AAddFunc; OperateFunc := AOpFunc; TotalCycle := ATotalCycle; end; end.
{******************************************************************************} { } { Indy (Internet Direct) - Internet Protocols Simplified } { } { https://www.indyproject.org/ } { https://gitter.im/IndySockets/Indy } { } {******************************************************************************} { } { This file is part of the Indy (Internet Direct) project, and is offered } { under the dual-licensing agreement described on the Indy website. } { (https://www.indyproject.org/license/) } { } { Copyright: } { (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { } {******************************************************************************} { } { Originally written by: Fabian S. Biehn } { fbiehn@aagon.com (German & English) } { } { Contributers: } { Here could be your name } { } {******************************************************************************} // This File is auto generated! // Any change to this file should be made in the // corresponding unit in the folder "intermediate"! // Generation date: 28.10.2020 15:24:13 unit IdOpenSSLHeaders_cryptoerr; interface // Headers for OpenSSL 1.1.1 // cryptoerr.h {$i IdCompilerDefines.inc} uses Classes, IdCTypes, IdGlobal, IdOpenSSLConsts; const (* * CRYPTO function codes. *) CRYPTO_F_CMAC_CTX_NEW = 120; CRYPTO_F_CRYPTO_DUP_EX_DATA = 110; CRYPTO_F_CRYPTO_FREE_EX_DATA = 111; CRYPTO_F_CRYPTO_GET_EX_NEW_INDEX = 100; CRYPTO_F_CRYPTO_MEMDUP = 115; CRYPTO_F_CRYPTO_NEW_EX_DATA = 112; CRYPTO_F_CRYPTO_OCB128_COPY_CTX = 121; CRYPTO_F_CRYPTO_OCB128_INIT = 122; CRYPTO_F_CRYPTO_SET_EX_DATA = 102; CRYPTO_F_FIPS_MODE_SET = 109; CRYPTO_F_GET_AND_LOCK = 113; CRYPTO_F_OPENSSL_ATEXIT = 114; CRYPTO_F_OPENSSL_BUF2HEXSTR = 117; CRYPTO_F_OPENSSL_FOPEN = 119; CRYPTO_F_OPENSSL_HEXSTR2BUF = 118; CRYPTO_F_OPENSSL_INIT_CRYPTO = 116; CRYPTO_F_OPENSSL_LH_NEW = 126; CRYPTO_F_OPENSSL_SK_DEEP_COPY = 127; CRYPTO_F_OPENSSL_SK_DUP = 128; CRYPTO_F_PKEY_HMAC_INIT = 123; CRYPTO_F_PKEY_POLY1305_INIT = 124; CRYPTO_F_PKEY_SIPHASH_INIT = 125; CRYPTO_F_SK_RESERVE = 129; (* * CRYPTO reason codes. *) CRYPTO_R_FIPS_MODE_NOT_SUPPORTED = 101; CRYPTO_R_ILLEGAL_HEX_DIGIT = 102; CRYPTO_R_ODD_NUMBER_OF_DIGITS = 103; procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList); procedure UnLoad; var ERR_load_CRYPTO_strings: function: TIdC_INT cdecl = nil; implementation procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList); function LoadFunction(const AMethodName: string; const AFailed: TStringList): Pointer; begin Result := LoadLibFunction(ADllHandle, AMethodName); if not Assigned(Result) then AFailed.Add(AMethodName); end; begin ERR_load_CRYPTO_strings := LoadFunction('ERR_load_CRYPTO_strings', AFailed); end; procedure UnLoad; begin ERR_load_CRYPTO_strings := nil; end; end.
unit ServiceDesktop; interface function InitServiceDesktop: boolean; procedure DoneServiceDeskTop; implementation uses Windows, SysUtils; const DefaultWindowStation = 'WinSta0'; DefaultDesktop = 'Default'; var hwinstaSave: HWINSTA; hdeskSave: HDESK; hwinstaUser: HWINSTA; hdeskUser: HDESK; function InitServiceDesktop: boolean; var dwThreadId: DWORD; begin dwThreadId := GetCurrentThreadID; // Ensure connection to service window station and desktop, and // save their handles. hwinstaSave := GetProcessWindowStation; hdeskSave := GetThreadDesktop(dwThreadId); hwinstaUser := OpenWindowStation(DefaultWindowStation, FALSE, MAXIMUM_ALLOWED); if hwinstaUser = 0 then begin OutputDebugString(PChar('OpenWindowStation failed' + SysErrorMessage(GetLastError))); Result := false; exit; end; if not SetProcessWindowStation(hwinstaUser) then begin OutputDebugString('SetProcessWindowStation failed'); Result := false; exit; end; hdeskUser := OpenDesktop(DefaultDesktop, 0, FALSE, MAXIMUM_ALLOWED); if hdeskUser = 0 then begin OutputDebugString('OpenDesktop failed'); SetProcessWindowStation(hwinstaSave); CloseWindowStation(hwinstaUser); Result := false; exit; end; Result := SetThreadDesktop(hdeskUser); if not Result then OutputDebugString(PChar('SetThreadDesktop' + SysErrorMessage(GetLastError))); end; procedure DoneServiceDeskTop; begin // Restore window station and desktop. SetThreadDesktop(hdeskSave); SetProcessWindowStation(hwinstaSave); if hwinstaUser <> 0 then CloseWindowStation(hwinstaUser); if hdeskUser <> 0 then CloseDesktop(hdeskUser); end; initialization InitServiceDesktop; finalization DoneServiceDesktop; end.
unit uWebgMap; interface uses Forms, SysUtils, Dialogs, Classes, Controls, windows, Registry, UWebGMapsCommon, UWebGMapsGeocoding, UWebGMaps, UWebGMapsMarkers, UWebGMapsClusters; type TmapInfo = record Latitude, Longitude : string; end; function GetMapInfo(address:string): TmapInfo; implementation uses uCOnfig; function GetMapInfo(address:string): TmapInfo; var WebGMapsGeocoding1 : TWebGMapsGeocoding; begin result.Latitude:= '0'; result.Longitude:= '0'; try if address <> '' then begin WebGMapsGeocoding1 := TWebGMapsGeocoding.Create(nil); WebGMapsGeocoding1.APIKey := configValue.varGoogleMapApiKey ; // 'AIzaSyDDXFkSwnTtomsoNXpVSKFoL1WqEcLAaQ0'; WebGMapsGeocoding1.Address := address; if WebGMapsGeocoding1.LaunchGeocoding = erOk then begin result.Latitude := floatToStr( WebGMapsGeocoding1.ResultLatitude); result.Longitude := floatToStr( WebGMapsGeocoding1.ResultLongitude); // updateGogekAddress(id, Latitude, Longitude ); end; end; finally WebGMapsGeocoding1.Free; end; end; end.
(* EasyRSS plugin. Copyright (C) 2012-2014 Silvio Clecio. Please see the LICENSE file. *) unit EasyRSS; {$mode objfpc}{$H+} interface uses DOM, XmlRead, FGL, HTTPDefs, FPHttpClient, Classes, SysUtils; type { TRSSImage } TRSSImage = class private FLink: string; FTitle: string; FUrl: string; function GetContent: string; protected function FormatTag(const AProp, ATag: string): string; public property Content: string read GetContent; property Title: string read FTitle write FTitle; property Url: string read FUrl write FUrl; property Link: string read FLink write FLink; end; { TRSSItem } TRSSItem = class private FAuthor: string; FCategory: string; FComments: string; FDescription: string; Fcontentencoded: string; FGuid: string; FIsPermaLink: Boolean; FLink: string; FPubDate: string; FTitle: string; function GetContent: string; protected function FormatTag(const AProp, ATag: string): string; public constructor Create; property Content: string read GetContent; property Title: string read FTitle write FTitle; property Link: string read FLink write FLink; property Guid: string read FGuid write FGuid; property IsPermaLink: Boolean read FIsPermaLink write FIsPermaLink; property Category: string read FCategory write FCategory; property PubDate: string read FPubDate write FPubDate; property Description: string read FDescription write FDescription; property Contentencoded: string read Fcontentencoded write Fcontentencoded; property Author: string read FAuthor write FAuthor; property Comments: string read FComments write FComments; end; TRSSItems = specialize TFPGList<TRSSItem>; { TRSS } TRSS = class private FCategory: string; FCopyright: string; FDocs: string; FGenerator: string; FImage: TRSSImage; FItems: TRSSItems; FLanguage: string; FLastBuildDate: string; FLink: string; FManagingEditor: string; FPubDate: string; FTitle: string; FUTF8: Boolean; FWebMaster: string; function GetContent: string; procedure FreeItems; function GetCount: Integer; function GetElements(AIndex: Integer): TRSSItem; procedure SetElements(AIndex: Integer; AValue: TRSSItem); protected function FormatTag(const AProp, ATag: string): string; public constructor Create; destructor Destroy; override; function Add: TRSSItem; procedure Clear; property Count: Integer read GetCount; property Content: string read GetContent; property Items: TRSSItems read FItems; property Elements[AIndex: Integer]: TRSSItem read GetElements write SetElements; default; property Title: string read FTitle write FTitle; property Link: string read FLink write FLink; property Language: string read FLanguage write FLanguage; property WebMaster: string read FWebMaster write FWebMaster; property Copyright: string read FCopyright write FCopyright; property PubDate: string read FPubDate write FPubDate; property LastBuildDate: string read FLastBuildDate write FLastBuildDate; property ManagingEditor: string read FManagingEditor write FManagingEditor; property Category: string read FCategory write FCategory; property Generator: string read FGenerator write FGenerator; property Docs: string read FDocs write FDocs; property Image: TRSSImage read FImage write FImage; property UTF8: Boolean read FUTF8 write FUTF8; end; { TRSSReader } TRSSReader = class(TRSS) protected function GetTagValue(ANode: TDOMNode; const ATagName: string): string; public procedure LoadFromStream(AStream: TStream); procedure LoadFromString(const S: string); procedure LoadFromFile(const AFileName: TFileName); procedure LoadFromHttp(const AUrl: string); end; { TRSSWriter } TRSSWriter = class(TRSS) public procedure SaveToStream(AStream: TStream); procedure SaveToFile(const AFileName: TFileName); end; function DateTimeToGMT(const ADateTime: TDateTime): string; function NewGuid: string; implementation type THttp = class(TFPHTTPClient) public procedure GetFeed(const AUrl: string; out AFeed: TStream); end; function DateTimeToGMT(const ADateTime: TDateTime): string; var VYear, VMonth, VDay, VHour, VMinute, VSecond, M: Word; begin DecodeDate(ADateTime, VYear, VMonth, VDay); DecodeTime(ADateTime, VHour, VMinute, VSecond, M); Result := Format('%s, %.2d %s %d %.2d:%.2d:%.2d GMT', [HTTPDays[DayOfWeek(ADateTime)], VDay, HTTPMonths[VMonth], VYear, VHour, VMinute, VSecond]); end; function NewGuid: string; var VGuid: TGuid; begin CreateGUID(VGuid); SetLength(Result, 36); StrLFmt(PChar(Result), 36,'%.8x-%.4x-%.4x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x', [VGuid.D1, VGuid.D2, VGuid.D3, VGuid.D4[0], VGuid.D4[1], VGuid.D4[2], VGuid.D4[3], VGuid.D4[4], VGuid.D4[5], VGuid.D4[6], VGuid.D4[7]]); end; { THttp } procedure THttp.GetFeed(const AUrl: string; out AFeed: TStream); begin AFeed := TMemoryStream.Create; DoMethod('GET', AUrl, AFeed, [200]); end; { TRSSImage } function TRSSImage.GetContent: string; begin Result := ' <image>'+#10+ FormatTag(FTitle, 'title')+ FormatTag(FUrl, 'url')+ FormatTag(FLink, 'link')+ ' </image>'+#10; end; function TRSSImage.FormatTag(const AProp, ATag: string): string; begin if AProp <> '' then Result := ' <'+ATag+'>'+AProp+'</'+ATag+'>'+#10 else Result := ''; end; { TRSSItem } constructor TRSSItem.Create; begin FPubDate := DateTimeToGMT(Now); FGuid := NewGuid; end; function TRSSItem.FormatTag(const AProp, ATag: string): string; begin if AProp <> '' then Result := ' <'+ATag+'>'+AProp+'</'+ATag+'>'+#10 else Result := ''; end; function TRSSItem.GetContent: string; begin Result := ' <item>'+#10+ FormatTag(FTitle, 'title')+ FormatTag(FLink, 'link')+ FormatTag(FAuthor, 'author')+ FormatTag(FComments, 'comments')+ Format(' <guid ispermalink="%s">%s</guid>', [BoolToStr(FIsPermaLink, 'true', 'false'), FGuid])+#10+ FormatTag(FCategory, 'category')+ FormatTag(FPubDate, 'pubdate')+ FormatTag(FDescription, 'description')+ FormatTag(Fcontentencoded, 'content:encoded')+ ' </item>'+#10; end; { TRSS } constructor TRSS.Create; begin FItems := TRSSItems.Create; FUTF8 := True; FLanguage := 'en-us'; FGenerator := 'EasyRSS plugin'; FPubDate := DateTimeToGMT(Now); FLastBuildDate := DateTimeToGMT(Now); end; destructor TRSS.Destroy; begin FreeAndNil(FImage); FreeItems; FItems.Free; inherited Destroy; end; function TRSS.GetCount: Integer; begin Result := FItems.Count; end; function TRSS.GetElements(AIndex: Integer): TRSSItem; begin Result := FItems[AIndex]; end; procedure TRSS.SetElements(AIndex: Integer; AValue: TRSSItem); begin FItems[AIndex] := AValue; end; function TRSS.GetContent: string; var I: Integer; begin Result := '<rss version="2.0">'+#10+ ' <channel>'+#10+ ' <title>'+FTitle+'</title>'+#10+ FormatTag(FGenerator, 'generator')+ FormatTag(FLink, 'link')+ FormatTag(FLanguage, 'language')+ FormatTag(FWebMaster, 'webmaster')+ FormatTag(FCopyright, 'copyright')+ FormatTag(FPubDate, 'pubdate')+ FormatTag(FLastBuildDate, 'lastbuilddate')+ FormatTag(FCategory, 'category')+ FormatTag(FDocs, 'docs')+ FormatTag(FManagingEditor, 'managingeditor'); if Assigned(FImage) then Result += FImage.Content; for I := 0 to Pred(FItems.Count) do Result += TRSSItem(FItems[I]).Content; Result += ' </channel>'+#10+ '</rss>'; end; procedure TRSS.FreeItems; var I: Integer; begin for I := 0 to Pred(FItems.Count) do TObject(FItems[I]).Free; end; function TRSS.FormatTag(const AProp, ATag: string): string; begin if AProp <> '' then Result := ' <'+ATag+'>'+AProp+'</'+ATag+'>'+#10 else Result := ''; end; function TRSS.Add: TRSSItem; begin Result := TRSSItem.Create; FItems.Add(Result); end; procedure TRSS.Clear; begin FreeItems; FItems.Clear; end; { TRSSReader } function TRSSReader.GetTagValue(ANode: TDOMNode; const ATagName: string): string; var VNode: TDOMNode; begin Result := ''; if Assigned(ANode) then begin VNode := ANode.FindNode(DOMString(ATagName)); if Assigned(VNode) then begin if FUTF8 then Result := UTF8Encode(VNode.TextContent) else Result := string(VNode.TextContent); end; end; end; procedure TRSSReader.LoadFromStream(AStream: TStream); var VRssItem: TRSSItem; VXml: TXMLDocument; VXmlChannel, VXmlImage, VXmlItem, VPermaLink: TDOMNode; begin try ReadXMLFile(VXml, AStream); VXmlChannel := VXml.DocumentElement.FindNode('channel'); FTitle := GetTagValue(VXmlChannel, 'title'); FLink := GetTagValue(VXmlChannel, 'link'); FLanguage := GetTagValue(VXmlChannel, 'language'); FWebMaster := GetTagValue(VXmlChannel, 'webmaster'); FCopyright := GetTagValue(VXmlChannel, 'copyright'); FPubDate := GetTagValue(VXmlChannel, 'pubdate'); FLastBuildDate := GetTagValue(VXmlChannel, 'lastbuilddate'); FManagingEditor := GetTagValue(VXmlChannel, 'managingeditor'); FCategory := GetTagValue(VXmlChannel, 'category'); FGenerator := GetTagValue(VXmlChannel, 'generator'); FDocs := GetTagValue(VXmlChannel, 'docs'); VXmlImage := VXmlChannel.FindNode('image'); if Assigned(VXmlImage) then begin if not Assigned(FImage) then FImage := TRSSImage.Create; FImage.Title := GetTagValue(VXmlImage, 'title'); FImage.Url := GetTagValue(VXmlImage, 'url'); FImage.Link := GetTagValue(VXmlImage, 'link'); end; VXmlItem := VXmlChannel.FindNode('item'); Clear; while Assigned(VXmlItem) do begin VRssItem := TRSSItem.Create; VRssItem.Title := GetTagValue(VXmlItem, 'title'); VRssItem.Link := GetTagValue(VXmlItem, 'link'); VRssItem.Guid := GetTagValue(VXmlItem, 'guid'); VPermaLink := VXmlItem.FindNode('guid'); if Assigned(VPermaLink) then begin VPermaLink := VPermaLink.Attributes.GetNamedItem('ispermalink'); if Assigned(VPermaLink) then VRssItem.IsPermaLink := StrToBoolDef( string(VPermaLink.TextContent), False); end; VRssItem.Category := GetTagValue(VXmlItem, 'category'); VRssItem.PubDate := GetTagValue(VXmlItem, 'pubdate'); VRssItem.Description := GetTagValue(VXmlItem, 'description'); VRssItem.Contentencoded := GetTagValue(VXmlItem, 'content:encoded'); VRssItem.Author := GetTagValue(VXmlItem, 'author'); VRssItem.Comments := GetTagValue(VXmlItem, 'comments'); FItems.Add(VRssItem); VXmlItem := VXmlItem.NextSibling; end; finally FreeAndNil(VXml); end; end; procedure TRSSReader.LoadFromString(const S: string); var VString: TStringStream; begin VString := TStringStream.Create(S); try LoadFromStream(VString); finally VString.Free; end; end; procedure TRSSReader.LoadFromFile(const AFileName: TFileName); var VFile: TFileStream; begin VFile := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(VFile); finally VFile.Free; end; end; procedure TRSSReader.LoadFromHttp(const AUrl: string); var VHttp: THttp; VFeed: TStream; begin VHttp := THttp.Create(nil); try VHttp.GetFeed(AUrl, VFeed); VFeed.Position := 0; LoadFromStream(VFeed); finally FreeAndNil(VFeed); VHttp.Free; end; end; { TRSSWriter } procedure TRSSWriter.SaveToStream(AStream: TStream); var S: String; begin S := GetContent; AStream.Write(Pointer(S)^, Length(S)); end; procedure TRSSWriter.SaveToFile(const AFileName: TFileName); var VFile: TFileStream; begin VFile := TFileStream.Create(AFileName, fmCreate); try SaveToStream(VFile); finally VFile.Free; end; end; end.
unit MainUnit; interface uses SDL, SDLKeyDatas; procedure FirstInit; function GetSDLFlags: LongWord; procedure InitGame; procedure DoEvents; function DoTime: LongWord; procedure DoPhysics(dT: LongWord); procedure DoGraphics; procedure CleanupGame; var LastTime: LongWord; Screen: PSDL_Surface; Done: Boolean = False; KeyData: TKeyData; implementation uses SysUtils, Math, Randomity, GL, GLD, GLImages, DUtils, D3Vectors, SpaceTextures, Buildings, BuildScripts; type TFColor = record R, G, B: TReal; end; TPlayerData = record Loc, Facing: T3Vector; Speed: TReal; end; TCameraData = record Loc, Facing: T3Vector; MouseYaw, MousePitch: TReal; FM: array[0..15] of Single; end; var Rot: TReal; Player: TPlayerData; Camera: TCameraData; FrameRate, SmoothedFrameRate: TReal; MouseSensitivity: TReal; bHasFocus: Boolean = True; procedure FirstInit; begin end; function GetSDLFlags: LongWord; begin Result := SDL_INIT_VIDEO; //Flags := Flags or SDL_INIT_AUDIO; end; procedure GenProcTextures; const kBlack: TRGBAColor = ( R: 0; G: 0; B: 0; A: 255 ); var ThisImage, ThatImage: TGLImage; I, X, Y, dX, dY, eX, eY: Integer; M, nM, ThatLight: TReal; C: TRGBAColor; Lights: array[0..19, 0..19] of TReal; begin ThisImage := TGLImage.Create; ThatImage := TGLImage.Create; ThisImage.Resize(256, 256, kBlack); ThatImage.Resize(256, 256, kBlack); //Random seed. for Y := 0 to 255 do for X := 0 to 255 do ThatImage.GreyPixel[X, Y] := RandByte ; //Blur. for Y := 0 to 255 do for X := 0 to 255 do ThisImage.GreyPixel[X, Y] := ( ThatImage.GreyPixel[X, Y] + ThatImage.GreyPixel[Byte(X + 255), Y] + ThatImage.GreyPixel[Byte(X + 1), Y] + ThatImage.GreyPixel[X, Byte(Y + 255)] + ThatImage.GreyPixel[X, Byte(Y + 1)] + 2) div 5 ; RoofTex := ThisImage.BakeToL; //Darken. for Y := 0 to 255 do for X := 0 to 255 do ThatImage.GreyPixel[X, Y] := ThisImage.GreyPixel[X, Y] shr 2 ; AsphaltTex := ThatImage.BakeToL; //Green. C := kBlack; for Y := 0 to 255 do for X := 0 to 255 do begin C.G := ThisImage.Pixel[X, Y].G; ThatImage.Pixel[X, Y] := C; end ; BushyTex := ThatImage.BakeToRGBA; FreeAndNil(ThatImage); //Lighten. for Y := 0 to 255 do for X := 0 to 255 do ThisImage.GreyPixel[X, Y] := (ThisImage.GreyPixel[X, Y] shr 1) or $80 ; ConcreteTex := ThisImage.BakeToL; //Bevel. for Y := 0 to 255 do for X := 0 to 7 do begin if X >= Y then Continue; if X >= 255-Y then Continue; M := X*(1/8); nM := 1 - M; ThisImage.GreyPixel[X, Y] := Round(ThisImage.GreyPixel[X, Y]*M + 255*nM); ThisImage.GreyPixel[255-X, Y] := Round(ThisImage.GreyPixel[255-X, Y]*M); //I know, it's kinda lame, but I already had everything calculated... ThisImage.GreyPixel[Y, X] := Round(ThisImage.GreyPixel[Y, X]*M + 255*nM); ThisImage.GreyPixel[Y, 255-X] := Round(ThisImage.GreyPixel[Y, 255-X]*M); end ; for I := 0 to 7 do begin M := I*(1/8); nM := 1 - M; ThisImage.GreyPixel[I, I] := Round(ThisImage.GreyPixel[I, I]*M + 255*nM); ThisImage.GreyPixel[255-I, 255-I] := Round(ThisImage.GreyPixel[255-I, 255-I]*M); end; SidewalkTex := ThisImage.BakeToL; ThisImage.Resize(160*3, 160*3, kBlack); //Randomly assign light levels to windows. for Y := 0 to 19 do for X := 0 to 19 do Lights[X, Y] := RandReal ; //Repeatedly blur adjacent-window light levels. for I := 1 to 6 do for Y := 0 to 19 do begin ThatLight := Lights[0, Y]; for X := 0 to 18 do begin M := RandReal; nM := 1 - M; Lights[X, Y] := Lights[X, Y]*M + Lights[X+1, Y]*nM; end; M := RandReal; nM := 1 - M; Lights[19, Y] := Lights[19, Y]*M + ThatLight*nM; end ; //Mostly snap to on or off. for Y := 0 to 19 do for X := 0 to 19 do Lights[X, Y] := Lights[X, Y]*0.4 + Ord(Lights[X, Y] >= 0.6)*0.6 ; //Final render. Upsampled for gluBuild2DMipmaps. for Y := 0 to 19 do for X := 0 to 19 do for dY := 3 to 6 do for dX := 1 to 6 do begin M := Lights[X, Y]*(dY-3)*(1/3); nM := Lights[X, Y]*(1 - M); with C do begin Color := (RandDWord and $01010101) * 255; R := (R + A) shr 1; G := (G + A) shr 1; B := (B + A) shr 1; R := Round(255*M + R*nM); G := Round(255*M + G*nM); B := Round(255*M + B*nM); A := 255; end; for eY := 0 to 2 do for eX := 0 to 2 do ThisImage.Pixel[(X*8+dX)*3+eX, (Y*8+dY)*3+eY] := C ; end ; WindowedTex := ThisImage.BakeToRGBA; FreeAndNil(ThisImage); end; { procedure NewBuildings; var iX, iZ: Integer; begin if Length(Neighborhood) = 0 then begin SetLength(Neighborhood, 1); Neighborhood[0] := TNeighborhood.Create; end; with Neighborhood[0] do for iX := Low(CityBlock) to High(CityBlock) do for iZ := Low(CityBlock[iX]) to High(CityBlock[iX]) do with CityBlock[iX, iZ] do begin PropertyValue := 192 + RandN(20) - Abs(iX) - Abs(iZ); if PropertyValue > 200 then Building := CubistTumorBuilding(CityBlock[iX, iZ]) else if PropertyValue > 195 then Building := GenSkyscraperBuilding(CityBlock[iX, iZ]) else if PropertyValue = 191 then Building := SmallParkBuilding(CityBlock[iX, iZ]) else if PropertyValue = 190 then Building := ParkingBuilding(CityBlock[iX, iZ]) else Building := GenericBuilding(CityBlock[iX, iZ]) ; OffsetBuilding(Building, Vector(26*iX, 0, 26*iZ)); end ; end; } function ExtractMousePos: TPoint; var X, Y, cX, cY: Integer; begin cX := Screen.w div 2; cY := Screen.h div 2; SDL_GetMouseState(X, Y); SDL_WarpMouse(cX, cY); Result.X := X - cX; Result.Y := Y - cY; end; procedure InitGame; const NearClip = 0.1; FarClip = NearClip * 20000; var AspectRoot, iAspectRoot: TReal; begin SDL_WM_SetCaption('Space', 'Space'); //Reset the current viewport. glViewport(0, 0, Screen.w, Screen.h); //Reset the projection matrix. glMatrixMode(GL_PROJECTION); glLoadIdentity(); AspectRoot := SqRt(Screen.w / Screen.h); iAspectRoot := 1 / AspectRoot; glFrustum(-NearClip/2 * AspectRoot, +NearClip/2 * AspectRoot, -NearClip/2 * iAspectRoot, +NearClip/2 * iAspectRoot, NearClip, FarClip); //Reset the modelview matrix. glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //Enable texture mapping. glEnable(GL_TEXTURE_2D); //Enable polycoloring. glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT, GL_DIFFUSE); //glMaterialfv(GL_FRONT, GL_AMBIENT, InstantArrayPtr(0, 0, 0, 1)); //glMaterialfv(GL_BACK, GL_AMBIENT_AND_DIFFUSE, InstantArrayPtr(1, 0, 0, 1)); //Enable vertex shading. glShadeModel(GL_SMOOTH); //Leave alpha blending off, but configure ahead of time for the few alpha-blended textures. //glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //Enable depth testing. glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); //Set clear color to black. glClearColor(0, 0, 0, 0); //Set clear depth to max. glClearDepth(1.0); //Really nice perspective calculations. glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //Enable lighting. glEnable(GL_LIGHTING); //glLightModelfv(GL_LIGHT_MODEL_AMBIENT, InstantArrayPtr(0.0, 0.0, 0.0, 1)); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, InstantArrayPtr(0.05, 0.025, 0.0, 1)); glEnable(GL_LIGHT0); //glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 1); //glLightfv(GL_LIGHT0, GL_AMBIENT, InstantArrayPtr(0.125, 0.125, 0.125, 1)); //glLightfv(GL_LIGHT0, GL_DIFFUSE, InstantArrayPtr(0.5, 0.5, 0.5, 1)); //glLightfv(GL_LIGHT0, GL_SPECULAR, InstantArrayPtr(0.25, 0.25, 0.5, 1)); glLightfv(GL_LIGHT0, GL_DIFFUSE, InstantArrayPtr(0.3, 0.35, 0.4, 1)); { //Enable lighting. glEnable(GL_LIGHTING); //glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.1); glLightfv(GL_LIGHT0, GL_AMBIENT, InstantArrayPtr(0.1, 0.1, 0.1, 1)); glLightfv(GL_LIGHT0, GL_DIFFUSE, InstantArrayPtr(1, 1, 1, 1)); //glLightfv(GL_LIGHT0, GL_SPECULAR, InstantArrayPtr(0.25, 0.25, 0.5, 1)); glEnable(GL_LIGHT0); //glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1); } KeyData := TKeyData.Create; LoadTexFont(MyFont, 'Verdana.ccf'); { InitGLibAperture; hStarImg := LoadRGBAPNG('Star.png'); } GenProcTextures; SetBoundTexture(0); LoadBuildScript; //NewBuildings; SetLength(Neighborhood, 1); Neighborhood[0] := BuildNeighborhoodFromType(NeighborhoodType[0]); Player.Loc := Vector(0, 0.5, 13); Player.Facing.Z := -1; Camera.Loc := Player.Loc; Camera.Facing := Player.Facing; Player.Speed := 3; MouseSensitivity := 8000 / Screen.w; ExtractMousePos; end; procedure CleanupGame; var I: Integer; begin for I := 0 to High(Neighborhood) do FreeAndNil(Neighborhood[I]); SetLength(Neighborhood, 0); for I := 0 to High(NeighborhoodType) do FreeAndNil(NeighborhoodType[I]); SetLength(NeighborhoodType, 0); for I := 0 to High(Faction) do FreeAndNil(Faction[I]); SetLength(Faction, 0); for I := 0 to High(FactionType) do FreeAndNil(FactionType[I]); SetLength(FactionType, 0); FreeAndNil(KeyData); glDeleteTextures(1, @WindowedTex); glDeleteTextures(1, @RoofTex); glDeleteTextures(1, @ConcreteTex); glDeleteTextures(1, @SidewalkTex); glDeleteTextures(1, @AsphaltTex); glDeleteTextures(1, @BushyTex); end; procedure DoEvents; var Event: TSDL_Event; begin while SDL_PollEvent(@Event) <> 0 do case event.type_ of SDL_ACTIVEEVENT: begin if (event.active.state and SDL_APPINPUTFOCUS) <> 0 then bHasFocus := event.active.gain <> 0; if bHasFocus then ExtractMousePos; end; { SDL_ACTIVEEVENT: if ((event.active.state and SDL_APPINPUTFOCUS) <> 0) and Player.bWantMouselook and (event.active.gain <> Byte(Ord(Player.bMouselook))) then begin SDL_ShowCursor(Ord(Player.bMouselook)); Player.bMouselook := not Player.bMouselook; if Player.bMouselook then SetCursorPos(Screen.w div 2, Screen.h div 2); end; } SDL_QUITEV: Done := True; SDL_KEYDOWN: begin if (event.key.keysym.sym = SDLK_Escape) and (KeyData.BuckyState = []) then Done := True; //if (event.key.keysym.sym = SDLK_Return) and (KeyData.BuckyState = []) then NewBuildings(); //if (event.key.keysym.sym = SDLK_S) and (KeyData.BuckyState = [bkCtrl]) then Player.DoSaveClick(event.key.keysym.sym); if event.key.keysym.sym < 512 then KeyData.KeyDown[event.key.keysym.sym] := True; end; SDL_KEYUP: if event.key.keysym.sym < 512 then KeyData.KeyDown[event.key.keysym.sym] := False; SDL_MOUSEBUTTONDOWN: if Event.button.button < SDLK_BACKSPACE then KeyData.KeyDown[Event.button.button] := True; SDL_MOUSEBUTTONUP : if Event.button.button < SDLK_BACKSPACE then KeyData.KeyDown[Event.button.button] := False; //SDL_MOUSEMOTION: ; end; end; function DoTime: LongWord; var ThisTime: LongWord; begin repeat DoEvents; ThisTime := SDL_GetTicks(); if ThisTime <> LastTime then Break; Sleep(0); until False; Result := ThisTime - LastTime; LastTime := ThisTime; if Result > 50 then Result := 50; end; procedure DoPhysics(dT: LongWord); const VNZ: T3Vector = (X: 0; Y: 0; Z: -1); var fdT: TReal; J, R, U: T3Vector; I: Integer; dMus: TPoint; begin fdT := dT * 0.001; FrameRate := 1 / fdT; SmoothedFrameRate := SmoothedFrameRate * 0.9 + FrameRate * 0.1; if fdT > 0.1 then fdT := 0.1; Rot := Rot + fdT * 360/45; if Rot >= 360 then Rot := Rot - 360; if bHasFocus then begin //Change camera facing based on mouselook. dMus := ExtractMousePos; with Camera do begin MouseYaw := MouseYaw - dMus.X*MouseSensitivity*fdT; MousePitch := Min(80, Max(-80, MousePitch + dMus.Y*MouseSensitivity*fdT)); Facing := VYaw(MouseYaw, VPitch(MousePitch, VNZ)); end; end; R := VNormal(VCrossProd(Camera.Facing, VY)); //Change player facing towards camera facing. U := VProd(Camera.Facing, 0.1); for I := 1 to dT do Player.Facing := VSum(VProd(Player.Facing, 0.9), U) ; VNormalize(Player.Facing); //Player movement. J.X := Ord(KeyData[SDLK_Right] or KeyData[SDLK_KP_Right]) - Ord(KeyData[SDLK_Left] or KeyData[SDLK_KP_Left]); J.Y := Ord(KeyData[SDLK_KP_Plus]) - Ord(KeyData[SDLK_KP_Enter]); J.Z := Ord(KeyData[SDLK_Up] or KeyData[SDLK_KP_Up]) - Ord(KeyData[SDLK_Down] or KeyData[SDLK_KP_Down]); if J.X <> 0 then VADD(Player.Loc, VProd(R, Player.Speed * J.X * fdT)); if J.Y <> 0 then VADD(Player.Loc, VProd(VY, Player.Speed * J.Y * fdT)); if J.Z <> 0 then VADD(Player.Loc, VProd(Camera.Facing, Player.Speed * J.Z * fdT)); KeyData.ClearPress; //Move camera to player. Camera.Loc := Player.Loc; //Build OpenGL matrix to represent camera facing. with Camera do begin U := VNormal(VCrossProd(R, Facing)); FM[0] := R.X; FM[1] := U.X; FM[2] := -Facing.X; FM[3] := 0; FM[4] := R.Y; FM[5] := U.Y; FM[6] := -Facing.Y; FM[7] := 0; FM[8] := R.Z; FM[9] := U.Z; FM[10] := -Facing.Z; FM[11] := 0; FM[12] := 0; FM[13] := 0; FM[14] := 0; FM[15] := 1; end; end; function VAvg(const A, B: T3Vector): T3Vector; begin Result.X := (A.X + B.X) * 0.5; Result.Y := (A.Y + B.Y) * 0.5; Result.Z := (A.Z + B.Z) * 0.5; end; procedure Triangle(const A, B, C: T3Vector); begin with A do glVertex3f(X, Y, Z); with B do glVertex3f(X, Y, Z); with C do glVertex3f(X, Y, Z); end; procedure SubdividedTriangle(const A, B, C: T3Vector; Subdivision: LongWord); var AB, BC, CA: T3Vector; begin AB := VAvg(A, B); BC := VAvg(B, C); CA := VAvg(C, A); if Subdivision > 1 then begin Dec(Subdivision); SubdividedTriangle(AB, BC, CA, Subdivision); SubdividedTriangle(A, AB, CA, Subdivision); SubdividedTriangle(B, BC, AB, Subdivision); SubdividedTriangle(C, CA, BC, Subdivision); end else begin Triangle(AB, BC, CA); Triangle(A, AB, CA); Triangle(B, BC, AB); Triangle(C, CA, BC); end; end; procedure TriangleWithNormals(const A, B, C: T3Vector; Subdivision: LongWord = 0); var xA, xB, N: T3Vector; begin //Split triangle into two vectors, B and C from A xA := VDiff(B, A); xB := VDiff(C, A); //N = normal cross product of xA and xB N := VNormal(VCrossProd(xA, xB)); with N do glNormal3f(X, Y, Z); if Subdivision = 0 then Triangle(A, B, C) else SubdividedTriangle(A, B, C, Subdivision) ; end; procedure DrawTriforce(ES, EC: Extended); begin glBegin(GL_TRIANGLES); TriangleWithNormals(Vector(0, 0, -0.2), Vector(ES, EC, 0), Vector(-ES, EC, 0)); TriangleWithNormals(Vector(0, 1, 0), Vector(0, 0, -0.2), Vector(-ES, EC, 0)); TriangleWithNormals(Vector(0, 1, 0), Vector(ES, EC, 0), Vector(0, 0, -0.2)); TriangleWithNormals(Vector(0, 0, +0.2), Vector(ES, EC, 0), Vector(0, 1, 0)); TriangleWithNormals(Vector(-ES, EC, 0), Vector(0, 0, +0.2), Vector(0, 1, 0)); TriangleWithNormals(Vector(-ES, EC, 0), Vector(ES, EC, 0), Vector(0, 0, +0.2)); glEnd; end; procedure PrintFPS(bX, bY, bZ, ThisRate: TReal); var I: Integer; Buf: String; begin Buf := IntToStr(Round(ThisRate)) + ' FPS'; for I := 1 to Length(Buf) do begin SetBoundTexture(MyFont[Byte(Buf[I])]); glBegin(GL_QUADS); glTexCoord2i(0, 0); glVertex3f(bX + I - 1, bY + 1, bZ); glTexCoord2i(0, 1); glVertex3f(bX + I - 1, bY - 1, bZ); glTexCoord2i(1, 1); glVertex3f(bX + I + 1, bY - 1, bZ); glTexCoord2i(1, 0); glVertex3f(bX + I + 1, bY + 1, bZ); glEnd; end; end; procedure RenderNeighborhoodWithStyle(N: TNeighborhood; Style: TPolyStyles); var iD, iX, iZ: Integer; begin with N do begin {//The naive implementation, in case the optimization becomes a problem. for iX := Low(CityBlock) to High(CityBlock) do for iZ := Low(CityBlock[iX]) to High(CityBlock[iX]) do RenderBuildingWithStyle(CityBlock[iX, iZ].Building, Style) ; } RenderBuildingWithStyle(CityBlock[0, 0].Building, Style); for iD := 1 to 20 do begin for iX := -iD to +iD do begin RenderBuildingWithStyle(CityBlock[iX, -iD].Building, Style); RenderBuildingWithStyle(CityBlock[iX, +iD].Building, Style); end; for iZ := -iD+1 to +iD-1 do begin RenderBuildingWithStyle(CityBlock[-iD, iZ].Building, Style); RenderBuildingWithStyle(CityBlock[+iD, iZ].Building, Style); end; end; end; end; procedure DoGraphics; begin glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glColor3f(1, 1, 1); glPushMatrix; glMultMatrixf(@Camera.FM[0]); //`@ Skybox... //glDisable(GL_DEPTH_TEST); //glEnable(GL_DEPTH_TEST); with Camera.Loc do glTranslatef(-X, -Y, -Z); glLightfv(GL_LIGHT0, GL_POSITION, InstantArrayPtr(-7, 13, 15, 0)); //Directional light. //`@ Eventually, we should split the polies by texture and style. //`@ And then sort the closest to the camera first. glDisable(GL_LIGHTING); RenderNeighborhoodWithStyle(Neighborhood[0], []); glEnable(GL_LIGHTING); RenderNeighborhoodWithStyle(Neighborhood[0], [psLit]); SetBoundTexture(AsphaltTex); //SetBoundTexture(ConcreteTex); glBegin(GL_QUADS); glNormal3f(0, 1, 0); glTexCoord2f(0, 1066); glVertex3f(-533, 0, 533); glTexCoord2f(1066, 1066); glVertex3f(533, 0, 533); glTexCoord2f(1066, 0); glVertex3f(533, 0, -533); glTexCoord2f(0, 0); glVertex3f(-533, 0, -533); glEnd; glPopMatrix; glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); if FrameRate < 10 then glColor3f(1, 0, 0) else glColor3f(1, 1, 1) ; PrintFPS(-15, +10, -30, FrameRate); if SmoothedFrameRate < 10 then glColor3f(1, 0, 0) else glColor3f(1, 1, 1) ; PrintFPS(-15, +8, -30, SmoothedFrameRate); glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); SDL_GL_SwapBuffers(); end; end.
unit DW.Toast.Android; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // Android Androidapi.JNI.Os, Androidapi.JNI.JavaTypes, Androidapi.JNIBridge; type TToast = class(TJavaLocal, JRunnable) private class var FToast: TToast; class destructor DestroyToast; private FHandler: JHandler; FMsg: string; FShort: Boolean; public { JRunnable } procedure run; cdecl; public /// <summary> /// Convenience equivalent of MakeToast /// </summary> class procedure Make(const AMsg: string; const AShort: Boolean); public constructor Create; /// <summary> /// Shows a toast with the message provided, for the length specified /// </summary> procedure MakeToast(const AMsg: string; const AShort: Boolean); end; implementation uses // Android Androidapi.Helpers, // DW DW.Androidapi.JNI.Toast; { TToast } constructor TToast.Create; begin inherited; FHandler := TJHandler.JavaClass.init(TJLooper.JavaClass.getMainLooper); end; class destructor TToast.DestroyToast; begin FToast.Free; end; class procedure TToast.Make(const AMsg: string; const AShort: Boolean); begin if FToast = nil then FToast := TToast.Create; FToast.MakeToast(AMsg, AShort); end; procedure TToast.MakeToast(const AMsg: string; const AShort: Boolean); begin FMsg := AMsg; FShort := AShort; FHandler.post(Self); end; procedure TToast.run; var LToastLength: Integer; begin if FShort then LToastLength := TJToast.JavaClass.LENGTH_SHORT else LToastLength := TJToast.JavaClass.LENGTH_LONG; TJToast.JavaClass.makeText(TAndroidHelper.Context.getApplicationContext, StrToJCharSequence(FMsg), LToastLength).show; end; end.
unit XRetrieval; interface uses Retrieval, Func1D, SignalField, NLO, FrogTrace, Strategy; type TXRetrieval = class(TRetrieval) private mERef: TEField; procedure MakeSignalField(pEk: TEField; pESig: TSignalField); override; function GetRescaleFactor(pXmin: double): double; override; procedure SetCurrentStrategy(pCurrStrat: TStrategy); override; procedure CenterRetrievedField; override; public property ReferenceField: TEField read mERef write mERef; constructor Create(pNLO: TNLOInteraction; pFrogI, pFrogIk: TFrogTrace; pEk, pERef: TEField); end; implementation constructor TXRetrieval.Create(pNLO: TNLOInteraction; pFrogI, pFrogIk: TFrogTrace; pEk, pERef: TEField); begin mERef := pERef; // This needs to be first. inherited Create(pNLO, pFrogI, pFrogIk, pEk); end; procedure TXRetrieval.MakeSignalField(pEk: TEField; pESig: TSignalField); begin mNLOInteraction.MakeXSignalField(pEk, mERef, pEsig); end; procedure TXRetrieval.CenterRetrievedField; begin // Don't center the retrieved field in XFROG end; function TXRetrieval.GetRescaleFactor(pXmin: double): double; begin // For XFrog, the signal field is always linear in the test field GetRescaleFactor := 0.5; end; procedure TXRetrieval.SetCurrentStrategy(pCurrStrat: TStrategy); begin mCurrentStrategy := pCurrStrat; mCurrentStrategy.ReferenceField := mERef; end; end.
unit Tasker.Plugin.Condition; interface type TDummy = class end; //// ----------------------------- CONDITION/EVENT PLUGIN ONLY --------------------------------- // // // public static class Condition { // // /** // * Used by: plugin QueryReceiver // * // * Indicates to plugin whether the host will process variables which it passes back // * // * @param extrasFromHost intent extras from the intent received by the QueryReceiver // * @see #addVariableBundle(Bundle, Bundle) // */ // public static boolean hostSupportsVariableReturn( Bundle extrasFromHost ) { // return hostSupports( extrasFromHost, EXTRA_HOST_CAPABILITY_CONDITION_RETURN_VARIABLES ); // } // } implementation end.
unit IdTest; { uses rtti helper from http://chris.lichti.org/Lab/RTTI_Lib/RTTI_Lib.shtml demonstrates how to use rtti to discover and call published methods } interface uses classes, sysutils, clRtti, btTest; type TIdTest = class; TIdTestClass = class of TIdTest; TIdTestMethod = procedure of object; //TIdTest adapts indy's test classes to my test framework TIdTest = class(TbtTest) protected //this is what my test framework calls procedure btDoTest;override; public //this is the only method that has to be provided class procedure RegisterTest(const aClass:TbtTestClass); end; implementation procedure TIdTest.btDoTest; var i:Integer; aList:TStringList; aMethod:TMethod; aObjMethod:TIdTestMethod; begin inherited; aList:=TStringList.Create; try //build list of published methods for this class GetMethodList(Self,aList); //for each method, check it runs without failure for i:=0 to aList.Count-1 do begin aMethod.Code:=Pointer(aList.Objects[i]); aMethod.Data:=Self; aObjMethod:=TIdTestMethod(aMethod); //run the test //aTest.DoBeforeTest; try btExpectPass(aObjMethod); finally // aTest.DoAfterTest; end; end; finally FreeAndNil(aList); end; end; class procedure TIdTest.RegisterTest(const aClass:TbtTestClass); begin //singleton list where test classes are registered in my framework SbtTestClassList.Add(aClass); end; end.
(****************************************************************************** PROYECTO FACTURACION ELECTRONICA Copyright (C) 2010-2014 - Bambu Code SA de CV Define las estructuras usadas como parametros para generar la factura electrónica. Pensado por si en el futuro el SAT cambia las estructuras sean fácilmente extendibles sin necesidad de cambiar el código que lo haya usado con anterioridad. Este archivo pertenece al proyecto de codigo abierto de Bambu Code: http://bambucode.com/codigoabierto La licencia de este codigo fuente se encuentra en: http://github.com/bambucode/tfacturaelectronica/blob/master/LICENCIA ******************************************************************************) unit FacturaTipos; interface uses SysUtils; type // El tipo de String en el que debe estar codificada la "Cadena Original" // ya que al estar en UTF8 Delphi 2007 necesita que sea del tipo UTF8String // y si es Delphi 2009 o superior necesita que sea RawByteString // Si NO se usan estos tipos de datos se pierden caracteres en memoria {$IF Compilerversion >= 20} TStringCadenaOriginal = RawByteString; {$ELSE} TStringCadenaOriginal = UTF8String; {$IFEND} TFEFolio = Integer; TFESerie = String[10]; TFEFormaDePago = (fpUnaSolaExhibicion, fpParcialidades); TFETipoComprobante = (tcIngreso, tcEgreso, tcTraslado); // Versiones de CFD soportadas, en caso de que se lea un XML y no este dentro de estas versiones // se lanzara una excepcion TFEVersionComprobante = (fev20, fev22,fev32); TFEDireccion = record Calle: String; NoExterior: String; NoInterior: String; CodigoPostal: String; Colonia: String; Municipio: String; Estado: String; Pais: String; Localidad: String; Referencia: String; end; // Expedido en es un "alias" de direccion, la definimos por si en el // futuro diferente en algo a al direccion TFEExpedidoEn = TFEDireccion; TFEDocumentoAduanero = record Numero: String; Fecha: TDateTime; Aduana: String; end; TFERFC = String[13]; // Un regimen es una cadena TFERegimenes = Array of String; TFEContribuyente = record Nombre: String; RFC: TFERFC; Direccion: TFeDireccion; ExpedidoEn: TFEExpedidoEn; // Un contribuyente puede tener muchos regímenes fiscales Regimenes : TFERegimenes; // Atributo opcional para almacenar el correo del contribuyente CorreoElectronico : String; end; // Pre-definimos los tipos de contribuyentes de Publico en General y Extranjero TContribuyentePublicoGeneral = TFEContribuyente; TContribuyenteExtranjero = TFEContribuyente; TFEDatosAduana = record NumeroDocumento: String; FechaExpedicion: TDateTime; Aduana: String; end; TFEConcepto = record Cantidad: Double; Unidad: String; Descripcion: String; ValorUnitario: Currency; // Almacenamos los valores globales ValorUnitarioFinal: Currency; Importe : Currency; // Datos opcionales NoIdentificacion: String; DatosAduana: TFEDatosAduana; CuentaPredial: String; Extra: String; end; TFEConceptos = Array of TFEConcepto; TFELlavePrivada = record Ruta: String; Clave: String; end; // Tipo del certificado leido (usado por Clase TCertificadoSellos) TFETipoCertificado = (tcSellos, tcFIEL); TFECertificado = record Ruta: String; LlavePrivada: TFELlavePrivada; VigenciaInicio: TDateTime; VigenciaFin: TDateTime; NumeroSerie: String; RFCAlQuePertenece: string; end; TFEBloqueFolios = record NumeroAprobacion: Integer; AnoAprobacion: Integer; Serie: TFESerie; // Opcional FolioInicial: Integer; FolioFinal: Integer; end; TFEImpuestoRetenido = record Nombre : String; // IVA, ISR Importe: Currency; end; TFEImpuestosRetenidos = Array of TFEImpuestoRetenido; TTipoImpuestoLocal = (tiRetenido, tiTrasladado); TFEImpuestoLocal = record Nombre: String; Tasa: Double; Importe : Currency; Tipo: TTipoImpuestoLocal; end; TFEImpuestosLocales = Array of TFEImpuestoLocal; TFETimbre = record Version : WideString; UUID : WideString; FechaTimbrado : TDateTime; SelloCFD : WideString; NoCertificadoSAT : WideString; SelloSAT : WideString; XML: WideString; end; TFEImpuestoTrasladado = record Nombre: String; // IVA, IEPS Tasa: Double; Importe : Currency; end; TFEImpuestosTrasladados = Array of TFEImpuestoTrasladado; // Usado por la clase ReporteMensual TFEPedimentos = Array of TFEDatosAduana; TOnTimbradoRecibidoEvent = procedure(Sender: TObject; const aTimbre: TFETimbre) of Object; TFEPACCredenciales = record RFC: string; Clave: String; DistribuidorID: string; // Usado por algunos PAC para la comunicacion (Ej: Ecodex) Certificado: TFECertificado; end; EFECertificadoNoExisteException = class(Exception); EFECertificadoNoEsDeSellosException = class(Exception); EFELlavePrivadaNoCorrespondeACertificadoException = class(Exception); EFECertificadoNoVigente = class(Exception); EFECertificadoNoCorrespondeAEmisor = class(Exception); EFECertificadoNoFueLeidoException = class(Exception); {$REGION 'Errores durante generacion de CFD/I'} EFEAtributoRequeridoNoPresenteException = class(Exception); EFECadenaMetodoDePagoNoEnCatalogoException = class(Exception); {$REGION 'Documentation'} /// <summary> /// Esta excepción se lanza cuando se intenta leer un XML de un CFD/I de una /// versión aun no soportada. Pensado para evitar leer futuras versiones aun /// no implementadas. /// </summary> {$ENDREGION} EFEVersionComprobanteNoSoportadaException = class(Exception); {$ENDREGION} {$REGION 'Otras excepciones que se presentan al usar el comprobante fiscal'} {$REGION 'Documentation'} /// <summary> /// Este error se presenta cuando se intenta acceder a una propiedad que la /// version especifica del CFD no soporta, por ejemplo cuando se quiere /// obtener el timbre de un CFD 2.2, etc. /// </summary> {$ENDREGION} EComprobanteNoSoportaPropiedadException = class(Exception); {$REGION 'Documentation'} /// <summary> /// Esta excepcion se lanza cuando el XML del CFD no tuvo una estrucutra /// correcta o estaba mal formado, etc. /// </summary> {$ENDREGION} EComprobanteEstructuraIncorrectaException = class(Exception); {$ENDREGION} {$REGION 'Documentation'} /// <summary> /// <para> /// Excepcion heredable que tiene la propiedad Reintentable para saber si /// dicha falla es temporal y el programa cliente debe de re-intentar la /// última petición. /// </para> /// <para> /// Si su valor es Falso es debido a que la falla está del lado del cliente /// y el PAC no puede procesar dicha petición (XML incorrecto, Sello mal /// generado, etc.) /// </para> /// </summary> {$ENDREGION} EPACException = class(Exception) private fCodigoErrorSAT: Integer; fCodigoErrorPAC: Integer; fReintentable : Boolean; public constructor Create(const aMensajeExcepcion: String; const aCodigoErrorSAT: Integer; const aCodigoErrorPAC: Integer; const aReintentable: Boolean); property CodigoErrorSAT: Integer read fCodigoErrorSAT; property CodigoErrrorPAC: Integer read fCodigoErrorPAC; property Reintentable : Boolean read fReintentable; end; // Excepciones que se lanzan durante el proceso de timbrado de un CFDI {$REGION 'Documentation'} /// <summary> /// Error estándard del SAT (301) el cual se lanza cuando el XML enviado al /// PAC no fue válido. /// </summary> {$ENDREGION} ETimbradoXMLInvalidoException = class(EPACException); ETimbradoImpuestoInvalidoException = class(EPACException); // Error 301 cuando un impuesto tiene un nombre no admitido {$REGION 'Documentation'} /// <summary> /// Error estándard del SAT (302) cuando el sello del comprobante no se /// generó correctamente por algún error en el comprobante o el cálculo del /// sello. /// </summary> {$ENDREGION} ETimbradoSelloEmisorInvalidoException = class(EPACException); // Error 302 ETimbradoCertificadoNoCorrespondeException = class(EPACException); // Error 303 ETimbradoCertificadoRevocadoException = class(EPACException); // Error 304 ETimbradoFechaEmisionSinVigenciaException = class(EPACException); // Error 305 ETimbradoLlaveInvalidaException = class(EPACException); // Error 306 ETimbradoPreviamenteException = class(EPACException); // Error 307 ETimbradoCertificadoApocrifoException = class(EPACException); // Error 308 ETimbradoFechaGeneracionMasDe72HorasException = class(EPACException); // Error 401 ETimbradoRegimenEmisorNoValidoException = class(EPACException); // Error 402 ETimbradoFechaEnElPasadoException = class(EPACException); // Error 403 // Excepciones comunes para todos los PAC {$REGION 'Documentation'} /// <summary> /// Representa una "caida" general del servicio del PAC. Es decir /// temporalmente fuera de servicio /// </summary> {$ENDREGION} EPACServicioNoDisponibleException = class(EPACException); EPACCredencialesIncorrectasException = class(EPACException); EPACEmisorNoInscritoException = class(EPACException); EPACErrorGenericoDeAccesoException = class(EPACException); EPACTimbradoRFCNoCorrespondeException = class(EPACException); EPACTimbradoVersionNoSoportadaPorPACException = class(EPACException); EPACTimbradoSinFoliosDisponiblesException = class(EPACException); EPACCAnceladoSinCertificadosException = class(EPACException); EPACNoSePudoObtenerAcuseException = class(EPACException); {$REGION 'Documentation'} /// <summary> /// Este tipo de excepcion se lanza cuando se detecta una falla con el /// internet del usuario el cual es un problema de comunicación con el PAC. /// </summary> {$ENDREGION} EPACProblemaConInternetException = class(EPACException); EPACProblemaTimeoutException = class(EPACException); {$REGION 'Documentation'} /// <summary> /// Excepcion general para errores no programados/manejados. /// </summary> /// <remarks> /// <note type="important"> /// Por defecto se establece que esta excepción es "re-intentable" para /// indicarle al cliente que debe de re-intentar realizar el ultimo proceso /// </note> /// </remarks> {$ENDREGION} EPACErrorGenericoException = class(EPACException); const _RFC_VENTA_PUBLICO_EN_GENERAL = 'XAXX010101000'; _RFC_VENTA_EXTRANJEROS = 'XEXX010101000'; _URL_PRUEBAS_ECODEX = 'https://pruebas.ecodex.com.mx:2045'; _NUMERO_CATALOGO_METODO_NA = '98'; // Errores ecodex _ERROR_ECODEX_CERTIFICADO_NUEVO = 'Error en Certificado:402'; _ERROR_ECODEX_CERTIFICADO_306 = '306 Certificado utilizado no es de sello'; _ERROR_ECODEX_CORREO_REPETIDO = 'El correo asignado ya est'; // Mensaje completo: El correo asignado ya está en uso por otro emisor // Códigos de error regresados por los PAC _ERROR_SAT_XML_INVALIDO = '301'; _ERROR_SAT_SELLO_EMISOR_INVALIDO = '302'; _ERROR_SAT_CERTIFICADO_NO_CORRESPONDE = '303'; _ERROR_SAT_CERTIFICADO_REVOCADO = '304'; _ERROR_SAT_FECHA_EMISION_SIN_VIGENCIA = '305'; _ERROR_SAT_LLAVE_NO_CORRESPONDE = '306'; _ERROR_SAT_PREVIAMENTE_TIMBRADO = '307'; _ERROR_SAT_CERTIFICADO_NO_FIRMADO_POR_SAT = '308'; _ERROR_SAT_FECHA_FUERA_DE_RANGO = '401'; _ERROR_SAT_REGIMEN_EMISOR_NO_VALIDO = '402'; _ERROR_SAT_FECHA_EMISION_EN_EL_PASADO = '403'; // Fecha de inicio de cambio a catalogo de método de pago {$IFDEF QA} // Si estamos en modo "QA" comenzamos desde ya a usar el cambio de metodo de pago // para poder hacer las pruebas usando los servidores de prueba de los PAC _ANO_CAMBIO_METODO_PAGO = 2016; _MES_CAMBIO_METODO_PAGO = 5; _DIA_CAMBIO_METODO_PAGO = 15; {$ELSE} _ANO_CAMBIO_METODO_PAGO = 2016; _MES_CAMBIO_METODO_PAGO = 7; _DIA_CAMBIO_METODO_PAGO = 15; {$ENDIF} implementation constructor EPACException.Create(const aMensajeExcepcion: String; const aCodigoErrorSAT: Integer; const aCodigoErrorPAC : Integer; const aReintentable: Boolean); begin inherited Create(aMensajeExcepcion); fReintentable := aReintentable; fCodigoErrorSAT := aCodigoErrorSAT; fCodigoErrorPAC := aCodigoErrorPAC; end; end.
unit MLP.Concret.NeuronPredict; interface uses MLP.Contract.NeuronPredict, MLP.Contract.Neuron, MLP.Contract.Activation, MLP.Concret.Matrix, System.SysUtils; type TNeuronPredict = class(TInterfacedObject, INeuronPredict) private { private declarations } FNeuronLayer: INeuronLayer; [weak] FActivation: IActivation; FInputs: TMatrixSingle; FOutputs: TMatrixSingle; protected { protected declarations } procedure Activation(var AValue: Single); function CalcOutputs(AInputs: TMatrixSingle; ALayer: INeuronLayer): TMatrixSingle; public { public declarations } function SetNeuronLayer(ANeuronLayer: INeuronLayer): INeuronPredict; function SetActivation(AActivation: IActivation): INeuronPredict; function SetInputs(AInputs: TMatrixSingle): INeuronPredict; function Predict(out AOutputs: TMatrixSingle): INeuronPredict; end; implementation uses MLP.Concret.Neuron; { TNeuronPredict } procedure TNeuronPredict.Activation(var AValue: Single); begin FActivation.Activation(AValue); end; function TNeuronPredict.CalcOutputs(AInputs: TMatrixSingle; ALayer: INeuronLayer): TMatrixSingle; var LWeigths: TMatrixSingle; LBias: TMatrixSingle; LCurrentNeuronLayerHack: INeuronLayerHack; LNextNeuronLayerHack: INeuronLayerHack; LNeuronLayerNavigator: INeuronLayerNavigator; LNextNeuronLayer: INeuronLayer; LNextNeuronLayerNavigator: INeuronLayerNavigator; begin if Supports(ALayer, INeuronLayerHack, LCurrentNeuronLayerHack) then begin if Supports(ALayer, INeuronLayerNavigator, LNeuronLayerNavigator) then begin LCurrentNeuronLayerHack.GetWeights(LWeigths).GetBias(LBias); FOutputs := LWeigths * AInputs; FOutputs := FOutputs + LBias; FOutputs.Map(Activation); if LNeuronLayerNavigator.HasNext then begin LNextNeuronLayer := LNeuronLayerNavigator.Next; if Supports(LNextNeuronLayer,INeuronLayerHack,LNextNeuronLayerHack) then begin LNextNeuronLayerHack.SetOutputs(FOutputs) end; if Supports(LNextNeuronLayer, INeuronLayerNavigator, LNextNeuronLayerNavigator) then begin if LNextNeuronLayerNavigator.HasNext then CalcOutputs(FOutputs, LNextNeuronLayer); end; end; end; end; end; function TNeuronPredict.Predict(out AOutputs: TMatrixSingle): INeuronPredict; begin Result := Self; CalcOutputs(FInputs, FNeuronLayer); AOutputs := FOutputs; end; function TNeuronPredict.SetActivation(AActivation: IActivation): INeuronPredict; begin Result := Self; FActivation := AActivation; end; function TNeuronPredict.SetInputs(AInputs: TMatrixSingle): INeuronPredict; begin Result := Self; FInputs := AInputs; end; function TNeuronPredict.SetNeuronLayer(ANeuronLayer: INeuronLayer): INeuronPredict; begin Result := Self; FNeuronLayer := ANeuronLayer; end; end.
unit tmbToolManutencaoTop; interface uses SysUtils, Classes, Controls, ToolWin, ComCtrls, ExtCtrls, Buttons, StdCtrls, Forms, DB, DBClient, Dialogs, Mask , u_dmGSI, FuncoesDSI; type TtmbManutTop = class(TCoolBar) private FCria: boolean; FPreencheCombos: boolean; FDmGsiLoc: TClientDataSet; FDataSource: TDataSource; FRetornoVisivel: boolean; FTtmbPesquisar: boolean; FTTmbValuesPesquisa: String; FTtmbCamposPesquisa: String; FUsuario: String; function PosCampoIdxPesq : Integer; procedure SetCria(const Value: boolean); procedure SetDataSource(const Value: TDataSource); procedure SetPreencheCombos(const Value: boolean); procedure SetDmGsiLoc(const Value: TClientDataSet); procedure SetRetornoVisivel(const Value: boolean); procedure SetTtmbPesquisar(const Value: boolean); procedure SetTtmbCamposPesquisa(const Value: String); procedure SetTTmbValuesPesquisa(const Value: String); function QuebraString(var Str: String): String; function AddParametroPesquisa( var CampoPesquisa : String ) : String; overload; function AddParametroPesquisa( var CampoPesquisa : String; Item : Integer ) : String; overload; procedure PesquisaNoForm; procedure PesquisaLoockup; procedure InicioDoCampo(Sender: TObject); procedure SetaComboCampo(Cp : String); { Private declarations } protected { Protected declarations } public { Public declarations } PnTool : TPanel; sbParametros, sbPesquisa, sbRetornar, sbAddFiltro, sbFindPadrao : TSpeedButton; cbxCampos, cbxCondicao : TComboBox; strlstIdxCampo : TStrings; mktConteudo : TMaskEdit; Bevel : TBevel; FDataSet : TClientDataSet; cdsAddFiltro : TClientDataSet; FSQLParam : WideString; constructor Create(AOwner : TComponent); override; Destructor Destroy; override; procedure ControiComponente(opc: boolean); function AnalisarParamPesq( Campo, Condicao, Conteudo : String ) : String; procedure PesquisaSql(Sender : TObject); procedure AddFiltro( Sender : TObject); procedure AddFindPadrao( Sender : TObject); procedure Retornar(Sender :TObject); procedure PressionarEnter( Sender: TObject; var Key: Char ); procedure PressionarTecla( Sender: TObject; var Key: Char); procedure AdicionarMascara( Sender: TObject ); published { Published declarations } property TtmbCria : boolean read FCria write SetCria; property TtmbPreencheCombos : boolean read FPreencheCombos write SetPreencheCombos; property TtmbDataSource : TDataSource read FDataSource write SetDataSource; property TtmbDmGsiCdsSQL : TClientDataSet read FDmGsiLoc write SetDmGsiLoc; property TtmbRetornoVisivel : boolean read FRetornoVisivel write SetRetornoVisivel; property TtmbPesquisar : boolean read FTtmbPesquisar write SetTtmbPesquisar; property TtmbCamposPesquisa : String read FTtmbCamposPesquisa write SetTtmbCamposPesquisa; property TTmbValuesPesquisa : String read FTTmbValuesPesquisa write SetTTmbValuesPesquisa; property TtmbUsuario : String read FUsuario write FUsuario; end; procedure Register; implementation uses FuncoesCliente, u_AdicionarPesquisa, StrUtils, MaskUtils; var PathBMP : String; procedure Register; begin RegisterComponents('CGLSOFT', [TtmbManutTop]); end; function TtmbManutTop.PosCampoIdxPesq : Integer; begin Result := StrToInt( strlstIdxCampo.Strings[cbxCampos.ItemIndex] ); end; procedure TtmbManutTop.SetaComboCampo(Cp : String); var i : Integer; Campo : String; begin for i := 0 to cbxCampos.Items.Count -1 do begin Campo := cbxCampos.Items[i]; RemoveString(Campo, ' '); RemoveString(Cp, ' '); if AnsiUpperCase(Campo) = AnsiUpperCase(Cp) then begin cbxCampos.ItemIndex := i; Break; end; end; end; procedure TtmbManutTop.PressionarEnter( Sender: TObject; var Key: Char ); begin if Key = #13 then SelectNext( Screen.ActiveControl, True, True ); end; procedure TtmbManutTop.PressionarTecla( Sender: TObject; var Key: Char ); begin if Key = #13 then begin if CheckSenha( FUsuario, TForm(Self.Owner).Caption, sbPesquisa.Hint, true) then begin if FTTmbValuesPesquisa = '' then PesquisaNoForm {Pesquisa internamente pelo botão Pesquisar} else PesquisaLoockup; {Pesquisa inicial chamada por um campo de Loockup} end; end; end; procedure TtmbManutTop.AdicionarMascara(Sender: TObject); begin if (Trim(cbxCampos.Text ) <> '' ) and (Trim(cbxCondicao.Text) <> '') then mktConteudo.EditMask := FDataSet.Fields.Fields[PosCampoIdxPesq].EditMask; end; procedure TtmbManutTop.InicioDoCampo(Sender: TObject); begin mktConteudo.SelStart := 0; end; { TtmbManutTop } function TtmbManutTop.AnalisarParamPesq(Campo, Condicao, Conteudo: String): String; var ParSQL : String; begin ParSQL := ''; {Todos} if Condicao = 'Igual' then ParSQL := Campo + ' = ' + QuotedStr( Conteudo ) else if Condicao = 'Diferente' then ParSQL := Campo + ' <> ' + QuotedStr( Conteudo ) else if Condicao = 'Maior' then ParSQL := Campo + '>' + QuotedStr( Conteudo ) else if Condicao = 'Maior e Igual' then ParSQL := Campo + ' >= ' + QuotedStr( Conteudo ) else if Condicao = 'Menor' then ParSQL := Campo + ' < ' + QuotedStr( Conteudo ) else if Condicao = 'Menor e Igual' then ParSQL := Campo + ' <= ' + QuotedStr( Conteudo ) else if Condicao = 'Contido' then ParSQL := Campo + ' LIKE ' + QuotedStr( '%' + Conteudo + '%' ) else if Condicao = 'Não Contido' then ParSQL := Campo + ' NOT LIKE ' + QuotedStr( '%' + Conteudo + '%' ) else if Condicao = 'Não Preenchido' then ParSQL := Campo + ' IS NULL ' else if Condicao = 'Preenchido' then ParSQL := Campo + ' IS NOT NULL ' else if Condicao = 'Inicie com' then ParSQL := Campo + ' LIKE ' + QuotedStr( Conteudo + '%' ); Result := ParSQL; end; procedure TtmbManutTop.ControiComponente(opc: boolean); begin if (opc = true) then begin cdsAddFiltro := TClientDataSet.Create( self ); cdsAddFiltro.FieldDefs.Add( 'Id', ftInteger, 0, False ); cdsAddFiltro.FieldDefs.Add( 'S1', ftString, 100, False, ); // Separador "(" cdsAddFiltro.FieldDefs.Add( 'Campo', ftString, 50, False, ); cdsAddFiltro.FieldDefs.Add( 'Condicao', ftString, 15, False, ); cdsAddFiltro.FieldDefs.Add( 'Conteudo', ftString, 100, False, ); cdsAddFiltro.FieldDefs.Add( 'Relacional', ftString, 5, False, ); cdsAddFiltro.FieldDefs.Add( 'S2', ftString, 200, False, ); // Separador ")" cdsAddFiltro.FieldDefs.Add( 'InstrucaoSQL', ftString,200, False, ); cdsAddFiltro.CreateDataSet; cdsAddFiltro.AddIndex( 'idx1','Id',[ixPrimary],'','',0); cdsAddFiltro.IndexName := 'idx1'; if PnTool = nil then PnTool := TPanel.Create(self); PnTool.Height := 28; PnTool.Width := 33; PnTool.BevelOuter := bvNone; PnTool.Caption := ''; {} if sbParametros = nil then sbParametros := TSpeedButton.Create(self); sbParametros.Name := 'SpParametro'; sbParametros.Caption := '&Parametros'; sbParametros.Left := 0; sbParametros.Height := 28; sbParametros.Width := 75; sbParametros.Flat := true; sbParametros.Parent := PnTool; sbParametros.Glyph.LoadFromFile(PathBMP +'\parametros.bmp'); {} if cbxCampos = nil then cbxCampos := TComboBox.Create(self); cbxCampos.Parent := PnTool; cbxCampos.Name := 'cbxCampos'; cbxCampos.Text := ''; cbxCampos.Top := 3; cbxCampos.Left := sbParametros.Left+sbParametros.width+8; cbxCampos.Height := 21; cbxCampos.BevelInner := bvLowered; cbxCampos.BevelKind := bkNone; cbxCampos.Width := 160; cbxCampos.OnKeyPress := PressionarEnter; cbxCampos.OnExit := AdicionarMascara; {} if cbxCondicao = nil then cbxCondicao := TComboBox.Create(self); cbxCondicao.Name := 'cbxCondicao'; cbxCondicao.Text := ''; cbxCondicao.Top := 3; cbxCondicao.Left := cbxCampos.Left+cbxCampos.width+4; cbxCondicao.Height := 21; cbxCondicao.BevelInner := bvLowered; cbxCondicao.BevelKind := bkNone; cbxCondicao.Width := 102; cbxCondicao.Parent := PnTool; cbxCondicao.OnKeyPress := PressionarEnter; {} if mktConteudo = nil then mktConteudo := TMaskEdit.Create(self); mktConteudo.Parent := PnTool; mktConteudo.Name := 'mktConteudo'; mktConteudo.Text := ''; mktConteudo.Top := 3; mktConteudo.Left := cbxCondicao.Left+cbxCondicao.width+4; mktConteudo.Height := 21; mktConteudo.BevelInner := bvRaised; mktConteudo.BevelKind := bkFlat; mktConteudo.BorderStyle := bsNone; mktConteudo.BevelOuter := bvLowered; mktConteudo.Width := 116; mktConteudo.CharCase := ecUpperCase; mktConteudo.OnKeyPress := PressionarTecla; mktConteudo.OnClick := InicioDoCampo; {} if sbPesquisa = nil then sbPesquisa := TSpeedButton.Create(self); sbPesquisa.Name := 'sbPesquisa'; sbPesquisa.Caption := 'P&esquisar'; sbPesquisa.Left := mktConteudo.Left+mktConteudo.width+4; sbPesquisa.Height := 28; sbPesquisa.Width := 80; sbPesquisa.Flat := true; sbPesquisa.Parent := PnTool; sbPesquisa.Hint := 'Pesquisar'; sbPesquisa.Glyph.LoadFromFile(PathBMP +'\pesquisa.bmp'); sbPesquisa.OnClick := PesquisaSql; {} Bevel := TBevel.Create(self); Bevel.Parent := PnTool; Bevel.Shape := bsLeftLine; Bevel.Width := 2; Bevel.Top := 3; Bevel.Height := 22; Bevel.Left := sbPesquisa.Left+ sbPesquisa.width+4; {} if sbAddFiltro = nil then sbAddFiltro := TSpeedButton.Create(self); sbAddFiltro.Name := 'sbAddFiltro'; sbAddFiltro.Left := sbPesquisa.Left+sbPesquisa.Width + 8; sbAddFiltro.Height := 28; sbAddFiltro.Width := 30; sbAddFiltro.Flat := true; sbAddFiltro.Parent := PnTool; sbAddFiltro.Hint := 'Adicionar filtro à pesquisa'; sbAddFiltro.Glyph.LoadFromFile(PathBMP +'\filtro.bmp'); sbAddFiltro.Visible := True; sbAddFiltro.OnClick := AddFiltro; {} if sbFindPadrao = nil then sbFindPadrao := TSpeedButton.Create(self); sbFindPadrao.Name := 'sbFindPadrao'; sbFindPadrao.Left := sbAddFiltro.Left+sbAddFiltro.Width + 5; sbFindPadrao.Height := 28; sbFindPadrao.Width := 30; sbFindPadrao.Flat := true; sbFindPadrao.Parent := PnTool; sbFindPadrao.Hint := 'Adicionar filtro padrão à pesquisa'; sbFindPadrao.Glyph.LoadFromFile(PathBMP +'\find.bmp'); sbFindPadrao.Visible := True; sbFindPadrao.OnClick := AddFindPadrao; {} if sbRetornar = nil then sbRetornar := TSpeedButton.Create( Self ); sbRetornar.Name := 'sbRetornar'; {sbRetornar.Caption := '&Retornar';} sbRetornar.Left := sbFindPadrao.Left + sbFindPadrao.Width + 4; sbRetornar.Height := 28; sbRetornar.Width := 30; sbRetornar.Flat := true; sbRetornar.Parent := PnTool; sbRetornar.Hint := 'Retornar registro selecionado da pesquisa'; sbRetornar.Glyph.LoadFromFile(PathBMP +'\retorno.bmp'); sbRetornar.Visible := True; sbRetornar.OnClick := Retornar; {} PnTool.Parent := self; Self.Bands[0].Control := PnTool; Self.align := alTop; Self.AutoSize := true; Self.EdgeBorders := [ebLeft,ebTop,ebRight,ebBottom]; {} strlstIdxCampo := TStringList.Create; end else begin if PnTool <> nil then FreeAndNil(PnTool); if sbParametros <> nil then FreeAndNil(sbParametros); if cbxCampos <> nil then FreeAndNil(cbxCampos); if cbxCondicao <> nil then FreeAndNil(cbxCondicao); if mktConteudo <> nil then FreeAndNil(mktConteudo); if Bevel <> nil then FreeAndNil(Bevel); if cdsAddFiltro <> nil then FreeAndNil(cdsAddFiltro); if strlstIdxCampo <> nil then FreeAndNil( strlstIdxCampo ); end; end; constructor TtmbManutTop.Create(AOwner: TComponent); begin inherited; if Assigned(dmGsi) then FUsuario := dmGsi.UsuarioAtivo; PathBMP := ExtractFileDir( Application.ExeName )+ '\imagens'; end; destructor TtmbManutTop.Destroy; begin inherited; end; procedure TtmbManutTop.PesquisaLoockup; var ParamPesquisa, StrCampo, StrValor, VrAnd : String; begin VrAnd := ''; while Trim(FTtmbCamposPesquisa) <> '' do begin StrCampo := QuebraString(FTtmbCamposPesquisa); StrValor := QuebraString(FTTmbValuesPesquisa); if Trim(StrValor) <> '' then begin if Pos('cpf', AnsiLowerCase(StrCampo) ) > 0 then StrValor := TransfNum(StrValor); if Trim(StrCampo) <> '' then ParamPesquisa := ParamPesquisa + VrAnd + AnalisarParamPesq( IdentificarNomeTabela( FDataSet.Name ) + '.' + StrCampo, cbxCondicao.Text, StrValor ); VrAnd := ' AND '; end; end; if Trim(ParamPesquisa) <> '' then GerarPesquisa( FDataSet, ParamPesquisa ); FTTmbValuesPesquisa := ''; end; procedure TtmbManutTop.PesquisaNoForm; var ParamPesquisa, CampoPesquisa : String; begin ParamPesquisa := AddParametroPesquisa( CampoPesquisa ); try if FSQLParam = '' then GerarPesquisa( FDataSet, ParamPesquisa ) else begin ExecDynamicProvider( -1, FSQLParam + ' AND ' + ParamPesquisa, FDataSet ); FDataSet.PacketRecords := -1; end; except on E:Exception do begin MessageDlg('Pesquisa não realizada. '+ #13+ 'O valor passado deve ser númerico.', mtInformation, [mbOk], 0); raise; end; end; end; procedure TtmbManutTop.PesquisaSql(Sender: TObject); begin if CheckSenha( FUsuario, TForm(Self.Owner).Caption, sbPesquisa.Hint, true) then begin if FTTmbValuesPesquisa = '' then PesquisaNoForm {Pesquisa internamente pelo botão Pesquisar} else PesquisaLoockup; {Pesquisa inicial chamada por um campo de Loockup} end; end; function TtmbManutTop.QuebraString(var Str: String): String; var ParteString : String; begin ParteString := ''; if Pos(';', Str) > 0 then begin ParteString := Copy( Str, 1 , Pos(';', Str) ); if Pos(';', ParteString) > 0 then Delete(ParteString, length(ParteString), 1); end else ParteString := Copy( Str,1 , Length(Str) ); Delete(Str,1, (Length(ParteString)+1) ); Result := ParteString; end; procedure TtmbManutTop.Retornar(Sender: TObject); begin if CheckSenha( FUsuario, TForm(self.Owner).Caption, sbRetornar.Hint, true) then begin TForm(Self.Parent).ModalResult := mrOk; TForm(Self.Parent).Close; end; end; procedure TtmbManutTop.SetCria(const Value: boolean); begin PathBMP := ExtractFileDir( Application.ExeName )+ '\imagens'; FCria := Value; if FCria = true then ControiComponente(true); end; procedure TtmbManutTop.SetDataSource(const Value: TDataSource); begin FDataSource := Value; FDataSet := ( FDataSource.DataSet as TClientDataSet ); end; procedure TtmbManutTop.SetDmGsiLoc(const Value: TClientDataSet); begin FDmGsiLoc := Value; end; procedure TtmbManutTop.SetPreencheCombos(const Value: boolean); var i : integer; NomeTabelaDic : String; procedure AdicCamposCombo( Sender : TObject ; Campos : TFields ); var a : Integer; begin TComboBox( Sender ).Items.Clear; strlstIdxCampo.Clear; for a := 0 to Campos.Count - 1 do begin if Campos[a].FieldKind = fkData then if Campos[a].DataType <> ftDataSet then begin TComboBox( Sender ).Items.Add( Campos[a].DisplayLabel ); strlstIdxCampo.Add( IntToStr( Campos[a].Index ) ); end; end; end; begin FPreencheCombos := Value; if (FPreencheCombos = true ) and (FDataSet <> nil ) then begin NomeTabelaDic := UpperCase( IdentificarNomeTabela( FDataSet.Name ) ); AtualizarDicionario( NomeTabelaDic, FDataSet ); AdicCamposCombo( cbxCampos, FDataSet.Fields ); end; cbxCondicao.Clear; for i := Low(CondicoesPesqSQL) to High(CondicoesPesqSQL) do cbxCondicao.Items.Add(CondicoesPesqSQL[i]); end; procedure TtmbManutTop.SetRetornoVisivel(const Value: boolean); begin FRetornoVisivel := Value; if FRetornoVisivel = true then TSpeedButton(sbRetornar).Visible := true else TSpeedButton(sbRetornar).Visible := false; end; procedure TtmbManutTop.SetTtmbCamposPesquisa(const Value: String); begin FTtmbCamposPesquisa := Value; end; procedure TtmbManutTop.SetTtmbPesquisar(const Value: boolean); var Cp : String; begin FTtmbPesquisar := Value; if FTtmbPesquisar = true then begin if Trim(FTTmbValuesPesquisa) <> '' then begin cbxCondicao.ItemIndex := 1; if Pos(';', FTTmbValuesPesquisa) > 0 then begin Cp := Copy( FTTmbCamposPesquisa, 1, Pos(';', FTTmbCamposPesquisa)-1); SetaComboCampo(Cp); mktConteudo.Text := Copy( FTTmbValuesPesquisa, 1, Pos(';', FTTmbValuesPesquisa)-1) end else begin mktConteudo.Text := FTTmbValuesPesquisa; SetaComboCampo(FTTmbCamposPesquisa); end; end else begin cbxCondicao.ItemIndex := 0; mktConteudo.Text := ''; cbxCampos.ItemIndex := 0; end; sbPesquisa.Click; end; end; procedure TtmbManutTop.SetTTmbValuesPesquisa(const Value: String); begin FTTmbValuesPesquisa := Value; end; function TtmbManutTop.AddParametroPesquisa( var CampoPesquisa : String ) : String; var NomeCampo, Conteudo : String; begin Result := ''; if (Trim(cbxCampos.Text ) <> '' ) and (Trim(cbxCondicao.Text) <> '') then begin NomeCampo := FDataSet.Fields.Fields[PosCampoIdxPesq].FieldName; if Pos('cpf', AnsiLowerCase(NomeCampo) ) > 0 then Conteudo := TransfNum( mktConteudo.Text ) else Conteudo := mktConteudo.Text; CampoPesquisa := IdentificarNomeTabelaCampo( IdentificarNomeTabela( FDataSet.Name ), NomeCampo ); Result := AnalisarParamPesq( CampoPesquisa, cbxCondicao.Text, Trim( Conteudo ) ); end; end; function TtmbManutTop.AddParametroPesquisa( var CampoPesquisa : String; Item : Integer ) : String; var NomeCampo, Conteudo : String; begin Result := ''; NomeCampo := FDataSet.Fields.Fields[Item].FieldName; if Pos('cpf', AnsiLowerCase(NomeCampo) ) > 0 then Conteudo := TransfNum( mktConteudo.Text ) else Conteudo := mktConteudo.Text; CampoPesquisa := IdentificarNomeTabelaCampo( IdentificarNomeTabela( FDataSet.Name ), NomeCampo ); Result := AnalisarParamPesq( CampoPesquisa, cbxCondicao.Text, Trim( Conteudo ) ); end; procedure TtmbManutTop.AddFiltro(Sender: TObject); var ParamPesquisa, Relacional, CampoPesquisa : String; begin ParamPesquisa := AddParametroPesquisa( CampoPesquisa ); Relacional := ''; if not cdsAddFiltro.IsEmpty then Relacional := 'E '; cdsAddFiltro.Insert; cdsAddFiltro.FieldByName('Id').AsInteger := cdsAddFiltro.RecordCount + 1; cdsAddFiltro.FieldByName('Campo').AsString := cbxCampos.Text; cdsAddFiltro.FieldByName('Condicao').AsString := cbxCondicao.Text; cdsAddFiltro.FieldByName('Conteudo').AsString := mktConteudo.Text; cdsAddFiltro.FieldByName('Relacional').AsString := Relacional; cdsAddFiltro.FieldByName('InstrucaoSQL').AsString := CampoPesquisa; cdsAddFiltro.Post; if not Assigned( frmAdicionarPesquisa ) then frmAdicionarPesquisa := TfrmAdicionarPesquisa.Create( Self ); // frmAdicionarPesquisa.Parent := Self; { Efeito legal de tela } frmAdicionarPesquisa.FcdsAdicionarPesquisa := FDataSet; frmAdicionarPesquisa.dsAddFiltro.DataSet := cdsAddFiltro; frmAdicionarPesquisa.Show; end; procedure TtmbManutTop.AddFindPadrao(Sender: TObject); var ParamPesquisa, Relacional, CampoPesquisa, TipoCondicao : String; i : Integer; procedure InserirItens( Campo, Condicao, Relacional, CampoPesquisa : String ); begin cdsAddFiltro.Insert; cdsAddFiltro.FieldByName('Id').AsInteger := cdsAddFiltro.RecordCount + 1; cdsAddFiltro.FieldByName('Campo').AsString := Campo; cdsAddFiltro.FieldByName('Condicao').AsString := TipoCondicao; cdsAddFiltro.FieldByName('Conteudo').AsString := ''; cdsAddFiltro.FieldByName('Relacional').AsString := Relacional; cdsAddFiltro.FieldByName('InstrucaoSQL').AsString := CampoPesquisa; cdsAddFiltro.Post; end; begin cdsAddFiltro.EmptyDataSet; Relacional := ''; // for i := 0 to cbxCampos.Items.Count - 1 do for i := 0 to strlstIdxCampo.Count - 1 do begin ParamPesquisa := AddParametroPesquisa( CampoPesquisa, StrToInt( strlstIdxCampo.Strings[i] ) ); case FDataSet.Fields.Fields[i].DataType of ftString : TipoCondicao := cbxCondicao.Items[7]; ftDate, ftDateTime, ftTimeStamp : TipoCondicao := cbxCondicao.Items[4]; else ; TipoCondicao := cbxCondicao.Items[1]; end; InserirItens( cbxCampos.Items[i], TipoCondicao, Relacional, CampoPesquisa ); if FDataSet.Fields.Fields[i].DataType in [ftDate,ftDateTime,ftTimeStamp] then begin TipoCondicao := cbxCondicao.Items[6]; InserirItens( cbxCampos.Items[i], TipoCondicao, Relacional, CampoPesquisa ); end; Relacional := 'E '; end; if not Assigned( frmAdicionarPesquisa ) then frmAdicionarPesquisa := TfrmAdicionarPesquisa.Create( Self ); // frmAdicionarPesquisa.Parent := Self; { Efeito legal de tela } frmAdicionarPesquisa.Top := 1; frmAdicionarPesquisa.Height := 500; cdsAddFiltro.First; frmAdicionarPesquisa.FcdsAdicionarPesquisa := FDataSet; frmAdicionarPesquisa.dsAddFiltro.DataSet := cdsAddFiltro; frmAdicionarPesquisa.Show; end; end.
// ============================================================================= // Module name : $RCSfile: FlashRunner.pas,v $ // description : This unit implements all methodes and properties of class // TFlashRunner for device FlashRunner // Compiler : Delphi 2007 // Author : 2015-08-14 /bsu/ // History : //============================================================================== unit FlashRunner; interface uses Serial3, Classes, SysUtils, StrUtils, Windows, Forms, IniFiles, ConnBase, RS232, DeviceBase; type // ============================================================================= // Class : TFlashRunner // Description : Definition of class TFlashRunner for FlashRunner deriving // from TDeviceBase // First author : 2015-08-14 /bsu/ // History : // ============================================================================= TFlashRunner = class(TDeviceBase) protected //t_ser: TSerial; protected function CheckAnswer(const ans: string): boolean; override; function Sync(): boolean; override; function IntToDMDataStr(const num: integer): string; public constructor Create(owner: TComponent); override; destructor Destroy; override; function GetLastError(var msg: string): Integer; override; function ConfigDevice(const ini: TMemIniFile): Boolean; override; function SetDynamicMem(const addr: word; const num: integer): boolean; function RunScript(const script: string; const msecs: integer = -1): boolean; end; var t_flashrunner: TFlashRunner; //a global variable of the FlashRunner instance implementation const C_ERR_PORT = $8001; // C_ERR_BAUDRATE = $8002; // C_ERR_WRONG_ANS = $8003; // C_ERR_WRONG_STA = $8004; // C_ERR_TIMEOUT = $8005; // CSTR_FR_SEC : string = 'FlashRunner'; // ============================================================================= // Class : -- // Function : Delay // delay for a moment in milli second // Parameter : msec, integer of milli seconds // Return : -- // Exceptions : -- // First author : 2015-08-14 /bsu/ // History : // ============================================================================= procedure Delay(const msec: cardinal); var i_timeout: cardinal; begin i_timeout := GetTickCount() + msec; repeat Application.ProcessMessages(); until (GetTickCount() >= i_timeout); end; // ============================================================================= // Class : -- // Function : IndexOfStr // return index of a string in an array // Parameter : aArray, in which the string is searched // S, string to search // Return : index of string in the array. -1 is returnd, if not found // Exceptions : -- // First author : 2015-08-14 /bsu/ // History : 2016-03-01 /bsu/ same as IndexText in StrUtils // ============================================================================= function IndexOfStr(const aArray: array of string; const S: string): integer; var I: Integer; begin Result := IndexText (S, aArray); { for I := Low(aArray) to High(aArray) do if SameText(S, aArray[I]) then begin Result := I; Break; end; } end; // ============================================================================= // Class : TFlashRunner // Function : IntToDMDataStr // convert an integer into a string with format of data // for FlashRunner-command DMSET in word-addressing, // e.g. 1050820084($3EA23DF4)->'$3E $00 $A2 $00 $3D $00 $F4 $00' // Parameter : num, integer to be converted // Return : string in format of DMSET-data // Exceptions : -- // First author : 2015-08-14 /bsu/ // History : // ============================================================================= function TFlashRunner.IntToDMDataStr(const num: integer): string; var str_data: string; begin str_data := RightStr(IntToHex(num, 8), 8); Insert(' $00 $', str_data, 7); Insert(' $00 $', str_data, 5); Insert(' $00 $', str_data, 3); result := '$' + str_data + ' $00'; end; // ============================================================================= // Class : TFlashRunner // Function : Create // constructor of the class, which initializes the instance with // default values // Parameter : owner, which instanced this class // Return : -- // Exceptions : -- // First author : 2015-08-14 /bsu/ // History : // ============================================================================= constructor TFlashRunner.Create(owner: TComponent); begin inherited Create(owner); end; // ============================================================================= // Class : TFlashRunner // Function : Destroy // destructor of the class, which finilizes the instance // Parameter : owner, which instanced this class // Return : -- // Exceptions : -- // First author : 2015-08-14 /bsu/ // History : // ============================================================================= destructor TFlashRunner.Destroy; begin ReleaseDevice(); inherited Destroy; end; // ============================================================================= // Class : TFlashRunner // Function : Sync // coordinate with the device // Parameter : -- // Return : true, if the device is accesible in the time of timeout // false, otherwise // Exceptions : -- // First author : 2015-08-14 /bsu/ // History : // ============================================================================= function TFlashRunner.Sync(): boolean; const C_STR_PING: string = 'SPING'; C_STR_PONG: string = 'PONG>'; var s_ans, s_que: string; ds_set : set of EDeviceState; i_len: integer; begin result := false; ds_set := [DS_CONNECTED, DS_COMERROR]; if (e_state in ds_set) then begin //clear receiving-buffer of t_ser t_conns[e_actconn].RecvData(t_rbuf, C_TIMEOUT_ONCE); //t_rbuf.Clear; ZeroMemory(@t_rbuf, length(t_rbuf)); ZeroMemory(@t_wbuf, length(t_wbuf)); //send string and wait til write-buffer is completely sent s_que := C_STR_PING + Char(13); //i_len := t_wbuf.WriteStr(s_que); i_len := length(s_que); StrCopy(@t_wbuf, PChar(@s_que)); if t_conns[e_actconn].SendData(t_wbuf, i_len, C_TIMEOUT_ONCE) then begin //receive string til read-buffer is empty or timeout i_len := t_conns[e_actconn].RecvData(t_rbuf, C_TIMEOUT_ONCE); if (i_len > 0) then begin //verify the received string //s_ans := trim(t_rbuf.ReadStr()); s_ans := Copy(t_rbuf, Low(t_rbuf), i_len); s_ans := trim(s_ans); result := SameText(C_STR_PONG, s_ans); if result then e_state := DS_READY; end; end; end; end; // ============================================================================= // Class : TFlashRunner // Function : CheckAnswer // check, if an error exists in the answer string from device // Parameter : ans, the received string // Return : integer, error number // Exceptions : -- // First author : 2015-08-14 /bsu/ // History : // ============================================================================= function TFlashRunner.CheckAnswer(const ans: string): boolean; const C_VALID_CHARS: set of char = ['>', '!']; var i_len: integer; begin //ans := trim(t_rbuf.ReadStr()); i_len := length(ans); s_lastmsg := format('answer string: %s', [IfThen(i_len>0, ans, '[empty]')]); if (i_len > 0) then begin if (ans[i_len] = '>') then i_lasterr := C_ERR_NOERROR //sucessful answer else if (ans[i_len] = '!') then if (not TryStrToInt(MidStr(ans, 1, i_len - 1), i_lasterr)) then i_lasterr := C_ERR_WRONG_ANS//failure answer else i_lasterr := C_ERR_UNKNOWN; end else i_lasterr := C_ERR_WRONG_ANS; result := (i_lasterr = C_ERR_NOERROR); end; // ============================================================================= // Class : TFlashRunner // Function : GetLastError // override function // Parameter : msg, output string // Return : integer, last error number and set msg with the last message // Exceptions : -- // First author : 2015-08-14 /bsu/ // History : // ============================================================================= function TFlashRunner.GetLastError(var msg: string): Integer; begin //todo result := i_lasterr; case i_lasterr of 0: msg := 'No error exist.'; else msg := 'This error is not specified.'; end; end; // ============================================================================= // Class : TFlashRunner // Function : ConfigDevice // config FlashRunner using settings from INI like: // [FlashRunner] // DESCRIPTION=A universal programmer for writing flash // PRODUCER=SMH Technologies // TYPE=FR01LAN // CONN_RS232=PORT:8|Baudrate:115200 // TIMEOUT=30000 // Parameter : ini, a instance of TMemIniFile, in which section [FlashRunner] // is saved // Return : true, if the device is configured successfully // false, otherwise // Exceptions : -- // First author : 2015-08-14 /bsu/ // History : // ============================================================================= function TFlashRunner.ConfigDevice(const ini: TMemIniFile): boolean; begin result := false; if (e_state in C_DEV_STATES[DE_CONFIG]) then begin //settings from ini file if (ini.SectionExists(CSTR_FR_SEC)) then begin c_timeout := ini.ReadInteger(CSTR_FR_SEC, CSTR_DEV_TIMEOUT, C_TIMEOUT_MSEC); result := (ConfigConnections(ini, CSTR_FR_SEC) > 0); if result then e_state := DS_CONFIGURED; end; end; end; // ============================================================================= // Class : TFlashRunner // Function : SetDynamicMem // builds a string for setting dynamic memory of flash runner and // sends it to flash runner, then receives the answer and checks it. // The dynamic memory has 512 bytes and is addressed from 0 on. // Parameter : addr, address of dynamic memory in flash runner // num, a integer which is being set in the dynamic memory // Return : true, if the device is released successfully // false, otherwise // Exceptions : -- // First author : 2015-08-14 /bsu/ // History : // ============================================================================= function TFlashRunner.SetDynamicMem(const addr: word; const num: integer): boolean; var s_send, s_answer: string; begin result := false; s_send := format('DMSET $%.4x 8 %s', [addr, IntToDMDataStr(num)]) + Char(13); if SendStr(s_send) then begin RecvStr(s_answer); result := (State = DS_READY); end; end; // ============================================================================= // Class : TFlashRunner // Function : RunScript // executs a script file from the sd card of FlashRunner // Parameter : script, name of the script file on sd card // msecs, t // Return : true, if the device is released successfully // false, otherwise // Exceptions : -- // First author : 2015-08-14 /bsu/ // History : // ============================================================================= function TFlashRunner.RunScript(const script: string; const msecs: integer): boolean; var s_send, s_answer: string; c_tmp: cardinal; begin result := false; c_tmp := Timeout; if (msecs > 0) then Timeout := msecs; s_send := format('RUN %s', [script]) + Char(13); if SendStr(s_send) then begin RecvStr(s_answer); result := (State = DS_READY); end; Timeout := c_tmp; end; end.
{####################################################################################} { } { DATA AUTOR Descrição } {----------- ------------------ ----------------------------------------------------} { 04/11/2016 guilherme.chiarini Criação de arquivo } {####################################################################################} unit uDataModule; interface uses System.SysUtils, System.Classes, Data.DBXInterBase, Data.DB, Data.SqlExpr, Data.FMTBcd, Datasnap.Provider, Datasnap.DBClient, Data.DBXOdbc, Vcl.Forms, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdLPR, IdRawBase, IdRawClient, IdIcmpClient, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.ODBC, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, FireDAC.Comp.Client, FireDAC.Phys.ODBCDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet; type TDM = class(TDataModule) WCURSOR: TFDGUIxWaitCursor; CONEXAO: TFDConnection; procedure ICMPReply(ASender: TComponent; const ReplyStatus: TReplyStatus); procedure verificarconexao; private { Private declarations } public { Public declarations } Empresa_Atual: Integer; chusuario: Integer; DatahoraServidor: TDateTime; function execSql(strQry:string): boolean; end; var DM: TDM; Respondeu: Boolean; ip: string; implementation {%CLASSGROUP 'System.Classes.TPersistent'} uses Winapi.Windows, IniFiles; {$R *.dfm} function TDM.execSql(strQry: string): boolean; begin end; procedure TDM.ICMPReply(ASender: TComponent; const ReplyStatus: TReplyStatus); var s: integer; begin s := ReplyStatus.BytesReceived; if s=0 then Respondeu:=false else Respondeu:=true; end; procedure TDM.verificarconexao; begin Application.ProcessMessages; end; end.
unit StringTrie; {Author: Nicholas Sherlock, 2006.} interface uses sysutils, contnrs, math; type TStringTrieNode = class private fKey: string; fOwnsObjects: boolean; public HasValue: boolean; Value: TObject; children: TObjectList; function Insert(const key: string; startindex: integer; value: TObject): boolean; function IsPrefix(const key: string; startindex: integer): Boolean; function Find(const key: string; startindex: integer; out value: TObject): Boolean; constructor CreateAssign(copyFrom: TStringTrieNode); constructor Create(ownsObjects: boolean); destructor Destroy; override; property Key: string read fkey write fkey; end; TStringTrie = class private fRoot: TStringTrieNode; fOwnsObjects, fCaseSensitive: boolean; public function PrintStructure: string; function PrintKeys: string; procedure Insert(const key: string; value: TObject); //Is the given key a prefix of a key/value pair in the tree? function IsPrefix(const key: string): Boolean; //Does the given key match a key/value pair in the tree? function Find(const key: string; out value: TObject): Boolean; constructor Create(ownsObjects: boolean; casesensitive: boolean); destructor Destroy; override; end; implementation constructor TStringTrieNode.createAssign(copyFrom: TStringTrieNode); begin Self.HasValue := copyFrom.HasValue; Self.Value := copyFrom.Value; Self.Key := copyFrom.Key; Self.children := copyFrom.children; //Note that we just get a reference to the other's list!! end; constructor TStringTrieNode.Create(ownsObjects: boolean); begin children := TObjectList.create; fOwnsObjects := ownsObjects; end; destructor TStringTrieNode.Destroy; begin children.free; if fOwnsObjects and HasValue then Value.free; inherited; end; //Return true if key/value was inserted into this trie, otherwise false if it doesn't belong here. function TStringTrieNode.Insert(const key: string; startindex: integer; value: TObject): boolean; var i: integer; child: TStringTrieNode; begin result := length(fKey) = 0; //special case for root node //Find the bits of our key that match the key provided... i := 1; while (i <= length(fkey)) and (startindex <= length(key)) do //check that Key matches fKey if AnsiCompareStr(fkey[i], key[startindex]) = 0 then begin result := true; inc(i); inc(startindex); end else break; {None of the provided key matched our key, provided key shouldn't be one of our children} if not result then exit; (*now i is the index of the first non-matched character in our key, startindex the index of the first non-matched in provided key.*) {If the whole provided key matches our key, then startindex>length(key) and i>length(fkey). Replace our value with the provided one} if (startIndex > length(key)) and (i > length(fKey)) then begin HasValue := true; Self.Value := value; end else if (i > length(fkey)) then begin {provided key matched our complete key, but there is still some provided key left over. Insert in one of our children or make a new child} for i := 0 to children.count - 1 do if TStringTrieNode(children[i]).Insert(key, startindex, value) then Exit; //job done //we must add a child child := TStringTrieNode.Create(fOwnsObjects); child.Key := Copy(key, startindex, length(key)); child.HasValue := true; child.value := value; children.add(child); end else if (startindex > length(key)) then begin //complete provided key matches only part of our key. We must split up //Take our contents and put into a new child child := TStringTrieNode.createAssign(self); child.fKey := copy(fkey, i, length(fkey)); children := TObjectList.create; //since they stole ours children.add(child); //we take the new values Self.Key := copy(Self.key, 1, i - 1); hasvalue := true; self.value := value; end else begin {some of the provided key matches some of our key.} //Take our contents and put into a new child child := TStringTrieNode.createAssign(self); //Take our contents child.fKey := copy(fkey, i, length(fkey)); children := TObjectList.create; //Since our new child stole ours children.add(child); //We take the shared parts of the key, but lose our value to become a branch Self.Key := copy(Self.Key, 1, i - 1); HasValue := false; Value := nil; //The provided key becomes our child too... child := TStringTrieNode.create(fownsobjects); child.Key := copy(key, startindex, length(key)); child.HasValue := true; child.Value := value; children.add(child); end; end; function TStringTrieNode.IsPrefix(const key: string; startindex: integer): Boolean; var i: integer; begin result := false; i := 1; while (i <= length(fkey)) and (startindex <= length(key)) do begin //check that Key matches fKey if AnsiCompareStr(fkey[i], key[startindex]) = 0 then begin inc(i); inc(startindex); end else exit; end; if startIndex > length(key) then begin //we have matched the whole key result := true; exit; end else //we haven't matched the whole key yet. Let's ask our children for i := 0 to children.count - 1 do if TStringTrieNode(children[i]).IsPrefix(key, startindex) then begin result := true; exit; end; end; function TStringTrieNode.Find(const key: string; startindex: integer; out value: TObject): Boolean; var i: integer; begin result := false; if length(key) - startindex + 1 < length(fkey) then exit; //can't match, it's too short! i := 1; while i <= length(fkey) do begin //check that Key matches fKey if AnsiCompareStr(fkey[i], key[startindex]) = 0 then begin inc(i); inc(startindex); end else exit; //key doesn't match, key can't be us or one of our children end; //if we're here, (the start of) Key matches our key if (startIndex > length(key)) and HasValue then begin //we have matched the whole key value := Self.Value; result := true; exit; end else //we haven't matched the whole key yet. Let's ask our children for i := 0 to children.count - 1 do if TStringTrieNode(children[i]).Find(key, startindex, value) then begin result := true; exit; end; end; function RecursePrintStructure(node: TStringTrieNode; indent: integer): string; var t1: integer; begin if node.HasValue then result := stringofchar(' ', indent) + node.fKey + ' (' + inttostr(integer(node.value)) + ')' + #13#10 else result := stringofchar(' ', indent) + node.fKey + #13#10; for t1 := 0 to node.children.count - 1 do result := result + RecursePrintStructure(TStringTrieNode(node.children[t1]), indent + 2); end; function RecursePrintKeys(node: TStringTrieNode; const key: string): string; var t1: integer; begin if node.HasValue then result := key + node.fKey + ' (' + inttostr(integer(node.value)) + ')' + #13#10 else result := ''; for t1 := 0 to node.children.count - 1 do result := result + RecursePrintKeys(TStringTrieNode(node.children[t1]), key + node.fkey); end; function TStringTrie.PrintKeys: string; begin result := RecursePrintkeys(froot, ''); end; function TStringTrie.PrintStructure: string; begin result := RecursePrintStructure(froot, 0); end; procedure TStringTrie.Insert(const key: string; value: TObject); begin fRoot.Insert(key, 1, value); end; function TStringTrie.IsPrefix(const key: string): Boolean; begin result := froot.IsPrefix(key, 1); end; function TStringTrie.Find(const key: string; out value: TObject): Boolean; begin result := fRoot.find(key, 1, value); end; constructor TStringTrie.Create(ownsobjects: boolean; casesensitive: boolean); begin fRoot := TStringTrieNode.Create(true); fOwnsObjects := ownsObjects; fCaseSensitive := caseSensitive; end; destructor TStringTrie.Destroy; begin fRoot.free; inherited; end; end.
unit UtilForms; interface uses Forms, Controls, Classes, JvCaptionButton, Dialogs, ActnList; type TCaptionButtons = set of (cbAlwaysOnTop, cbMaximize); TActionForm = class(TComponent) private Action: TAction; Form: TForm; FormClass: TFormClass; procedure OnExecute(Sender: TObject); public constructor Create(const AOwner: TComponent; const Action: TAction; const FormClass: TFormClass); reintroduce; destructor Destroy; override; end; function CreateUniqueForm(const formClass: TFormClass; const Owner: TComponent; const name: string): TForm; overload; function CreateUniqueForm(const formClass: TFormClass; const Owner: TComponent): TForm; overload; function ShowFormModal(const formClass: TFormClass): TModalResult; overload; function ShowFormModal(const formClass: TFormClass; const Owner: TComponent): TModalResult; overload; function ShowForm(const formClass: TFormClass; const Owner: TComponent; const name: string): TForm; overload; function ShowForm(const formClass: TFormClass; const Owner: TComponent): TForm; overload; function FindForm(const Owner: TComponent; const name: string): TForm; procedure MaximizeRestoreCaptionButton(Form: TCustomForm; JvCaptionButton: TJvCaptionButton); procedure DrawRounded(Control: TWinControl); procedure AddCaptionButtons(const Form: TForm; const buttons: TCaptionButtons); function ShowMensaje(const titulo, mensaje: string; const DlgType: TMsgDlgType; const Buttons: TMsgDlgButtons): integer; implementation uses Windows, Messages, dmRecursosListas, SysUtils; type TCaptionButton = class(TJvCaptionButton) protected procedure OnClickEvent(Sender: TObject); virtual; abstract; public constructor Create(AOwner: TComponent); override; end; TCaptionButtonAlwaysOnTop = class(TCaptionButton) protected procedure OnClickEvent(Sender: TObject); override; public constructor Create(AOwner: TComponent); override; end; TCaptionButtonMaximize = class(TCaptionButton) protected procedure OnClickEvent(Sender: TObject); override; public constructor Create(AOwner: TComponent); override; end; procedure AddCaptionButtons(const Form: TForm; const buttons: TCaptionButtons); var pos: integer; begin pos := 0; if cbMaximize in buttons then begin TCaptionButtonMaximize.Create(Form).Position := pos; inc(pos); end; if cbAlwaysOnTop in buttons then TCaptionButtonAlwaysOnTop.Create(Form).Position := pos; end; procedure MaximizeRestoreCaptionButton(Form: TCustomForm; JvCaptionButton: TJvCaptionButton); var R:TRect; Tasklist : HWnd; begin if Form.WindowState = wsMaximized then begin Form.WindowState := wsNormal; JvCaptionButton.Standard := tsbMax; end else begin Form.WindowState := wsMaximized; JvCaptionButton.Standard := tsbRestore; // Al maximizar la barra de windows tapa un trozo. Se modifica el Height // para que vaya por encima de la barra de windows. Tasklist := FindWindow('Shell_TrayWnd', nil); GetWindowRect(Tasklist, R); Form.Height := Form.Height - (R.Bottom - R.Top) - 2; end; end; procedure DrawRounded(Control: TWinControl); var R: TRect; Rgn: HRGN; begin with Control do begin R := ClientRect; rgn := CreateRoundRectRgn(R.Left, R.Top, R.Right, R.Bottom, 20, 20) ; Perform(EM_GETRECT, 0, lParam(@r)) ; InflateRect(r, - 4, - 4) ; Perform(EM_SETRECTNP, 0, lParam(@r)) ; SetWindowRgn(Handle, rgn, True) ; Invalidate; end; end; function ShowFormModal(const formClass: TFormClass; const Owner: TComponent): TModalResult; var form: TForm; begin Screen.Cursor := crHourGlass; try form := formClass.Create(Owner); try Screen.Cursor := crDefault; result := form.ShowModal; finally form.Free; end; finally Screen.Cursor := crDefault; end; end; function ShowFormModal(const formClass: TFormClass): TModalResult; begin result := ShowFormModal(formClass, nil); end; function FindForm(const Owner: TComponent; const name: string): TForm; begin result := Owner.FindComponent(name) as TForm; end; function ShowForm(const formClass: TFormClass; const Owner: TComponent): TForm; begin result := ShowForm(formClass, Owner, formClass.ClassName); end; function ShowForm(const formClass: TFormClass; const Owner: TComponent; const name: string): TForm; var form: TForm; begin Screen.Cursor := crHourGlass; try form := CreateUniqueForm(formClass, Owner, name); form.Show; finally Screen.Cursor := crDefault; end; result := form; end; function CreateUniqueForm(const formClass: TFormClass; const Owner: TComponent; const name: string): TForm; var form: TForm; begin form := Owner.FindComponent(name) as TForm; if form = nil then begin form := formClass.Create(Owner); form.Name := name; end; result := form; end; function CreateUniqueForm(const formClass: TFormClass; const Owner: TComponent): TForm; begin result := CreateUniqueForm(formClass, Owner, formClass.ClassName); end; function ShowMensaje(const titulo, mensaje: string; const DlgType: TMsgDlgType; const Buttons: TMsgDlgButtons): integer; var flag: integer; begin case DlgType of mtWarning: flag := MB_ICONWARNING; mtError: flag := MB_ICONERROR; mtInformation: flag := MB_ICONINFORMATION; mtConfirmation: flag := MB_ICONQUESTION; else raise Exception.Create('DlgType not supported'); end; if Buttons = mbYesNo then flag := flag + MB_YESNO else if Buttons = [mbOK] then flag := flag + MB_OK else flag := flag + MB_YESNOCANCEL; result := Application.MessageBox(PChar(mensaje), PChar(titulo), flag); end; { TCaptionButtonAlwaysOnTop } constructor TCaptionButtonAlwaysOnTop.Create(AOwner: TComponent); begin inherited Create(AOwner); Images := RecursosListas.ImageListAlwaysOnTop; ImageIndex := 0; end; procedure TCaptionButtonAlwaysOnTop.OnClickEvent(Sender: TObject); var Form: TForm; begin Form := Owner as TForm; if Form.FormStyle = fsNormal then begin Form.FormStyle := fsStayOnTop; Standard := tsbMinimizeToTray; end else begin Form.FormStyle := fsNormal; Standard := tsbNone; end; end; { TCaptionButton } constructor TCaptionButton.Create(AOwner: TComponent); begin inherited Create(AOwner); OnClick := OnClickEvent; end; { TCaptionButtonMaximize } constructor TCaptionButtonMaximize.Create(AOwner: TComponent); var Form: TForm; begin inherited Create(AOwner); Form := AOwner as TForm; if Form.WindowState = wsMaximized then Standard := tsbRestore else Standard := tsbMax; end; procedure TCaptionButtonMaximize.OnClickEvent(Sender: TObject); begin MaximizeRestoreCaptionButton(Owner as TForm, Self); end; { TActionForm } constructor TActionForm.Create(const AOwner: TComponent; const Action: TAction; const formClass: TFormClass); begin inherited Create(AOwner); Self.FormClass := FormClass; Self.Action := Action; Action.OnExecute := OnExecute; if Action.Checked then OnExecute(nil); end; destructor TActionForm.Destroy; begin if Form <> nil then Form.Free; inherited; end; procedure TActionForm.OnExecute(Sender: TObject); begin if Form = nil then begin Form := FormClass.Create(nil); Form.Show; Action.Checked := true; end else begin FreeAndNil(Form); Action.Checked := False; end; end; end.
unit BufferedStream; interface Uses Classes; type TBufferedStream = class(TStream) private FBuf: array[0..1023] of Byte; FBufPos: Integer; FBufSize: Integer; FStream: TStream; FStreamPos: Int64; FStreamSize: Int64; FWriting: Boolean; procedure WriteBuffer; protected function GetSize: Int64; override; procedure SetSize(const NewSize: Int64); override; public constructor Create(Stream: TStream); destructor Destroy; override; function Read(var Buffer; Count: Longint): Longint; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; function Write(const Buffer; Count: Longint): Longint; override; end; implementation Uses Math; constructor TBufferedStream.Create(Stream: TStream); begin inherited Create; FStream := Stream; FStreamPos := Stream.Position; FStreamSize := Stream.Size; end; destructor TBufferedStream.Destroy; begin if FWriting and (FBufSize > 0) then FStream.WriteBuffer(FBuf, FBufSize); inherited; end; function TBufferedStream.GetSize: Int64; begin Result := FStreamSize; end; function TBufferedStream.Read(var Buffer; Count: Longint): Longint; var i: Integer; P: PByte; begin if FWriting then begin if FBufSize > 0 then FStream.WriteBuffer(FBuf, FBufSize); FWriting := False; Inc(FStreamPos, FBufPos); FStream.Position := FStreamPos; FBufPos := 0; FBufSize := 0; end; if Count > SizeOf(FBuf) then begin FStream.Seek(FStreamPos + FBufPos, soBeginning); Result := FStream.Read(Buffer, Count); FStreamPos := FStream.Position; FBufPos := 0; FBufSize := 0; Exit; end; Result := 0; P := @Buffer; while Count > 0 do begin if FBufPos = FBufSize then begin Inc(FStreamPos, FBufSize); FBufSize := FStream.Read(FBuf, SizeOf(FBuf)); FBufPos := 0; if FBufSize = 0 then Break; end; i := Min(Count, FBufSize - FBufPos); Move(FBuf[FBufPos], P^, i); Inc(FBufPos, i); Inc(P, i); Dec(Count, i); Inc(Result, i); end; end; function TBufferedStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin Result := Offset; case Origin of soCurrent: Inc(Result, FStreamPos + FBufPos); soEnd: Result := FStreamSize + Result; end; if Result < 0 then Result := 0 else if Result > FStreamSize then Result := FStreamSize; if (Result >= FStreamPos) and (Result <= FStreamPos + FBufSize) then FBufPos := Result - FStreamPos else begin if FWriting and (FBufSize > 0) then WriteBuffer; FStream.Position := Result; FStreamPos := Result; FBufPos := 0; FBufSize := 0; end; end; procedure TBufferedStream.SetSize(const NewSize: Int64); begin if FStreamSize <> NewSize then begin if FWriting and (FBufSize > 0) then WriteBuffer; FStream.Size := NewSize; FStreamPos := NewSize; FStreamSize := NewSize; end; end; function TBufferedStream.Write(const Buffer; Count: Longint): Longint; var i: Integer; P: PByte; begin if Count > SizeOf(FBuf) then begin if FWriting AND (FBufSize > 0) then begin WriteBuffer; FWriting := False; end; Result := FStream.Write(Buffer, Count); FStreamPos := FStream.Position; FStreamSize := FStream.Size; FBufPos := 0; FBufSize := 0; Exit; end; if not FWriting then begin FWriting := True; Inc(FStreamPos, FBufPos); FStream.Position := FStreamPos; FBufPos := 0; FBufSize := 0; end; Result := 0; P := @Buffer; while Count > 0 do begin i := Min(Count, SizeOf(FBuf) - FBufPos); Move(P^, FBuf[FBufPos], i); Inc(FBufPos, i); if FBufPos > FBufSize then begin FBufSize := FBufPos; if FStreamPos + FBufSize > FStreamSize then FStreamSize := FStreamPos + FBufSize; end; Inc(P, i); Dec(Count, i); Inc(Result, i); if FBufPos = SizeOf(FBuf) then WriteBuffer; end; end; procedure TBufferedStream.WriteBuffer; begin FStream.WriteBuffer(FBuf, FBufSize); Inc(FStreamPos, FBufSize); FBufPos := 0; FBufSize := 0; end; end.
unit Versao; interface type TVersao = class private FVersaoBancoDeDados :Integer; FCodigo :Integer; private procedure SetCodigo (const Value: Integer); procedure SetVersaoBancoDeDados (const Value: Integer); public property Codigo :Integer read FCodigo write SetCodigo; property VersaoBancoDeDados :Integer read FVersaoBancoDeDados write SetVersaoBancoDeDados; end; implementation { TVersao } procedure TVersao.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TVersao.SetVersaoBancoDeDados(const Value: Integer); begin FVersaoBancoDeDados := Value; end; end.
unit uConfigBaseIni; interface {$TYPEINFO ON} type IConfigurableSettings = interface ['{41935A6A-6FFE-45D8-A3D6-FF74BD3E0655}'] {$REGION 'Private Getters and Setters'} function GetSection: string; function GetConfigFilename: string; procedure SetSection(const Value: string); procedure SetConfigFilename(const Value: string); {$ENDREGION} procedure Save; procedure Load; property Section: string read GetSection write SetSection; property Configfilename: string read GetConfigFilename write SetConfigFilename; end; TCustomConfigSettings = class(TObject, IConfigurableSettings) strict private {$REGION 'private fields'} FSection: string; FAppDataPath: string; FConfigFilename: string; {$ENDREGION} private {$REGION 'IConfigurable getters and setters'} function GetSection: string; function GetConfigFilename: string; procedure SetSection(const AValue: string); procedure SetConfigFilename(const Value: string); {$ENDREGION} protected procedure CustomSave; virtual; abstract; procedure CustomLoad; virtual; abstract; // IInterface -- not descended from TInterfacedObject because don't want reference counting function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; public constructor Create(ASection: string = ''); overload; virtual; procedure Save; virtual; procedure Load; virtual; published property AppDataPath: string read FAppDataPath write FAppDataPath; property Section: string read GetSection write SetSection; property Configfilename: string read GetConfigFilename write SetConfigFilename; end; implementation uses {$IFDEF UseCodeSite} CodeSiteLogging, {$ENDIF} SysUtils; {$REGION 'TCustomConfigSettings'} constructor TCustomConfigSettings.Create(ASection: string = ''); begin {$IFDEF UseCodeSite} CodeSite.EnterMethod(Self, 'Create'); {$ENDIF} {$IFDEF UseCodeSite} CodeSite.Send('ASection', ASection); {$ENDIF} {$IFDEF DEBUG} ReportMemoryLeaksOnShutdown := True; {$ENDIF} FSection := ASection; {$IFDEF UseCodeSite} CodeSite.ExitMethod(Self, 'Create'); {$ENDIF} end; function TCustomConfigSettings.GetConfigFilename: string; begin Result := FConfigFilename; end; function TCustomConfigSettings.GetSection: string; begin Result := FSection; end; procedure TCustomConfigSettings.Load; begin {$IFDEF UseCodeSite} CodeSite.EnterMethod(Self, 'Load'); {$ENDIF} if Length(FConfigFilename) = 0 then raise EProgrammerNotFound.Create('[Load] Did not set configuration filename: ' + self.ClassName); CustomLoad; {$IFDEF UseCodeSite} CodeSite.ExitMethod(Self, 'Load'); {$ENDIF} end; procedure TCustomConfigSettings.Save; begin {$IFDEF UseCodeSite} CodeSite.EnterMethod(Self, 'Save'); {$ENDIF} if Length(FConfigFilename) = 0 then raise EProgrammerNotFound.Create('[Save] Did not set configuration filename: ' + self.ClassName); CustomSave; {$IFDEF UseCodeSite} CodeSite.ExitMethod(Self, 'Save'); {$ENDIF} end; procedure TCustomConfigSettings.SetConfigFilename(const Value: string); begin {$IFDEF UseCodeSite} CodeSite.EnterMethod(Self, 'SetConfigFilename'); {$ENDIF} {$IFDEF UseCodeSite} CodeSite.Send('value', value); {$ENDIF} FConfigFilename := Value; {$IFDEF UseCodeSite} CodeSite.ExitMethod(Self, 'SetConfigFilename'); {$ENDIF} end; procedure TCustomConfigSettings.SetSection(const AValue: string); begin FSection := AValue; end; function TCustomConfigSettings.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; function TCustomConfigSettings._AddRef: Integer; begin // don't reference count Result := -1; end; function TCustomConfigSettings._Release: Integer; begin // don't reference count Result := -1; end; {$ENDREGION} end.
unit TarFTP.Controller; interface uses Windows, SysUtils, Dialogs, Classes, TarFTP.MVC, Generics.Collections; type TViewRegistry = TDictionary<TGUID, IView>; TController = class(TInterfacedObject, IController) private FModel: IModel; FViewRegistry : TViewRegistry; procedure TaskEvent(Task : TTaskKind; State : TTaskState); public { IController } procedure RegisterView(const Kind : TGUID; const View : IView); procedure CompressAndUpload; { Common } constructor Create(const Model : IModel); destructor Destroy; override; end; implementation uses IOUtils; { TController } constructor TController.Create(const Model: IModel); begin Assert( Assigned( Model ), 'Model is unassigned' ); FViewRegistry := TViewRegistry.Create; FModel := Model; FModel.OnTaskEvent := Self.TaskEvent; end; destructor TController.Destroy; begin FModel := nil; FreeAndNil( FViewRegistry ); inherited; end; procedure TController.RegisterView(const Kind: TGUID; const View: IView); begin Assert( Assigned( View ), 'View is unassigned' ); FViewRegistry.AddOrSetValue( Kind, View ); end; procedure TController.TaskEvent(Task: TTaskKind; State: TTaskState); var view : IView; begin case Task of tkCompress : view := FViewRegistry[ IFileCompressionView ]; tkUpload : view := FViewRegistry[ IFileUploadView ]; else Exit; end; if State = tsBeforeStarted then view.Display else begin view.Close; FViewRegistry[ IMainView ].ProcessErrors; if not ( FModel.Error or FModel.Terminated ) then if ( Task = tkCompress ) then FModel.Upload else ShowMessage( 'File sent' ); end; end; procedure TController.CompressAndUpload; var fileName : String; begin FModel.Reset; fileName := TPath.GetTempFileName; DeleteFile( fileName ); fileName := ChangeFileExt( fileName, '.tar' ); FModel.SetOutputFile( fileName ); FModel.Compress; end; end.
unit RepositorioCampoAlteradoAuditoria; interface uses Repositorio, DB; type TRepositorioCampoAlteradoAuditoria = class(TRepositorio) protected function Get (Dataset :TDataSet) :TObject; overload; override; function GetNomeDaTabela :String; override; function GetIdentificador(Objeto :TObject) :Variant; override; function GetRepositorio :TRepositorio; override; protected function SQLGet :String; override; function SQLSalvar :String; override; function SQLGetAll :String; override; function SQLRemover :String; override; function SQLGetExiste(campo: String) :String; override; protected function IsInsercao(Objeto :TObject) :Boolean; override; protected procedure SetParametros (Objeto :TObject ); override; procedure SetIdentificador(Objeto :TObject; Identificador :Variant); override; end; implementation uses CampoAlteracaoAuditoria; { TRepositorioCampoAlteradoAuditoria } function TRepositorioCampoAlteradoAuditoria.Get( Dataset: TDataSet): TObject; var Campo :TCampoAlteracaoAuditoria; begin Campo := TCampoAlteracaoAuditoria.Create; Campo.Codigo := Dataset.FieldByName('codigo').AsInteger; Campo.NomeCampo := Dataset.FieldByName('nome_campo').AsString; Campo.ValorCampoNovo := Dataset.FieldByName('valor_campo_novo').AsString; Campo.ValorCampoAntigo := Dataset.FieldByName('valor_campo_antigo').AsString; Campo.CodigoAuditoria := Dataset.FieldByName('codigo_auditoria').AsInteger; Result := Campo; end; function TRepositorioCampoAlteradoAuditoria.GetIdentificador( Objeto: TObject): Variant; begin result := TCampoAlteracaoAuditoria(Objeto).Codigo; end; function TRepositorioCampoAlteradoAuditoria.GetNomeDaTabela: String; begin result := 'ALTERACOES_AUDITORIA'; end; function TRepositorioCampoAlteradoAuditoria.GetRepositorio: TRepositorio; begin result := TRepositorioCampoAlteradoAuditoria.Create; end; function TRepositorioCampoAlteradoAuditoria.IsInsercao( Objeto: TObject): Boolean; begin result := (TCampoAlteracaoAuditoria(Objeto).Codigo <= 0); end; procedure TRepositorioCampoAlteradoAuditoria.SetIdentificador( Objeto: TObject; Identificador: Variant); begin TCampoAlteracaoAuditoria(Objeto).Codigo := Integer(Identificador); end; procedure TRepositorioCampoAlteradoAuditoria.SetParametros( Objeto: TObject); var Obj :TCampoAlteracaoAuditoria; begin Obj := (Objeto as TCampoAlteracaoAuditoria); inherited SetParametro('codigo', Obj.Codigo); inherited SetParametro('nome_campo', Obj.NomeCampo); inherited SetParametro('valor_campo_novo', Obj.ValorCampoNovo); inherited SetParametro('valor_campo_antigo', Obj.ValorCampoAntigo); inherited SetParametro('codigo_auditoria', Obj.Auditoria.Codigo); end; function TRepositorioCampoAlteradoAuditoria.SQLGet: String; begin result := 'select * from '+self.GetNomeDaTabela+' where codigo = :codigo'; end; function TRepositorioCampoAlteradoAuditoria.SQLGetAll: String; begin result := 'select * from '+self.GetNomeDaTabela; end; function TRepositorioCampoAlteradoAuditoria.SQLGetExiste( campo: String): String; begin result := 'select '+ campo +' from '+self.GetNomeDaTabela+' where '+ campo +' = :ncampo'; end; function TRepositorioCampoAlteradoAuditoria.SQLRemover: String; begin result := 'delete from '+self.GetNomeDaTabela+' where codigo = :codigo '; end; function TRepositorioCampoAlteradoAuditoria.SQLSalvar: String; begin result := ' update or insert into alteracoes_auditoria '+ ' (codigo, codigo_auditoria, nome_campo, valor_campo_antigo, valor_campo_novo) '+ ' values (:codigo, :codigo_auditoria, :nome_campo, :valor_campo_antigo, :valor_campo_novo) '; end; end.
unit Project87.BigEnemy; interface uses QGame.Scene, Strope.Math, Project87.BaseUnit, Project87.BaseEnemy, Project87.Types.Weapon, Project87.Types.GameObject, Project87.Types.StarMap; const MAX_LIFE = 300; MAX_FIRE_DISTANCE = 450 * 450; MIN_FIRE_DISTANCE = 300 * 300; MAX_BIG_UNIT_SPEED = 400; type TBigEnemy = class (TBaseEnemy) protected FLauncher: TLauncher; procedure AIAct(const ADelta: Double); override; public constructor CreateUnit(const APosition: TVector2F; AAngle: Single; ASide: TLifeFraction); override; procedure OnDraw; override; procedure OnUpdate(const ADelta: Double); override; procedure Kill; override; end; implementation uses QEngine.Core, Project87.Hero, Project87.Fluid, Project87.Resources; {$REGION ' TBaseEnemy '} constructor TBigEnemy.CreateUnit(const APosition: TVector2F; AAngle: Single; ASide: TLifeFraction); begin inherited; FLauncher := TLauncher.Create(oEnemy, 3, 70 * THero.GetInstance.ExpFactor, 200); FRadius := 85; FMass := 3; FLife := MAX_LIFE * THero.GetInstance.ExpFactor; FMaxLife := MAX_LIFE * THero.GetInstance.ExpFactor; end; procedure TBigEnemy.OnDraw; var ShieldAlpha: Byte; begin ShieldAlpha := Trunc(FShowShieldTime * $52); TheResources.FieldTexture.Draw(FPosition, Vec2F(170, 170), FTowerAngle, ShieldAlpha * $1000000 + FColor - $FF000000); TheResources.BigEnemyTexture.Draw(FPosition, Vec2F(150, 150), FAngle, FColor); TheResources.MachineGunTexture.Draw(FPosition, Vec2F(20, 30), FTowerAngle, FColor); if FLife < FMaxLife then TheRender.Rectangle( FPosition.X - 50, FPosition.Y - 53, FPosition.X - 50 + FLife / FMaxLife * 100, FPosition.Y - 50, $FF00FF00); end; procedure TBigEnemy.AIAct(const ADelta: Double); begin FDistanceToHero := (FPosition - THeroShip.GetInstance.Position).LengthSqr; FActionTime := FActionTime - ADelta; case FCurrentAction of None: begin FCurrentAction := FlyToHeroAndFire; end; FlyToHeroAndFire: begin //FAngle := RotateToAngle(FAngle, GetAngle(FPosition, THeroShip.GetInstance.Position), 3); FVelocity := FVelocity * (1 - ADelta) + GetRotatedVector(GetAngle(FPosition, THeroShip.GetInstance.Position), MAX_BIG_UNIT_SPEED) * (ADelta); if FDistanceToHero < MAX_FIRE_DISTANCE then SetAction(StopAndFireToHero, Random(10) / 10 + 1); end; FlyBack: begin FVelocity := FVelocity * (1 - ADelta) + GetRotatedVector(GetAngle(THeroShip.GetInstance.Position, FPosition), MAX_BIG_UNIT_SPEED) * (ADelta); if FDistanceToHero > MIN_FIRE_DISTANCE then SetAction(StopAndFireToHero, Random(10) / 10 + 1); end; StopAndFireToHero: begin FVelocity := FVelocity * (1 - ADelta); if FDistanceToHero < MIN_FIRE_DISTANCE then SetAction(FlyBack, Random(10) / 10 + 1); if FDistanceToHero > MAX_FIRE_DISTANCE then SetAction(FlyToHeroAndFire, Random(10) / 10 + 1); end; end; if FDistanceToHero < DISTANCE_TO_FIRE then begin FCannon.Fire(FPosition, FTowerAngle); FLauncher.Fire(FPosition, THeroShip.GetInstance.Position, FTowerAngle); end; end; procedure TBigEnemy.OnUpdate(const ADelta: Double); begin inherited; FLauncher.OnUpdate(ADelta); FAngle := FAngle + 1; FTowerAngle := RotateToAngle(FTowerAngle, GetAngle(FPosition, THeroShip.GetInstance.Position), 10); end; procedure TBigEnemy.Kill; begin THero.GetInstance.AddExp(9); FIsDead := True; TFluid.EmmitFluids(6, FPosition, TFluidType(Random(4))); end; {$ENDREGION} end.
unit Controller; interface uses Data.DBXMySQL, Data.FMTBcd, Vcl.Dialogs,Vcl.Forms, Datasnap.DBClient, Datasnap.Provider, Data.DB, Data.SqlExpr, Vcl.StdCtrls, system.SysUtils, System.Generics.Collections,NewLibrary_Intf, uROClient, uROClientIntf, uRORemoteService, uROBinMessage, uROWinInetHTTPChannel, uROChannelAwareComponent, uROBaseConnection, uROTransportChannel, uROBaseHTTPClient, uROComponent, uROMessage; type IAtualizaTela = interface ['{45A3240D-60C7-4DD3-A1A2-0F8EE1BF056A}'] //['{8FF85A15-68A4-4284-AF2E-CE7521D70C14}'] procedure AtualizaTela; end; TController = class(TObject) {ROMessage: TROBinMessage; ROChannel: TROWinInetHTTPChannel; RORemoteService: TRORemoteService;} strict private class var FInstance : TController; private class procedure ReleaseInstance(); private FTelaPrincipal: TForm; FTelaSecundaria: TForm; procedure SetTelaPrincipal(const Value: TForm); procedure SetTelaSecundaria(const Value: TForm); public class function GetInstance(): TController; constructor create; reintroduce; destructor destroy; override; function ctrlspeciality(CSpeciality:speciality; ClientDataSet : TClientDataSet) : speciality; procedure clientrefresh(ClientDataSet:TClientDataSet); procedure pesquisar(especialidade,OS : String; ClientDataSet : TClientDataSet); procedure carregarCBAdmGroup(Cb : TCombobox); procedure AdminRefresh(ClientDataSet : TClientDataSet); procedure pesquisaradm(descricao, OS : String; ClientDataSet : TClientDataSet); function ctrladm(Cadmingroup:Admingroup; ClientDataSet : TClientDataSet) : admingroup; procedure AtualizarTelas(); property TelaPrincipal : TForm read FTelaPrincipal write SetTelaPrincipal; property TelaSecundaria : TForm read FTelaSecundaria write SetTelaSecundaria; end; implementation uses fClientForm; class function TController.GetInstance: TController; begin if not Assigned(FInstance) then FInstance := TController.Create; Result := FInstance; end; class procedure TController.ReleaseInstance; begin if Assigned(FInstance) then FInstance.Free; end; procedure TController.SetTelaPrincipal(const Value: TForm); begin FTelaPrincipal := Value; end; procedure TController.SetTelaSecundaria(const Value: TForm); begin FTelaSecundaria := Value; end; function TController.ctrlspeciality(CSpeciality:speciality; ClientDataSet : TClientDataSet) : speciality; var res : boolean; begin try case Cspeciality.comando of specCMDDetalhes: result := (ClientForm.RORemoteService as INewService).carregarSpeciality(Cspeciality.id); specCMDExcluir: (ClientForm.RORemoteService as INewService).excluirspeciality(ClientDataSet.Fields[0].AsString); specCMDAlterar: (ClientForm.RORemoteService as INewService).alterarSpeciality(Cspeciality.description,CSpeciality.flag_funcao_oper,CSpeciality.codg_admingroup_fk, Cspeciality.id); specCMDInserir: res :=(ClientForm.RORemoteService as INewService).inserirSpeciality(Cspeciality.id, Cspeciality.description, CSpeciality.flag_funcao_oper, CSpeciality.codg_admingroup_fk); end; if (CSpeciality.comando = specCMDInserir) then begin if not res then begin showmessage('Código ja foi inserido'); result := (ClientForm.RORemoteService as INewService).carregarSpeciality(Cspeciality.id); end; end; finally if Cspeciality.comando <> specCMDDetalhes then begin ClientRefresh(ClientDataSet); end; end; end; destructor TController.destroy; begin {ROMessage.Free; ROChannel.Free; RORemoteService.Free;} inherited; end; procedure TController.ClientRefresh(ClientDataSet : TClientDataSet); var i : integer; lista : ArraySpeciality; begin ClientDataSet.DisableControls; i:=0; try ClientDataSet.EmptyDataSet; ClientDataSet.First; lista := (ClientForm.RORemoteService as INewService).ListaSpeciality; while (i < lista.count) do begin ClientDataSet.Append; ClientDataSet.FieldByName('specialityid').AsString := lista[i].id; ClientDataSet.FieldByName('description').AsString := lista[i].description; ClientDataSet.FieldByName('flag_funcao_oper').AsBoolean := lista[i].flag_funcao_oper; //PODE DAR RUIM ClientDataSet.FieldByName('codg_admingroup_fk').AsString := lista[i].codg_admingroup_fk; ClientDataSet.Next; i:=i+1; end; ClientDataSet.First; finally ClientDataSet.EnableControls; lista.Free; end; end; constructor TController.create; begin inherited; {ROMessage := TROBinMessage.Create; ROChannel := TROWinInetHTTPChannel.Create(nil); ROChannel.UserAgent := 'RemObjects SDK'; ROChannel.TargetUrl := 'http://127.0.0.1:8099/bin'; ROChannel.TrustInvalidCA := False; RORemoteService := TRORemoteService.Create(nil); RORemoteService.ServiceName := 'NewService'; RORemoteService.Channel := ROChannel; RORemoteService.Message := ROMessage;} end; procedure TController.pesquisar(especialidade, OS : String; ClientDataSet : TClientDataSet); var i : integer; lista : ArraySpeciality; begin ClientDataSet.DisableControls; lista := (ClientForm.RORemoteService as INewService).pesquisarSpeciality(especialidade, OS); i := 0; try ClientDataSet.EmptyDataSet; ClientDataSet.First; while (i < lista.count) do begin ClientDataSet.Append; ClientDataSet.FieldByName('specialityid').AsString := lista[i].id; ClientDataSet.FieldByName('description').AsString := lista[i].description; ClientDataSet.FieldByName('flag_funcao_oper').AsBoolean := lista[i].flag_funcao_oper; //PODE DAR MUITO RUIM ClientDataSet.FieldByName('codg_admingroup_fk').AsString := lista[i].codg_admingroup_fk; ClientDataSet.Next; i := i + 1; end; ClientDataSet.First; finally ClientDataSet.EnableControls; lista.Free; end; end; procedure TController.carregarCBAdmGroup(Cb : TCombobox); var i : integer; begin i:=0; cb.Clear; while (i <(ClientForm.RORemoteService as INewService).ListaAdminGroup.Count) do begin Cb.Items.Add((ClientForm.RORemoteService as INewService).ListaAdminGroup[i].id); i := i + 1; end; end; procedure TController.AdminRefresh(ClientDataSet : TClientDataSet); var i : integer; lista : ArrayAdmin; begin ClientDataSet.First; ClientDataSet.EmptyDataSet; ClientDataSet.DisableControls; i:=0; lista := (ClientForm.RORemoteService as INewService).ListaAdminGroup; try ClientDataSet.EmptyDataSet; ClientDataSet.First; while (i < lista.count) do begin ClientDataSet.Append; ClientDataSet.Fields[0].AsString := lista[i].id; ClientDataSet.Fields[1].AsString := lista[i].description; ClientDataSet.Next; i:=i+1; end; ClientDataSet.First; finally ClientDataSet.EnableControls; lista.Free; end; end; procedure TController.pesquisaradm(descricao, OS : String; ClientDataSet : TClientDataSet); var i : integer; lista : ArrayAdmin; begin ClientDataSet.DisableControls; i := 0; lista := (ClientForm.RORemoteService as INewService).pesquisaradmin(descricao, OS); try ClientDataSet.EmptyDataSet; ClientDataSet.First; while (i < lista.count) do begin ClientDataSet.Append; ClientDataSet.FieldByName('admingroupid').AsString := lista[i].id; ClientDataSet.FieldByName('description').AsString := lista[i].description; ClientDataSet.Next; i := i + 1; end; ClientDataSet.First; finally ClientDataSet.EnableControls; lista.Free; end; end; procedure TController.AtualizarTelas(); var lAtualizaTela : IAtualizaTela; lAtualizaTela2 : IAtualizaTela; begin //(FTelaPrincipal as IAtualizaTela).atualizaTela; //problema ? if supports(FTelaPrincipal, IAtualizaTela, lAtualizaTela) then begin lAtualizaTela.atualizaTela; end; if supports(FTelaSecundaria, IAtualizaTela, lAtualizaTela2) then begin lAtualizaTela2.atualizaTela; end; end; function TController.ctrladm(Cadmingroup:Admingroup; ClientDataSet : TClientDataSet) : admingroup; var res : boolean; begin try case Cadmingroup.comando of admCMDDetalhes: result := (ClientForm.RORemoteService as INewService).carregaradmingroup(Cadmingroup.id); admCMDExcluir: (ClientForm.RORemoteService as INewService).excluiradmingroup(ClientDataSet.Fields[0].AsString); admCMDAlterar: (ClientForm.RORemoteService as INewService).alteraradmingroup(Cadmingroup.description, Cadmingroup.id); admCMDInserir: res := (ClientForm.RORemoteService as INewService).inseriradmingroup(Cadmingroup.id, Cadmingroup.description); end; finally if Cadmingroup.comando = admCMDInserir then if not res then begin showmessage('Código ja foi inserido!'); result := (ClientForm.RORemoteService as INewService).carregaradmingroup(Cadmingroup.id); end; if Cadmingroup.comando <> admCMDDetalhes then begin adminRefresh(ClientDataSet); //comentado? AtualizarTelas; end; end; end; initialization finalization TController.ReleaseInstance(); end.
program RGBBoxes; {$IFNDEF HASAMIGA} {$FATAL This source is compatible with Amiga, AROS and MorphOS only !} {$ENDIF} { Project : RGBBoxes Source : RKRM } {* ** The following example creates a View consisting of one ViewPort set ** to an NTSC, high-resolution, interlaced display mode of nominal ** dimensions. This example shows both the old 1.3 way of setting up ** the ViewPort and the new method used in Release 2. *} {$MODE OBJFPC}{$H+}{$HINTS ON} {$UNITPATH ../../../Base/CHelpers} {$UNITPATH ../../../Base/Trinity} Uses Exec, AmigaDOS, AGraphics, Utility, CHelpers, Trinity; Type PUByte = ^UBYTE; const DEPTH = 2; //* The number of bitplanes. */ WIDTH = 640; //* Nominal width and height */ HEIGHT = 400; //* used in 1.3. */ procedure drawFilledBox(fillcolor: SmallInt; plane: SmallInt); forward; //* Function prototypes */ procedure cleanup(returncode: Integer); forward; procedure fail(errorstring: STRPTR); forward; Var {$IF DEFINED(AMIGA) or DEFINED(MORPHOS)} GfxBase : PGfxBase absolute AGraphics.GfxBase; {$ENDIF} //* Construct a simple display. These are global to make freeing easier. */ view : TView; oldview : PView = nil; //* Pointer to old View we can restore it.*/ viewport : TViewPort; bitMap : TBitmap; cm : PColorMap = nil; vextra : PViewExtra = nil; //* Extended structures used in Release 2 */ monspec : PMonitorSpec = nil; vpextra : PViewPortExtra = nil; dimquery : TDimensionInfo; displaymem : PByte = nil; //* Pointer for writing to BitMap memory. */ Const BLACK = $000; //* RGB values for the four colors used. */ RED = $f00; GREEN = $0f0; BLUE = $00f; {* * main(): create a custom display; works under either 1.3 or Release 2 *} procedure main; var depthidx, boxidx : SmallInt; rasInfo : TRasInfo; modeID : ULONG; vcTags : array [0..3] of TTagItem = ( ( ti_Tag: VTAG_ATTACH_CM_SET; ti_Data: 0 ), ( ti_Tag: VTAG_VIEWPORTEXTRA_SET; ti_Data: 0 ), ( ti_Tag: VTAG_NORMAL_DISP_SET; ti_Data: 0 ), ( ti_Tag: VTAG_END_CM; ti_Data: 0 ) ); //* Offsets in BitMap where boxes will be drawn. */ boxoffsets: array[0..2] of SmallInt = ( 802, 2010, 3218 ); colortable: array[0..3] of UWORD = ( BLACK, RED, GREEN, BLUE ); begin {$IF DEFINED(AMIGA) or DEFINED(MORPHOS)} GfxBase := PGfxBase(OpenLibrary('graphics.library', 33)); if (GfxBase = nil) then fail('Could not open graphics library' + LineEnding); {$ENDIF} //* Example steals screen from Intuition if Intuition is around. */ oldview := GfxBase^.ActiView; //* Save current View to restore later. */ InitView(@view); //* Initialize the View and set View.Modes. */ view.Modes := view.Modes or LACE; //* This is the old 1.3 way (only LACE counts). */ if (GfxBase^.LibNode.lib_Version >= 36) then begin //* Form the ModeID from values in <displayinfo.h> */ modeID := DEFAULT_MONITOR_ID or HIRESLACE_KEY; //* Make the ViewExtra structure */ if SetAndTest(vextra, GfxNew(VIEW_EXTRA_TYPE) ) then begin //* Attach the ViewExtra to the View */ GfxAssociate(@view , Pointer(vextra)); view.Modes := view.Modes or EXTEND_VSTRUCT; //* Create and attach a MonitorSpec to the ViewExtra */ if SetAndTest(monspec, OpenMonitor(nil, modeID) ) then vextra^.Monitor := monspec else fail('Could not get MonitorSpec' + LineEnding); end else fail('Could not get ViewExtra' + LineEnding); end; //* Initialize the BitMap for RasInfo. */ InitBitMap(@bitMap, DEPTH, WIDTH, HEIGHT); //* Set the plane pointers to NULL so the cleanup routine */ //* will know if they were used. */ for depthidx := 0 to Pred(DEPTH) do bitMap.Planes[depthidx] := nil; //* Allocate space for BitMap. */ for depthidx :=0 to Pred(DEPTH) do begin bitMap.Planes[depthidx] := (AllocRaster(WIDTH, HEIGHT)); if (bitMap.Planes[depthidx] = nil) then fail('Could not get BitPlanes' + LineEnding); end; rasInfo.BitMap := @bitMap; //* Initialize the RasInfo. */ rasInfo.RxOffset := 0; rasInfo.RyOffset := 0; rasInfo.Next := nil; InitVPort(@viewPort); //* Initialize the ViewPort. */ view.ViewPort := @viewPort; //* Link the ViewPort into the View. */ viewPort.RasInfo := @rasInfo; viewPort.DWidth := WIDTH; viewPort.DHeight := HEIGHT; //* Set the display mode the old-fashioned way */ viewPort.Modes := HIRES or LACE; if (GfxBase^.LibNode.lib_Version >= 36) then begin //* Make a ViewPortExtra and get ready to attach it */ if SetAndTest(vpextra, GfxNew(VIEWPORT_EXTRA_TYPE) ) then begin vcTags[1].ti_Data := ULONG(vpextra); //* Initialize the DisplayClip field of the ViewPortExtra */ if (GetDisplayInfoData(nil, PChar(@dimquery), sizeof(dimquery), DTAG_DIMS, modeID) <> 0) then begin vpextra^.DisplayClip := dimquery.Nominal; //* Make a DisplayInfo and get ready to attach it */ if not(SetAndTest(vcTags[2].ti_Data, ULONG(FindDisplayInfo(modeID))) ) then fail('Could not get DisplayInfo' + LineEnding); end else fail('Could not get DimensionInfo ' + LineEnding); end else fail('Could not get ViewPortExtra' + LineEnding); //* This is for backwards compatibility with, for example, */ //* a 1.3 screen saver utility that looks at the Modes field */ viewPort.Modes := UWORD((modeID and $0000ffff)); end; //* Initialize the ColorMap. */ //* 2 planes deep, so 4 entries (2 raised to the #_planes power). */ cm := GetColorMap(4); if (cm = nil) then fail('Could not get ColorMap' + LineEnding); if (GfxBase^.LibNode.lib_Version >= 36) then begin //* Get ready to attach the ColorMap, Release 2-style */ vcTags[0].ti_Data := ULONG(@viewPort); //* Attach the color map and Release 2 extended structures */ if ( VideoControl(cm, vcTags) ) then fail('Could not attach extended structures' + LIneEnding); end else //* Attach the ColorMap, old 1.3-style */ viewPort.ColorMap := cm; LoadRGB4(@viewPort, colortable, 4); //* Change colors to those in colortable. */ MakeVPort(@view, @viewPort); //* Construct preliminary Copper instruction list. */ //* Merge preliminary lists into a real Copper list in the View structure. */ MrgCop(@view); //* Clear the ViewPort */ for depthidx := 0 to Pred(DEPTH) do begin displaymem := PUBYTE(bitMap.Planes[depthidx]); BltClear(displaymem, (bitMap.BytesPerRow * bitMap.Rows), 1); end; LoadView(@view); //* Now fill some boxes so that user can see something. */ //* Always draw into both planes to assure true colors. */ for boxidx := 1 to 3 do //* Three boxes; red, green and blue. */ begin for depthidx := 0 to Pred(Depth) do //* Two planes. */ begin displaymem := bitMap.Planes[depthidx] + boxoffsets[boxidx-1]; drawFilledBox(boxidx, depthidx); end; end; DOSDelay(10 * TICKS_PER_SECOND); //* Pause for 10 seconds. */ LoadView(oldview); //* Put back the old View. */ WaitTOF(); //* Wait until the the View is being */ //* rendered to free memory. */ FreeCprList(view.LOFCprList); //* Deallocate the hardware Copper list */ if (view.SHFCprList <> nil) //* created by MrgCop(). Since this */ then FreeCprList(view.SHFCprList);//* is interlace, also check for a */ //* short frame copper list to free. */ FreeVPortCopLists(@viewPort); //* Free all intermediate Copper lists */ //* from created by MakeVPort(). */ cleanup(RETURN_OK); //* Success. */ end; {* * fail(): print the error string and call cleanup() to exit *} procedure fail(errorstring: STRPTR); begin Write(errorstring); cleanup(RETURN_FAIL); end; {* * cleanup(): free everything that was allocated. *} procedure cleanup(returncode: integer); var depthidx : SmallInt; begin //* Free the color map created by GetColorMap(). */ if assigned(cm) then FreeColorMap(cm); //* Free the ViewPortExtra created by GfxNew() */ if assigned(vpextra) then GfxFree(pointer(vpextra)); //* Free the BitPlanes drawing area. */ for depthidx := 0 to Pred(DEPTH) do begin if (bitMap.Planes[depthidx] <> nil) then FreeRaster(bitMap.Planes[depthidx], WIDTH, HEIGHT); end; //* Free the MonitorSpec created with OpenMonitor() */ if assigned(monspec) then CloseMonitor(monspec); //* Free the ViewExtra created with GfxNew() */ if assigned(vextra) then GfxFree(pointer(vextra)); {$IF DEFINED(AMIGA) or DEFINED(MORPHOS)} //* Close the graphics library */ CloseLibrary(PLibrary(GfxBase)); {$ENDIF} halt(returncode); end; {* * drawFilledBox(): create a WIDTH/2 by HEIGHT/2 box of color * "fillcolor" into the given plane. *} procedure drawFilledBox(fillcolor: SmallInt; plane: SmallInt); var value: UBYTE; boxHeight, boxWidth, widthidx : SmallInt; begin //* Divide (WIDTH/2) by eight because each UBYTE that */ //* is written stuffs eight bits into the BitMap. */ boxWidth := (WIDTH div 2) div 8; boxHeight := HEIGHT div 2; if ((fillcolor and (1 shl plane)) <> 0) then value := $ff else value := $00; while (boxHeight <> 0) do begin for widthidx := 0 to Pred(boxWidth) do begin displaymem^ := value; inc(displaymem); end; displaymem := displaymem + (bitMap.BytesPerRow - boxWidth); dec(boxHeight); end; end; begin {$IFDEF AROS} WriteLn('This example does not work for AROS for various reasons'); {$ENDIF} Main; end.
{ $HDR$} {**********************************************************************} { Unit archived using Team Coherence } { Team Coherence is Copyright 2002 by Quality Software Components } { } { For further information / comments, visit our WEB site at } { http://www.TeamCoherence.com } {**********************************************************************} {} { $Log: 116690: IdServerIOHandlerTls.pas { { Rev 1.0 27-03-05 10:04:20 MterWoord { Second import, first time the filenames weren't prefixed with Id } { { Rev 1.0 27-03-05 09:08:54 MterWoord { Created } unit IdServerIOHandlerTls; interface uses IdSSL, IdTlsServerOptions, Mono.Security.Protocol.Tls, IdCarrierStream, IdSocketStream, System.IO, System.Security.Cryptography, IdGlobal, IdYarn, System.Security.Cryptography.X509Certificates, Mono.Security.Authenticode, IdIOHandler, IdSocketHandle, IdThread; type TIdServerIOHandlerTls = class(TIdServerIOHandlerSSLBase) protected FOptions: TIdTlsServerOptions; function NewServerSideIOHandlerTls: TIdSSLIOHandlerSocketBase; procedure InitComponent; override; public function MakeFTPSvrPasv: TIdSSLIOHandlerSocketBase; override; function MakeFTPSvrPort: TIdSSLIOHandlerSocketBase; override; function MakeClientIOHandler(AYarn: TIdYarn) : TIdIOHandler; override; function MakeClientIOHandler: TIdSSLIOHandlerSocketBase; override; function Accept(ASocket: TIdSocketHandle; AListenerThread: TIdThread; AYarn: TIdYarn): TIdIOHandler; override; published property Options: TIdTlsServerOptions read FOptions write FOptions; end; implementation type TIdServerSideIOHandlerTls = class(TIdSSLIOHandlerSocketBase) protected FOptions: TIdTlsServerOptions; FTlsServerStream: SslServerStream; FTlsClientStream: SslClientStream; FCarrierStream: TIdCarrierStream; FSocketStream: TIdSocketStream; FActiveStream: Stream; FPassThrough: Boolean; function PrivateKeySelection(certificate: X509Certificate; TargetHost: string): AsymmetricAlgorithm; function ReadFromSource(ARaiseExceptionIfDisconnected: Boolean; ATimeout: Integer; ARaiseExceptionOnTimeOut: Boolean): Integer; override; procedure SetPassThrough(const AValue: Boolean); override; public procedure CheckForDataOnSource(ATimeOut: Integer); override; procedure StartSSL; override; procedure AfterAccept; override; procedure CheckForDisconnect(ARaiseExceptionIfDisconnected: Boolean; AIgnoreBuffer: Boolean); override; function Clone: TIdSSLIOHandlerSocketBase; override; procedure WriteDirect(ABuffer: TIdBytes); override; procedure Close; override; published property Options: TIdTlsServerOptions read FOptions write FOptions; end; { TServerSideIOHandlerTls } function TIdServerSideIOHandlerTls.Clone: TIdSSLIOHandlerSocketBase; var TEmpResult : TIdServerSideIOHandlerTls; begin TempResult := TIdServerSideIOHandlerTls.Create; TempResult.Options.ClientNeedsCertificate := Options.ClientNeedsCertificate; TempResult.Options.PrivateKey := Options.PrivateKey; TempResult.Options.Protocol := Options.Protocol; TempResult.Options.PublicCertificate := Options.PublicCertificate; TempResult.IsPeer := IsPeer; TempResult.PassThrough := PassThrough; Result := TempResult; end; procedure TIdServerSideIOHandlerTls.StartSSL; begin inherited; PassThrough := False; end; function TIdServerSideIOHandlerTls.PrivateKeySelection( certificate: X509Certificate; TargetHost: string): AsymmetricAlgorithm; begin Result := FOptions.PrivateKey.RSA; end; function TIdServerSideIOHandlerTls.ReadFromSource( ARaiseExceptionIfDisconnected: Boolean; ATimeout: Integer; ARaiseExceptionOnTimeOut: Boolean): Integer; var TempBuff: array of byte; TotalBytesRead: Integer; StartTime: Cardinal; BytesRead: Integer; TempBytes: array of byte; begin Result := 0; if FInputBuffer = nil then Exit; if FActiveStream <> nil then begin SetLength(TempBuff, 512); TotalBytesRead := 0; StartTime := Ticks; repeat BytesRead := FActiveStream.Read(TempBuff, 0, 512); if BytesRead <> 0 then begin TempBytes := ToBytes(TempBuff, BytesRead); FInputBuffer.Write(TempBytes); TotalBytesRead := TotalBytesRead + BytesRead; end; if BytesRead <> 512 then begin Result := TotalBytesRead; Exit; end; Sleep(2); until ( (Abs(GetTickDiff(StartTime, Ticks)) > ATimeOut) and (not ((ATimeOut = IdTimeoutDefault) or (ATimeOut = IdTimeoutInfinite))) ); Result := TotalBytesRead; end; end; procedure TIdServerSideIOHandlerTls.CheckForDisconnect( ARaiseExceptionIfDisconnected, AIgnoreBuffer: Boolean); begin try if FActiveStream = nil then begin if AIgnoreBuffer then begin CloseGracefully; end else begin if FInputBuffer.Size = 0 then begin CloseGracefully; end; end; end else begin if ( (not FActiveStream.CanRead) or (not FActiveStream.CanWrite) ) then begin if AIgnoreBuffer then begin CloseGracefully; end else begin if FInputBuffer.Size = 0 then begin CloseGracefully; end; end; end; end; except on E: Exception do begin CloseGracefully; end; end; if ( (ARaiseExceptionIfDisconnected) and (ClosedGracefully) ) then RaiseConnClosedGracefully; end; procedure TIdServerSideIOHandlerTls.CheckForDataOnSource(ATimeOut: Integer); begin if Connected then begin ReadFromSource(false, ATimeOut, false); end; end; procedure TIdServerSideIOHandlerTls.AfterAccept; begin inherited; FSocketStream := TIdSocketStream.Create(Binding.Handle); FCarrierStream := TIdCarrierStream.Create(FSocketStream); FTlsServerStream := SslServerStream.Create(FCarrierStream, FOptions.PublicCertificate, FOptions.ClientNeedsCertificate, true, FOptions.Protocol); GC.SuppressFinalize(FSocketStream); GC.SuppressFinalize(FCarrierStream); GC.SuppressFinalize(FTlsServerStream); FActiveStream := FCarrierStream; FTlsServerStream.PrivateKeyCertSelectionDelegate := PrivateKeySelection; IsPeer := true; PassThrough := true; end; procedure TIdServerSideIOHandlerTls.Close; begin if not PassThrough then begin if IsPeer then begin if FTlsServerStream <> nil then begin FTlsServerStream.Close; FTlsServerStream := nil; end; end else begin if FTlsClientStream <> nil then begin FTlsClientStream.Close; FTlsClientStream := nil; end; end; end; if FCarrierStream <> nil then begin FCarrierStream.Close; FCarrierStream := nil; end; if FSocketStream <> nil then begin FSocketStream.Close; FSocketStream := nil; end; inherited; end; procedure TIdServerSideIOHandlerTls.WriteDirect(ABuffer: TIdBytes); begin if Intercept <> nil then Intercept.Send(ABuffer); if FActiveStream <> nil then begin FActiveStream.Write(ABuffer, 0, Length(ABuffer)); FActiveStream.Flush; end else raise Exception.Create('No active stream!'); end; procedure TIdServerSideIOHandlerTls.SetPassThrough(const AValue: Boolean); var TempBuff: array[0..0] of byte; begin inherited; if AValue then begin if FActiveStream <> nil then begin FActiveStream.Close; FActiveStream := nil; end; FActiveStream := FSocketStream; if IsPeer then begin if FTlsServerStream <> nil then begin FTlsServerStream.Close; FTlsServerStream := nil; end; FTlsServerStream := SslServerStream.Create(FCarrierStream, FOptions.PublicCertificate, FOptions.ClientNeedsCertificate, true, FOptions.Protocol); GC.SuppressFinalize(FTlsServerStream); FTlsServerStream.PrivateKeyCertSelectionDelegate := PrivateKeySelection; end else begin if FTlsClientStream <> nil then begin FTlsClientStream.Close; FTlsClientStream := nil; end; FTlsClientStream := SslClientStream.Create(FCarrierStream, Destination, true, FOptions.Protocol); GC.SuppressFinalize(FTlsClientStream); end; end else begin if IsPeer then begin FActiveStream := FTlsServerStream; end else begin FActiveStream := FTlsClientStream; end; FActiveStream.Read(TempBuff, 0, 0); end; end; { TServerIOHandlerTls } procedure TIdServerIOHandlerTls.InitComponent; begin inherited; FOptions := TIdTlsServerOptions.Create; end; function TIdServerIOHandlerTls.NewServerSideIOHandlerTls: TIdSSLIOHandlerSocketBase; var TempResult: TIdServerSideIOHandlerTls; begin TempResult := TIdServerSideIOHandlerTls.Create; TempResult.Options := FOptions; Result := TempResult; end; function TIdServerIOHandlerTls.MakeClientIOHandler: TIdSSLIOHandlerSocketBase; begin Result := NewServerSideIOHandlerTls; end; function TIdServerIOHandlerTls.MakeClientIOHandler(AYarn: TIdYarn): TIdIOHandler; begin Result := NewServerSideIOHandlerTls; end; function TIdServerIOHandlerTls.MakeFTPSvrPort: TIdSSLIOHandlerSocketBase; begin Result := NewServerSideIOHandlerTls; end; function TIdServerIOHandlerTls.Accept(ASocket: TIdSocketHandle; AListenerThread: TIdThread; AYarn: TIdYarn): TIdIOHandler; var LIOHandler: TIdServerSideIOHandlerTls; begin LIOHandler := TIdServerSideIOHandlerTls.Create; LIOHandler.Options := FOptions; LIOHandler.Open; while not AListenerThread.Stopped do begin try if ASocket.Select(250) then begin if LIOHandler.Binding.Accept(ASocket.Handle) then begin LIOHandler.AfterAccept; Result := LIOHandler; Exit; end else begin LIOHandler.Close; Result := nil; Exit; end; end; finally if AListenerThread.Stopped then begin LIOHandler.Close; end; end; end; Result := nil; end; function TIdServerIOHandlerTls.MakeFTPSvrPasv: TIdSSLIOHandlerSocketBase; begin Result := NewServerSideIOHandlerTls; end; end.
unit EspecificacaoLoteNFePorCodigoNotaFiscal; interface uses Especificacao; type TEspecificacaoLoteNFePorCodigoNotaFiscal = class(TEspecificacao) private FCodigoNotaFiscal :Integer; public constructor Create(const CodigoNotaFiscal :Integer); public function SatisfeitoPor(LoteNFe :TObject) :Boolean; override; end; implementation uses ExcecaoParametroInvalido, LoteNFe; { TEspecificacaoLoteNFePorCodigoNotaFiscal } constructor TEspecificacaoLoteNFePorCodigoNotaFiscal.Create(const CodigoNotaFiscal: Integer); begin if (CodigoNotaFiscal <= 0) then raise TExcecaoParametroInvalido.Create(self.ClassName, 'Create(const CodigoNotaFiscal: Integer)', 'CodigoNotaFiscal'); self.FCodigoNotaFiscal := CodigoNotaFiscal; end; function TEspecificacaoLoteNFePorCodigoNotaFiscal.SatisfeitoPor( LoteNFe: TObject): Boolean; var L :TLoteNFe; begin L := (LoteNFe as TLoteNFe); result := (L.CodigoNotaFiscal = self.FCodigoNotaFiscal); end; end.